summaryrefslogtreecommitdiff
path: root/com32/chain/mangle.c
blob: 8358106e197cba7bc9d0460c46d5de7e7ad7df10 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
#include <com32.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <dprintf.h>
#include <syslinux/config.h>
#include "common.h"
#include "chain.h"
#include "options.h"
#include "utility.h"
#include "partiter.h"
#include "mangle.h"

static const char cmldr_signature[8] = "cmdcons";

/* Create boot info table: needed when you want to chainload
 * another version of ISOLINUX (or another bootlaoder that needs
 * the -boot-info-table switch of mkisofs)
 * (will only work when run from ISOLINUX)
 */
int manglef_isolinux(struct data_area *data)
{
    const union syslinux_derivative_info *sdi;
    unsigned char *isolinux_bin;
    uint32_t *checksum, *chkhead, *chktail;
    uint32_t file_lba = 0;

    if (!(opt.file && opt.isolinux))
	return 0;

    sdi = syslinux_derivative_info();

    if (sdi->c.filesystem != SYSLINUX_FS_ISOLINUX) {
	error ("The isolinux= option is only valid when run from ISOLINUX.\n");
	goto bail;
    }

    /* Boot info table info (integers in little endian format)

       Offset Name         Size      Meaning
       8      bi_pvd       4 bytes   LBA of primary volume descriptor
       12     bi_file      4 bytes   LBA of boot file
       16     bi_length    4 bytes   Boot file length in bytes
       20     bi_csum      4 bytes   32-bit checksum
       24     bi_reserved  40 bytes  Reserved

       The 32-bit checksum is the sum of all the 32-bit words in the
       boot file starting at byte offset 64. All linear block
       addresses (LBAs) are given in CD sectors (normally 2048 bytes).

       LBA of primary volume descriptor should already be set to 16.
       */

    isolinux_bin = (unsigned char *)data->data;

    /* Get LBA address of bootfile */
    file_lba = get_file_lba(opt.file);

    if (file_lba == 0) {
	error("Failed to find LBA offset of the boot file\n");
	goto bail;
    }
    /* Set it */
    *((uint32_t *) & isolinux_bin[12]) = file_lba;

    /* Set boot file length */
    *((uint32_t *) & isolinux_bin[16]) = data->size;

    /* Calculate checksum */
    checksum = (uint32_t *) & isolinux_bin[20];
    chkhead = (uint32_t *) & isolinux_bin[64];
    chktail = (uint32_t *) & isolinux_bin[data->size & ~3u];
    *checksum = 0;
    while (chkhead < chktail)
	*checksum += *chkhead++;

    /*
     * Deal with possible fractional dword at the end;
     * this *should* never happen...
     */
    if (data->size & 3) {
	uint32_t xword = 0;
	memcpy(&xword, chkhead, data->size & 3);
	*checksum += xword;
    }
    return 0;
bail:
    return -1;
}

/*
 * Legacy grub's stage2 chainloading
 */
int manglef_grub(const struct part_iter *iter, struct data_area *data)
{
    /* Layout of stage2 file (from byte 0x0 to 0x270) */
    struct grub_stage2_patch_area {
	/* 0x0 to 0x205 */
	char unknown[0x206];
	/* 0x206: compatibility version number major */
	uint8_t compat_version_major;
	/* 0x207: compatibility version number minor */
	uint8_t compat_version_minor;

	/* 0x208: install_partition variable */
	struct {
	    /* 0x208: sub-partition in sub-partition part2 */
	    uint8_t part3;
	    /* 0x209: sub-partition in top-level partition */
	    uint8_t part2;
	    /* 0x20a: top-level partiton number */
	    uint8_t part1;
	    /* 0x20b: BIOS drive number (must be 0) */
	    uint8_t drive;
	} __attribute__ ((packed)) install_partition;

	/* 0x20c: deprecated (historical reason only) */
	uint32_t saved_entryno;
	/* 0x210: stage2_ID: will always be STAGE2_ID_STAGE2 = 0 in stage2 */
	uint8_t stage2_id;
	/* 0x211: force LBA */
	uint8_t force_lba;
	/* 0x212: version string (will probably be 0.97) */
	char version_string[5];
	/* 0x217: config filename */
	char config_file[89];
	/* 0x270: start of code (after jump from 0x200) */
	char codestart[1];
    } __attribute__ ((packed)) *stage2;

    if (!(opt.file && opt.grub))
	return 0;

    if (data->size < sizeof(struct grub_stage2_patch_area)) {
	error("The file specified by grub=<loader> is too small to be stage2 of GRUB Legacy.\n");
	goto bail;
    }
    stage2 = data->data;

    /*
     * Check the compatibility version number to see if we loaded a real
     * stage2 file or a stage2 file that we support.
     */
    if (stage2->compat_version_major != 3
	    || stage2->compat_version_minor != 2) {
	error("The file specified by grub=<loader> is not a supported stage2 GRUB Legacy binary.\n");
	goto bail;
    }

    /*
     * GRUB Legacy wants the partition number in the install_partition
     * variable, located at offset 0x208 of stage2.
     * When GRUB Legacy is loaded, it is located at memory address 0x8208.
     *
     * It looks very similar to the "boot information format" of the
     * Multiboot specification:
     *   http://www.gnu.org/software/grub/manual/multiboot/multiboot.html#Boot-information-format
     *
     *   0x208 = part3: sub-partition in sub-partition part2
     *   0x209 = part2: sub-partition in top-level partition
     *   0x20a = part1: top-level partition number
     *   0x20b = drive: BIOS drive number (must be 0)
     *
     * GRUB Legacy doesn't store the BIOS drive number at 0x20b, but at
     * another location.
     *
     * Partition numbers always start from zero.
     * Unused partition bytes must be set to 0xFF.
     *
     * We only care about top-level partition, so we only need to change
     * "part1" to the appropriate value:
     *   -1:   whole drive (default) (-1 = 0xFF)
     *   0-3:  primary partitions
     *   4-*:  logical partitions
     */
    stage2->install_partition.part1 = (uint8_t)(iter->index - 1);

    /*
     * Grub Legacy reserves 89 bytes (from 0x8217 to 0x826f) for the
     * config filename. The filename passed via grubcfg= will overwrite
     * the default config filename "/boot/grub/menu.lst".
     */
    if (opt.grubcfg) {
	if (strlen(opt.grubcfg) > sizeof(stage2->config_file) - 1) {
	    error ("The config filename length can't exceed 88 characters.\n");
	    goto bail;
	}

	strcpy((char *)stage2->config_file, opt.grubcfg);
    }

    return 0;
bail:
    return -1;
}
#if 0
/*
 * Dell's DRMK chainloading.
 */
int manglef_drmk(struct data_area *data)
{
    /*
     * DRMK entry is different than MS-DOS/PC-DOS
     * A new size, aligned to 16 bytes to ease use of ds:[bp+28].
     * We only really need 4 new, usable bytes at the end.
     */

    if (!(opt.file && opt.drmk))
	return 0;

    uint32_t tsize = (data->size + 19) & 0xfffffff0;
    const union syslinux_derivative_info *sdi;
    uint64_t fs_lba;

    sdi = syslinux_derivative_info();
    /* We should lookup the Syslinux partition offset and use it */
    fs_lba = *sdi->disk.partoffset;

    /*
     * fs_lba should be verified against the disk as some DRMK
     * variants will check and fail if it does not match
     */
    dprintf("  fs_lba offset is %d\n", fs_lba);
    /* DRMK only uses a DWORD */
    if (fs_lba > 0xffffffff) {
	error("LBA very large; Only using lower 32 bits; DRMK will probably fail\n");
    }
    opt.regs.ss = opt.regs.fs = opt.regs.gs = 0;	/* Used before initialized */
    if (!realloc(data->data, tsize)) {
	error("Failed to realloc for DRMK.\n");
	goto bail;
    }
    data->size = tsize;
    /* ds:bp is assumed by DRMK to be the boot sector */
    /* offset 28 is the FAT HiddenSectors value */
    opt.regs.ds = (uint16_t)((tsize >> 4) + (opt.fseg - 2));
    /* "Patch" into tail of the new space */
    *(uint32_t *)((char*)data->data + tsize - 4) = (uint32_t)fs_lba;

    return 0;
bail:
    return -1;
}
#endif
/* Adjust BPB common function */
static int mangle_bpb(const struct part_iter *iter, struct data_area *data, const char *tag)
{
    unsigned int off;
    int type = bpb_detect(data->data, tag);

    /* BPB: hidden sectors 32bit*/
    if (type >= bpbV34) {
	if (iter->start_lba < ~0u)
	    *(uint32_t *) ((char *)data->data + 0x1c) = (uint32_t)iter->start_lba;
	else
	    /* won't really help much, but ... */
	    *(uint32_t *) ((char *)data->data + 0x1c) = ~0u;
    }
    /* BPB: hidden sectors 16bit*/
    if (bpbV30 <= type && type <= bpbV32) {
	if (iter->start_lba < 0xFFFF)
	    *(uint16_t *) ((char *)data->data + 0x1c) = (uint16_t)iter->start_lba;
	else
	    /* won't really help much, but ... */
	    *(uint16_t *) ((char *)data->data + 0x1c) = (uint16_t)~0u;
    }
    /* BPB: legacy geometry */
    if (type >= bpbV30) {
	if (iter->di.cbios)
	    *(uint32_t *)((char *)data->data + 0x18) = (uint32_t)((iter->di.head << 16) | iter->di.spt);
	else {
	    if (iter->di.disk & 0x80)
		*(uint32_t *)((char *)data->data + 0x18) = 0x00FF003F;
	    else
		*(uint32_t *)((char *)data->data + 0x18) = 0x00020012;
	}
    }
    /* BPB: drive */
    if (drvoff_detect(type, &off)) {
	*(uint8_t *)((char *)data->data + off) = (uint8_t)
	    (opt.swap ? iter->di.disk & 0x80 : iter->di.disk);
    }

    return 0;
}

/*
 * Adjust BPB of a BPB-compatible file
 */
int manglef_bpb(const struct part_iter *iter, struct data_area *data)
{
    if (!(opt.file && opt.filebpb))
	return 0;

    return mangle_bpb(iter, data, "file");
}

/*
 * Adjust BPB of a sector
 */
int mangles_bpb(const struct part_iter *iter, struct data_area *data)
{
    if (!(opt.sect && opt.setbpb))
	return 0;

    return mangle_bpb(iter, data, "sect");
}

/*
 * This function performs full BPB patching, analogously to syslinux's
 * native BSS.
 */
int manglesf_bss(struct data_area *sec, struct data_area *fil)
{
    int type1, type2;
    unsigned int cnt = 0;

    if (!(opt.sect && opt.file && opt.bss))
	return 0;

    type1 = bpb_detect(fil->data, "bss/file");
    type2 = bpb_detect(sec->data, "bss/sect");

    if (!type1 || !type2) {
	error("Couldn't determine the BPB type for option 'bss'.\n");
	goto bail;
    }
    if (type1 != type2) {
	error("Option 'bss' can't be used,\n"
		"when a sector and a file have incompatible BPBs.\n");
	goto bail;
    }

    /* Copy common 2.0 data */
    memcpy((char *)fil->data + 0x0B, (char *)sec->data + 0x0B, 0x0D);

    /* Copy 3.0+ data */
    if (type1 <= bpbV30) {
	cnt = 0x06;
    } else if (type1 <= bpbV32) {
	cnt = 0x08;
    } else if (type1 <= bpbV34) {
	cnt = 0x0C;
    } else if (type1 <= bpbV40) {
	cnt = 0x2E;
    } else if (type1 <= bpbVNT) {
	cnt = 0x3C;
    } else if (type1 <= bpbV70) {
	cnt = 0x42;
    }
    memcpy((char *)fil->data + 0x18, (char *)sec->data + 0x18, cnt);

    return 0;
bail:
    return -1;
}

/*
 * Save sector.
 */
int mangles_save(const struct part_iter *iter, const struct data_area *data, void *org)
{
    if (!(opt.sect && opt.save))
	return 0;

    if (memcmp(org, data->data, data->size)) {
	if (disk_write_sectors(&iter->di, iter->start_lba, data->data, 1)) {
	    error("Cannot write the updated sector.\n");
	    goto bail;
	}
	/* function can be called again */
	memcpy(org, data->data, data->size);
    }

    return 0;
bail:
    return -1;
}

/*
 * To boot the Recovery Console of Windows NT/2K/XP we need to write
 * the string "cmdcons\0" to memory location 0000:7C03.
 * Memory location 0000:7C00 contains the bootsector of the partition.
 */
int mangles_cmldr(struct data_area *data)
{
    if (!(opt.sect && opt.cmldr))
	return 0;

    memcpy((char *)data->data + 3, cmldr_signature, sizeof(cmldr_signature));
    return 0;
}

/* Set common registers */
int mangler_init(const struct part_iter *iter)
{
    /* Set initial registry values */
    if (opt.file) {
	opt.regs.cs = opt.regs.ds = opt.regs.ss = (uint16_t)opt.fseg;
	opt.regs.ip = (uint16_t)opt.fip;
    } else {
	opt.regs.cs = opt.regs.ds = opt.regs.ss = (uint16_t)opt.sseg;
	opt.regs.ip = (uint16_t)opt.sip;
    }

    if (opt.regs.ip == 0x7C00 && !opt.regs.cs)
	opt.regs.esp.l = 0x7C00;

    /* DOS kernels want the drive number in BL instead of DL. Indulge them. */
    opt.regs.ebx.b[0] = opt.regs.edx.b[0] = (uint8_t)iter->di.disk;

    return 0;
}

/* ds:si & ds:bp */
int mangler_handover(const struct part_iter *iter, const struct data_area *data)
{
    if (opt.file && opt.maps && !opt.hptr) {
	opt.regs.esi.l = opt.regs.ebp.l = opt.soff;
	opt.regs.ds = (uint16_t)opt.sseg;
	opt.regs.eax.l = 0;
    } else if (opt.hand) {
	/* base is really 0x7be */
	opt.regs.esi.l = opt.regs.ebp.l = data->base;
	opt.regs.ds = 0;
	if (iter->index && iter->type == typegpt)   /* must be iterated and GPT */
	    opt.regs.eax.l = 0x54504721;	/* '!GPT' */
	else
	    opt.regs.eax.l = 0;
    }

    return 0;
}

/*
 * GRLDR of GRUB4DOS wants the partition number in DH:
 * -1:   whole drive (default)
 * 0-3:  primary partitions
 * 4-*:  logical partitions
 */
int mangler_grldr(const struct part_iter *iter)
{
    if (opt.grldr)
	opt.regs.edx.b[1] = (uint8_t)(iter->index - 1);

    return 0;
}

/*
 * try to copy values from temporary iterator, if positions match
 */
static void push_embr(struct part_iter *diter, struct part_iter *siter)
{
    if (diter->sub.dos.cebr_lba == siter->sub.dos.cebr_lba &&
	    diter->di.disk == siter->di.disk) {
	memcpy(diter->data, siter->data, sizeof(struct disk_dos_mbr));
    }
}

static int mpe_sethide(struct part_iter *iter, struct part_iter *miter)
{
    struct disk_dos_part_entry *dp;
    static const uint16_t mask =
	(1 << 0x01) | (1 << 0x04) | (1 << 0x06) |
	(1 << 0x07) | (1 << 0x0b) | (1 << 0x0c) | (1 << 0x0e);
    uint8_t t;

    dp = (struct disk_dos_part_entry *)iter->record;
    t = dp->ostype;

    if ((t <= 0x1f) && ((mask >> (t & ~0x10u)) & 1)) {
	/* It's a hideable partition type */
	if (miter->index == iter->index || opt.hide & 4)
	    t &= (uint8_t)(~0x10u);	/* unhide */
	else
	    t |= 0x10u;	/* hide */
    }
    if (dp->ostype != t) {
	dp->ostype = t;
	return -1;
    }
    return 0;
}

/*
 * miter - iterator we match against
 * hide bits meaning:
 * ..| - enable (1) / disable (0)
 * .|. - all (1) / pri (0)
 * |.. - unhide (1) / hide (0)
 */
int manglepe_hide(struct part_iter *miter)
{
    int wb = 0, werr = 0;
    struct part_iter *iter = NULL;
    struct disk_dos_part_entry *dp;
    int ridx;

    if (!opt.hide)
	return 0;

    if (miter->type != typedos) {
	error("Options '*hide*' is meaningful only for legacy partition scheme.\n");
	return -1;
    }

    if (miter->index < 1)
	error("WARNING: It's impossible to unhide a disk.\n");

    if (miter->index > 4 && !(opt.hide & 2))
	error("WARNING: your partition is beyond mbr, so it can't be unhidden without '*hideall'.\n");

    if (!(iter = pi_begin(&miter->di, 1)))  /* turn stepall on */
	return -1;

    while (!pi_next(&iter) && !werr) {
	ridx = iter->rawindex;
	if (!(opt.hide & 2) && ridx > 4)
	    break;  /* skip when we're constrained to pri only */

	dp = (struct disk_dos_part_entry *)iter->record;
	if (dp->ostype)
	    wb |= mpe_sethide(iter, miter);

	if (ridx >= 4 && wb && !werr) {
	    push_embr(miter, iter);
	    werr |= disk_write_sectors(&iter->di, iter->sub.dos.cebr_lba, iter->data, 1);
	    wb = 0;
	}
    }

    if (iter->status > PI_DONE)
	goto bail;

    /* last write */
    if (wb && !werr) {
	push_embr(miter, iter);
	werr |= disk_write_sectors(&iter->di, iter->sub.dos.cebr_lba, iter->data, 1);
    }
    if (werr)
	error("WARNING: failed to write E/MBR during '*hide*'\n");

bail:
    pi_del(&iter);
    return 0;
}

static int mpe_setchs(const struct disk_info *di,
		     struct disk_dos_part_entry *dp,
		     uint32_t lba1)
{
    uint32_t ochs1, ochs2;

    ochs1 = *(uint32_t *)dp->start;
    ochs2 = *(uint32_t *)dp->end;

    lba2chs(&dp->start, di, lba1, l2c_cadd);
    lba2chs(&dp->end, di, lba1 + dp->length - 1, l2c_cadd);

    return
	*(uint32_t *)dp->start != ochs1 ||
	*(uint32_t *)dp->end != ochs2;
}

/*
 * miter - iterator we match against
 */
int manglepe_fixchs(struct part_iter *miter)
{
    int wb = 0, werr = 0;
    struct part_iter *iter = NULL;
    struct disk_dos_part_entry *dp;
    int ridx;

    if (!opt.fixchs)
	return 0;

    if (miter->type != typedos) {
	error("Options 'fixchs' is meaningful only for legacy partition scheme.\n");
	return -1;
    }

    if (!(iter = pi_begin(&miter->di, 1)))  /* turn stepall on */
	return -1;

    while (!pi_next(&iter) && !werr) {
	ridx = iter->rawindex;
	dp = (struct disk_dos_part_entry *)iter->record;

	wb |= mpe_setchs(&iter->di, dp, (uint32_t)iter->start_lba);
	if (ridx > 4)
		wb |= mpe_setchs(&iter->di, dp + 1, iter->sub.dos.nebr_lba);

	if (ridx >= 4 && wb && !werr) {
	    push_embr(miter, iter);
	    werr |= disk_write_sectors(&iter->di, iter->sub.dos.cebr_lba, iter->data, 1);
	    wb = 0;
	}
    }

    if (iter->status > PI_DONE)
	goto bail;

    /* last write */
    if (wb && !werr) {
	push_embr(miter, iter);
	werr |= disk_write_sectors(&iter->di, iter->sub.dos.cebr_lba, iter->data, 1);
    }
    if (werr)
	error("WARNING: failed to write E/MBR during 'fixchs'\n");

bail:
    pi_del(&iter);
    return 0;
}

/* vim: set ts=8 sts=4 sw=4 noet: */