patch-cmdline.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /*
  2. * patch-cmdline.c - patch the kernel command line
  3. *
  4. * Copyright (C) 2006 Felix Fietkau <[email protected]>
  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. */
  21. #include <stdio.h>
  22. #include <stdlib.h>
  23. #include <stddef.h>
  24. #include <unistd.h>
  25. #include <fcntl.h>
  26. #include <sys/mman.h>
  27. #include <sys/stat.h>
  28. #include <string.h>
  29. #define SEARCH_SPACE (16 * 1024)
  30. #define CMDLINE_MAX 512
  31. int main(int argc, char **argv)
  32. {
  33. int fd, found = 0, len, ret = -1;
  34. char *ptr, *p;
  35. unsigned int search_space;
  36. if (argc <= 2 || argc > 4) {
  37. fprintf(stderr, "Usage: %s <file> <cmdline> [size]\n", argv[0]);
  38. goto err1;
  39. } else if (argc == 3) {
  40. fprintf(stdout, "search space used is default of 16KB\n");
  41. search_space = SEARCH_SPACE;
  42. } else {
  43. search_space = atoi(argv[3]);
  44. }
  45. len = strlen(argv[2]);
  46. if (len + 9 > CMDLINE_MAX) {
  47. fprintf(stderr, "Command line string too long\n");
  48. goto err1;
  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. for (p = ptr; p < (ptr + search_space); p += 4) {
  56. if (memcmp(p, "CMDLINE:", 8) == 0) {
  57. found = 1;
  58. p += 8;
  59. break;
  60. }
  61. }
  62. if (!found) {
  63. fprintf(stderr, "Command line marker not found!\n");
  64. goto err3;
  65. }
  66. memset(p, 0, CMDLINE_MAX - 8);
  67. strcpy(p, argv[2]);
  68. msync(p, CMDLINE_MAX, MS_SYNC|MS_INVALIDATE);
  69. ret = 0;
  70. err3:
  71. munmap((void *) ptr, len);
  72. err2:
  73. if (fd > 0)
  74. close(fd);
  75. err1:
  76. return ret;
  77. }