[tools] firmware-utils/mkfwimage: fix Ubiquiti firmware generation (closes #4414)
[openwrt.git] / tools / firmware-utils / src / mkfwimage.c
1 /*
2  * Copyright (C) 2007 Ubiquiti Networks, Inc.
3  * Copyright (C) 2008 Lukas Kuna <ValXdater@seznam.cz>
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License as
7  * published by the Free Software Foundation; either version 2 of the
8  * License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  */
19
20 #include <sys/types.h>
21 #include <sys/stat.h>
22 #include <fcntl.h>
23 #include <unistd.h>
24 #include <string.h>
25 #include <errno.h>
26 #include <zlib.h>
27 #include <sys/mman.h>
28 #include <netinet/in.h>
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <limits.h>
32 #include "fw.h"
33
34 typedef struct fw_layout_data {
35         char            name[PATH_MAX];
36         u_int32_t       kern_start;
37         u_int32_t       kern_len;
38         u_int32_t       root_start;
39         u_int32_t       root_len;
40         u_int32_t       kern_entry;
41         u_int32_t       firmware_max_length;
42 } fw_layout_t;
43
44 fw_layout_t fw_layout_data[] = {
45         {
46                 .name           =       "XS2",
47                 .kern_start     =       0xbfc30000,
48                 .kern_len       =       0x00140000,
49                 .root_start     =       0xbfc30000,
50                 .root_len       =       0x002C0000,
51                 .kern_entry     =       0x80041000,
52                 .firmware_max_length=   0x00390000,
53         },
54         {
55                 .name           =       "XS5",
56                 .kern_start     =       0xbe030000,
57                 .kern_len       =       0x00140000,
58                 .root_start     =       0xbe030000,
59                 .root_len       =       0x002C0000,
60                 .kern_entry     =       0x80041000,
61                 .firmware_max_length=   0x00390000,
62         },
63         {
64                 .name           =       "RS",
65                 .kern_start     =       0x00000000,
66                 .kern_len       =       0x00140000,
67                 .root_start     =       0x00000000,
68                 .root_len       =       0x002C0000,
69                 .kern_entry     =       0x80060000,
70                 .firmware_max_length=   0x00140000 + 0x002C0000,
71         },
72         {       .name           =       "",
73         },
74 };
75
76 typedef struct part_data {
77         char    partition_name[64];
78         int     partition_index;
79         u_int32_t       partition_baseaddr;
80         u_int32_t       partition_startaddr;
81         u_int32_t       partition_memaddr;
82         u_int32_t       partition_entryaddr;
83         u_int32_t  partition_length;
84
85         char    filename[PATH_MAX];
86         struct stat stats;
87 } part_data_t;
88
89 #define MAX_SECTIONS    8
90 #define DEFAULT_OUTPUT_FILE     "firmware-image.bin"
91 #define DEFAULT_VERSION         "UNKNOWN"
92
93 #define OPTIONS "B:hv:o:r:k:"
94
95 static int debug = 0;
96
97 typedef struct image_info {
98         char version[256];
99         char outputfile[PATH_MAX];
100         u_int32_t       part_count;
101         part_data_t parts[MAX_SECTIONS];
102 } image_info_t;
103
104 static void write_header(void* mem, const char* version)
105 {
106         header_t* header = mem;
107         memset(header, 0, sizeof(header_t));
108
109         memcpy(header->magic, MAGIC_HEADER, MAGIC_LENGTH);
110         strncpy(header->version, version, sizeof(header->version));
111         header->crc = htonl(crc32(0L, (unsigned char *)header,
112                                 sizeof(header_t) - 2 * sizeof(u_int32_t)));
113         header->pad = 0L;
114 }
115
116
117 static void write_signature(void* mem, u_int32_t sig_offset)
118 {
119         /* write signature */
120         signature_t* sign = (signature_t*)(mem + sig_offset);
121         memset(sign, 0, sizeof(signature_t));
122
123         memcpy(sign->magic, MAGIC_END, MAGIC_LENGTH);
124         sign->crc = htonl(crc32(0L,(unsigned char *)mem, sig_offset));
125         sign->pad = 0L;
126 }
127
128 static int write_part(void* mem, part_data_t* d)
129 {
130         char* addr;
131         int fd;
132         part_t* p = mem;
133         part_crc_t* crc = mem + sizeof(part_t) + d->stats.st_size;
134
135         fd = open(d->filename, O_RDONLY);
136         if (fd < 0)
137         {
138                 ERROR("Failed opening file '%s'\n", d->filename);
139                 return -1;
140         }
141
142         if ((addr=(char*)mmap(0, d->stats.st_size, PROT_READ, MAP_SHARED, fd, 0)) == MAP_FAILED)
143         {
144                 ERROR("Failed mmaping memory for file '%s'\n", d->filename);
145                 close(fd);
146                 return -2;
147         }
148
149         memcpy(mem + sizeof(part_t), addr, d->stats.st_size);
150         munmap(addr, d->stats.st_size);
151
152         memset(p->name, 0, sizeof(p->name));
153         strncpy(p->magic, MAGIC_PART, MAGIC_LENGTH);
154         strncpy(p->name, d->partition_name, sizeof(p->name));
155         p->index = htonl(d->partition_index);
156         p->data_size = htonl(d->stats.st_size);
157         p->part_size = htonl(d->partition_length);
158         p->baseaddr = htonl(d->partition_baseaddr);
159         p->memaddr = htonl(d->partition_memaddr);
160         p->entryaddr = htonl(d->partition_entryaddr);
161
162         crc->crc = htonl(crc32(0L, mem, d->stats.st_size + sizeof(part_t)));
163         crc->pad = 0L;
164
165         return 0;
166 }
167
168 static void usage(const char* progname)
169 {
170         INFO("Version %s\n"
171              "Usage: %s [options]\n"
172              "\t-v <version string>\t - firmware version information, default: %s\n"
173              "\t-o <output file>\t - firmware output file, default: %s\n"
174              "\t-k <kernel file>\t\t - kernel file\n"
175              "\t-r <rootfs file>\t\t - rootfs file\n"
176              "\t-B <board name>\t\t - choose firmware layout for specified board (XS2, XS5, RS)\n"
177              "\t-h\t\t\t - this help\n", VERSION,
178              progname, DEFAULT_VERSION, DEFAULT_OUTPUT_FILE);
179 }
180
181 static void print_image_info(const image_info_t* im)
182 {
183         int i = 0;
184         INFO("Firmware version: '%s'\n"
185              "Output file: '%s'\n"
186              "Part count: %u\n",
187              im->version, im->outputfile,
188              im->part_count);
189
190         for (i = 0; i < im->part_count; ++i)
191         {
192                 const part_data_t* d = &im->parts[i];
193                 INFO(" %10s: %8ld bytes (free: %8ld)\n",
194                      d->partition_name,
195                      d->stats.st_size,
196                      d->partition_length - d->stats.st_size);
197         }
198 }
199
200
201
202 static u_int32_t filelength(const char* file)
203 {
204         FILE *p;
205         int ret = -1;
206
207         if ( (p = fopen(file, "rb") ) == NULL) return (-1);
208
209         fseek(p, 0, SEEK_END);
210         ret = ftell(p);
211
212         fclose (p);
213
214         return (ret);
215 }
216
217 static int create_image_layout(const char* kernelfile, const char* rootfsfile, char* board_name, image_info_t* im)
218 {
219         part_data_t* kernel = &im->parts[0];
220         part_data_t* rootfs = &im->parts[1];
221
222         fw_layout_t* p;
223
224         p = &fw_layout_data[0];
225         while ((strlen(p->name) != 0) && (strncmp(p->name, board_name, sizeof(board_name)) != 0))
226                 p++;
227         if (p->name == NULL) {
228                 printf("BUG! Unable to find default fw layout!\n");
229                 exit(-1);
230         }
231
232         printf("board = %s\n", p->name);
233         strcpy(kernel->partition_name, "kernel");
234         kernel->partition_index = 1;
235         kernel->partition_baseaddr = p->kern_start;
236         if ( (kernel->partition_length = filelength(kernelfile)) < 0) return (-1);
237         kernel->partition_memaddr = p->kern_entry;
238         kernel->partition_entryaddr = p->kern_entry;
239         strncpy(kernel->filename, kernelfile, sizeof(kernel->filename));
240
241         if (filelength(rootfsfile) + kernel->partition_length > p->firmware_max_length)
242                 return (-2);
243
244         strcpy(rootfs->partition_name, "rootfs");
245         rootfs->partition_index = 2;
246         rootfs->partition_baseaddr = kernel->partition_baseaddr + kernel->partition_length;
247         rootfs->partition_length = p->firmware_max_length - kernel->partition_length;
248         rootfs->partition_memaddr = 0x00000000;
249         rootfs->partition_entryaddr = 0x00000000;
250         strncpy(rootfs->filename, rootfsfile, sizeof(rootfs->filename));
251
252 printf("kernel: %d 0x%08x\n", kernel->partition_length, kernel->partition_baseaddr);
253 printf("root: %d 0x%08x\n", rootfs->partition_length, rootfs->partition_baseaddr);
254         im->part_count = 2;
255
256         return 0;
257 }
258
259 /**
260  * Checks the availability and validity of all image components.
261  * Fills in stats member of the part_data structure.
262  */
263 static int validate_image_layout(image_info_t* im)
264 {
265         int i;
266
267         if (im->part_count == 0 || im->part_count > MAX_SECTIONS)
268         {
269                 ERROR("Invalid part count '%d'\n", im->part_count);
270                 return -1;
271         }
272
273         for (i = 0; i < im->part_count; ++i)
274         {
275                 part_data_t* d = &im->parts[i];
276                 int len = strlen(d->partition_name);
277                 if (len == 0 || len > 16)
278                 {
279                         ERROR("Invalid partition name '%s' of the part %d\n",
280                                         d->partition_name, i);
281                         return -1;
282                 }
283                 if (stat(d->filename, &d->stats) < 0)
284                 {
285                         ERROR("Couldn't stat file '%s' from part '%s'\n",
286                                         d->filename, d->partition_name);
287                         return -2;
288                 }
289                 if (d->stats.st_size == 0)
290                 {
291                         ERROR("File '%s' from part '%s' is empty!\n",
292                                         d->filename, d->partition_name);
293                         return -3;
294                 }
295                 if (d->stats.st_size > d->partition_length) {
296                         ERROR("File '%s' too big (%d) - max size: 0x%08X (exceeds %lu bytes)\n",
297                                         d->filename, i, d->partition_length,
298                                         d->stats.st_size - d->partition_length);
299                         return -4;
300                 }
301         }
302
303         return 0;
304 }
305
306 static int build_image(image_info_t* im)
307 {
308         char* mem;
309         char* ptr;
310         u_int32_t mem_size;
311         FILE* f;
312         int i;
313
314         // build in-memory buffer
315         mem_size = sizeof(header_t) + sizeof(signature_t);
316         for (i = 0; i < im->part_count; ++i)
317         {
318                 part_data_t* d = &im->parts[i];
319                 mem_size += sizeof(part_t) + d->stats.st_size + sizeof(part_crc_t);
320         }
321
322         mem = (char*)calloc(mem_size, 1);
323         if (mem == NULL)
324         {
325                 ERROR("Cannot allocate memory chunk of size '%u'\n", mem_size);
326                 return -1;
327         }
328
329         // write header
330         write_header(mem, im->version);
331         ptr = mem + sizeof(header_t);
332         // write all parts
333         for (i = 0; i < im->part_count; ++i)
334         {
335                 part_data_t* d = &im->parts[i];
336                 int rc;
337                 if ((rc = write_part(ptr, d)) != 0)
338                 {
339                         ERROR("ERROR: failed writing part %u '%s'\n", i, d->partition_name);
340                 }
341                 ptr += sizeof(part_t) + d->stats.st_size + sizeof(part_crc_t);
342         }
343         // write signature
344         write_signature(mem, mem_size - sizeof(signature_t));
345
346         // write in-memory buffer into file
347         if ((f = fopen(im->outputfile, "w")) == NULL)
348         {
349                 ERROR("Can not create output file: '%s'\n", im->outputfile);
350                 return -10;
351         }
352
353         if (fwrite(mem, mem_size, 1, f) != 1)
354         {
355                 ERROR("Could not write %d bytes into file: '%s'\n",
356                                 mem_size, im->outputfile);
357                 return -11;
358         }
359
360         free(mem);
361         fclose(f);
362         return 0;
363 }
364
365
366 int main(int argc, char* argv[])
367 {
368         char kernelfile[PATH_MAX];
369         char rootfsfile[PATH_MAX];
370         char board_name[PATH_MAX];
371         int o, rc;
372         image_info_t im;
373
374         memset(&im, 0, sizeof(im));
375         memset(kernelfile, 0, sizeof(kernelfile));
376         memset(rootfsfile, 0, sizeof(rootfsfile));
377         memset(board_name, 0, sizeof(board_name));
378
379         strcpy(im.outputfile, DEFAULT_OUTPUT_FILE);
380         strcpy(im.version, DEFAULT_VERSION);
381
382         while ((o = getopt(argc, argv, OPTIONS)) != -1)
383         {
384                 switch (o) {
385                 case 'v':
386                         if (optarg)
387                                 strncpy(im.version, optarg, sizeof(im.version));
388                         break;
389                 case 'o':
390                         if (optarg)
391                                 strncpy(im.outputfile, optarg, sizeof(im.outputfile));
392                         break;
393                 case 'h':
394                         usage(argv[0]);
395                         return -1;
396                 case 'k':
397                         if (optarg)
398                                 strncpy(kernelfile, optarg, sizeof(kernelfile));
399                         break;
400                 case 'r':
401                         if (optarg)
402                                 strncpy(rootfsfile, optarg, sizeof(rootfsfile));
403                         break;
404                 case 'B':
405                         if (optarg)
406                                 strncpy(board_name, optarg, sizeof(board_name));
407                         break;
408                 }
409         }
410         if (strlen(board_name) == 0)
411                 strcpy(board_name, "XS2"); /* default to XS2 */
412
413         if (strlen(kernelfile) == 0)
414         {
415                 ERROR("Kernel file is not specified, cannot continue\n");
416                 usage(argv[0]);
417                 return -2;
418         }
419
420         if (strlen(rootfsfile) == 0)
421         {
422                 ERROR("Root FS file is not specified, cannot continue\n");
423                 usage(argv[0]);
424                 return -2;
425         }
426
427         if ((rc = create_image_layout(kernelfile, rootfsfile, board_name, &im)) != 0)
428         {
429                 ERROR("Failed creating firmware layout description - error code: %d\n", rc);
430                 return -3;
431         }
432
433         if ((rc = validate_image_layout(&im)) != 0)
434         {
435                 ERROR("Failed validating firmware layout - error code: %d\n", rc);
436                 return -4;
437         }
438
439         print_image_info(&im);
440
441         if ((rc = build_image(&im)) != 0)
442         {
443                 ERROR("Failed building image file '%s' - error code: %d\n", im.outputfile, rc);
444                 return -5;
445         }
446
447         return 0;
448 }