makedisk.c 27.3 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 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <limits.h>
#include <getopt.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <wait.h>

#include "makedisk.h"

// Function prototypes for Internal functions
//
static void usage(void);
static void doWave(Wave *);
static void nameTempFiles(void);
static void unlinkTempFiles(void);
static void wavePrint(void);
static void cleanup(int);
static void getOsVersion(void);
static int checkIdoVersion(char*);
static void printVersion(void);
static void getBootFile(char * bootFileName);
static void getPif2BootFile(char *pif2bootFileName);
static void getRomheaderFile(char *headerFileName);
static void getFontDataFile(char *fontFileName);
static char *gloadFindFile(char *fullpath, char *postRootSuffix, char *fname);

// Internal variables
//
static const struct sigaction act = {0, cleanup, 0};
static char segmentSymbolSource[_POSIX_PATH_MAX];
static char segmentSymbolObject[_POSIX_PATH_MAX];
static char entrySource[_POSIX_PATH_MAX];
static char entryObject[_POSIX_PATH_MAX];
static char objectListFile[_POSIX_PATH_MAX];
static char *romFile = "rom";
static char *diskFile = "disk";
static int  checkOverlap = 1;
static char *progName;

// Global variables
//
unsigned char	*bootBuf, *headerBuf, *pif2bootBuf, *fontBuf;
int		bootWordAlignedByteSize;
int		pif2bootWordAlignedByteSize;
int		headerWordAlignedByteSize;
int		fontdataWordAlignedByteSize;
Segment		*segmentList = (Segment *)NULL;
Wave		*waveList = (Wave *)NULL;
char		*fileName;
char		*bootEntryName;
char		*bootStackName;
unsigned int	bootStackOffset;
int 	 	debug = 0;
int 	 	cosim = 0;
int		emulator = 0;
int		loadMap;
int		nofont = 0;
int		gcord;
int  		finalromSize = 0;
char 		fillData = 0xff;
int		offset = 0;
int 	 	keep_going = 0;	/* if TRUE, ignore failures of children */
int		irixVersion;
int 	        disktype = 0;
int		generateArgs = 0; /* if TRUE, generate "arg file" for leowrite */
char		*argFileName;
int		existIDFile = 0;
char		*idFileName;
int		booter = 0; /* if TRUE, generate booter game */
int		bootee = 0; /* if TRUE, generate bootee game */
char 		*scriptFile = "gwrite";

int		ramStartLba[] = 
{
  1418, 1966, 2514, 3062, 3610, 4088, 4292
};

main(int argc, char *argv[]) {
  int c;
  FILE *f;
  Wave *wave;
  char *cppCmd;
  long cppCmdCount;
  int headerFd, pif2bootFd;
  char *bootFileName = NULL;
  char *headerFileName = NULL;
  char *pif2bootFileName = NULL;
  char *fontFileName = NULL;
  int createRom = 1;
  char CheckerBuf[NAME_MAX];
  char NameBuf[NAME_MAX];
  char *rootName;
  int quietMode = 0;
  
  progName = argv[0];
  if ((cppCmdCount = sysconf(_SC_ARG_MAX)) == -1) {
    fprintf(stderr, "makedisk: sysconf(_SC_ARG_MAX): %s\n",
	    sys_errlist[errno]);
    exit(1);
  }
  if ((cppCmd = malloc(cppCmdCount)) == NULL) {
    fprintf(stderr, "malloc failed\n");
    return(-1);
  }
  sprintf(cppCmd, "/usr/lib/cpp -D_LANGUAGE_MAKEDISK");
  cppCmdCount -= (strlen(cppCmd) + 1);
  
  // Parse options
  //
  while ((c = getopt(argc, argv, "D:I:U:cdei:mnor:gb:h:p:s:f:A:O:t:QqVvB:R:S:")) != EOF) {
    switch (c) {
    case 'D':
    case 'I':
    case 'U':
      cppCmdCount -= 3+strlen(optarg);
      if (cppCmdCount <= 0) {
	fprintf(stderr,
		"makedisk: too many -[DIU] flags\n");
	exit(1);
      }
      sprintf(cppCmd, "%s -%c%s", cppCmd, c, optarg);
      break;
    case 'c':
      cosim = 1;
      break;
    case 'd':   // Print debug messages
      debug = 1;
      break;
    case 'g':
      gcord = 1;
      break;
    case 'k':	// if TRUE, ignore failures of children 
      keep_going = 1;
      break;
    case 'e':   // Used if we're on the software emulator
      emulator = 1;
      break;
    case 'm':   // Print symbol map
      loadMap = 1; 
      break;
    case 'n':   // Turn off use of font file
      nofont = 1;
      break;
    case 'o':   // Turn off overlap checking
      checkOverlap = 0;
      break;
    case 'r':   // Name rom file
      romFile = optarg;
      break;
    case 'b':   // Name boot file
      bootFileName = optarg;
      break;
    case 'h':   // Name romheader file
      headerFileName = optarg;
      break;
    case 'p':   // Name pif2 boot file
      pif2bootFileName = (char *)optarg;
      break;
    case 's':   // Give explicit rom file size
      finalromSize = strtol(optarg, (char **)NULL, 0);
      break;
    case 'f':   // Give data byte to fill extra rom space with
      fillData = strtol(optarg, (char **)NULL, 0);
      break;
    case 'A':
      generateArgs = 1;
      argFileName = optarg;
      break;
    case 'O':
      offset = strtol(optarg, (char **)NULL, 0);
      break;
    case 't':
      disktype = strtol(optarg, (char **)NULL, 0);
      if ( (disktype < 0) || (disktype > 6) ) {
	fprintf(stderr, "makedisk: disk type specified is illegal\n");
	exit(1);
      }
      break;
    case 'i':
      existIDFile = 1;
      idFileName = optarg;
      break;
    case 'B':
      {
	  int		bootType;
	  
	  bootType = strtol(optarg, (char **)NULL, 0);
	  if (bootType == 0)
	      booter = 1;
	  else if (bootType == 1)
	      bootee = 1;
	  else
	  {
	      fprintf(stderr, "makedisk: invalid argument for -B option (-B 0 or -B 1)\n");
	      exit(1);
	  }
      }
      break;
    case 'R':
      diskFile = optarg;
      break;
    case 'S':
      scriptFile = optarg;
      break;
    case '?':
      usage();
      exit(1);
    case 'Q':
    case 'q':   // Don't print messages
      quietMode = 1;
      break;
    case 'V':   // Print version number
    case 'v':
      printVersion();
      exit (1);
    }
  }

  // Print usage message if incorrect number of parameters
  if ((argc - optind) != 1) {
    usage();
    exit(1);
  }
  
  if ((cosim + emulator) > 1) {
    fprintf(stderr, "makedisk: only specify one of -c, -e, or -i\n");
    exit(1);
  }
  
  if (booter && bootee)
  {
      fprintf(stderr, "makedisk: \"-B 0\" and \"-B 1\" may not be specified at a time\n");
      exit(1);
  }

  getOsVersion();
  
  // Print the version number if not in quiet mode.
  if (!quietMode) {
    printVersion();
  }
  
  // Load some necessary files.
  getBootFile(bootFileName);
  getPif2BootFile(pif2bootFileName);
  getRomheaderFile(headerFileName);
  getFontDataFile(fontFileName);
  
  // Make sure rom file doesn't already exist.
  if ((unlink(romFile) == -1) && (errno != ENOENT)) {
    fprintf(stderr, "makedisk: %s: %s\n",
	    romFile, sys_errlist[errno]);
    exit(1);
  }

  // Setup for spec file parse
  fileName = argv[optind];
  if ((yyin = fopen(fileName, "r")) == NULL) {
    fprintf(stderr, "makedisk: %s: %s\n",
	    fileName, sys_errlist[errno]);
    exit(1);
  }
  fclose(yyin);

  // Call "CPP" on the spec file, by making the parser input be the
  //   output from the cpp command.
  cppCmdCount -= strlen(fileName);
  if (cppCmdCount <= 0) {
    fprintf(stderr,
	    "makedisk: cpp command line too long\n");
    exit(1);
  }
  sprintf(cppCmd, "%s %s", cppCmd, fileName);
  if ((yyin = popen(cppCmd, "r")) == NULL) {
    fprintf(stderr, "makedisk: could not run cpp on %s: %s\n",
	    fileName, sys_errlist[errno]);
    exit(1);
  }
  
  // Build waves from spec file
  if (yyparse())
    exit(1);
  
  // Wait for and check error return of cpp
  if (pclose(yyin) != 0)
    exit(1);
  
  //////////////////////////////////
  // SPEC file is done being parsed
  //////////////////////////////////

  /*
   * カートリッジ起動ゲームは、被起動ゲームになれない
   */
  if ( cartBoot && bootee )
  {
      fprintf(stderr, "\"Bootee\" game should be a disk game\n");
      exit(1);
  }

  // Check for unreferenced segments and get segment sizes
  if (scanSegments() == -1)
    exit(1);
  
  // Check that segment sizes are within various limits
  if (checkSizes())
    createRom = 0;
  
  // If desired, check for overlapping direct mapped CPU segments
  if (checkOverlap && checkOverlaps())
    createRom = 0;
  
  // Create temp file names
  nameTempFiles();
  
  // Hook signals for cleanup on abnormal termination
  sigaction(SIGHUP, &act, NULL);
  sigaction(SIGINT, &act, NULL);
  sigaction(SIGTERM, &act, NULL);
  
  // Create file of segment start/end symbols
  if (debug)
    printf("Creating segment symbol source file in %s\n",
	   segmentSymbolSource);
  
  if (createSegmentSymbols(segmentSymbolSource,
			   segmentSymbolObject, romFile, diskFile) == -1) {
    unlinkTempFiles();
    exit(1);
  }

  // For each wave, call the 'doWave' routine, which creates an 
  //   elspec file and runs the linker to generate an elf object file.
  //
  for (wave = waveList; wave != (Wave *)NULL; wave = wave->next)
    doWave(wave);
  
  ///////////////////////////
  // Linking stage complete!
  ///////////////////////////

#ifdef DEBUG
  wavePrint();
#endif /* DEBUG */

  if ((rootName = getenv("ROOT")) == NULL) {
    rootName = "/";
  }

  // check multiply instruction pair
  if (irixVersion >= OS_VERSION_62) {
    // Check to make sure we're not running an old IDO on a new IRIX.
    if (checkIdoVersion(rootName) < IDO_VERSION_71) {
      fprintf(stderr, "makedisk: This IDO version is not compatible with the\n");
      fprintf(stderr, "          Nintendo64 development environment on this\n");
      fprintf(stderr, "          version of IRIX.\n");
      exit (1);
    }
    sprintf(CheckerBuf, 
	    "%s/usr/sbin/u64check -fmulmul:check:noforce:norepair", 
	    rootName);
  } else {
    // This should be IRIX 5.3, IDO 5.3.
    sprintf(CheckerBuf, "%s/usr/sbin/r4300_check", rootName);
  }
  if (debug) {
    printf("Checking fmulmul status\n");
  }
  for (wave = waveList; wave != (Wave *)NULL; wave = wave->next) {
    sprintf(NameBuf,"%s %s",CheckerBuf,wave->name);
    if (debug)
      printf("  %s\n", NameBuf);
    if (execCommand(NameBuf) == -1 && !keep_going) {
      unlinkTempFiles();
      exit(1);
    }
  }

  if ( gcord ) {
    char gcordFileBuf[NAME_MAX];
    
    sprintf(CheckerBuf, "%s/usr/lib/PR/gcord ", rootName);
    
    for (wave = waveList; wave != (Wave *)NULL; wave = wave->next) {
      sprintf(NameBuf,"%s %s",CheckerBuf,wave->name);
      if (debug)
	printf("makedisk: %s\n", NameBuf);
      if (execCommand(NameBuf) == -1 && !keep_going) {
	unlinkTempFiles();
	exit(1);
      }
      strcat(strcpy( gcordFileBuf, wave->name), ".cord" );
      strcpy(wave->name , gcordFileBuf);
    }
    
  }
  
  if (debug)
    printf("Creating entry source file in %s\n", entrySource);
  
  if (createEntryFile(entrySource, entryObject) == -1) {
    unlinkTempFiles();
    exit(1);
  }
  
  // If no size violation or overlap occurred, create the rom image
  if (createRom) {
    if (debug) {
      printf("Extracting sections from ELF wave files");
      printf(" to create ROM image in %s\n", romFile);
    }
    
    if (createRomImage(romFile, diskFile, entryObject) == -1) {
      unlinkTempFiles();
      exit(1);
    }
    
  }
  
  // Remove all created temp files
  unlinkTempFiles();
  
  // Clean up memory buffers.
  if (bootBuf)
    free(bootBuf);
  if (headerBuf)
    free(headerBuf);
  if (fontBuf)
    free(fontBuf);
  
  exit(createRom ? 0 : 1);
}


////////////////////////////////////////////////////////////////////////////////
// usage()
//
// Print a usage message describing appropriate options.
//
static void usage(void) {
  fprintf(stderr, "usage: makedisk [-D<define>] [-I<dir>] -[U<define>]\n");
  fprintf(stderr, "                [-c] [-n] [-d] [-g] [-e] [-m] [-q] [-v]\n");
  fprintf(stderr, "                [-o] [-b bootfile] [-h headerfile]\n");
  fprintf(stderr, "                [-p pif2bootfile]\n");
  fprintf(stderr, "                [-s romsize (Mbits)]\n");
  fprintf(stderr, "                [-f filldata (0x00 - 0xff)]\n");
  fprintf(stderr, "                [-t type]\n");
  fprintf(stderr, "                [-i idfile]\n");
  fprintf(stderr, "                [-S scriptfile] \n");
  fprintf(stderr, "                [-R diskfile]\n");
  fprintf(stderr, "                [-B (0|1)]\n");
  fprintf(stderr, "                [-r romfile] specfile\n");
}


////////////////////////////////////////////////////////////////////////////////
// getOsVersion()
//
// Determine the IRIX version by running the 'uname' command and parsing
//   its output.  Store the version number in the variable 'irixVersion'.
//
static void getOsVersion(void) {
  char* cmd = "/sbin/uname -r";
  char  buf[BUFSIZ];
  FILE* procPtr;
  
  if ((procPtr = popen(cmd, "r")) != NULL) {
    fgets(buf, BUFSIZ, procPtr);
    pclose(procPtr);
    if (!strcmp(buf, "5.3\n")) {
      irixVersion = OS_VERSION_53;
    } else if (!strcmp(buf, "6.2\n")) {
      irixVersion = OS_VERSION_62;
    } else if (!strcmp(buf, "6.3\n")) {
      irixVersion = OS_VERSION_63;
    } else if (!strcmp(buf, "6.4\n")) {
      irixVersion = OS_VERSION_64;
    } else {
      irixVersion = OS_VERSION_OTHER;
      fprintf(stderr, "makedisk: Operating system not recognized.  Trying 6.x ...\n");
    }
  } else {
    fprintf(stderr, "makedisk: Unable to find uname command!\n");
    exit(1);
  }
}

////////////////////////////////////////////////////////////////////////////////
// checkIdoVersion()
//
// IDO 7.x has u64check.  But we can only use IDO 7.1.
// This function checks to make sure that the IDO version is okay.
//
static int checkIdoVersion(char* rootName) {
  int u64CheckFound;
  int v70Found;
  char cmd[NAME_MAX];
  char buffer[NAME_MAX];
  struct stat statBuffer;
  FILE* procPtr;

  /* Check for existence of u64check.
   */
  sprintf(buffer, "%s/usr/sbin/u64check", rootName);
  if (stat(buffer, &statBuffer) != 0) {
    /* Not found. */
    u64CheckFound = 0;
  } else {
    u64CheckFound = 1;
  }
  
  /* Make sure we're not on IDO 7.0.
   */
  sprintf(cmd, "/usr/sbin/showprods -D 1 dev");
  if ((procPtr = popen(cmd, "r")) != NULL) {
    fgets(buffer, NAME_MAX, procPtr);
    fgets(buffer, NAME_MAX, procPtr);
    fgets(buffer, NAME_MAX, procPtr);
    fgets(buffer, NAME_MAX, procPtr);
    pclose(procPtr);
    if (strstr(buffer, "7.0")) {
      v70Found = 1;
    } else {
      v70Found = 0;
    }
  }

  if (v70Found) {
    fprintf(stderr, "makedisk: IDO v7.0 does not work with the Nintendo64\n");
    fprintf(stderr, "          development environment.  Please upgrade to\n");
    fprintf(stderr, "          IDO v7.1.\n");
    exit (1);
  }
  if (u64CheckFound) {
    /* This should be 7.1 or later. */
    return IDO_VERSION_71;
  } else {
    /* This should be 5.3. */
    return IDO_VERSION_53;
  }
}


////////////////////////////////////////////////////////////////////////////////
// printVersion()
//
// Print out the version number of this executable.
//
static void printVersion(void) {

  if (irixVersion == OS_VERSION_53)
     printf("Nintendo64 Makedisk v2.5 for IRIX.\n");
  else
     printf("Nintendo64 Makedisk v2.5 -BETA- for IRIX.\n");

}


////////////////////////////////////////////////////////////////////////////////
// getBootFile()
//
// Get the contents of the file /usr/lib/PR/Boot, load it into bootBuf.
//
static void getBootFile(char *bootFileName) {
  int bootFd;
  char scratchFileName[NAME_MAX];
  struct stat buf;
  char errMessage[NAME_MAX];
  
  /*
   * Load the bootstrap file (provide a default if none was supplied)
   */
  if (!bootFileName) {
    if ( gloadFindFile(scratchFileName, "/usr/lib/PR", "Boot") ) {
      bootFileName = scratchFileName;
    }
  }
  
  if (bootFileName) {
    if ((bootFd = open(bootFileName, O_RDONLY | O_NOCTTY)) < 0) {
      sprintf(errMessage, "%s: unable to open %s", progName, bootFileName);
      perror(errMessage);
      exit(1);
    }
    /*
     * Load the bootstrap file.
     */
    if (fstat(bootFd, &buf) < 0) {
      sprintf(errMessage, "%s unable to stat %s", progName, bootFileName);
      perror(errMessage);
      close(bootFd);
      exit(1);
    }
    
    bootBuf = malloc(buf.st_size);
    if (bootBuf == NULL) {
      fprintf(stderr, "%s: unable to malloc buffer to hold %d bytes\n",
	      progName, buf.st_size);
      close(bootFd);
      exit(1);
    }
    close(bootFd);
    bootWordAlignedByteSize = readCoff(bootFileName, (unsigned int *)bootBuf);
  } else {
    bootBuf = NULL;
  }
}


////////////////////////////////////////////////////////////////////////////////
// getPif2BootFile()
//
// Get the contents of the file /usr/lib/PR/pif2Boot, load it into pif2BootBuf.
//
static void getPif2BootFile(char *pif2bootFileName) {
  int pif2bootFd;
  char scratchFileName[NAME_MAX];
  struct stat buf;
  char errMessage[NAME_MAX];
  
  /*
   * Load the pif2bootstrap file (provide a default if none was supplied)
   */
  if (!pif2bootFileName) {
    if ( gloadFindFile(scratchFileName, "/usr/lib/PR", "pif2Boot") ) {
      pif2bootFileName = scratchFileName;
    }
  }
  
  if (pif2bootFileName) {
    if ((pif2bootFd = open(pif2bootFileName, O_RDONLY | O_NOCTTY)) < 0) {
      sprintf(errMessage, "%s: unable to open %s", progName, pif2bootFileName);
      perror(errMessage);
      exit(1);
    }
    /*
     * Load the pif2bootstrap file.
     */
    if (fstat(pif2bootFd, &buf) < 0) {
      sprintf(errMessage, "%s unable to stat %s", progName, pif2bootFileName);
      perror(errMessage);
      close(pif2bootFd);
      exit(1);
    }
    
    pif2bootBuf = malloc(buf.st_size);
    if (pif2bootBuf == NULL) {
      fprintf(stderr, "%s: unable to malloc buffer to hold %d bytes\n", 
	      progName, buf.st_size);
      close(pif2bootFd);
      exit(1);
    }
    close(pif2bootFd);
    pif2bootWordAlignedByteSize = readCoff(pif2bootFileName, (unsigned int *)pif2bootBuf);
  } else {
    pif2bootBuf = NULL;
  }
}


////////////////////////////////////////////////////////////////////////////////
// getRomheaderFile()
//
// Get the contents of the file /usr/lib/PR/romheader, load it into headerBuf.
//
static void getRomheaderFile(char *headerFileName) {
  int headerFd;
  char scratchFileName[NAME_MAX];
  struct stat buf;
  char errMessage[NAME_MAX];
  char nibbleString[2];
  int nibbleVal;
  int i, readPtr, retval;
  
  /*
   * Load the romheader file (provide a default, if none was supplied).
   * It's in ascii format, so we convert each character to hexadecimal and
   * prepare words of data to be loaded into memory.
   */
  if (!headerFileName) {
    if ( gloadFindFile(scratchFileName, "/usr/lib/PR", "romheader") ) {
      headerFileName = scratchFileName;
    }
  }
  if (headerFileName) {
    
    if ((headerFd = open(headerFileName, O_RDONLY | O_NOCTTY)) < 0) {
      sprintf(errMessage, "%s unable to open %s", progName, headerFileName);
      perror(errMessage);
      exit(1);
    }
    /*
     * Load the romheader file
     */
    if (fstat(headerFd, &buf) < 0) {
      sprintf(errMessage, "%s unable to stat %s", progName, headerFileName);
      perror(errMessage);
      close(headerFd);
      exit(1);
    }
    headerWordAlignedByteSize = buf.st_size;
    
    /*
     * Since each byte corresponds to an ascii character describing a 
     * nibble, this is twice as big as we need, but we'll need it larger
     * in case we need to word align ourselves.
     */
    headerBuf = malloc(headerWordAlignedByteSize);
    if (headerBuf == NULL) {
      fprintf(stderr, "%s: unable to malloc buffer to hold %d bytes\n", 
	      progName, headerWordAlignedByteSize);
      close(headerFd);
      exit(1);
    }
    nibbleString[1] = '\0';
    for (i = 0, readPtr = 0; readPtr < headerWordAlignedByteSize; i++, readPtr++) {
      retval = read(headerFd, ( (void *)(&(nibbleString[0])) ), 1);
      if (retval != 1) {
	fprintf(stderr, "%s: short read from %s.\n",
		progName, headerFileName);
	free(headerBuf);
	close(headerFd);
	exit(1);
      }
      /*
       * Eat line feeds at end of line.
       */
      if ( (nibbleString[0] == '\n') && 
	   (++readPtr < headerWordAlignedByteSize) ) {
	retval = read(headerFd, ( (void *)(&(nibbleString[0])) ), 1);
	if (retval != 1) {
	  fprintf(stderr, "%s: short read from %s.\n",
		  progName, headerFileName);
	  free(headerBuf);
	  close(headerFd);
	  exit(1);
	}
      }
      
      /*
       * Do a hex to int conversion on each nibble as they come in.
       */
      nibbleVal = strtol(nibbleString, NULL, 16);
      
      if (i % 2) {
	headerBuf[ (i >> 1) ] |= nibbleVal;
      } else {
	headerBuf[ (i >> 1) ] = (nibbleVal << 4);
      }
#ifdef DEBUG
      printf("headerBuf[%d] now = 0x%x, char read was 0x%x\n", 
	     (i >> 1), headerBuf[ (i >> 1) ], nibbleString[0]);
#endif
    }

    /*
     * Write the contents of the ramromheader file into the beginning of 
     * ramrom.  Divide number of nibbles read by 2 to get number of bytes.
     */
    headerWordAlignedByteSize = ((i - 1) >> 1);
    
    /* 
     * We must transfer an integral number of words.  Doesn't hurt to 
     * transfer a couple of extra bytes of crap.
     */
    
    if (headerWordAlignedByteSize & 3){
      headerWordAlignedByteSize += 4;
      headerWordAlignedByteSize &= ~(3);
    }
    close(headerFd);
  } else {
    headerBuf = NULL;
  }
}


////////////////////////////////////////////////////////////////////////////////
// getFontDataFile() 
//
// Get the contents of the file /usr/lib/PR/font, load it into fontBuf.
//
static void getFontDataFile(char *fontFileName) {
  int fontFd;
  char scratchFileName[NAME_MAX];
  struct stat buf;
  char errMessage[NAME_MAX];
  
  /*
   * Load the fontdata file 
   */
  if ( gloadFindFile(scratchFileName, "/usr/lib/PR", "font") ) {
    fontFileName = scratchFileName;
  }
  
  if (fontFileName) {
    if ((fontFd = open(fontFileName, O_RDONLY | O_NOCTTY)) < 0) {
      sprintf(errMessage, "%s: unable to open %s", progName, fontFileName);
      perror(errMessage);
      exit(1);
    }
    /*
     * Load the fontdata file.
     */
    if (fstat(fontFd, &buf) < 0) {
      sprintf(errMessage, "%s unable to stat %s", progName, fontFileName);
      perror(errMessage);
      close(fontFd);
      exit(1);
    }
    
    fontBuf = malloc(buf.st_size);
    if (fontBuf == NULL) {
      fprintf(stderr, "%s: unable to malloc buffer to hold %d bytes\n",
	      progName, buf.st_size);
      close(fontFd);
      exit(1);
    }
    fontdataWordAlignedByteSize = buf.st_size;
    if (read(fontFd, fontBuf, fontdataWordAlignedByteSize) !=
	fontdataWordAlignedByteSize) {
      sprintf(errMessage, "%s unable to read %s", progName, fontFileName);
      perror(errMessage);
      close(fontFd);
      exit(1);
    }
    close(fontFd);
  } else {
    fontBuf = NULL;
  }
}


////////////////////////////////////////////////////////////////////////////////
// gloadFindFile()
//
// Find the filename 'fname', using the suggested directory 'postRootSuffix'.
// Use ROOT, WORKAREA, and then NULL as prefixes to find the file.
// If found, return the filename in 'fullpath', else return NULL.
//
static char *gloadFindFile(char *fullpath, char *postRootSuffix, char *fname) {
  char *rootname, *rootpath;
  int try;
  
  for (try = 0; try <= 2; try++) {
    fullpath[0] = '\0';
    
    switch (try) {
    case 0: rootname = "ROOT"; break;
    case 1: rootname = "WORKAREA"; break;
    case 2: rootname = NULL; break;
    }
    if (rootname != NULL) {
      if ((rootpath = (char *)getenv(rootname)) == NULL)
	continue;
      strcat(fullpath, rootpath);
    }
    
    if (postRootSuffix) {
      strcat(fullpath, postRootSuffix);
      strcat(fullpath, "/");
    }
    
    strcat(fullpath, fname);
    
    if (!access(fullpath, R_OK))
      return(fullpath);
  }
  
  fprintf(stderr, "gloadFindFile: can't find file %s\n", fullpath);
  fullpath[0] = '\0';
  return(NULL);
}


////////////////////////////////////////////////////////////////////////////////
// doWave()
//
//
//
static void doWave(Wave *wave) {
  
  /* Create linker spec file from wave information */
  
  if (debug) {
    printf("Translating ROM spec file into");
    printf(" linker spec file in %s\n", wave->elspecFile);
  }
  
  if (createElspec(wave) == -1) {
    unlinkTempFiles();
    exit(1);
  }

  // Execute linker to create a.out
  //
  if (runLinker(wave, segmentSymbolObject, objectListFile) == -1 && 
      !keep_going) {
    unlinkTempFiles();
    exit(1);
  }
}


////////////////////////////////////////////////////////////////////////////////
// wavePrint()
//
//
//
#ifdef DEBUG
static void wavePrint(void) {
  Wave *w;
  Segment *s;
  SegmentChain *sc;
  Path *p;
  
  printf("segments:\n");
  for (s = segmentList; s != NULL; s = s->next) {
    printf("name = %s address = 0x%x text 0x%x data 0x%x romOffset 0x%x\n",
	   s->name, s->address/*+s->adjust_address*/, s->textSize, s->dataSize, s->romOffset);
    for (p = s->pathList; p != NULL; p = p->next) {
      printf("\t%s\n", p->name);
    }
  }
  printf("waves:\n");
  for (w = waveList; w != NULL; w = w->next) {
    printf("name = %s\n", w->name);
    printf("segments:\n");
    for (sc = w->segmentChain; sc != NULL; sc = sc->next) {
      printf("\t%s\n", sc->segment->name);
    }
  }
}
#endif


////////////////////////////////////////////////////////////////////////////////
// nameTempFiles()
//
// Create the names for temporary files used by this app.
//   - elspec files
//   - segment symbols file
//   - entry point file
//   - object list file for linker
//
static void nameTempFiles(void) {
  Wave *wave;
  char *tmpdir;
  
  // Choose the temporary directory.
  // "/tmp", or TMPDIR if set.
  //
  if ((tmpdir = getenv("TMPDIR")) ==  NULL)
    tmpdir = "/tmp";
  
  // Create a temporary elspec file for each wave in the spec file.
  //
  for (wave = waveList; wave != (Wave *)NULL; wave = wave->next) {
    sprintf(wave->elspecFile,
	    "%s/%sElspecXXXXXX", tmpdir, wave->name);
    mktemp(wave->elspecFile);
  }
  
  // Create a temporary file for the segment symbols.
  //
  sprintf(segmentSymbolSource, "%s/segmentXXXXXX", tmpdir);
  mktemp(segmentSymbolSource);
  strcpy(segmentSymbolObject, segmentSymbolSource);
  strcat(segmentSymbolSource, ".s");
  strcat(segmentSymbolObject, ".o");

  // Create a temporary file for the entry point.
  //
  sprintf(entrySource, "%s/entryXXXXXX", tmpdir);
  mktemp(entrySource);
  strcpy(entryObject, entrySource);
  strcat(entrySource, ".s");
  strcat(entryObject, ".o");
  
  // Create a temporary file for the object list file, which will
  //   be passed to the linker on its command line.
  //
  sprintf(objectListFile, "%s/objListXXXXXX", tmpdir);
  mktemp(objectListFile);
}


////////////////////////////////////////////////////////////////////////////////
// unlinkTempFiles()
//
// Remove all of the temporary files which were created by this app.
//
static void unlinkTempFiles(void) {
  Wave *wave;
  
  if (!debug) {
    for (wave = waveList; wave != (Wave *)NULL; wave = wave->next) {
      unlink(wave->elspecFile);
    }
    unlink(segmentSymbolSource);
    unlink(segmentSymbolObject);
    unlink(entrySource);
    unlink(entryObject);
    unlink(objectListFile);
  }
}


////////////////////////////////////////////////////////////////////////////////
// cleanup()
//
// Callback routine which is called by the OS on SIGHUP, SIGINT, SIGTERM.
// Clean up the temp files, and exit.
//
static void cleanup(int sig) {
  unlinkTempFiles();
  exit(1);
}


////////////////////////////////////////////////////////////////////////////////
// execCommand()
//
// Execute a command by calling "system".  If it returns an error, print out
//   an error message.
//
int execCommand(char *s) {
  int status;
  
  status = system(s);
  
  if (status == -1) {
    fprintf(stderr, "makedisk: cannot execute command: %s\n",
	    sys_errlist[errno]);
    return(-1);
  } else if (WIFEXITED(status) && (WEXITSTATUS(status) == 0)) {
    return(0);	/* sucess! */
  } else if (keep_going && 
	     (WIFEXITED(status) && (WEXITSTATUS(status) == 1))) {
    return(1);	/* warning! */
  } else {
    if (debug) {
      fprintf(stderr, "makedisk: [%s] returned %d (%08x), errno=%d\n",
	      s, WEXITSTATUS(status), status, errno);
    }
    return(-1);	/* failure! */
  }
}