romhack.cpp 25.8 KB
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 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <sys/stat.h>
#include <getopt.h>
#include <netinet/in.h>
#include <list>

using namespace std;

#include "romhack.h"

#define ERRATA_MAX_SIZE 16384
#define ERRATA_START_ADDR 0x807bc000
u8 *errata_start, *errata_end;

struct {
    char version;
    char *sgi_sigs;
    char *pc_sigs;
} libraries[] = {
    'D', "sigs/os20d_sgi_rom", NULL,
    'E', "sigs/os20e_sgi_rom", NULL,
    'F', "sigs/os20f_sgi_rom", NULL,
    'G', "sigs/os20g_sgi_rom", NULL,
    'H', "sigs/os20h_sgi_rom", "sigs/os20h_pc_rom",
    'I', "sigs/os20i_sgi_rom", "sigs/os20i_pc_rom",
    'J', "sigs/os20j_sgi_rom", "sigs/os20j_pc_rom",
    'K', "sigs/os20k_sgi_rom", "sigs/os20k_pc_rom",
    'L', "sigs/os20l_sgi_rom", "sigs/os20l_pc_rom",
};

sigmap_t sigs;
symmap_t syms;
sigmap_t patch_sigs;
symmap_t patch_syms;

list<override_t> override, override_mem;
list<dynamic_t> dynamics;

char *infile = NULL;
char *binary = NULL;
char *outfile = NULL;
char *patch_funcs = NULL;
char *patch_with = NULL;
char *scan_with = NULL;
int do_vitbl = 0;
int do_crc = 0;
int do_pal = 0;
int do_osinit = 0;
int do_disk = 0;
int do_ramrom = 0;
int do_debugger = 0;
char *jdebug_file = NULL;
int use_sgi = 1;
char force_lib = 0;
int force_hi_mem = 0;
int dynamic = 0;
u32 dynamic_disk = 0;
u32 bootaddr = 0;

char *strstrip(char *s)
{
    int x;

    x = strlen(s) - 1;
    while (x>=0 && isspace(s[x])) s[x--] = '\0';

    while (*s && isspace(*s)) s++;

    return s;
}

void byteswap(u8* rom, u32 rom_len)
{
    u32 i;
    u32 *p = (u32 *)rom;

    for (i = 0; i < rom_len; i += 4) {
       *p++ = htonl(*p); 
    }
}

int load_file(char *filename, u8 **buf, u32 *size)
{
    FILE *in;
    struct stat sb;

    if ((in = fopen(filename, "r")) == NULL) {
        perror("fopen");
        return -1;
    }

    if (fstat(fileno(in), &sb) < 0) {
        perror("fstat");
        return -1;
    }

    if ((*buf = (u8*)malloc(sb.st_size)) == NULL) {
        fprintf(stderr, "Unable to malloc %d bytes\n", sb.st_size);
        return -1;
    }

    fprintf(stderr, "Loading '%s'\n", filename);
    if (fread(*buf, sb.st_size, 1, in) != 1) {
        fprintf(stderr, "Unable to read %d bytes\n", sb.st_size);
        return -1;
    }
    fclose(in);
    *size = sb.st_size;
    fprintf(stderr, "  %d bytes loaded.\n", *size);
    return 0;
}

void patch_rom(u8 *rom, char *filename)
{
    int i;
    FILE *fp;
    char line[256], *p;
    u32 poffset;
    u32 jump_addr;

    if ((fp = fopen(filename, "r")) == NULL) {
        perror("fopen");
        return;
    }
 
    while (fgets(line, sizeof(line), fp)) {
        sig_t *rs, *ps;
        char rname[256];
        u32 rsize, *rp, *pp;
        u32 hi16 = 0, lo16 = 0, rel26;
        u8 *r;
        list<rel_t *>::iterator rel;
        sym_t dummy_sym;

        if (line[0] == '#') continue;
        p = strstrip(line);
        sigmap_t::iterator si = sigs.find(p);
        if (si == sigs.end()) {
            fprintf(stderr, "Unable to locate '%s' in rom sigs\n\n", p);
            continue;
        }
        rs = si->second;

        if (rs->offsets.empty()) {
            fprintf(stderr, "Unable to patch. '%s' has not been found in the ROM\n\n", rs->symbol);
            continue;
        }

        sigmap_t::iterator pi = patch_sigs.find(p);
        if (pi == patch_sigs.end()) {
            fprintf(stderr, "Unable to locate '%s' in patch sigs\n\n", p);
            continue;
        }
        ps = pi->second;

        for (list<u32>::iterator ii = rs->offsets.begin(); ii != rs->offsets.end(); ++ii) {
            u32 offset = *ii;
            if (ps->num_ops > rs->num_ops ||
                offset & 0x80000000 ||
                force_hi_mem ||
                dynamic) {

                offset &= ~0x80000000;
                fprintf(stderr, "Unable to patch '%s' in place. New routine is larger than original (%d > %d)\n", rs->symbol, ps->num_ops, rs->num_ops);
                poffset = errata_end - rom;
                jump_addr = ERRATA_START_ADDR+(errata_end-errata_start);
                fprintf(stderr, "Insert jump to 0x%08x\n", jump_addr);

                errata_end += ps->num_ops<<2;
            } else {
                poffset = offset;
                jump_addr = 0;
            }
            fprintf(stderr, "Patching '%s' [%d] with [%d] @ 0x%08x\n", rs->symbol, rs->num_ops, ps->num_ops, offset);
            snprintf(rname, sizeof(rname), "routines/%s", p);
            load_file(rname, &r, &rsize);
            byteswap(r, rsize);
            rp =  (u32 *)(rom + offset);
            rel = rs->relocs.begin();
            for (i = 0; i < rs->num_ops; ++i) {
                u32 op = *rp++;
                if (rel != rs->relocs.end() && i == (*rel)->index) {
                    if ((*rel)->sym == NULL && (*rel)->text) {
                        switch ((*rel)->type) {
                        case R_MIPS_HI16:
                            hi16 = (op & 0xffff) - (*rel)->hi_offset;
                            fprintf(stderr, "In '%s': setting hi16=0x%04x\n", rs->symbol, hi16);
                            break;
                        case R_MIPS_LO16:
                            lo16 = (op & 0xffff) - (*rel)->lo_offset;
                            fprintf(stderr, "In '%s': setting lo16=0x%04x\n", rs->symbol, lo16);
                            break;
                        case R_MIPS_26:
                            rel26 = (op & 0x03ffffff) - (*rel)->hi_offset;
                            hi16 = (rel26 >> 14) | 0x8000;
                            lo16 = (rel26 << 2) & 0xffff;
                            fprintf(stderr, "In '%s': setting hi16=0x%04x, lo16=0x%04x (rel26=0x%08x)\n", rs->symbol, hi16, lo16, rel26);
                            break;
                        }
                    }
                    ++rel;
                }
            }
            if (jump_addr) {
                if (dynamic) {
                    dynamic_t d;
                    d.src = 0x80000000 | offset;
                    d.dst = jump_addr;
                    dynamics.push_back(d);
                } else {
                    /* la $t2, jump_addr */
                    /* jr $t2           */
                    /* nop              */
                    rp =  (u32 *)(rom + offset);
                    *rp++ = 0x3c0a0000 | ((jump_addr >> 16) & 0xffff);
                    *rp++ = 0x354a0000 | ((jump_addr >>  0) & 0xffff);
                    *rp++ = 0x01400008;
                    *rp++ = 0;
                }
            }
            rp =  (u32 *)(rom + poffset);
            pp = (u32 *) r;
            rel = ps->relocs.begin();
            for (i = 0; i < ps->num_ops; ++i) {
                u32 op = *pp++;
                if (rel != ps->relocs.end() && i == (*rel)->index) {
                    sym_t *s;
                    if ((*rel)->sym) {
                        symmap_t::iterator si = syms.find((*rel)->sym->symbol);
                        s = (si != syms.end()) ? si->second : NULL;
                    } else {
                        if (!(*rel)->text) {
                            fprintf(stderr, "ERROR: Don't know how to handle .rodata!!!\n");
                        }
                        dummy_sym.symbol = ".text";
                        if (hi16 || lo16) {
                            dummy_sym.hi = hi16;
                            dummy_sym.lo = lo16;
                        } else {
                            dummy_sym.hi = ((bootaddr - 0x1000 + offset) >> 16) & 0xffff;
                            dummy_sym.lo = ((bootaddr - 0x1000 + offset) >> 0) & 0xffff;
                        }
                        if (jump_addr) {
                            dummy_sym.hi = (jump_addr >> 16) & 0xffff;
                            dummy_sym.lo = (jump_addr >>  0) & 0xffff;
                        }
                        dummy_sym.found = 1;
                        s = &dummy_sym;
                    }
                    if (!s) {
                        fprintf(stderr, "Ack!!! Unable to find symbol '%s'\n", (*rel)->sym->symbol);
                    } else {
                        switch ((*rel)->type) {
                        case R_MIPS_HI16:
                            if (s->found) {
                                op = (op & 0xffff0000) | ((op & 0xffff) + s->hi);
                                fprintf(stderr, "relocating '%s' to 0x%08x @ %d\n", s->symbol, s->hi, i);
                            } else {
                                fprintf(stderr, "ERROR: '%s' has not been found in rom\n", s->symbol);
                            }
                            break;
                        case R_MIPS_LO16:
                            if (s->found) {
                                op = (op & 0xffff0000) | ((op & 0xffff) + s->lo);
                                fprintf(stderr, "relocating '%s' to 0x%08x @ %d\n", s->symbol, s->lo, i);
                            } else {
                                fprintf(stderr, "ERROR: '%s' has not been found in rom\n", s->symbol);
                            }
                            break;
                        case R_MIPS_26:
                            if (s->found) {
                                u32 reloc = s->lo;
                                op = (op & 0xfc000000) | ((op & 0x03ffffff) + (((s->hi<<16)|s->lo)>>2)&0x03ffffff);
                                fprintf(stderr, "relocating '%s' to 0x%08x @ %d\n", s->symbol, (((s->hi<<16)|s->lo)>>2)&0x03ffffff, i);
                            } else {
                                fprintf(stderr, "ERROR: '%s' has not been found in rom\n", s->symbol);
                            }
                            break;
                        }
                    }
                    ++rel;
                }
       
                *rp++ = op;
            } 
            free(r);
            fprintf(stderr, "\n");
        }
    }

    fclose(fp);
}

static char *progname;

void Usage(void)
{
    fprintf(stderr, "Usage: %s [options] rom\n", progname);
    fprintf(stderr,
            "\t-i, --input <rom>        Read rom image from <rom>\n"
            "\t-o, --output <rom>       Write patched rom file to <rom>\n"
            "\t-j, --jdebug <file>      Dump symbol information for jdebug\n"
            "\t-p, --patch <funcfile>   Attempt to patch the functions in <funcfile>\n"
            "\t    --sgi                Use the SGI signatures\n"
            "\t    --pc                 Use the PC signatures\n"
            "\t-f, --force-lib <lib>    Use OS 20<lib> signatures\n"
            "\t-D <symbol>=<offset>     Override <symbol> @ <offset>\n"
            "\t-v, --vitbl              Scan for and patch vitbl\n"
            "\t-b, --boot <addr>        Set the boot addr in the rom header\n"
            "\t    --disk               Scan for and patch disk detection code\n"
            "\t    --ramrom             Scan for and patch RAMROM accesses\n"
            "\t    --debugger           Scan for and patch debugger check\n"
            "\t    --osinit             Scan for and patch osInitialize\n"
            "\t-c, --crc                Scan for and patch crc miscompare (Indy)\n"
            "\t    --pal                Scan boot code and set osTvType = PAL(Indy)\n"
            "\t-h, --help               Print this message and exit\n"
           );
    exit(EXIT_FAILURE);
}

void parse_args(int argc, char *argv[])
{
    static struct option long_options[] = {
        {"patch", 1, 0, 'p'},
        {"vitbl", 0, 0, 'v'},
        {"crc", 0, 0, 'c'},
        {"osinit", 0, &do_osinit, 1},
        {"disk", 0, &do_disk, 1},
        {"ramrom", 0, &do_ramrom, 1},
        {"debug", 0, &do_debugger, 1},
        {"input", 1, 0, 'i'},
        {"output", 1, 0, 'o'},
        {"pal", 0, &do_pal, 1},
        {"sgi", 0, &use_sgi, 1},
        {"pc", 0, &use_sgi, 0},
        {"hi", 0, &force_hi_mem, 1},
        {"force-lib", 1, 0, 'f'},
        {"help", 0, 0, 'h'},
        {"jdebug", 1, 0, 'j'},
        {"boot", 1, 0, 'b'},
        {"binary", 1, 0, 0},
        {"dynamic", 1, 0, 'd'},
        {"dynamic-disk", 1, 0, 0},
        {0, 0, 0, 0,}
    };
    int longindex;
    progname = argv[0];

    while (1) {
        int c;
        char *p;

        if ((c = getopt_long(argc, argv, "b:cd:f:hi:j:o:p:vD:M:", long_options, &longindex)) == -1) {
            break;
        }
        switch(c) {
        case 0:
            if (!strcmp(long_options[longindex].name, "binary")) {
                binary = optarg;
            } else if (!strcmp(long_options[longindex].name, "dynamic-disk")) {
                dynamic_disk = strtoul(optarg, NULL, 0);
            }
            break;
        case 'c':
            do_crc = !do_crc;
            break;
        case 'd':
            dynamic = strtoul(optarg, NULL, 0);
            break;
        case 'f':
            force_lib = optarg[0];
            break;
        case 'h':
            Usage();
            break;
        case 'i':
            infile = optarg;
            break;
        case 'j':
            jdebug_file = optarg;
            break;
        case 'o':
            outfile = optarg;
            break;
        case 'p':
            patch_funcs = optarg;
            break;
        case 'v':
            do_vitbl++;
            break;
        case 'D':
            if ((p = strchr(optarg, '='))) {
                override_t o;
                *p++ = 0;
                o.symbol = optarg;
                o.offset = strtoul(p, NULL, 0);
                override.push_back(o);
            } else {
                fprintf(stderr, "-D<symbol>=<offset>\n");
            }
            break;
        case 'M':
            if ((p = strchr(optarg, '='))) {
                override_t o;
                *p++ = 0;
                o.symbol = optarg;
                o.offset = strtoul(p, NULL, 0);
                override_mem.push_back(o);
            } else {
                fprintf(stderr, "-M<symbol>=<offset>\n");
            }
            break;
        case 'b':
            bootaddr = strtoul(optarg, NULL, 0);
            break;
        default:
            fprintf(stderr, "Illegal option '%c'\n", c);
            Usage();
            break;
        }
    }

    if (infile == NULL) {
        fprintf(stderr, "You must specify an input rom file\n");
        Usage();
    }
}

int output_rom(u8 *rom, u32 rom_size, char *outfile)
{
    FILE *out;

    byteswap(rom, rom_size);
    if ((out = fopen(outfile, "w+")) == NULL) {
        perror(outfile);
        return -1;
    }
    if (fwrite(rom, rom_size, 1, out) != 1) {
        fprintf(stderr, "Unable to write %d bytes\n", rom_size);
        return -1;
    }
    fclose(out);
}

void patch_crc(u8 *rom, u32 rom_size)
{
    u32 *p = (u32 *)rom;
    u32 *end = (u32 *) (rom_size < 0x1000 ? rom+rom_size : rom+0x1000);

    fprintf(stderr, "Scanning ROM boot code for infinite loop...\n");
    while (p < end) {
        if (*p == 0x0411ffff) {
            fprintf(stderr, "  Patching infinite loop @ 0x%x\n", (u8*)p-rom);
            *p = 0;
        }
        ++p;
    }
    fprintf(stderr, "done\n\n");
}

void patch_pal(u8 *rom, u32 rom_size)
{
    u32 *p = (u32 *)rom;
    u32 *end = (u32 *) (rom_size < 0x1000 ? rom+rom_size : rom+0x1000);

    fprintf(stderr, "Scanning ROM boot code for osTvType...\n");
    while (p < end) {
        if (*p == 0xad140000) {
            fprintf(stderr, "  Patching osTvType @ 0x%x\n", (u8*)p-rom);
            *p = 0xad000000;
        }
        ++p;
    }
    fprintf(stderr, "done\n\n");
}

void patch_disk(u8 *rom, u32 rom_size)
{
    u32 *p = (u32 *)rom;
    u32 *end = (u32 *) (rom+rom_size);
    fprintf(stderr, "Scanning ROM for disk detection code...\n");
    while (p < end-1) {
        if (*p == 0x3c0aa500 && *(p+1) == 0x8d4b0508) {
            fprintf(stderr, "  Patching disk detection code @ 0x%x\n", (u8*)p-rom);
            *p = 0x1000000d;
            *(p+1) = 0;
            ++p;
        } else if ((*p & 0xfc00ffff) == 0x3c00a600 && 
                   (*(p+1) & 0xfc00ffff) == 0x8c001010) {
            fprintf(stderr, "  Patching other disk detection code @ 0x%x\n", (u8*)p-rom);
            *(p+1) = 0;
            ++p;
        }
        ++p;
    }
    fprintf(stderr, "done.\n\n");
}

void patch_ramrom(u8 *rom, u32 rom_size)
{
    u32 *p = (u32 *)rom;
    u32 *end = (u32 *) (rom+rom_size);
    fprintf(stderr, "Scanning ROM for RAMROM reading code...\n");
    while (p < end-1) {
        if ((*p & 0xfc00ffff) == 0x3c0000ff && (*(p+1) & 0xfc00ffff) == 0x3400b000) {
            p += 2;
            while (p < end-1 && ((*p >> 24) != 0x0c)) {
                ++p;
            }
            fprintf(stderr, "  Patching RAMROM reading code @ 0x%x\n", (u8*)p-rom);
            *p = 0;
            break;
        }
        ++p;
    }
    fprintf(stderr, "done.\n\n");
}

void patch_debugger(u8 *rom, u32 rom_size)
{
    u32 *p = (u32 *)rom;
    u32 *end = (u32 *) (rom+rom_size);
    fprintf(stderr, "Scanning ROM for debugger detection code...\n");
    while (p < end-1) {
        if ((*p & 0xfc00ffff) == 0x3c00bff0 && (*(p+1) & 0xfc00ffff) == 0x8c000000) {
            p++;
            fprintf(stderr, "  Patching debugger detection code @ 0x%x\n", (u8*)p-rom);
            *p = 0;
     //       break;
        }
        ++p;
    }
    fprintf(stderr, "done.\n\n");
}

void patch_osinit(u8 *rom, u32 rom_size)
{
    u32 *p = (u32 *)rom;
    u32 *end = (u32 *) (rom+rom_size);
    static u32 sgi_initcode[] = {
        0x3c041fc0, 0x348407fc, 0x0c000000, 0x27a50034, 0x10400007, 0x00000000,
        0x3c041fc0, 0x348407fc, 0x0c000000, 0x27a50034, 0x1440fffb, 0x00000000,
        0x8fa50034, 0x3c041fc0, 0x348407fc, 0x34af0008, 0x0c000000, 0x01e02825,
        0x10400009, 0x00000000, 0x8fa50034, 0x3c041fc0, 0x348407fc, 0x34b80008,
        0x0c000000, 0x03002825, 0x1440fff9
    };
    static u32 sgi_initmask[] = {
        0xffffffff, 0xffffffff, 0xfc000000, 0xffffffe7, 0xffffffff, 0xffffffff, 
        0xffffffff, 0xffffffff, 0xfc000000, 0xffffffe7, 0xffffffff, 0xffffffff, 
        0xffffffe7, 0xffffffff, 0xffffffff, 0xffffffff, 0xfc000000, 0xffffffff, 
        0xffffffff, 0xffffffff, 0xffffffe7, 0xffffffff, 0xffffffff, 0xffffffff, 
        0xfc000000, 0xffffffff, 0xffffffff
    };
    static u32 pc_initcode[] = {
        0x3c041fc0, 0x348407fc, 0x0c000000, 0x27a50010, 0x1440fffc, 0x3c041fc0,
        0x8fa50010, 0x3c041fc0, 0x348407fc, 0x0c000000, 0x34a50008, 0x1440fffa
    };
    static u32 pc_initmask[] = {
        0xffffffff, 0xffffffff, 0xfc000000, 0xffffffff, 0xffffffff, 0xffffffff,
        0xffffffff, 0xffffffff, 0xffffffff, 0xfc000000, 0xffffffff, 0xffffffff
    };
    u32 *initcode, *initmask, codesize;
    if (use_sgi) {
        initcode = sgi_initcode;
        initmask = sgi_initmask;
        codesize = sizeof(sgi_initcode);
    } else {
        initcode = pc_initcode;
        initmask = pc_initmask;
        codesize = sizeof(pc_initcode);
    }

    fprintf(stderr, "Scanning ROM for osInitialize chunk...\n");
    while (p < end) {
        if (*p == initcode[0]) {
            int i;
            for (i = 1; i < codesize/sizeof(u32); ++i) {
                if ((p[i] & initmask[i]) != (initcode[i] & initmask[i])) {
                    break;
                }
            }
            if (i == codesize/sizeof(u32)) {
                fprintf(stderr, "  Patching osInitialize chunk @ 0x%x\n", (u8*)p-rom);
                bzero(p, codesize);
                p += i-1;
            }
        }
        ++p;
    }
    fprintf(stderr, "done.\n\n");
}

void dump_jdebug(const char *file)
{
    FILE *fp;

    fprintf(stderr, "Dumping jdebug data:");
    if ((fp = fopen(file, "w")) == NULL) {
        perror(file);
        return;
    }
    for (symmap_t::iterator i = syms.begin(); i != syms.end(); ++i) {
        sym_t *s = i->second;
        if (s->found) {
            s32 addr = s->lo;
            addr = (addr << 16) >> 16;
            addr += (s->hi << 16);
            fprintf(fp, "%s 0x%08x 0x%x\n", s->symbol, addr, s->size);
        }
    }
    fprintf(stderr, "done.\n\n");
    fclose(fp);
}

void patch_dynamic(u8 *rom, u32 rom_size, u32 dynamic)
{
    u32 *rp;
    u32 jump_addr = ERRATA_START_ADDR+(errata_end-errata_start);
    u32 real_jump;

    fprintf(stderr, "Adding dynamic patch:\n");
    rp =  (u32 *)(rom + dynamic);
    if ((*rp >> 26) != 3) {
        fprintf(stderr, "  ERROR! Instruction not 'jal' (%08x)\n", *rp);
    }

    /* Remember "real" jal target and jump to our routine */
    real_jump = *rp & 0x03ffffff;
    *rp = 0x0c000000 | ((jump_addr&0x1fffffff) >> 2);

    /* Place a marker in SRAM to indicate that our patch routine got called */
    rp = (u32 *)errata_end;
    *rp++ = 0x3c09babe;
    *rp++ = 0x3529cafe;
    *rp++ = 0x3c08bfc4;
    *rp++ = 0xad097300;

    for (list<dynamic_t>::iterator p = dynamics.begin(); p != dynamics.end(); ++p) {
        /*
         * For each function, insert a jump to the himem version
         *
         * lui $t0, d.src >> 16 
         * ori $t0, $t0, d.src & 0xffff
         *
         * lui $t1, 0x3c0a
         * ori $t1, $t1, d.dst >> 16
         * sw $t1, 0($t0)
         *
         * lui $t1, 0x254a
         * ori $t1, $t1, d.dst & 0xffff
         * sw $t1, 4($t0)
         *
         * lui $t1, 0x0140
         * ori $t1, $t1, 0x8
         * sw $t1, 8($t0)
         *
         * lui $t1, 0
         * sw $t1, 12($t0)
         */

        fprintf(stderr, "  Dynamic patch from 0x%08x to 0x%08x\n", p->src, p->dst);
        *rp++ = 0x3c080000 | ((p->src >> 16) & 0xffff);
        *rp++ = 0x35080000 | ((p->src >>  0) & 0xffff);

        *rp++ = 0x3c093c0a;
        *rp++ = 0x35290000 | ((p->dst >> 16) & 0xffff);
        *rp++ = 0xad090000;

        *rp++ = 0x3c09254a;
        *rp++ = 0x35290000 | ((p->dst >>  0) & 0xffff);
        *rp++ = 0xad090004;

        *rp++ = 0x3c090140;
        *rp++ = 0x35290008;
        *rp++ = 0xad090008;

        *rp++ = 0x3c090000;
        *rp++ = 0xad09000c;
    }

    if (dynamic_disk) {
        *rp++ = 0x3c08800a;
        *rp++ = 0x3c091000;
        *rp++ = 0x3529000d;
        *rp++ = 0xad09d7bc;
        *rp++ = 0xad00d7c0;
    }

    /* End the function with a j back to the "real" jal target */
    *rp++ = 0x08000000 | real_jump;     /* j real_jump */
    *rp++ = 0;                          /* nop */
    *rp++ = 0x03e00008;                 /* jr $ra */
    *rp++ = 0;                          /* nop */
    errata_end = (u8*)rp;

    fprintf(stderr, "done.\n\n");
}

void override_symbols(void)
{
    fprintf(stderr, "Overriding symbols:\n");
    for (list<override_t>::iterator p = override.begin(); p != override.end(); ++p) {
        sigmap_t::iterator si = sigs.find(p->symbol);
        if (si != sigs.end()) {
            fprintf(stderr, "  overriding '%s' to 0x%08x\n", p->symbol, p->offset);
            si->second->offsets.push_back(0x80000000|p->offset);
        } else {
            fprintf(stderr, "  Unable to override '%s', not found.\n", p->symbol);
        }
    }
    for (list<override_t>::iterator p = override_mem.begin(); p != override_mem.end(); ++p) {
        symmap_t::iterator si = syms.find(p->symbol);
        if (si != syms.end()) {
            sym_t *s = si->second;
            fprintf(stderr, "  overriding '%s' to 0x%08x\n", p->symbol, p->offset);
            s->found = 1;
            s->hi = p->offset >> 16;
            s->lo = p->offset & 0xffff;
        } else {
            fprintf(stderr, "  Unable to override '%s', not found.\n", p->symbol);
        }
    }
    fprintf(stderr, "done.\n\n");
}

int main(int argc, char *argv[])
{
    u8 *rom, *lib;
    u32 rom_size;
    int i;
    char version;
    u32 pad;

    parse_args(argc, argv);

    if (load_file(infile, &rom, &rom_size) < 0 ) {
        return -1;
    }
    byteswap(rom, rom_size);
    make_crc_table();

    pad = (rom_size + 0x3fff) & ~0x3fff;
    rom = (u8 *) realloc(rom, pad+ERRATA_MAX_SIZE);
    errata_start = errata_end = rom + pad;
    bzero(errata_start, ERRATA_MAX_SIZE);

    version = rom[12];
    fprintf(stderr, "Rom is using version '%c'\n", version);
    if (force_lib) {
        fprintf(stderr, "Forcing version '%c'\n", force_lib);
        version = force_lib;
    }
    for (i = 0; i < sizeof(libraries)/sizeof(libraries[0]); ++i) {
        if (version == libraries[i].version) {
            if (use_sgi && libraries[i].sgi_sigs) {
                read_library(libraries[i].sgi_sigs, syms, sigs);
            } else if (libraries[i].pc_sigs) {
                read_library(libraries[i].pc_sigs, syms, sigs);
            }

            break;
        }
    }
    if (syms.size()) {
        fprintf(stderr, "  found signatures for this library\n");
    } else {
        fprintf(stderr, "  Unable to locate signatures for %c (%s)\n", version, use_sgi?"SGI":"PC");
        return -1;
    }
    read_library("sigs/bb_rom", patch_syms, patch_sigs);


    if (do_vitbl) {
        patch_vitbl(rom, rom_size);
    }

    if (do_crc) {
        patch_crc(rom, rom_size);
    }
    
#if 0
    if (do_pal) {
        patch_pal(rom, rom_size);
    }
#endif

    if (patch_funcs || jdebug_file) {
        if (binary) {
            u8 *chunk;
            u32 chunk_size;
            if (load_file(binary, &chunk, &chunk_size) < 0 ) {
                return -1;
            }
            byteswap(chunk, chunk_size);
            scan_rom(chunk, chunk_size, sigs);
        } else {
            scan_rom(rom, rom_size, sigs);
        }
    }

    if (!override.empty() || !override_mem.empty()) {
        override_symbols();
    }

    if (bootaddr) {
        ((u32 *)rom)[2] = bootaddr;
    } else {
        bootaddr = ((u32 *)rom)[2];
    }

    if (patch_funcs) {
        patch_rom(rom, patch_funcs);
    }

    if (do_disk) {
        patch_disk(rom, rom_size);
    }

    if (do_ramrom) {
        patch_ramrom(rom, rom_size);
    }

    if (do_debugger) {
        patch_debugger(rom, rom_size);
    }

    if (do_osinit) {
        patch_osinit(rom, rom_size);
    }

    if (dynamic) {
        patch_dynamic(rom, rom_size, dynamic);
    }

    if (jdebug_file) {
        dump_jdebug(jdebug_file);
    }

    if (outfile) {
        u32 size = (errata_start == errata_end) ? rom_size : (errata_end - rom);
        if (output_rom(rom, size, outfile) < 0) {
            return -1;
        }
    }

    return 0;
}