Merge remote-tracking branch 'hpa/master'
[profile/ivi/syslinux.git] / utils / isohybrid.c
1 /*
2  * isohybrid.c: Post process an ISO 9660 image generated with mkisofs or
3  * genisoimage to allow - hybrid booting - as a CD-ROM or as a hard
4  * disk.
5  *
6  * This is based on the original Perl script written by H. Peter Anvin. The
7  * rewrite in C is to avoid dependency on Perl on a system under installation.
8  *
9  * Copyright (C) 2010 P J P <pj.pandit@yahoo.co.in>
10  *
11  * isohybrid is a free software; you can redistribute it and/or modify it
12  * under the terms of GNU General Public License as published by Free Software
13  * Foundation; either version 2 of the license, or (at your option) any later
14  * version.
15  *
16  * isohybrid is distributed in the hope that it will be useful, but WITHOUT
17  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
18  * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
19  * more details.
20  *
21  * You should have received a copy of the GNU General Public License along
22  * with isohybrid; if not, see: <http://www.gnu.org/licenses>.
23  *
24  */
25
26 #include <err.h>
27 #include <time.h>
28 #include <ctype.h>
29 #include <fcntl.h>
30 #include <stdio.h>
31 #include <alloca.h>
32 #include <getopt.h>
33 #include <signal.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <unistd.h>
37 #include <sys/stat.h>
38 #include <inttypes.h>
39
40 #include "isohybrid.h"
41
42 char *prog = NULL;
43 extern int opterr, optind;
44
45 uint8_t mode = 0;
46 enum { VERBOSE = 1 };
47
48 /* user options */
49 uint16_t head = 64;             /* 1 <= head <= 256 */
50 uint8_t sector = 32;            /* 1 <= sector <= 63  */
51
52 uint8_t entry = 1;              /* partition number: 1 <= entry <= 4 */
53 uint8_t offset = 0;             /* partition offset: 0 <= offset <= 64 */
54 uint16_t type = 0x17;           /* partition type: 0 <= type <= 255 */
55 uint32_t id = 0;                /* MBR: 0 <= id <= 0xFFFFFFFF(4294967296) */
56
57 uint8_t hd0 = 0;                /* 0 <= hd0 <= 2 */
58 uint8_t partok = 0;             /* 0 <= partok <= 1 */
59
60 uint16_t ve[16];
61 uint32_t catoffset = 0;
62 uint32_t c = 0, cc = 0, cs = 0;
63
64 /* boot catalogue parameters */
65 uint32_t de_lba = 0;
66 uint16_t de_seg = 0, de_count = 0, de_mbz2 = 0;
67 uint8_t de_boot = 0, de_media = 0, de_sys = 0, de_mbz1 = 0;
68
69
70 void
71 usage(void)
72 {
73     printf("Usage: %s [OPTIONS] <boot.iso>\n", prog);
74 }
75
76
77 void
78 printh(void)
79 {
80 #define FMT "%-18s %s\n"
81
82     usage();
83
84     printf("\n");
85     printf("Options:\n");
86     printf(FMT, "   -h <X>", "Number of default geometry heads");
87     printf(FMT, "   -s <X>", "Number of default geometry sectors");
88     printf(FMT, "   -e --entry", "Specify partition entry number (1-4)");
89     printf(FMT, "   -o --offset", "Specify partition offset (default 0)");
90     printf(FMT, "   -t --type", "Specify partition type (default 0x17)");
91     printf(FMT, "   -i --id", "Specify MBR ID (default random)");
92
93     printf("\n");
94     printf(FMT, "   --forcehd0", "Assume we are loaded as disk ID 0");
95     printf(FMT, "   --ctrlhd0", "Assume disk ID 0 if the Ctrl key is pressed");
96     printf(FMT, "   --partok", "Allow booting from within a partition");
97
98     printf("\n");
99     printf(FMT, "   -? --help", "Display this help");
100     printf(FMT, "   -v --verbose", "Display verbose output");
101     printf(FMT, "   -V --version", "Display version information");
102
103     printf("\n");
104     printf("Report bugs to <pj.pandit@yahoo.co.in>\n");
105 }
106
107
108 int
109 check_option(int argc, char *argv[])
110 {
111     char *err = NULL;
112     int n = 0, ind = 0;
113
114     const char optstr[] = ":h:s:e:o:t:i:fcp?vV";
115     struct option lopt[] = \
116     {
117         { "entry", required_argument, NULL, 'e' },
118         { "offset", required_argument, NULL, 'o' },
119         { "type", required_argument, NULL, 't' },
120         { "id", required_argument, NULL, 'i' },
121
122         { "forcehd0", no_argument, NULL, 'f' },
123         { "ctrlhd0", no_argument, NULL, 'c' },
124         { "partok", no_argument, NULL, 'p'},
125
126         { "help", no_argument, NULL, '?' },
127         { "verbose", no_argument, NULL, 'v' },
128         { "version", no_argument, NULL, 'V' },
129
130         { 0, 0, 0, 0 }
131     };
132
133     opterr = mode = 0;
134     while ((n = getopt_long_only(argc, argv, optstr, lopt, &ind)) != -1)
135     {
136         switch (n)
137         {
138         case 'h':
139             head = strtoul(optarg, &err, 0);
140             if (head < 1 || head > 256)
141                 errx(1, "invalid head: `%s', 1 <= head <= 256", optarg);
142             break;
143
144         case 's':
145             sector = strtoul(optarg, &err, 0);
146             if (sector < 1 || sector > 63)
147                 errx(1, "invalid sector: `%s', 1 <= sector <= 63", optarg);
148             break;
149
150         case 'e':
151             entry = strtoul(optarg, &err, 0);
152             if (entry < 1 || entry > 4)
153                 errx(1, "invalid entry: `%s', 1 <= entry <= 4", optarg);
154             break;
155
156         case 'o':
157             offset = strtoul(optarg, &err, 0);
158             if (*err || offset > 64)
159                 errx(1, "invalid offset: `%s', 0 <= offset <= 64", optarg);
160             break;
161
162         case 't':
163             type = strtoul(optarg, &err, 0);
164             if (*err || type > 255)
165                 errx(1, "invalid type: `%s', 0 <= type <= 255", optarg);
166             break;
167
168         case 'i':
169             id = strtoul(optarg, &err, 0);
170             if (*err)
171                 errx(1, "invalid id: `%s'", optarg);
172             break;
173
174         case 'f':
175             hd0 = 1;
176             break;
177
178         case 'c':
179             hd0 = 2;
180             break;
181
182         case 'p':
183             partok = 1;
184             break;
185
186         case 'v':
187             mode |= VERBOSE;
188             break;
189
190         case 'V':
191             printf("%s version %s\n", prog, VERSION);
192             exit(0);
193
194         case ':':
195             errx(1, "option `-%c' takes an argument", optopt);
196
197         default:
198         case '?':
199             if (optopt)
200                 errx(1, "invalid option `-%c', see --help", optopt);
201
202             printh();
203             exit(0);
204         }
205     }
206
207     return optind;
208 }
209
210
211 uint16_t
212 lendian_short(const uint16_t s)
213 {
214     uint16_t r = 1;
215
216     if (*(uint8_t *)&r)
217         return s;
218
219     r = (s & 0x00FF) << 8 | (s & 0xFF00) >> 8;
220
221     return r;
222 }
223
224
225 uint32_t
226 lendian_int(const uint32_t s)
227 {
228     uint32_t r = 1;
229
230     if (*(uint8_t *)&r)
231         return s;
232
233     r = (s & 0x000000FF) << 24 | (s & 0xFF000000) >> 24
234         | (s & 0x0000FF00) << 8 | (s & 0x00FF0000) >> 8;
235
236     return r;
237 }
238
239
240 int
241 check_banner(const uint8_t *buf)
242 {
243     static const char banner[] = "\0CD001\1EL TORITO SPECIFICATION\0\0\0\0" \
244         "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" \
245         "\0\0\0\0\0";
246
247     if (!buf || memcmp(buf, banner, sizeof(banner) - 1))
248         return 1;
249
250     buf += sizeof(banner) - 1;
251     memcpy(&catoffset, buf, sizeof(catoffset));
252
253     catoffset = lendian_int(catoffset);
254
255     return 0;
256 }
257
258
259 int
260 check_catalogue(const uint8_t *buf)
261 {
262     int i = 0;
263
264     for (i = 0, cs = 0; i < 16; i++)
265     {
266         ve[i] = 0;
267         memcpy(&ve[i], buf, sizeof(ve[i]));
268
269         ve[i] = lendian_short(ve[i]);
270
271         buf += 2;
272         cs += ve[i];
273
274         if (mode & VERBOSE)
275             printf("ve[%d]: %d, cs: %d\n", i, ve[i], cs);
276     }
277     if ((ve[0] != 0x0001) || (ve[15] != 0xAA55) || (cs & 0xFFFF))
278         return 1;
279
280     return 0;
281 }
282
283
284 int
285 read_catalogue(const uint8_t *buf)
286 {
287     memcpy(&de_boot, buf++, 1);
288     memcpy(&de_media, buf++, 1);
289
290     memcpy(&de_seg, buf, 2);
291     de_seg = lendian_short(de_seg);
292     buf += 2;
293
294     memcpy(&de_sys, buf++, 1);
295     memcpy(&de_mbz1, buf++, 1);
296
297     memcpy(&de_count, buf, 2);
298     de_count = lendian_short(de_count);
299     buf += 2;
300
301     memcpy(&de_lba, buf, 4);
302     de_lba = lendian_int(de_lba);
303     buf += 4;
304
305     memcpy(&de_mbz2, buf, 2);
306     de_mbz2 = lendian_short(de_mbz2);
307     buf += 2;
308
309     if (de_boot != 0x88 || de_media != 0
310         || (de_seg != 0 && de_seg != 0x7C0) || de_count != 4)
311         return 1;
312
313     return 0;
314 }
315
316
317 void
318 display_catalogue(void)
319 {
320     printf("de_boot: %hhu\n", de_boot);
321     printf("de_media: %hhu\n", de_media);
322     printf("de_seg: %hu\n", de_seg);
323     printf("de_sys: %hhu\n", de_sys);
324     printf("de_mbz1: %hhu\n", de_mbz1);
325     printf("de_count: %hu\n", de_count);
326     printf("de_lba: %u\n", de_lba);
327     printf("de_mbz2: %hu\n", de_mbz2);
328 }
329
330
331 int
332 initialise_mbr(uint8_t *mbr)
333 {
334     int i = 0;
335     uint32_t psize = 0, tmp = 0;
336     uint8_t ptype = 0, *rbm = mbr;
337     uint8_t bhead = 0, bsect = 0, bcyle = 0;
338     uint8_t ehead = 0, esect = 0, ecyle = 0;
339
340     extern unsigned char isohdpfx[][MBRSIZE];
341
342     memcpy(mbr, &isohdpfx[hd0 + 3 * partok], MBRSIZE);
343     mbr += MBRSIZE;                                 /* offset 432 */
344
345     tmp = lendian_int(de_lba * 4);
346     memcpy(mbr, &tmp, sizeof(tmp));
347     mbr += sizeof(tmp);                             /* offset 436 */
348
349     tmp = 0;
350     memcpy(mbr, &tmp, sizeof(tmp));
351     mbr += sizeof(tmp);                             /* offset 440 */
352
353     tmp = lendian_int(id);
354     memcpy(mbr, &tmp, sizeof(tmp));
355     mbr += sizeof(tmp);                             /* offset 444 */
356
357     mbr[0] = '\0';
358     mbr[1] = '\0';
359     mbr += 2;                                       /* offset 446 */
360
361     ptype = type;
362     psize = c * head * sector - offset;
363
364     bhead = (offset / sector) % head;
365     bsect = (offset % sector) + 1;
366     bcyle = offset / (head * sector);
367
368     bsect += (bcyle & 0x300) >> 2;
369     bcyle  &= 0xFF;
370
371     ehead = head - 1;
372     esect = sector + (((cc - 1) & 0x300) >> 2);
373     ecyle = (cc - 1) & 0xFF;
374
375     for (i = 1; i <= 4; i++)
376     {
377         memset(mbr, 0, 16);
378         if (i == entry)
379         {
380             mbr[0] = 0x80;
381             mbr[1] = bhead;
382             mbr[2] = bsect;
383             mbr[3] = bcyle;
384             mbr[4] = ptype;
385             mbr[5] = ehead;
386             mbr[6] = esect;
387             mbr[7] = ecyle;
388
389             tmp = lendian_int(offset);
390             memcpy(&mbr[8], &tmp, sizeof(tmp));
391
392             tmp = lendian_int(psize);
393             memcpy(&mbr[12], &tmp, sizeof(tmp));
394         }
395         mbr += 16;
396     }
397     mbr[0] = 0x55;
398     mbr[1] = 0xAA;
399     mbr += 2;
400
401     return mbr - rbm;
402 }
403
404
405 void
406 display_mbr(const uint8_t *mbr, size_t len)
407 {
408     unsigned char c = 0;
409     unsigned int i = 0, j = 0;
410
411     printf("sizeof(MBR): %zu bytes\n", len);
412     for (i = 0; i < len; i++)
413     {
414         if (!(i % 16))
415             printf("%04d ", i);
416
417         if (!(i % 8))
418             printf(" ");
419
420         c = mbr[i];
421         printf("%02x ", c);
422
423         if (!((i + 1) % 16))
424         {
425             printf(" |");
426             for (; j <= i; j++)
427                 printf("%c", isprint(mbr[j]) ? mbr[j] : '.');
428             printf("|\n");
429         }
430     }
431 }
432
433
434 int
435 main(int argc, char *argv[])
436 {
437     int i = 0;
438     FILE *fp = NULL;
439     struct stat isostat;
440     uint8_t *buf = NULL, *bufz = NULL;
441     int cylsize = 0, frac = 0, padding = 0;
442
443     prog = strcpy(alloca(strlen(argv[0]) + 1), argv[0]);
444     i = check_option(argc, argv);
445     argc -= i;
446     argv += i;
447
448     if (!argc)
449     {
450         usage();
451         return 1;
452     }
453     srand(time(NULL) << (getppid() << getpid()));
454
455     if (!(fp = fopen(argv[0], "r+")))
456         err(1, "could not open file `%s'", argv[0]);
457     if (fseek(fp, 17 * 2048, SEEK_SET))
458         err(1, "%s: seek error - 1", argv[0]);
459
460     bufz = buf = calloc(BUFSIZE, sizeof(char));
461     if (fread(buf, sizeof(char), BUFSIZE, fp) != BUFSIZE)
462         err(1, "%s", argv[0]);
463
464     if (check_banner(buf))
465         errx(1, "%s: could not find boot record", argv[0]);
466
467     if (mode & VERBOSE)
468         printf("catalogue offset: %d\n", catoffset);
469
470     if (fseek(fp, catoffset * 2048, SEEK_SET))
471         err(1, "%s: seek error - 2", argv[0]);
472
473     buf = bufz;
474     memset(buf, 0, BUFSIZE);
475     if (fread(buf, sizeof(char), BUFSIZE, fp) != BUFSIZE)
476         err(1, "%s", argv[0]);
477
478     if (check_catalogue(buf))
479         errx(1, "%s: invalid boot catalogue", argv[0]);
480
481     buf += sizeof(ve);
482     if (read_catalogue(buf))
483         errx(1, "%s: unexpected boot catalogue parameters", argv[0]);
484
485     if (mode & VERBOSE)
486         display_catalogue();
487
488     if (fseek(fp, (de_lba * 2048 + 0x40), SEEK_SET))
489         err(1, "%s: seek error - 3", argv[0]);
490
491     buf = bufz;
492     memset(buf, 0, BUFSIZE);
493     if (fread(buf, sizeof(char), 4, fp) != 4)
494         err(1, "%s", argv[0]);
495
496     if (memcmp(buf, "\xFB\xC0\x78\x70", 4))
497         errx(1, "%s: boot loader does not have an isolinux.bin hybrid " \
498                  "signature. Note that isolinux-debug.bin does not support " \
499                  "hybrid booting", argv[0]);
500
501     if (stat(argv[0], &isostat))
502         err(1, "%s", argv[0]);
503
504     cylsize = head * sector * 512;
505     frac = isostat.st_size % cylsize;
506     padding = (frac > 0) ? cylsize - frac : 0;
507
508     if (mode & VERBOSE)
509         printf("imgsize: %zu, padding: %d\n", (size_t)isostat.st_size, padding);
510
511     cc = c = (isostat.st_size + padding) / cylsize;
512     if (c > 1024)
513     {
514         warnx("Warning: more than 1024 cylinders: %d", c);
515         warnx("Not all BIOSes will be able to boot this device");
516         cc = 1024;
517     }
518
519     if (!id)
520     {
521         if (fseek(fp, 440, SEEK_SET))
522             err(1, "%s: seek error - 4", argv[0]);
523
524         if (fread(&id, 1, 4, fp) != 4)
525             err(1, "%s: read error", argv[0]);
526
527         id = lendian_int(id);
528         if (!id)
529         {
530             if (mode & VERBOSE)
531                 printf("random ");
532             id = rand();
533         }
534     }
535     if (mode & VERBOSE)
536         printf("id: %u\n", id);
537
538     buf = bufz;
539     memset(buf, 0, BUFSIZE);
540     i = initialise_mbr(buf);
541
542     if (mode & VERBOSE)
543         display_mbr(buf, i);
544
545     if (fseek(fp, 0, SEEK_SET))
546         err(1, "%s: seek error - 5", argv[0]);
547
548     if (fwrite(buf, sizeof(char), i, fp) != (size_t)i)
549         err(1, "%s: write error - 1", argv[0]);
550
551     if (padding)
552     {
553         if (fsync(fileno(fp)))
554             err(1, "%s: could not synchronise", argv[0]);
555
556         if (ftruncate(fileno(fp), isostat.st_size + padding))
557             err(1, "%s: could not add padding bytes", argv[0]);
558     }
559
560     free(buf);
561     fclose(fp);
562
563     return 0;
564 }