Guest User

Untitled

a guest
Jun 25th, 2018
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.57 KB | None | 0 0
  1.  
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include <stdlib.h>
  5.  
  6. #define MAX_FILES 128
  7. #define MAX_FILENAME 64
  8. #define INITRD_MAGIC 0xBF
  9.  
  10. struct initrd_header
  11. {
  12. unsigned char magic; // The magic number is there to check for consistency.
  13. char name[64];
  14. unsigned int offset; // Offset in the initrd the file starts.
  15. unsigned int length; // Length of the file.
  16. };
  17.  
  18. struct mkinitrd_file {
  19. char file_src[MAX_FILENAME];
  20. char initrd_path[MAX_FILENAME];
  21. };
  22.  
  23. struct mkinitrd_args {
  24. char outpath[256];
  25. int nfiles;
  26. struct mkinitrd_file files[MAX_FILES];
  27. };
  28.  
  29. void parse_args(int argc, char **argv, struct mkinitrd_args *out)
  30. {
  31. int count = argc;
  32. int file_i = 0;
  33. int i = 0;
  34.  
  35. strcpy(out->outpath, "./initrd.img");
  36. out->nfiles = 0;
  37. for (i=1; i<argc; ++i) {
  38. if (strcmp(argv[i], "-o") == 0 && argc > (i+1)) {
  39. strcpy(out->outpath, argv[i+1]);
  40. i++; // skip outpath arg.
  41. } else {
  42. strcpy(out->files[file_i].file_src, argv[i]);
  43. strcpy(out->files[file_i].initrd_path, argv[i+1]);
  44. i++;
  45. file_i++;
  46. out->nfiles++;
  47. }
  48. }
  49. }
  50.  
  51. int main(int argc, char **argv)
  52. {
  53. struct initrd_header headers[64];
  54. unsigned int off = sizeof(struct initrd_header) * MAX_FILES + sizeof(int);
  55. struct mkinitrd_args args;
  56. int i;
  57.  
  58. parse_args(argc, argv, &args);
  59.  
  60. for(i = 0; i < args.nfiles; i++) {
  61. strcpy(headers[i].name, args.files[i].initrd_path);
  62. headers[i].offset = off;
  63. FILE *stream = fopen(args.files[i].file_src, "r");
  64. if(stream == 0) {
  65. printf("Error: file not found: %s\n", args.files[i].file_src);
  66. return;
  67. }
  68. fseek(stream, 0, SEEK_END);
  69. headers[i].length = ftell(stream);
  70. off += headers[i].length;
  71. fclose(stream);
  72. headers[i].magic = INITRD_MAGIC;
  73. }
  74.  
  75. FILE *wstream = fopen(args.outpath, "w");
  76. unsigned char *data = (unsigned char *)malloc(off);
  77. fwrite(&(args.nfiles), sizeof(int), 1, wstream);
  78. fwrite(headers, sizeof(struct initrd_header), MAX_FILES, wstream);
  79.  
  80. for(i = 0; i < args.nfiles; i++) {
  81. FILE *stream = fopen(args.files[i].file_src, "r");
  82. unsigned char *buf = (unsigned char *)malloc(headers[i].length);
  83. fread(buf, 1, headers[i].length, stream);
  84. fwrite(buf, 1, headers[i].length, wstream);
  85. fclose(stream);
  86. free(buf);
  87. }
  88.  
  89. fclose(wstream);
  90. free(data);
  91.  
  92. return 0;
  93. }
Add Comment
Please, Sign In to add comment