2 * uimage_padhdr.c : add zero paddings after the tail of uimage header
4 * Copyright (C) 2019 NOGUCHI Hiroshi <drvlabo@gmail.com>
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 * version 2 as published by the Free Software Foundation.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
23 #include <arpa/inet.h>
27 /* from u-boot/include/image.h */
28 #define IH_MAGIC 0x27051956 /* Image Magic Number */
29 #define IH_NMLEN 32 /* Image Name Length */
32 * Legacy format image header,
33 * all data in network byte order (aka natural aka bigendian).
35 typedef struct image_header {
36 uint32_t ih_magic; /* Image Header Magic Number */
37 uint32_t ih_hcrc; /* Image Header CRC Checksum */
38 uint32_t ih_time; /* Image Creation Timestamp */
39 uint32_t ih_size; /* Image Data Size */
40 uint32_t ih_load; /* Data Load Address */
41 uint32_t ih_ep; /* Entry Point Address */
42 uint32_t ih_dcrc; /* Image Data CRC Checksum */
43 uint8_t ih_os; /* Operating System */
44 uint8_t ih_arch; /* CPU architecture */
45 uint8_t ih_type; /* Image Type */
46 uint8_t ih_comp; /* Compression Type */
47 uint8_t ih_name[IH_NMLEN]; /* Image Name */
51 /* default padding size */
52 #define IH_PAD_BYTES (32)
55 static void usage(char *prog)
58 "%s -i <input_uimage_file> -o <output_file> [-l <padding bytes>]\n",
62 int main(int argc, char *argv[])
73 char *outfname = NULL;
74 int padsz = IH_PAD_BYTES;
77 while ((opt = getopt(argc, argv, "i:o:l:")) != -1) {
86 ltmp = strtol(optarg, NULL, 0);
95 if (!infname || !outfname) {
100 if (stat(infname, &statbuf) < 0) {
102 "could not find input file. (errno = %d)\n", errno);
106 filebuf = malloc(statbuf.st_size + padsz);
108 fprintf(stderr, "buffer allocation failed\n");
112 ifd = open(infname, O_RDONLY);
115 "could not open input file. (errno = %d)\n", errno);
119 ofd = open(outfname, O_WRONLY | O_CREAT, 0644);
122 "could not open output file. (errno = %d)\n", errno);
126 rsz = read(ifd, filebuf, sizeof(*imgh));
127 if (rsz != sizeof(*imgh)) {
129 "could not read input file (errno = %d).\n", errno);
133 memset(&(filebuf[sizeof(*imgh)]), 0, padsz);
135 rsz = read(ifd, &(filebuf[sizeof(*imgh) + padsz]),
136 statbuf.st_size - sizeof(*imgh));
137 if (rsz != (int32_t)(statbuf.st_size - sizeof(*imgh))) {
139 "could not read input file (errno = %d).\n", errno);
143 imgh = (image_header_t *)filebuf;
146 crc_recalc = crc32(0, filebuf, sizeof(*imgh) + padsz);
147 imgh->ih_hcrc = htonl(crc_recalc);
149 rsz = write(ofd, filebuf, statbuf.st_size + padsz);
150 if (rsz != (int32_t)statbuf.st_size + padsz) {
152 "could not write output file (errnor = %d).\n", errno);