d4636f773207fd24c1094936e527083424e6d965
[openwrt-10.03/.git] / tools / patch-cmdline / src / patch-cmdline.c
1 /*
2  * patch-cmdline.c - patch the kernel command line on rb532
3  *
4  * Copyright (C) 2006 Felix Fietkau <nbd@openwrt.org>
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19  *
20  * $Id:$
21  */
22
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <stddef.h>
26 #include <unistd.h>
27 #include <fcntl.h>
28 #include <sys/mman.h>
29 #include <sys/stat.h>
30 #include <string.h>
31
32 #define SEARCH_SPACE    (16 * 1024)
33 #define CMDLINE_MAX             512
34
35 int main(int argc, char **argv)
36 {
37         int fd, found = 0, len, ret = -1;
38         char *ptr, *p;
39
40         if (argc != 3) {
41                 fprintf(stderr, "Usage: %s <file> <cmdline>\n", argv[0]);
42                 goto err1;
43         }
44         len = strlen(argv[2]);
45         if (len + 9 > CMDLINE_MAX) {
46                 fprintf(stderr, "Command line string too long\n");
47                 goto err1;
48         }
49         
50         if (((fd = open(argv[1], O_RDWR)) < 0) ||
51                 (ptr = (char *) mmap(0, SEARCH_SPACE + CMDLINE_MAX, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0)) == (void *) (-1)) {
52                 fprintf(stderr, "Could not open kernel image");
53                 goto err2;
54         }
55         
56         for (p = ptr; p < (ptr + SEARCH_SPACE); p += 4) {
57                 if (memcmp(p, "CMDLINE:", 8) == 0) {
58                         found = 1;
59                         p += 8;
60                         break;
61                 }
62         }
63         if (!found) {
64                 fprintf(stderr, "Command line marker not found!\n");
65                 goto err3;
66         }
67
68         memset(p, 0, CMDLINE_MAX - 8);
69         strcpy(p, argv[2]);
70         msync(p, CMDLINE_MAX, MS_SYNC|MS_INVALIDATE);
71         ret = 0;
72
73 err3:
74         munmap((void *) ptr, len);
75 err2:
76         if (fd > 0)
77                 close(fd);
78 err1:
79         return ret;
80 }