Advertisement
Guest User

mkimage.c

a guest
Nov 14th, 2014
277
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.09 KB | None | 0 0
  1. #include <stdint.h>
  2. #include <unistd.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <sys/types.h>
  6. #include <sys/stat.h>
  7.  
  8. #define PART_MAGIC        0x58881688
  9. #define BLK_SIZE          512
  10.  
  11. typedef union {
  12.     struct {    
  13.         unsigned int magic;        /* partition magic */
  14.         unsigned int dsize;        /* partition data size */
  15.         char         name[32];     /* partition name */
  16.     } info;
  17.     unsigned char data[BLK_SIZE];
  18. } part_hdr_t;
  19.  
  20. unsigned int filesize(char *name)
  21. {
  22.     struct stat statbuf;
  23.  
  24.     if(stat(name, &statbuf) != 0) {
  25.         fprintf(stderr, "Cannot open file %s\n", name);
  26.         exit(0);
  27.     }
  28.     return statbuf.st_size;
  29. }
  30.  
  31. char *readfile(char *name, unsigned int size)
  32. {
  33.     FILE *f;
  34.     char *buf;
  35.  
  36.     f = fopen(name, "rb");
  37.     if(f == NULL) {
  38.         fprintf(stderr, "Cannot open file %s\n", name);
  39.         exit(0);
  40.     }
  41.     buf = (char *)malloc(size);
  42.     if (!buf) {
  43.         fprintf(stderr, "error while malloc(%ld)\n", size);
  44.         fclose(f);
  45.         exit(1);
  46.     }
  47.     if(fread(buf, 1, size, f) != size) {
  48.         fprintf(stderr, "Error while reading file %s\n", name);
  49.         fclose(f);
  50.         exit(0);
  51.     }
  52.     fclose(f);
  53.     return buf;
  54. }
  55.  
  56. int main(int argc, char *argv[])
  57. {
  58.     part_hdr_t part_hdr;
  59.     char *img;
  60.     uint32_t imgsize;
  61.  
  62.     if(argc != 3) {
  63.         fprintf(stderr, "\nUsage: ./mkimage <image_file> <image_name>\n\n");
  64.         fprintf(stderr, "  e.g. <image_file>: Image, rootfs.gz\n");
  65.         fprintf(stderr, "  e.g. <image_name>: KERNEL, ROOTFS\n\n");
  66.         return 0;
  67.     }
  68.    
  69.     memset(&part_hdr, 0xff, sizeof(part_hdr_t));
  70.  
  71.     part_hdr.info.magic = PART_MAGIC;
  72.     part_hdr.info.dsize = filesize(argv[1]);
  73.     strncpy(part_hdr.info.name, argv[2], sizeof(part_hdr.info.name));
  74.  
  75.     /*
  76.     fprintf(stderr, "[MKIMAGE] '%s'(%d bytes)\n", part_hdr.info.name,
  77.         part_hdr.info.dsize);
  78.     */
  79.  
  80.     img = readfile(argv[1], part_hdr.info.dsize);
  81.  
  82.     write(STDOUT_FILENO, &part_hdr, sizeof(part_hdr_t));
  83.     write(STDOUT_FILENO, img, part_hdr.info.dsize);
  84.  
  85.     return 0;
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement