segment.c 43 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 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617
#include <stdlib.h>
#include <sys/stat.h>

#include <elf.h>
#include <errno.h>
#include <fcntl.h>
#include <stddef.h>
#include <string.h>
#include <unistd.h>
#include <wait.h>

#include <R4300.h>
#include <ramrom.h>

#include "makerom.h"

#ifndef __sgi__
#define ELF_TEXT	".text"
#define ELF_DATA	".data"
#define ELF_RODATA	".rodata"
#define ELF_BSS		".bss"
#define MIPS_SBSS	".sbss"
#define MIPS_SDATA	".sdata"
#endif

// Function prototypes for internal functions.
//
static int		sizeObject(Segment *);
static int		sizeRaw(Segment *);
static void *		lookupSymbol(Wave *, char *);
static int		openAouts(void);
static Elf32_Shdr	*lookupShdr(Wave *, char *);
static int		readObject(Segment *);
static int		readRaw(Segment *);

// Internal variables
//
static char *		romImage;   // Pointer to the accumulated rom image
static int		cryptRomBoot(Wave *);
static int 		getSymbolValue(char *name, unsigned long *value);


////////////////////////////////////////////////////////////////////////////////
// scanSegments()
//
// For each segment in a spec file,
//   Examine the segment and compute the important information about it.
//   This info includes size, its "after" status, and sometimes the
//     alignment.  
//   Keep a running total of the size, and at the end malloc() all the
//     space which should be necessary for the ROM image.
//
int scanSegments(void) {
    Segment *s;
    unsigned int offset = SizeofEntryRoutine;  // offset = size of ROM image.
    int rom_size;

    // Check to be sure ELF version is current
    //
    if (elf_version(EV_CURRENT) == EV_NONE) {
	fprintf(stderr, "makerom: out of date\n");
	return(-1);
    }

    // For each segment in the spec file
    //
    for (s = segmentList; s != NULL; s = s->next) {
	
	// Check to make sure the segment is in a wave.
	if (s->wave == (Wave *)NULL) {
	    fprintf(stderr,
		    "makerom: segment \"%s\": not found in any wave\n",
		    s->name);
#if 0
	    return(-1);
#endif
	}
	
	s->romOffset = offset;
	
	// Get size of segment's sections, depending on OBJECT or RAW
	if (s->flags & SEGFLAG_OBJECT) {
	    if (sizeObject(s) == -1)
		return(-1);
	} else if (s->flags & SEGFLAG_RAW) {
	    if (sizeRaw(s) == -1)
		return(-1);
	}
	
	// In case this value was altered (boot segment does this!) we need
	//   to re-set this value.
	offset = s->romOffset;

	// This computes the amount of space this needs to take up on 
	//   the ROM.  That's why it is only text, data, and sdata.
	// This can ignore the alignment issues in code space.
	offset += (s->textSize + s->dataSize + s->sdataSize);

	offset = ALIGNn(s->romalign,offset);
    }
    
    // Ensure that rom size is at least as large as the entry routine
    rom_size = (offset > SizeofEntryRoutine) ? offset : SizeofEntryRoutine;
    
    // Malloc the rom size that we need!!
    // Changed this to a calloc so that rom image would be zeroed
    //   unless data was written into it.
    romImage = (char*) calloc(rom_size,1);
    
    // Fixed by yasu@rd3.nintendo.co.jp */
			    // Check to make sure malloc did not fail.
			    if (NULL == romImage){
				fprintf(stderr, "makerom: malloc failed [RomSize= %d kB]\n",
					(rom_size + 1023) / 1024);
				return(-1);
			    }

    return(0);
}



////////////////////////////////////////////////////////////////////////////////
// sizeObject()
//
// For each file listed in a segment,
//   Examine each section in the file.
//   For particular sections, record the important information about the
//     section.  This important info is usually just size, but sometimes 
//     alignment is also important.
//
static int sizeObject(Segment *s) {
    unsigned int address1, address2;
    int fd;
    Elf *elf;
    Elf_Scn *scn;
    Elf32_Ehdr *ehdr;
    Elf32_Shdr *shdr;
    Path *p;
    size_t index;
    char *sectName;
    int currAddress;
    int firstSection = 1;

    // Initialize this segment's alignment
    // Minimum is 16B alignment.
    s->textAlign = 16;

    // Print out some useful debug info
    //
    if (debug) {
	if ((s->align != 16) && (s->align != 0))
	    printf("Segment %s: alignment %x\n", s->name, s->align);
	if ((s->romalign != 16) && (s->romalign != 0))
	    printf("Segment %s: romalign %x\n", s->name, s->romalign);
    }

    // For each file in the segment
    for (p = s->pathList; p != NULL; p = p->next) {

	// Initialize values
	p->textSize = 0;
	p->dataSize = 0;
	p->sdataSize = 0;
	p->sbssSize = 0;
	p->bssSize = 0;
	p->textAlign = 0;
	p->dataAlign = 0;
	p->sdataAlign = 0;
	p->sbssAlign = 0;
	p->bssAlign = 0;

#ifndef __sgi__
	// need to make a pass over each file with ld to force allocation
	// of common
	{
	char cmd[1024];
	char tmp[] = "/tmp/mkrXXXXXX";
	mktemp(tmp);
	strcpy(cmd, "mips-linux-ld --no-warn-mismatch -non_shared -G 0 -r -d -o ");
	strcat(cmd, tmp);
	strcat(cmd, " ");
	strcat(cmd, p->name);
        execCommand(cmd);
	if ((fd = open(tmp, O_RDONLY)) == -1) {
	    unlink(tmp);
	    fprintf(stderr,
		    "makerom: %s: %s\n",
		    p->name, sys_errlist[errno]);
	    return -1;
	}
	unlink(tmp);
	}
#else
	// Open the file
	if ((fd = open(p->name, O_RDONLY)) == -1) {
	    fprintf(stderr,
		    "makerom: %s: %s\n",
		    p->name, sys_errlist[errno]);
	    return(-1);
	}
#endif
	if (debug)
	    printf("Scanning %s\n", p->name);
	elf = elf_begin(fd, ELF_C_READ, (Elf *)NULL);
	if ((elf_kind(elf) != ELF_K_ELF) ||
	    ((ehdr = elf32_getehdr(elf)) == NULL)) {
	    fprintf(stderr,
		    "makerom: %s: not a valid ELF object file\n", p->name);
	    return(-1);
	}

	// For each section in the file
	for (index = 1; index < ehdr->e_shnum; index++) {
	    if (((scn = elf_getscn(elf, index)) == NULL) ||
		((shdr = elf32_getshdr(scn)) == NULL)) {
		fprintf(stderr,
			"makerom: %s: can't get section index %d\n",
			p->name, index);
		return(-1);
	    }
	    sectName = elf_strptr(elf, ehdr->e_shstrndx,
				  (size_t)shdr->sh_name);
	    
	    if (NULL == sectName){
		fprintf(stderr,
			"makerom: %s: detect unnamed section\n", p->name);
		return(-1);
	    }
	    
	    // Examine and record sizes and characteristics of each particular 
	    //   section in the file.
	    //
	    // As we go through these files, we record the maximum alignment
	    //   in each section in the s->*Align variable.
	    if (strcmp(sectName, ELF_TEXT) == 0) {                    // .text
		s->textSize += shdr->sh_size;
		p->textAlign = shdr->sh_addralign;
		p->textSize = shdr->sh_size;
		p->sectionsExisting |= TEXT_EXISTS;
		s->sectionsExisting |= TEXT_EXISTS;
		if (p->textAlign > s->textAlign)
		    s->textAlign = p->textAlign;
		if (debug) {
		    printf("  text size  = %x\n", shdr->sh_size);
		    printf("       align = %x\n", shdr->sh_addralign);
		}
	    } else if ((strcmp(sectName, ELF_DATA) == 0) ||       // .data & .rodata
		       (strcmp(sectName, ELF_RODATA) == 0)) {
		s->dataSize += shdr->sh_size;
		p->dataAlign = shdr->sh_addralign;
		p->dataSize += shdr->sh_size;
		p->sectionsExisting |= DATA_EXISTS;
		s->sectionsExisting |= DATA_EXISTS;
		if (p->dataAlign > s->dataAlign)
		    s->dataAlign = p->dataAlign;
		if (debug) {
		    printf("  data&rodata size  = %x\n", shdr->sh_size);
		    printf("       align = %x\n", shdr->sh_addralign);
		}
	    } else if (strcmp(sectName, MIPS_SDATA) == 0) {           // .sdata
		s->sdataSize += shdr->sh_size;
		p->sdataAlign = shdr->sh_addralign;
		p->sdataSize = shdr->sh_size;
		s->sectionsExisting |= SDATA_EXISTS;
		p->sectionsExisting |= SDATA_EXISTS;
		if (p->sdataAlign > s->sdataAlign)
		    s->sdataAlign = p->sdataAlign;
		if (debug) {
		    printf("  sdata size  = %x\n", shdr->sh_size);
		    printf("        align = %x\n", shdr->sh_addralign);
		}
	    } else if (strcmp(sectName, MIPS_SBSS) == 0) {            // .sbss
		s->sbssSize += shdr->sh_size;
		p->sbssAlign = shdr->sh_addralign;
		p->sbssSize = shdr->sh_size;
		p->sectionsExisting |= SBSS_EXISTS;
		s->sectionsExisting |= SBSS_EXISTS;
		if (p->sbssAlign > s->sbssAlign)
		    s->sbssAlign = p->sbssAlign;
		if (debug) {
		    printf("  sbss size  = %x\n", shdr->sh_size);
		    printf("       align = %x\n", shdr->sh_addralign);
		}
	    } else if (strcmp(sectName, ELF_BSS) == 0) {              // .bss
		s->bssSize += shdr->sh_size;
		p->bssAlign = shdr->sh_addralign;
		p->bssSize = shdr->sh_size;
		p->sectionsExisting |= BSS_EXISTS;
		s->sectionsExisting |= BSS_EXISTS;
		if (p->bssAlign > s->bssAlign)
		    s->bssAlign = p->bssAlign;
		if (debug) {
		    printf("  bss size  = %x\n", shdr->sh_size);
		    printf("      align = %x\n", shdr->sh_addralign);
		}
	    } 
	}
	close(fd);
    }

    // Now we need to know where this segment intends to start in memory.
    //
    switch (s->addrFunc) {
      case AFTERFUNC_MAX:
	address1 = s->afterSeg1->address + s->afterSeg1->totalSize;
	address2 = s->afterSeg2->address + s->afterSeg2->totalSize;
	currAddress = MAX(address1, address2);
	break;
      case AFTERFUNC_MIN:
	address1 = s->afterSeg1->address + s->afterSeg1->totalSize;
	address2 = s->afterSeg2->address + s->afterSeg2->totalSize;
	currAddress = MIN(address1, address2);
	break;
      case AFTERFUNC_UNARY:
	address1 = s->afterSeg1->address + s->afterSeg1->totalSize;
	currAddress = address1;
	break;
      case ADDRFUNC_ADDRESS:
	currAddress = s->address;
	break;
      case ADDRFUNC_SEGMENT:
	currAddress = s->address;
	break;
      default:
	break;
    }

    // This will align the top of the segment to some address specified
    //   in the spec file.  By default, if nothing was specified in spec,
    //   this value will be 16.
    currAddress = ALIGNn(s->align, currAddress);

    // Just in case there are no recognizable sections in this segment,
    //   we'll set up the starting address for this segment to be the
    //   address we're currently at.  That'll keep us from erroring out.
    s->address = currAddress;

    // This is IMPORTANT!  If the top address of this segment has been
    //   adjusted, and it is the boot segment, the top of the segment
    //   in the rom file must also be adjusted.  Otherwise, when the 
    //   first MB of the rom file is loaded into RDRAM, the entry point
    //   indicated by the boot stub will be incorrect!
    // Another addition: Be sure to align the boot segment in the rom
    //   by the align keyword if it is used!  This is important since the 
    //   first segment is DMA'd into RAM automatically at x400.
    if (s->flags & SEGFLAG_BOOT) {

	currAddress = ALIGNn(s->textAlign, currAddress);
	s->romOffset = ALIGNn(s->textAlign, s->romOffset);
	s->romOffset = ALIGNn(s->align, s->romOffset);
    }

    // Now loop through and do some address computation.
    //

    // Text sections
    if (s->sectionsExisting & TEXT_EXISTS) {
	// Align top of output section to max align of 
	//   text sections (in case > 16)
	currAddress = ALIGNn(s->textAlign, currAddress);
	s->textStart = currAddress;
	s->address = currAddress;
	firstSection = 0;

	for (p=s->pathList; p!=NULL; p=p->next) {
	    if (p->sectionsExisting & TEXT_EXISTS) {
		currAddress = ALIGNn(p->textAlign, currAddress);
		p->textStart = currAddress;
		currAddress += p->textSize;
	    }
	}
    } else {
	s->textStart = currAddress;
    }

    // Data sections
    if (s->sectionsExisting & DATA_EXISTS) {
	// Align top of output section to max align of 
	//   data sections (in case > 16)
	currAddress = ALIGNn(s->dataAlign, currAddress);
	s->dataStart = currAddress;
	if (firstSection) {
	    s->address = currAddress;
	    firstSection = 0;
	}
	for (p=s->pathList; p!=NULL; p=p->next) {
	    if (p->sectionsExisting & DATA_EXISTS) {
		currAddress = ALIGNn(p->dataAlign, currAddress);
		p->dataStart = currAddress;
		currAddress += p->dataSize;
	    }
	}
    } else {
	s->dataStart = currAddress;
    }

    // Sdata sections
    if (s->sectionsExisting & SDATA_EXISTS) {

	// Align top of output section to max align of 
	//   sdata sections (in case > 16)
	currAddress = ALIGNn(s->sdataAlign, currAddress);
	s->sdataStart = currAddress;
	if (firstSection) {
	    s->address = currAddress;
	    firstSection = 0;
	}
	for (p=s->pathList; p!=NULL; p=p->next) {
	    if (p->sectionsExisting & SDATA_EXISTS) {
		currAddress = ALIGNn(p->sdataAlign, currAddress);
		p->sdataStart = currAddress;
		currAddress += p->sdataSize;
	    }
	}
    } else {
	s->sdataStart = currAddress;
    }

    // Sbss sections
    if (s->sectionsExisting & SBSS_EXISTS) {

	// Align top of output section to max align of 
	//   sbss sections (in case > 16)
	currAddress = ALIGNn(s->sbssAlign, currAddress);
	s->sbssStart = currAddress;
	if (firstSection) {
	    s->address = currAddress;
	    firstSection = 0;
	}
	for (p=s->pathList; p!=NULL; p=p->next) {
	    if (p->sectionsExisting & SBSS_EXISTS) {
		currAddress = ALIGNn(p->sbssAlign, currAddress);
		p->sbssStart = currAddress;
		currAddress += p->sbssSize;
	    }
	}
    } else {
	s->sbssStart = currAddress;
    }

    // Bss sections
    if (s->sectionsExisting & BSS_EXISTS) {
	
	// Align top of output section to max align of 
	//   bss sections (in case > 16)
	currAddress = ALIGNn(s->bssAlign, currAddress);
	s->bssStart = currAddress;
	if (firstSection) {
	    s->address = currAddress;
	    firstSection = 0;
	}
	for (p=s->pathList; p!=NULL; p=p->next) {
	    if (p->sectionsExisting & BSS_EXISTS) {
		currAddress = ALIGNn(p->bssAlign, currAddress);
		p->bssStart = currAddress;
		currAddress += p->bssSize;
	    }
	}
    } else {
	s->bssStart = currAddress;
    }

    s->textSize  = s->dataStart - s->address;
    s->dataSize  = s->sdataStart - s->dataStart;
    s->sdataSize = s->sbssStart - s->sdataStart;
    s->sbssSize  = s->bssStart - s->sbssStart;
    s->bssSize   = currAddress - s->bssStart;

    s->totalSize = currAddress - s->address;

    return(0);
}


////////////////////////////////////////////////////////////////////////////////
// sizeRaw()
//
// For each file in the segment
//   Open the file and determine its size.  Add its size
//     to the totalSize for this segment.
//
static int sizeRaw(Segment *s) {
    unsigned int address1, address2;
    unsigned int currAddress;
    int		fd;
    Path		*p;
    struct stat	statBuffer;

    // Minimum data align value
    //
    s->dataAlign = 16;
    s->sectionsExisting = DATA_EXISTS;

    for (p = s->pathList; p != NULL; p = p->next) {

	// Initialize values
	p->textSize = 0;
	p->dataSize = 0;
	p->sdataSize = 0;
	p->sbssSize = 0;
	p->bssSize = 0;
	p->textAlign = 0;
	p->dataAlign = 16;
	p->sdataAlign = 0;
	p->sbssAlign = 0;
	p->bssAlign = 0;
	p->sectionsExisting = DATA_EXISTS;

	if ((fd = open(p->name, O_RDONLY)) == -1) {
	    fprintf(stderr,
		    "makerom: %s: %s\n",
		    p->name, sys_errlist[errno]);
	    return(-1);
	}
	if (fstat(fd, &statBuffer) == -1) {
	    fprintf(stderr, "makerom: lstat failed: %s\n",
		    sys_errlist[errno]);
	    return(-1);
	}
	s->dataSize  += statBuffer.st_size;

	close(fd);
    }

    // Align the data size to a multiple of 16B.
    s->totalSize = s->dataSize = ALIGN128(s->dataSize);

    // Now we need to know where this segment intends to start in memory.
    //
    switch (s->addrFunc) {
      case AFTERFUNC_MAX:
	address1 = s->afterSeg1->address + s->afterSeg1->totalSize;
	address2 = s->afterSeg2->address + s->afterSeg2->totalSize;
	currAddress = MAX(address1, address2);
	break;
      case AFTERFUNC_MIN:
	address1 = s->afterSeg1->address + s->afterSeg1->totalSize;
	address2 = s->afterSeg2->address + s->afterSeg2->totalSize;
	currAddress = MIN(address1, address2);
	break;
      case AFTERFUNC_UNARY:
	address1 = s->afterSeg1->address + s->afterSeg1->totalSize;
	currAddress = address1;
	break;
      case ADDRFUNC_ADDRESS:
	currAddress = s->address;
	break;
      case ADDRFUNC_SEGMENT:
	currAddress = s->address;
	break;
      default:
	break;
    }

    // This will align the top of the segment to some address specified
    //   in the spec file.  By default, if nothing was specified in spec,
    //   this value will be 16.
    currAddress = ALIGNn(s->align, currAddress);

    // NOTE: Since the file is never actually looked at for ELF info, we don't
    //   worry about the specified data alignment.  However, let's do an align
    //   by the default, anyway.
    currAddress = ALIGNn(s->dataAlign, currAddress);

    // Set the segment starting address to our "alignment-modified" version.
    s->address = currAddress;

    return(0);
}


////////////////////////////////////////////////////////////////////////////////
// checkSizes()
//
//
//
int checkSizes(void) {
    Segment *s;
    int sizeViolation = 0;
    
    for (s = segmentList; s != NULL; s = s->next) {
	
	if ((s->flags & SEGFLAG_BOOT) &&
	    ((s->textSize + s->dataSize + s->sdataSize) > MAX_BOOTSIZE)) {
	    fprintf(stderr,
		    "makerom: segment \"%s\" (text+data) size ",
		    s->name);
	    fprintf(stderr, "(%d+%d) = %d (0x%x)\n         ",
		    s->textSize, s->dataSize + s->sdataSize,
		    s->textSize + s->dataSize + s->sdataSize,
		    s->textSize + s->dataSize + s->sdataSize);
	    fprintf(stderr,
		    "exceeds maximum BOOT segment size %d (0x%x)\n",
		    MAX_BOOTSIZE, MAX_BOOTSIZE);
	    sizeViolation = 1;
	}
	
	if (s->totalSize > s->maxSize) {
	    fprintf(stderr, "makerom: segment \"%s\" (text+data+bss) size ",
		    s->name);
	    fprintf(stderr, "(%d+%d+%d) = %d (0x%x)\n         ",
		    s->textSize,
		    s->dataSize + s->sdataSize,
		    s->bssSize + s->sbssSize,
		    s->totalSize, s->totalSize);
	    fprintf(stderr,
		    "exceeds given maximum segment size %d (0x%x)\n",
		    s->maxSize, s->maxSize);
	    sizeViolation = 1;
	}
    }

    if (sizeViolation)
	return(-1);
    else
	return(0);

}



////////////////////////////////////////////////////////////////////////////////
// checkOverlaps()
//
//
//
int checkOverlaps(void) {
    Wave *w;
    SegmentChain *sc, *tc;
    Segment *s, *t;
    int isOverlap = 0;
    
    for (w = waveList; w != (Wave *)NULL; w = w->next) {
	for (sc = w->segmentChain; sc != NULL; sc = sc->next) {
	    for (tc = sc->next; tc != NULL; tc = tc->next) {
		s = sc->segment;
		t = tc->segment;
		if ((IS_KSEGDM(s->address)) &&
		    (IS_KSEGDM(t->address)) &&
		    ((KDM_TO_PHYS(s->address) + s->totalSize)
		     > KDM_TO_PHYS(t->address)) &&
		    ((KDM_TO_PHYS(t->address) + t->totalSize)
		     > KDM_TO_PHYS(s->address))) {
		    fprintf(stderr,
			    "makerom: segment \"%s\" [0x%x, 0x%x) overlaps with\n",
			    s->name, s->address, s->address + s->totalSize);
		    fprintf(stderr,
			    "         segment \"%s\" [0x%x, 0x%x)\n",
			    t->name, t->address, t->address + t->totalSize);
		    fprintf(stderr, "         in wave \"%s\"\n", w->name);
		    isOverlap =1;
		}
	    }
	}
    }
    return(isOverlap);
}


////////////////////////////////////////////////////////////////////////////////
// createSegmentSymbols()
//
// The "offset" variable used in here is 0 unless set with -O option.
//
int createSegmentSymbols(char *source, char *object) {
    FILE	*f;
    Segment	*s;
    char	*cmd;
    
    if ((f = fopen(source, "w")) == NULL) {
	fprintf(stderr, "makerom: %s: cannot create\n", source);
	return(-1);
    }
    
    for (s = segmentList; s != NULL; s = s->next) {
	fprintf(f, ".globl _%sSegmentRomStart; ", s->name);
	fprintf(f, "_%sSegmentRomStart = 0x%08x\n",
		s->name, s->romOffset + RAMROM_GAME_OFFSET + offset);
	fprintf(f, ".globl _%sSegmentRomEnd; ", s->name);
	fprintf(f, "_%sSegmentRomEnd = 0x%08x\n", s->name,
		s->romOffset + RAMROM_GAME_OFFSET + offset + 
		s->textSize + s->dataSize + s->sdataSize);
	
	if (s->flags & SEGFLAG_OBJECT) {
	    fprintf(f, ".globl _%sSegmentStart; ", s->name);
	    fprintf(f, "_%sSegmentStart = 0x%08x\n",
		    s->name, s->address);
	    
	    /*
	     * text section
	     */
	    fprintf(f, ".globl _%sSegmentTextStart; ", s->name);
	    fprintf(f, "_%sSegmentTextStart = 0x%08x\n",
		    s->name, s->textStart);
	    fprintf(f, ".globl _%sSegmentTextEnd; ", s->name);
	    fprintf(f, "_%sSegmentTextEnd = 0x%08x\n",
		    s->name,
		    s->textStart + s->textSize);

	    /*
	     * data section
	     */
	    fprintf(f, ".globl _%sSegmentDataStart; ", s->name);
	    fprintf(f, "_%sSegmentDataStart = 0x%08x\n",
		    s->name,
		    s->dataStart);
	    fprintf(f, ".globl _%sSegmentDataEnd; ", s->name);
	    fprintf(f, "_%sSegmentDataEnd = 0x%08x\n",
		    s->name,
		    s->dataStart + s->dataSize + s->sdataSize);

	    /*
	     * bss section
	     */
	    fprintf(f, ".globl _%sSegmentBssStart; ", s->name);
	    fprintf(f, "_%sSegmentBssStart = 0x%08x\n",
		    s->name,
		    s->sbssStart);
	    fprintf(f, ".globl _%sSegmentBssEnd; ", s->name);
	    fprintf(f, "_%sSegmentBssEnd = 0x%08x\n",
		    s->name,
		    s->sbssStart + s->sbssSize + s->bssSize);
	    
	    fprintf(f, ".globl _%sSegmentEnd; ", s->name);
	    fprintf(f, "_%sSegmentEnd = 0x%08x\n",
		    s->name,
		    s->bssStart + s->bssSize);

	} /* if (s->flags & SEGFLAG_OBJECT) */

    } /* for (s = segmentList; s != NULL; s = s->next) */
    
    fclose(f);
    
    if ((cmd = (char *)malloc(sysconf(_SC_ARG_MAX))) == NULL) {
	fprintf(stderr, "malloc failed\n");
	return(-1);
    }
#ifdef __sgi__
    strcpy(cmd, "$TOOLROOT/usr/bin/cc -c -non_shared -o ");
#else
    strcpy(cmd, "mips-linux-gcc -c -non_shared -o ");
#endif
    strcat(cmd, object);
    strcat(cmd, " ");
    strcat(cmd, source);
    
    if (debug)
	printf("  %s\n", cmd);
    
    return(execCommand(cmd));
}


////////////////////////////////////////////////////////////////////////////////
// createRomImage()
//
// object == entry object filename
//
int createRomImage(char *romFile, char *object) {
    FILE		*f;
    Segment	*s;
    ptrdiff_t	bootStack;
    char		*sectName;
    size_t	romSize;
    int		fd;
    Elf		*elf;
    Elf32_Ehdr 	*ehdr;
    Elf_Scn	*scn;
    Elf32_Shdr	*shdr;
    int		index;
    int		end;
    int 		i;
    char 		*fillbuffer;
    Wave		*wave;
    
    // Open the entry object
    // Find the TEXT section of the entry object, do some checking
    //   to make sure it is the proper size.
    // Copy the entry object's text section into the beginning of
    //   the rom image.
    //
    if ((fd = open(object, O_RDONLY)) == -1) {
	fprintf(stderr,
		"makerom: %s: %s\n",
		object, sys_errlist[errno]);
	return(-1);
    }
    elf = elf_begin(fd, ELF_C_READ, (Elf *)NULL);
    ehdr = elf32_getehdr(elf);
    for (index = 1; index < ehdr->e_shnum; index++) {
	scn = elf_getscn(elf, index);
	shdr = elf32_getshdr(scn);
	sectName = elf_strptr(elf,ehdr->e_shstrndx,(size_t)shdr->sh_name);
	if (strcmp(sectName, ELF_TEXT) == 0)
	    break;
    }
    if (shdr->sh_size > SizeofEntryRoutine) {
	fprintf(stderr, "makerom: entr size %d is larger than %d\n", 
		shdr->sh_size, SizeofEntryRoutine);
	return(-1);
    }
    if (lseek(fd, shdr->sh_offset, SEEK_SET) == -1) {
	fprintf(stderr, "makerom: lseek of entry section failed\n");
	return(-1);
    }
    if (read(fd, romImage, shdr->sh_size) != shdr->sh_size) {
	fprintf(stderr, "makerom: read of entry section failed\n");
	return(-1);
    }
    
    // Open all of the a.outs, giving them both a
    // file descriptor and an Elf descriptor.
    //
    if (openAouts())
	return(-1);
    
    // Read all the a.outs
    for (s = segmentList; s != NULL; s = s->next) {
	if (s->flags & SEGFLAG_OBJECT)
	    readObject(s);
	else if (s->flags & SEGFLAG_RAW)
	    readRaw(s);
	
	romSize = s->romOffset +
	    s->textSize + s->dataSize + s->sdataSize;
    }
    
    
    /*
     * 起動ゲームの場合、LeoBootGame 関数を探し出して
     * 暗号化する
     */
    if (booter)
    {
	for (wave = waveList; wave != (Wave *)NULL; wave = wave->next)
	    if (cryptRomBoot(wave))
	    {
		return(-1);
	    }
    }
    
    //
    // Should close up all of the file and Elf descriptors,
    // but we're almost ready to exit, so skip it.
    //
    
    // Open rom file
    if ((f = fopen(romFile, "w+")) == NULL) {
	fprintf(stderr, "makerom: %s: %s\n",
		romFile, sys_errlist[errno]);
	return(-1);
    }

    // If offset set, seek to a position after the offset.
    // If not set, offset value is 0.
    if (offset != 0)
	if (fseek(f, offset, SEEK_SET) != 0) {
	    fprintf(stderr, "makerom: %s: fseek error (%s)\n",
		    romFile, sys_errlist[errno]);
	    return(-1);
	} 

    // Write out the headerBuf
    if (fwrite(headerBuf, sizeof(char), headerWordAlignedByteSize, f) != headerWordAlignedByteSize) {
	fprintf(stderr, "makerom: %s: write error\n", romFile);
	return(-1);
    }

    // Seek to byte 8
    if (fseek(f, RAMROM_BOOTADDR_OFFSET + offset, SEEK_SET) != 0) {
	fprintf(stderr, "makerom: %s: fseek error (%s)\n",
		romFile, sys_errlist[errno]);
	return(-1);
    }
    // Write the boot address (4 bytes) to the rom file
    bootAddress=htonl(bootAddress);
    if (fwrite(&bootAddress, sizeof(int), 1, f) != 1) {
	fprintf(stderr, "makerom: %s: write error\n", romFile);
	return(-1);
    }

    // Seek to byte x40 (x400 for HW1)
    if (fseek(f, RAMROM_BOOTSTRAP_OFFSET + offset, SEEK_SET) != 0) {
	fprintf(stderr, "makerom: %s: fseek error (%s)\n",
		romFile, sys_errlist[errno]);
	return(-1);
    }
    // Write bootbuf to rom file
    if (fwrite(bootBuf, sizeof(char), bootWordAlignedByteSize, f) != bootWordAlignedByteSize) {
	fprintf(stderr, "makerom: %s: write error\n", romFile);
	return(-1);
    }

    // Seek and write pif2boot to rom file if HW1
#ifdef _HW_VERSION_1
    if (fseek(f, RAMROM_PIF2BOOTSTRAP_OFFSET + offset, SEEK_SET) != 0) {
	fprintf(stderr, "makerom: %s: fseek error (%s)\n",
		romFile, sys_errlist[errno]);
	return(-1);
    }
    if (fwrite(pif2bootBuf, sizeof(char), pif2bootWordAlignedByteSize, f) != pif2bootWordAlignedByteSize) {
	fprintf(stderr, "makerom: %s: write error\n", romFile);
	return(-1);
    }
#else

    if (nofont == 0) {
	// Seek to byte xb70
	if (fseek(f, RAMROM_FONTDATA_OFFSET + offset, SEEK_SET) != 0) {
	    fprintf(stderr, "makerom: %s: fseek error (%s)\n",
		    romFile, sys_errlist[errno]);
	    return(-1);
	}
	// Write fontBuf to rom file
	if (fwrite(fontBuf, sizeof(char), fontdataWordAlignedByteSize, f) != fontdataWordAlignedByteSize) {
	    fprintf(stderr, "makerom: %s: write error\n", romFile);
	    return(-1);
	}
    }
#endif /* _HW_VERSION_1 */

    // Seek to byte x1000 (x2000 for HW1)
    if (fseek(f, RAMROM_GAME_OFFSET + offset, SEEK_SET) != 0) {
	fprintf(stderr, "makerom: %s: fseek error (%s)\n",
		romFile, sys_errlist[errno]);
	return(-1);
    }
    // Write romImage to rom file
    if (fwrite(romImage, sizeof(char), romSize, f) != romSize) {
	fprintf(stderr, "makerom: %s: write error\n", romFile);
	return(-1);
    }
    
    // Fill rom file with fill bytes if requested
    end = romSize + RAMROM_GAME_OFFSET + offset;
    finalromSize *= (0x100000/8);
    if ((finalromSize != 0) && ( finalromSize > end)) {
	if ((fillbuffer = (char *)malloc(FILLBUFFER)) == NULL) {
	    fprintf(stderr, "malloc failed\n");
	    return(-1);
	}
	for (i = 0; i < FILLBUFFER; i++)
	    *(fillbuffer + i) = fillData;
	while (end < finalromSize) {
	    if ((finalromSize - end) > FILLBUFFER){
		if (fwrite(fillbuffer, sizeof(char), 
			   FILLBUFFER, f) != FILLBUFFER){
		    fprintf(stderr, "makerom: %s: write error %x\n",
			    romFile, end);
		    return(-1);
		}
		end += FILLBUFFER;
	    } else {
		if (fwrite(fillbuffer, sizeof(char), 
			   (finalromSize - end), f) != (finalromSize - end)){
		    fprintf(stderr, "makerom: %s: write error\n",
			    romFile);
		    return(-1);
		}
		end += (finalromSize - end);
	    }
	    
	}
    }
    
    return(0);
}


////////////////////////////////////////////////////////////////////////////////
// openAouts()
//
// For each wave, open the generated a.out file and use it to create the
//   Rom later on.
//
static int openAouts(void) {
    Wave *wave;
    char gcordFileBuf[256];
    
    // For each wave in the spec file.
    //
    for (wave = waveList; wave != (Wave *)NULL; wave = wave->next) {
	if ( gcord )
	    strcat( strcpy( gcordFileBuf, wave->name ), ".cord" );
	else
	    strcpy( gcordFileBuf, wave->name );
	
	if ((wave->fd = open(wave->name, O_RDONLY)) == -1) {
	    fprintf(stderr,
		    "makerom: %s: %s\n",
		    wave->name, sys_errlist[errno]);
	    return(-1);
	}
	wave->elf = elf_begin(wave->fd, ELF_C_READ, (Elf *)NULL);
	if ((elf_kind(wave->elf) != ELF_K_ELF) ||
	    ((wave->ehdr = elf32_getehdr(wave->elf)) == NULL)) {
	    fprintf(stderr,
		    "makerom: %s: not a valid ELF object file\n",
		    wave->name);
	    return(-1);
	}
    }
    return(0);
}


////////////////////////////////////////////////////////////////////////////////
// lookupSymbol()
//
//
//
static void *lookupSymbol(Wave *wave, char *name) {
    Elf_Scn *scn;
    Elf32_Shdr *shdr;
    Elf_Data *data;
    Elf32_Sym *sym;
    size_t index;
    int i, count;
    
    for (index = 1; index < wave->ehdr->e_shnum; index++) {
	if (((scn = elf_getscn(wave->elf, index)) == NULL) ||
	    ((shdr = elf32_getshdr(scn)) == NULL)) {
	    return(NULL);
	}
	if (shdr->sh_type != SHT_SYMTAB)
	    continue;
	data = (Elf_Data *)NULL;
	if ((data = elf_getdata(scn, data)) == NULL)
	    return(NULL);
	count = data->d_size/sizeof(Elf32_Sym);
	sym = (Elf32_Sym *)data->d_buf;
	sym++;		/* first symbol is for undefined */
	for (i = 1; i < count; i++) {
	    if (strcmp(name,
		       elf_strptr(wave->elf, shdr->sh_link, sym->st_name))
		== 0)
		return((void *)sym->st_value);
	    sym++;
	}
    }
    return(NULL);
}


////////////////////////////////////////////////////////////////////////////////
// lookupShdr()
//
//
//
static Elf32_Shdr *lookupShdr(Wave *wave, char *segSectName) {
    Elf_Scn *scn;
    Elf32_Shdr *shdr;
    size_t index;
    char *sectName;
    
    for (index = wave->searchIndex; index < wave->ehdr->e_shnum; index++) {
	if (((scn = elf_getscn(wave->elf, index)) == NULL) ||
	    ((shdr = elf32_getshdr(scn)) == NULL)) {
	    fprintf(stderr,
		    "makerom: %s: can't get section index %d\n",
		    wave->name, index);
	    return(NULL);
	}
	sectName = elf_strptr(wave->elf, wave->ehdr->e_shstrndx,
			      (size_t)shdr->sh_name);
	if (strcmp(sectName, segSectName) == 0)
	    break;
    }
    if (index < wave->ehdr->e_shnum) {
	wave->searchIndex = index + 1;
	return(shdr);
    }

    for (index = 1; index < wave->searchIndex; index++) {
	if (((scn = elf_getscn(wave->elf, index)) == NULL) ||
	    ((shdr = elf32_getshdr(scn)) == NULL)) {
	    fprintf(stderr,
		    "makerom: %s: can't get section index %d\n",
		    wave->name, index);
	    return(NULL);
	}
	sectName = elf_strptr(wave->elf, wave->ehdr->e_shstrndx,
			      (size_t)shdr->sh_name);
	if (strcmp(sectName, segSectName) == 0)
	    break;
    }
    if (index >= wave->searchIndex) {
	fprintf(stderr, "makerom: %s: cannot find %s section\n",
		wave->name, segSectName);
	return(NULL);
    }

    wave->searchIndex = index + 1;
    return(shdr);

}


////////////////////////////////////////////////////////////////////////////////
// readObject()
//
// Reads the good stuff out of an a.out and stores it in the proper
//   position in the romImage memory buffer.
//
static int readObject(Segment *s) {
    char		*segSectName;
    Elf32_Shdr	*shdr;
    
    if ((segSectName = (char *)malloc(strlen(s->name)+9)) == NULL) {
	fprintf(stderr, "malloc failed\n");
	return(-1);
    }
    
    // read in the text
    //
    sprintf(segSectName, ".%s.text", s->name);
    if ((shdr = lookupShdr(s->wave, segSectName)) == NULL)
	return(-1);
    
    if (shdr->sh_size != s->textSize) {
	fprintf(stderr,
		"makerom: %s: section size for %s does not match input section sizes\n",
		s->wave->name, segSectName);
	fprintf(stderr, 
		"makerom:   shdr = %d, textSize = %d\n", shdr->sh_size, s->textSize);
	free(segSectName);
	return(-1);
    }
    
    if (lseek(s->wave->fd, shdr->sh_offset, SEEK_SET) == -1) {
	fprintf(stderr, "makerom: %s: seek to section %s failed\n",
		s->wave->name, segSectName);
	free(segSectName);
	return(-1);
    }
    if (read(s->wave->fd, romImage + s->romOffset,
	     shdr->sh_size) != shdr->sh_size) {
	fprintf(stderr, "makerom: %s: read of section %s failed\n",
		s->wave->name, segSectName);
	free(segSectName);
	return(-1);
    }
    
    // read in the (large) data
    //
    sprintf(segSectName, ".%s.data", s->name);
    if ((shdr = lookupShdr(s->wave, segSectName)) == NULL)
	return(-1);
    if (shdr->sh_size != s->dataSize) {
	fprintf(stderr,
		"makerom: %s: section size for %s does not match input section sizes\n",
		s->wave->name, segSectName);
	fprintf(stderr, "large data failed\n");
	fprintf(stderr, "%s, file large=%x, our dataSize=%x\n",s->name,
		shdr->sh_size, s->dataSize);
	free(segSectName);
	return(-1);
    }
    if (lseek(s->wave->fd, shdr->sh_offset, SEEK_SET) == -1) {
	fprintf(stderr, "makerom: %s: seek to section %s failed\n",
		s->wave->name, segSectName);
	free(segSectName);
	return(-1);
    }
    if (read(s->wave->fd, romImage + s->romOffset + s->textSize,
	     shdr->sh_size) != shdr->sh_size) {
	fprintf(stderr, "makerom: %s: read of section %s failed\n",
		s->wave->name, segSectName);
	free(segSectName);
	return(-1);
    }
    
#ifdef __sgi__
    // read in the small data
    //
    sprintf(segSectName, ".%s.sdata", s->name);
    if ((shdr = lookupShdr(s->wave, segSectName)) == NULL)
	return(-1);
    if (shdr->sh_size != s->sdataSize) {
	fprintf(stderr,
		"makerom: %s: section size for %s does not match input section sizes\n",
		s->wave->name, segSectName);
	fprintf(stderr, "small data failed\n");
	free(segSectName);
	return(-1);
    }
    if (lseek(s->wave->fd, shdr->sh_offset, SEEK_SET) == -1) {
	fprintf(stderr, "makerom: %s: seek to section %s failed\n",
		s->wave->name, segSectName);
	free(segSectName);
	return(-1);
    }
    if (read(s->wave->fd,
	     romImage + s->romOffset + s->textSize + s->dataSize,
	     shdr->sh_size) != shdr->sh_size) {
	fprintf(stderr, "makerom: %s: read of section %s failed\n",
		s->wave->name, segSectName);
	free(segSectName);
	return(-1);
    }
#endif
    
    free(segSectName);
    return(0);
}


////////////////////////////////////////////////////////////////////////////////
// readRaw()
//
//
//
static int readRaw(Segment *s) {
    Path *p;
    int fd;
    unsigned int offset;
    off_t fileSize, totalSize = 0;
    struct stat statBuffer;
    
    offset = s->romOffset;
    
    for (p = s->pathList; p != NULL; p = p->next) {
	if ((fd = open(p->name, O_RDONLY)) == -1) {
	    fprintf(stderr, "makerom: %s: %s\n",
		    p->name, sys_errlist[errno]);
	    return(-1);
	}
	if (fstat(fd, &statBuffer) == -1) {
	    fprintf(stderr, "makerom: lstat failed: %s\n",
		    sys_errlist[errno]);
	    return(-1);
	}
	fileSize = statBuffer.st_size;
	totalSize += fileSize;
	if (totalSize > s->dataSize) {
	    fprintf(stderr, "makerom: %s: segment size changed\n",
		    s->name);
	    return(-1);
	}
	if (read(fd, romImage + offset, fileSize) != fileSize) {
	    fprintf(stderr, "makerom: %s: read failed (%s)\n",
		    p->name, sys_errlist[errno]);
	    return(-1);
	}
	close(fd);
	offset += fileSize;
    }
    return(0);
}


////////////////////////////////////////////////////////////////////////////////
// createEntryFile()
//
// This is called after the linking stage and fmulmul has been checked.
// Therefore the entry point symbol address is created by looking at the
//   linked ELF file.
//
int createEntryFile(char *source, char *object) {
    Segment 	*s;
    FILE		*f;
    char		*cmd;
    char		*segSectName;
    void 		*BssStart;
    struct Wave_s	*wave;
    void 		*bootEntry = NULL, *bootStack = NULL;
    char		romsymbol[14] = "__osFinalrom";
#ifndef __sgi__
    unsigned		bssSize;
#endif
    
    // Open up file to put source into.
    if ((f = fopen(source, "w")) == NULL) {
	fprintf(stderr, "makerom: %s: cannot create\n", source);
	return(-1);
    }
    
    // Look for the boot segment
    for (s = segmentList; s != NULL; s = s->next) {
	if (s->flags & SEGFLAG_BOOT) {
	    wave = s->wave;
	    if ((wave->fd = open(wave->name, O_RDONLY)) == -1) {
		fprintf(stderr,
			"makerom: %s: %s\n",
			wave->name, sys_errlist[errno]);
		return(-1);
	    }
	    wave->elf = elf_begin(wave->fd, ELF_C_READ, (Elf *)NULL);
	    if ((elf_kind(wave->elf) != ELF_K_ELF) ||
		((wave->ehdr = elf32_getehdr(wave->elf)) == NULL)) {
		fprintf(stderr,
			"makerom: %s: not a valid ELF object file\n",
			wave->name);
		return(-1);
	    }
	    if (finalromSize != 0) {
		if (lookupSymbol(s->wave,romsymbol) == NULL){
		    fprintf(stderr,
			    "makerom: use libultra_rom.a to build real game cassette\n");
		    return(-1);
		}
	    }

	    // Find the boot entry point address
	    if (bootEntryName != NULL) {
		bootEntry = lookupSymbol(s->wave, 
					 bootEntryName); 
		if (bootEntry == NULL) {
		    fprintf(stderr,
			    "makerom: %s: cannot find entry symbol %s\n",
			    s->wave->name, bootEntryName);
		    return(-1);
		}
	    }

	    // Find the boot stack address
	    if (bootStackName != (char *)NULL) {
		if ((bootStack =
		     lookupSymbol(s->wave, bootStackName)) == NULL) {
		    fprintf(stderr,
			    "makerom: %s: cannot find stack symbol %s\n",
			    s->wave->name, bootStackName);
		    return(-1);
		}
	    } else {
		bootStack = 0;
	    }
	    bootStack = (void *) ((ptrdiff_t)bootStack +
				  bootStackOffset);
	    
	    // find Bss address
	    /*
	     * 下記のルーチンは絶対に変更しないでください
	     * (if (bootEntry) の終りまで)
	     * DD のプログラムで、ドライブが挿さっているかの
	     * 判断に使用されます。
	     */
	    if (s->bssSize > 0 && (cosim == 0)) {
		if ((segSectName = (char *)malloc(strlen(s->name)+16+1)) == NULL) {
		    fprintf(stderr, "malloc failed\n");
		    return(-1);
		}
		sprintf(segSectName, "_%sSegmentBssStart", s->name);
		BssStart = lookupSymbol(s->wave, segSectName);
		fprintf(f, " la	$8, 0x%x\n", BssStart);
#ifdef __sgi__
		fprintf(f, " li	$9, 0x%x\n", s->bssSize);
#else
		/* gcc doesn't force allocation of common symbols until
		 * linking, so bssSize isn't correct.  Compute it instead.
		 */
		sprintf(segSectName, "_%sSegmentBssEnd", s->name);
		bssSize = lookupSymbol(s->wave, segSectName) - BssStart;
		fprintf(f, " li	$9, 0x%x # 0x%x\n", bssSize&~7, s->bssSize + s->sbssSize);
#endif
		fprintf(f, "1:\n");
		fprintf(f, " sw $0, 0($8)\n");
		fprintf(f, " sw $0, 4($8)\n");
		fprintf(f, " addi $8, 8\n");
		fprintf(f, " addi $9, 0xfff8\n");
		fprintf(f, " bne  $9, $0, 1b\n");
#ifndef __sgi__
		if (bssSize & 7)
		    fprintf(f, " sw $0, 0($8)\n");
#endif
	    }
	    if (bootStack)
		fprintf(f, " la	$29, 0x%x\n", bootStack);
	    if (bootEntry) {
		fprintf(f, " la $10, 0x%x\n", bootEntry);
		fprintf(f, " j $10\n");
	    }
	}
    }
    free(segSectName);
    fclose(f);
    
    // Compile the entry point source code
    if ((cmd = (char *)malloc(sysconf(_SC_ARG_MAX))) == NULL) {
	fprintf(stderr, "malloc failed\n");
	return(-1);
    }
#ifdef __sgi__
    strcpy(cmd, "$TOOLROOT/usr/bin/cc -c -non_shared -o ");
#else
    strcpy(cmd, "mips-linux-gcc -c -non_shared -o ");
#endif
    strcat(cmd, object);
    strcat(cmd, " ");
    strcat(cmd, source);
    
    if (debug) {
	printf("Compiling entry source file\n");
	printf("  %s\n", cmd);
    }

    return(execCommand(cmd));
}


////////////////////////////////////////////////////////////////////////////////
// ALIGNn()
//
// Given a number of bytes n and an alignment value romalign, return the number
//   of bytes which indicates the romalign-aligned size of the n-byte buffer.
//
unsigned int ALIGNn(unsigned int romalign, int n) {
    if(romalign == 0) 
	romalign = 16;
    return (((n + (romalign-1))/romalign)*romalign);
}

/*
 * 同じ定義が bootdisk.c にもあるので、必ず同じ値にしておくこと
 */
#define BOOT1_SIZE	0x344  		/* __LeoBootGame2 のサイズ */
#define BOOT2_SIZE	0x50		/* __LeoBootGame3 のサイズ */

int cryptRomBoot(Wave *wave)
{
    Segment	*s;
    char	string[255];
    void 	*addr, *currSegmentStartAddr, *currSegmentEndAddr;
    void	*segmentRomStart;
    char	*romAddr, *seedAddr;
    char 	*tmpdir;
    int		result, i;
    char	seed;
    static int	isCrypted = 0;

    /*
     * すでに一度暗号化していれば、リターンする
     */
    if(isCrypted)
	return 0;
    
    isCrypted = 1;
    
    // Choose the temporary directory.
    // "/tmp", or TMPDIR if set.
    //
    if ((tmpdir = getenv("TMPDIR")) ==  NULL)
	tmpdir = "/tmp";
    
    /*
     * 後にシンボルの値を入手するため、nm の出力をファイルに落としておく
     */
    sprintf(string, "gnm -Bvx %s > %s/grepResultXXXXX", wave->name, tmpdir);
    result = execCommand(string);
    if(result)
    {
	fprintf(stderr, "error occurred\n");
	return(-1);
    }
    
    /*
     * __LeoBootGame2 がどこにあるかを入手
     */
    result = getSymbolValue("__LeoBootGame2", (u32 *)&addr);
    if(result == 1)
    {
	/* __LeoBootGame2 がないので、そのままリターン */
	return 0;
    }
    else if (result == -1)
    {
	return (-1);
    }
    
    /*
     * __LeoBootGame2 のアドレスを暗号鍵にする。
     */
    seed = ( ( ( (long)addr & 0xff000000 ) >> 24 ) + 
	    ( ( (long)addr & 0x00ff0000 ) >> 16 ) + 
	    ( ( (long)addr & 0x0000ff00 ) >> 8 ) + 
	    ( ( (long)addr & 0x000000ff ) ) ) & 0xff;
    
    /*
     * __LeoBootGame2 はどのセグメントにあるかを調べる
     */
    for (s = segmentList; s != NULL; s = s->next)
    {
	sprintf(string, "_%sSegmentStart", s->name);
	result = getSymbolValue(string, (u32 *)&currSegmentStartAddr);
	if(result)
	{
	    fprintf(stderr, "makerom: get symbol failed\n");
	    return (-1);
	}

	sprintf(string, "_%sSegmentEnd", s->name);
	result = getSymbolValue(string, (u32 *)&currSegmentEndAddr);
	if(result)
	{
	    fprintf(stderr, "makerom: get symbol failed\n");
	    return (-1);
	}

	if ( ((u32)currSegmentStartAddr <= (u32)addr) &&
	    ((u32)addr <= (u32)currSegmentEndAddr) )
	{
	    break;
	}
	
    }

    sprintf(string, "_%sSegmentRomStart", s->name);
    result = getSymbolValue(string, (u32 *)&segmentRomStart);
    if(result)
    {
	fprintf(stderr, "makerom: get symbol failed\n");
	return (-1);
    }

    romAddr = romImage +
	( (u32)segmentRomStart + ((u32)addr - (u32)currSegmentStartAddr) )
	    - (RAMROM_GAME_OFFSET + offset);
    
    /*
     * 実際にエンクリプトをする
     */
    for(i = 0; i < BOOT1_SIZE; i += 4)
    {
	romAddr[2] += seed;
	romAddr[3] -= seed;
	romAddr += 4;
    }
    
    /*
     * __LeoBootGame3 がどこにあるかを入手
     */
    result = getSymbolValue("__LeoBootGame3", (u32 *)&addr);
    if(result)
    {
	fprintf(stderr, "makerom: get symbol failed\n");
	return (-1);
    }
    
    romAddr = romImage +
	( (u32)segmentRomStart + ((u32)addr - (u32)currSegmentStartAddr) )
	    - (RAMROM_GAME_OFFSET + offset);
    
    /*
     * 実際にエンクリプトをする
     */
    for(i = 0; i < BOOT2_SIZE; i += 4)
    {
	romAddr[2] += seed;
	romAddr[3] -= seed;
	romAddr += 4;
    }

    sprintf(string, "%s/grepResultXXXXX", tmpdir);
    unlink(string);

    return 0;
    

} /* cryptRomBoot() */


static int getSymbolValue(char *name, unsigned long *val)
{
    char	string[255];
    char	fileName[255];
    int		result;
    FILE	*f;
    char	value[11];
    void 	*addr;
    char 	*tmpdir;
    int		status;
    
    // Choose the temporary directory.
    // "/tmp", or TMPDIR if set.
    //
    if ((tmpdir = getenv("TMPDIR")) ==  NULL)
	tmpdir = "/tmp";
    
    sprintf(string, "grep %s %s/grepResultXXXXX > %s/grep1LineXXXXX",
	    name, tmpdir, tmpdir);
    status = system(string);
    
    if (status == -1) {
	fprintf(stderr, "makedisk: cannot execute grep\n");
	return(-1);
    } else if ( !(WIFEXITED(status) && (WEXITSTATUS(status) == 0)) ) {
	return(1);	/* grep failed */
    }
    
    sprintf(fileName, "%s/grep1LineXXXXX", tmpdir);
    if ((f = fopen(fileName, "r")) == NULL) {
	fprintf(stderr, "makerom: grep file: cannot open\n");
	unlink(fileName);
	return(-1);
    }
    
    if (fread(value, sizeof(char), 8, f) != 8) {
	fprintf(stderr,"makerom: grep file: read error \n");
	fclose(f);
	unlink(fileName);
	return(-1);
    }
    
    value[8] = 0;
    
    fclose(f);
    
    *val = (unsigned long)strtoul(value, (char **)NULL, 16);

    unlink(fileName);
    
    return 0;
    
}