rsp2elfm.cxx 24.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
#include <string.h>
#include <fstream.h>
#include <elf.h>
#include <symconst.h>
#include <ctype.h>
#include <netinet/in.h>

#if defined( MSDOS )
#include <dir.h>
#include <io.h>
#else
#include <unistd.h>
#endif

#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>

#include "rsp2elf.h"

char filenamebuf[256], exenamebuf[256];
ifstream IMEMfile, DMEMfile, symFile, lineFile;
ofstream ELFfile;
int padOutputSections;
int stringTableSize, symStrings, sectStrings;
long stringTableOffset;
long shStringTableOffset;
long sectionTableOffset;
long textSectionOffset;
int textSectionSize;
long dataSectionOffset;
int dataSectionSize;
long symbolTableOffset;
int symbolTableSize;
extern long debugInfoOffset;
extern int debugInfoSize;
extern unsigned long codeBase;
int textName, stringName, dataName, symtName, shstName, mdebName;
int hasData, hasMain, hasLineInfo;
int fileGlobals, labelCount;
int relocatableOutput, verbose;
char * cwd;
char hostName[32];
struct stat IMEMstat;
int includeConstants, simplified, constants = 0;

/*
	sections:
	abs	rel	descr
	0	0	null
	1	1	text section
	2	2	data section (maybe)
	3	-	debug section
	4	3	string tab
	5	4	sym tab
	6	5	section hdr string tab
	7	6	section table
*/

#define TEXT_SECT 1
#define DATA_SECT 2
#define STRING_SECT 4

symbol * symTable, * symLast;
char symbuffer[256];

/************************************************************************
Function: nospace
Args: none
Type: void
Purpose: This function complains about the inability to obtain memory
	and dies.
************************************************************************/
void nospace( void )
{
	cerr << "PANIC: Out of memory" << endl;
	exit( 1 );
}

/************************************************************************
Function: NewSymbol
Args:
	char * name - The name of the symbol to be added.
	unsigned long value - The value associated with the symbol.
	int type - The symbol type (label, constant, etc.)
Type: int - returns 1 if symbol added, 0 if dup
Purpose: This function adds a new entry into the symbol table. It is
	called by the functions that read the .sym and .dbg files.
	Note that the symbol table isn't; it's just a linked list
	with records added to the end. We do not allow duplicate
	symbols, however, so processing will grow slower as the size
	of the list grows...
************************************************************************/
int NewSymbol( char * name, unsigned long value, int type )
{
	symbol * sym;

	/* Search the list to see if it is there... */

	sym = symTable;
	while ( sym )
		if ( sym->matches( name ) )
			return 0;
		else
			sym = sym->next;

	/* OK, it's not there */

        sym = new symbol( name, value, type );
	if ( !symTable )
		symTable = symLast = sym;
	else
	{
		symLast->next = sym;
		symLast = sym;
	}
	++fileGlobals;
        if ( type == stLabel )
	{
		++labelCount;
		AddSymToFile( sym );
	}
	else if ( type == stConstant )
		++constants;
        return 1;
}

/************************************************************************
Function: CleanupSymTab
Args: none
Type: void
Purpose: This function simply walks the symbol table after the file table
	has been built and assigns file numbers to each symbol. (They should
	all be proc symbols at this point.)
************************************************************************/
void CleanupSymTab( void )
{
	symbol * sym = symTable;

	while ( sym )
	{
		sym->AsgFile();
		sym = sym->next;
	}
}

/************************************************************************
Function: NoDots
Args: char * s - A string to purge of dots and other nonsense
Type: void
Purpose: This function walks a string and replaces any chars that are
	not either letters or numbers with underscores. This makes them C
	legal - useful for the Text and BSS symbols made from filenames.
************************************************************************/
static void NoDots( char * s )
{
	char c;

    while ( c = *s )
	{
		if ( !isalnum( c ) )
			*s = '_';
		++s;
	}
}

/************************************************************************
Function: CreateFileSymbols
Args: char * s - pointer used in building names
Type: void
Purpose: This function synthesizes symbols for a relocatabale ucode file
	such that the ucode can be accessed by a C program.
************************************************************************/
void CreateFileSymbols( char * s )
{
	char * name;

	NewSymbol( ".text", 0, STT_SECTION );
	NewSymbol( ".data", 0, STT_SECTION );

	strcpy( s, "TextStart" );
	if ( (name = (char *) malloc( strlen( filenamebuf ) + 1 )) == 0 )
		nospace();
	strcpy( name, filenamebuf );
	NoDots( name );
	NewSymbol( name, 0, STT_OBJECT );

	strcpy( s, "TextEnd" );
	if ( (name = (char *) malloc( strlen( filenamebuf ) + 1 )) == 0 )
		nospace();
	strcpy( name, filenamebuf );
	NoDots( name );
	NewSymbol( name, textSectionSize, STT_OBJECT );

	strcpy( s, "DataStart" );
	if ( (name = (char *) malloc( strlen( filenamebuf ) + 1 )) == 0 )
		nospace();
	strcpy( name, filenamebuf );
	NoDots( name );
	NewSymbol( name, 0, STT_OBJECT );

	strcpy( s, "DataEnd" );
	if ( (name = (char *) malloc( strlen( filenamebuf ) + 1 )) == 0 )
		nospace();
	strcpy( name, filenamebuf );
	NoDots( name );
	NewSymbol( name, dataSectionSize, STT_OBJECT );
}

/************************************************************************
Function: ReadSymbols
Args: none
Type: void
Purpose: This function reads the symbol file (.dbg) and adds the
	symbols found there to the symbol table. When done, it synthesizes
	a proc name symbol and places it at the head of the list (yes,
	it needs to be first). This symbol is named main if there was no
	user defined main symbol. If there was a user defined main, then
	it is called __IMEM. If there is already a proc symbol in the
	symbol table for a user-defined label, it is skipped by AddSymbol.
************************************************************************/
void ReadSymbols( void )
{
	register char * s, *symName;
	symbol * sym;
	int symLength;
	unsigned long symValue;

	symFile.open( filenamebuf, ios::in );
	if ( symFile.fail() )
	{
		cerr << "WARNING: Can't open debug symbol file " <<
			filenamebuf << endl;
		return;
	}
	while ( symFile.getline( symbuffer, 256 ) != NULL )
	{
		if ( !(s = strchr( symbuffer, ' ' )) )
			continue;	/* bad record */
		symLength = s - symbuffer;
		if ( (symName = (char *) malloc( symLength + 1 )) == NULL )
			nospace();
		strncpy( symName, symbuffer, symLength );
		symName[symLength] = 0;
		if ( !strcmp( symName, "main" ) )
			++hasMain;
		while ( *s == ' ' )
			++s;
		if ( *s == '\n' || *s == 0 )	/* uh-oh */
			symValue = 0L;
		else
		{
			symValue = strtoul( s, (char **) NULL, 16 );
			if ( symValue < DMEM_START )
				symValue += IMEM_START;
		}
		NewSymbol( symName, symValue, stLabel );
	}

	/* Add main/start symbol to head of list */

	if ( simplified )
	{
		sym = new symbol( hasMain ? (char *)"__IMEM" : (char*)"main", codeBase, stProc );
		sym->AsgSymIndex( 1 );
		sym->next = symTable;
		symTable = sym;
		++fileGlobals;
	}
}
void DumpSymbols( void )
{
	symbol * sym;

	cout << "Symbol table:" << endl;
	sym = symTable;
	while ( sym )
	{
        	sym->print();
		sym = sym->next;
	}
}
/************************************************************************
Function: WriteString
Args: char * s - The string to write (what else?)
Type: void
Purpose: This function writes a string to the ELF file and increments
	the global stringTableSize variable. This global variable is
	cleared at the start of every table. Thus, checking it before
	calling WriteString always returns the index of the string in
	the table. Note that this function writes a zero byte in the
	file after every string. Thus calling it with the null string
	("", not 0) results in writing one zero byte into the file.
************************************************************************/
void WriteString( char * s )
{
	char c;

	stringTableSize += (strlen( s ) + 1);
	while ( c = *s++ )
		ELFfile.put( c );
	ELFfile.put( c );	/* a null, too */
}
/************************************************************************
Function: WriteELFHeader
Args: none
Type: void
Purpose: This function writes the ELF header at the very beginning of
	the ELF file. Some of the information is not yet available
	since this gets called very early in the program. Those variables
	are fixed up later when their values become known.
************************************************************************/
void WriteELFHeader( void )
{
	register int i;
	Elf32_Ehdr header;

	header.e_ident[0] = 0x7f;
	strcpy( (char *) &header.e_ident[1], "ELF" );
	header.e_ident[4] = 1;	/* 32 bit */
	header.e_ident[5] = 2;	/* MS bit */
	header.e_ident[6] = 1;	/* version */
	for ( i = 7; i < 16; ++i )
		header.e_ident[i] = 0;
	if ( relocatableOutput )
	{
		header.e_phoff = 0;
		header.e_type = htons(ET_REL);
		header.e_phnum = 0;
		header.e_phentsize = 0;
		header.e_shnum = htons(hasData ? 6 : 5);
	}
	else
	{
		header.e_phoff = htonl(sizeof( Elf32_Ehdr ));
		header.e_type = htons(ET_EXEC);
		header.e_phnum = htons(hasData ? 2 : 1);
		header.e_phentsize = htonl(sizeof( Elf32_Phdr ));
		header.e_shnum = htons(hasData ? 7 : 6);
	}
	header.e_machine = htons(EM_MIPS);
	header.e_version = htonl(EV_CURRENT);
	header.e_entry = htonl(codeBase);
	header.e_shoff = 0x0;	/* fix up later */
#ifdef __linux__
	header.e_flags = htonl(0x20000101);	/* noabi MIPS-3, 32bitmode */
#else
	header.e_flags = htonl(0x10000000);	/* MIPS-2 */
#endif
	header.e_ehsize = htons(sizeof( Elf32_Ehdr ));
	header.e_shentsize = htons(sizeof( Elf32_Shdr ));
	header.e_shstrndx = htons(ntohs(header.e_shnum) - 1);
	ELFfile.write( (char *) &header, sizeof( Elf32_Ehdr ) );
	if ( ELFfile.fail() )
		cerr << "Write failed in WriteElfHeader" << endl;
}

/************************************************************************
Function: WriteProgramHeader
Args: none
Type: void
Purpose: This function writes the program header table into the ELF
	file. There will be either one or two entries in this table.
	There is always an executable, but there is only a data entry
	if there was a .dat file.
************************************************************************/
void WriteProgramHeader( void )
{
	Elf32_Phdr header;

	header.p_type = htonl(PT_LOAD);
	header.p_vaddr = header.p_paddr = htonl(0x4001000);
	header.p_filesz = 0;	/* don't know yet */
	header.p_memsz = htonl(4096);
	header.p_flags = htonl(PF_X | PF_R);
	header.p_align = htonl(4);
	ELFfile.write( (char *) &header, sizeof( Elf32_Phdr ) );
	if ( ELFfile.fail() )
        	cerr << "Write failed in WriteProgHeader" << endl;
	if ( hasData )
	{
		header.p_type = htonl(PT_LOAD);
		header.p_vaddr = header.p_paddr = htonl(DMEM_START);
		header.p_filesz = 0;	/* don't know yet */
		header.p_memsz = htonl(4096);
		header.p_flags = htonl(PF_W | PF_R);
		header.p_align = htonl(4);
		ELFfile.write( (char *) &header, sizeof( Elf32_Phdr ) );
		if ( ELFfile.fail() )
        		cerr << "Write failed in WriteProgHeader" << endl;
	}
}

/************************************************************************
Function: WriteTextSection
Args: none
Type: void
Purpose: This function copies the .out file to the .text section of
	the ELF file.
************************************************************************/
void WriteTextSection( void )
{
	int c;

	textSectionOffset = ELFfile.tellp();
	cout << "Writing Text section at offset " << hex <<
		textSectionOffset << endl;
	while ( (c = IMEMfile.get()) != EOF )
	{
		ELFfile.put( c );
		++textSectionSize;
	}
	if ( padOutputSections )
		while ( textSectionSize & 0xf )
		{
			++textSectionSize;
			ELFfile.put( 0 );
		}
}

/************************************************************************
Function: WriteDataSection
Args: none
Type: void
Purpose: This function copies the .dat file to the .data section of
	the ELF file.
************************************************************************/
void WriteDataSection( void )
{
	int c;

	dataSectionOffset = ELFfile.tellp();
	cout << "Writing Data section at offset " << hex <<
		dataSectionOffset << endl;
	while ( (c = DMEMfile.get()) != EOF )
	{
		ELFfile.put( c );
		++dataSectionSize;
	}
	if ( padOutputSections )
		while ( dataSectionSize & 0xf )
		{
			++dataSectionSize;
			ELFfile.put( 0 );
		}
}

/************************************************************************
Function: WriteShStringTable
Args: none
Type: void
Purpose: This function writes the string table for the section headers
	to the ELF file.
************************************************************************/
void WriteShStringTab( void )
{
	stringTableSize = 0;
	shStringTableOffset = ELFfile.tellp();
	cout << "Writing shString table at offset " << hex <<
		shStringTableOffset << endl;
	WriteString( "" );
	textName = stringTableSize;
	WriteString( ".text" );
	dataName = stringTableSize;
	WriteString( ".data" );
	mdebName = stringTableSize;
	WriteString( ".mdebug" );
	stringName = stringTableSize;
	WriteString( ".strtab" );
	symtName = stringTableSize;
	WriteString( ".symtab" );
	shstName = stringTableSize;
	WriteString( ".shstrtab" );
	while ( stringTableSize & 3 )
		WriteString( "" );	/* should be even */
	sectStrings = stringTableSize;
}

/************************************************************************
Function: WriteSymbolTable
Args: none
Type: void
Purpose: This function writes the symbol table to the ELF file. The
	debugger does not use this information (or so it seems), but
	someone might. Also, it lets elfdump work on these files.
************************************************************************/
void WriteSymbolTable( void )
{
	Elf32_Sym header;
	int symCount = 1;
	symbol * sym;

	stringTableSize = 0;
	stringTableOffset = ELFfile.tellp();
	cout << "Writing String table at offset " << hex <<
		stringTableOffset << endl;
	WriteString( "" );

	sym = symTable;
	while ( sym )
	{
		sym->AsgGlobalIndex( stringTableSize );
		WriteString( sym->NameIs() );
		sym = sym->next;
	}

	/* Close out the string table */

	WriteString( "" );
	while ( stringTableSize & 3 )
		WriteString( "" );	/* should be even */
	symStrings = stringTableSize;

	symbolTableOffset = ELFfile.tellp();
	cout << "Writing Symbol table at offset " << hex <<
		symbolTableOffset << endl;
	
	/* Write out 0 symbol */

	header.st_name = 0;
	header.st_value = 0;
	header.st_size = 0;
	header.st_info = 0;
	header.st_other = 0;
	header.st_shndx = htons(SHN_UNDEF);
	ELFfile.write( (char *) &header, sizeof( Elf32_Sym ) );
	if ( ELFfile.fail() )
		cerr << "Write failed in WriteSymTab" << endl;

	sym = symTable;
	while ( sym )
	{
		header.st_name = htonl(sym->GetGlobalIndex());
		header.st_value = htonl(sym->GetValue());
		header.st_size = 0;
		if ( relocatableOutput )
		{
			if ( sym->GetType() == STT_SECTION )
				header.st_info = (STB_LOCAL << 4) +
					ELF32_ST_TYPE(STT_SECTION);
			else switch ( symCount )
			{
			case 3:
				header.st_size = htonl(textSectionSize);
			case 4:
				header.st_info = (STB_GLOBAL << 4) + 
					ELF32_ST_TYPE(STT_FUNC);
				break;

			case 5:
				header.st_size = htonl(dataSectionSize);
			case 6:
				header.st_info = (STB_GLOBAL << 4) +
					ELF32_ST_TYPE(STT_OBJECT);
				break;

			default:
				cout << "Unexpected object at sym " << symCount
					<< endl;
			}
			header.st_shndx = htons(symCount > 4 ? DATA_SECT : TEXT_SECT);
		}
		else
		{
			header.st_info = (STB_GLOBAL << 4) + (sym->GetType() ==
				stConstant ? ELF32_ST_TYPE(STT_NOTYPE) :
				ELF32_ST_TYPE(STT_FUNC));
			header.st_shndx = htons(TEXT_SECT);
		}
		header.st_other = 0;
		ELFfile.write( (char *) &header, sizeof( Elf32_Sym ) );
		if ( ELFfile.fail() )
			cerr << "Write failed in WriteSymTab" << endl;
		++symCount;
		sym = sym->next;
	}
	symbolTableSize = symCount * sizeof( Elf32_Sym );
}

/************************************************************************
Function: WriteSectionHeader
Args: none
Type: void
Purpose: This function writes the section header table to the ELF file.
************************************************************************/
void WriteSectionHeader( void )
{
	Elf32_Shdr header;

	sectionTableOffset = ELFfile.tellp();
	cout << "Writing Section table at offset " << hex <<
		sectionTableOffset << endl;

	/* section 0 */

	header.sh_name = 0;
	header.sh_type = htonl(SHT_NULL);
	header.sh_flags = 0;
	header.sh_addr = 0;
	header.sh_offset = 0;
	header.sh_size = 0;
	header.sh_link = htonl(SHN_UNDEF);
	header.sh_info = 0;
	header.sh_addralign = 0;
	header.sh_entsize = 0;
	ELFfile.write( (char *) &header, sizeof( Elf32_Shdr ) );
	if ( ELFfile.fail() )
		cerr << "Write failed in WriteSectHdr" << endl;

	/* text section */

	header.sh_name = htonl(textName);
	header.sh_type = htonl(SHT_PROGBITS);
	header.sh_flags = htonl(SHF_ALLOC + SHF_EXECINSTR);
	header.sh_addr = htonl(codeBase);
	header.sh_offset = htonl(textSectionOffset);
	header.sh_size = htonl(textSectionSize);
	header.sh_link = htonl(SHN_UNDEF);
	header.sh_info = 0;
	if ( relocatableOutput )
		header.sh_addralign = htonl(16);
	else
		header.sh_addralign = htonl(4);
	header.sh_entsize = 0;
	ELFfile.write( (char *) &header, sizeof( Elf32_Shdr ) );
	if ( ELFfile.fail() )
		cerr << "Write failed in WriteSectHdr" << endl;

	/* optional data section */

	if ( hasData )
	{
		header.sh_name = htonl(dataName);
		header.sh_type = htonl(SHT_PROGBITS);
		header.sh_flags = htonl(SHF_ALLOC + SHF_WRITE);
		header.sh_addr = htonl(relocatableOutput ? 0 : DMEM_START);
		header.sh_offset = htonl(dataSectionOffset);
		header.sh_size = htonl(dataSectionSize);
		header.sh_link = htonl(SHN_UNDEF);
		header.sh_info = 0;
		if ( relocatableOutput )
			header.sh_addralign = htonl(16);
		else
			header.sh_addralign = htonl(4);
		header.sh_entsize = 0;
		ELFfile.write( (char *) &header, sizeof( Elf32_Shdr ) );
		if ( ELFfile.fail() )
			cerr << "Write failed in WriteSectHdr" << endl;
	}

	/* debug section */

	if ( !relocatableOutput )
	{
		header.sh_name = htonl(mdebName);
		header.sh_type = htonl(0x70000005);
		header.sh_flags = 0;
		header.sh_addr = 0;
		header.sh_offset = htonl(debugInfoOffset);
		header.sh_size = htonl(debugInfoSize);
		header.sh_link = htonl(SHN_UNDEF);
		header.sh_info = 0;
		header.sh_addralign = 0;
		header.sh_entsize = 0;
		ELFfile.write( (char *) &header, sizeof( Elf32_Shdr ) );
		if ( ELFfile.fail() )
			cerr << "Write failed in WriteSectHdr" << endl;
	}

	/* string table section */

	header.sh_name = htonl(stringName);
	header.sh_type = htonl(SHT_STRTAB);
	header.sh_flags = 0;
	header.sh_addr = 0;
	header.sh_offset = htonl(stringTableOffset);
	header.sh_size = htonl(symStrings);
	header.sh_link = htonl(SHN_UNDEF);
	header.sh_info = 0;
	header.sh_addralign = 0;
	header.sh_entsize = 0;
	ELFfile.write( (char *) &header, sizeof( Elf32_Shdr ) );
	if ( ELFfile.fail() )
		cerr << "Write failed in WriteSectHdr" << endl;

	/* symbol table section */

	header.sh_name = htonl(symtName);
	header.sh_type = htonl(SHT_SYMTAB);
	header.sh_flags = 0;
	header.sh_addr = 0;
	header.sh_offset = htonl(symbolTableOffset);
	header.sh_size = htonl(symbolTableSize);
	if ( relocatableOutput )
	{
		header.sh_link = htonl(hasData ? 3 : 2);
		header.sh_info = htonl(3);
	}
	else
	{
		header.sh_link = htonl(hasData ? STRING_SECT : STRING_SECT - 1);
		header.sh_info = htonl(1);
	}
	header.sh_addralign = 0;
	header.sh_entsize = htonl(sizeof( Elf32_Sym ));
	ELFfile.write( (char *) &header, sizeof( Elf32_Shdr ) );
	if ( ELFfile.fail() )
		cerr << "Write failed in WriteSectHdr" << endl;

	/* section header string table section */

	header.sh_name = htonl(shstName);
	header.sh_type = htonl(SHT_STRTAB);
	header.sh_flags = 0;
	header.sh_addr = 0;
	header.sh_offset = htonl(shStringTableOffset);
	header.sh_size = htonl(sectStrings);
	header.sh_link = htonl(SHN_UNDEF);
	header.sh_info = 0;
	header.sh_addralign = 0;
	header.sh_entsize = 0;
	ELFfile.write( (char *) &header, sizeof( Elf32_Shdr ) );
	if ( ELFfile.fail() )
		cerr << "Write failed in WriteSectHdr" << endl;
}

void usage( void )
{
	cerr << "usage: rsp2elf [-c] [-s] [-r] filename" << endl;
	cerr << "\t-c\tinclude reg names as constants" << endl;
	cerr << "\t-r\tmake a relocatable for makerom" << endl;
	cerr << "\t-s\tplace all labels in synthesized proc" << endl;
	cerr << endl << "Do not use any other options with -r" << endl;
	cerr << "Output file filename.o if -r specified, filename.tvd otherwise"
		<< endl;
	exit( 1 );
}

int main( int argc, char ** argv )
{
	register char *s;

	cout << endl << "rspasm to ELF Converter V0.8" << endl;
#if !defined( MSDOS )
	gethostname( hostName, 32 );
#endif
	cwd = getcwd( NULL, 1024 );
	if ( argc < 2 )
		usage();
	--argc;
	++argv;
	while ( argc )
	{
		if ( argv[0][0] == '-' )
		{
			if ( argv[0][1] == 'c' )
				++includeConstants;
			else if ( argv[0][1] == 'p' )
				++padOutputSections;
			else if ( argv[0][1] == 'r' )
				++relocatableOutput;
			else if ( argv[0][1] == 's' )
				++simplified;
			else if ( argv[0][1] == 'v' )
				++verbose;
			else
				usage();
			--argc;
			++argv;
		}
		else
			break;	// sorry, this is positional
	}
	if ( !argc )
		usage();
	if ( strlen( argv[0] ) > 250 )
	{
		cerr << "Try using a shorter name, please..." << endl;
		exit( 1 );
	}
	strcpy( exenamebuf, argv[0] );

	/*
		We will try to be very tolerant of file names here,
		because there are so many choices of how names are
		used. We must deal with the following possibilities:

		Option		Exe	Others
		(none)		a.out	a.out.dbg, etc.
		-o fred		fred	fred.dbg, etc.
		ren f => f.out	f.out	f.dbg, etc.
	*/

	strcpy( filenamebuf, exenamebuf );
	if( s = strrchr( filenamebuf, '.' ) )
	{
		if ( !strcmp( s, ".out" ) )
		{
			if ( strcmp( exenamebuf, "a.out" ) )
				*s = 0;
		}
	}

	cout << "Opening IMEM image " << exenamebuf << endl;
	s = filenamebuf + strlen( filenamebuf );
        IMEMfile.open( exenamebuf, ios::in );
	if ( IMEMfile.fail() )
	{
		cerr << "Can't open IMEM file " << exenamebuf << endl;
		exit( 1 );
	}
	if ( stat( exenamebuf, &IMEMstat ) == -1 )
		cerr << "Couldn't stat file " << exenamebuf << endl;

	if ( relocatableOutput )
		strcpy( s, ".o" );
	else
		strcpy( s, ".tvd" );
	cout << "Creating ELF file " << filenamebuf << endl;
	ELFfile.open( filenamebuf, ios::out 
#ifdef MSDOS
		| ios::binary 
#endif
		);
	if ( ELFfile.fail() )
	{
		cerr << "Can't create " << filenamebuf << endl;
		IMEMfile.close();
		exit( 1 );
	}
#if !defined( MSDOS )
	chmod( filenamebuf, 0755 );
#endif
	strcpy( s, ".dat" );
        DMEMfile.open( filenamebuf, ios::in );
	if ( DMEMfile.fail() )
	{
		cerr << "WARNING: Can't open DMEM file " << filenamebuf <<
			endl;
	}
	else
		++hasData;

	strcpy( s, ".sym" );
        lineFile.open( filenamebuf, ios::in );
	if ( lineFile.fail() )
	{
		cerr << "WARNING: Can't open line file " << filenamebuf <<
			endl;
	}
	else if ( !relocatableOutput )
	{
		++hasLineInfo;
		BuildFileTable();
		CleanupSymTab();	/* add file numbers */
	}

	if ( relocatableOutput )
		codeBase = 0;
	else
		codeBase += IMEM_START;
	strcpy( s, ".dbg" );
	if ( !relocatableOutput )
	{
		cout << "Reading symbols" << endl;
		ReadSymbols();
	}
	cout << "Code base for this build was " << hex << codeBase << endl;
	if ( !relocatableOutput )
		CleanupInfo();
	WriteELFHeader();
	if ( !relocatableOutput )
		WriteProgramHeader();
	WriteTextSection();
	if ( hasData )
		WriteDataSection();
	if ( relocatableOutput )
		CreateFileSymbols( s );
	if ( verbose )
		DumpSymbols();
	strcpy( s, ".s" );	/* for debug info */
	if ( simplified )
		AddSyntheticProc();
	if ( !relocatableOutput )
		WriteDebugInfo();
	WriteSymbolTable();
	WriteShStringTab();
	WriteSectionHeader();
	if ( verbose )
		DumpFileTable();

	/* fix up ptr to section table */

	ELFfile.seekp( 32L );
	long tmp = htonl(sectionTableOffset);
	ELFfile.write( (char *) &tmp, 4 );
	if ( ELFfile.fail() )
        	cerr << "Write failed during fixup" << endl;

	/* fix up loadable image size */

	if ( !relocatableOutput )
	{
		ELFfile.seekp( sizeof( Elf32_Ehdr ) + 4L );
		tmp = htonl(textSectionOffset);
		ELFfile.write( (char *) &tmp, 4 );
		if ( ELFfile.fail() )
        		cerr << "Write failed during fixup" << endl;
		ELFfile.seekp( sizeof( Elf32_Ehdr ) + 16L );
		tmp = htonl(textSectionSize);
		ELFfile.write( (char *) &tmp, 4 );
		if ( ELFfile.fail() )
        		cerr << "Write failed during fixup" << endl;
		if ( hasData )
		{
			ELFfile.seekp( sizeof( Elf32_Ehdr ) +
				sizeof( Elf32_Phdr ) + 4L );
			tmp = htonl(dataSectionOffset);
			ELFfile.write( (char *) &tmp, 4 );
			if ( ELFfile.fail() )
        			cerr << "Write failed during fixup" << endl;
			ELFfile.seekp( sizeof( Elf32_Ehdr ) +
				sizeof( Elf32_Phdr ) + 16L );
			tmp = htonl(dataSectionSize);
			ELFfile.write( (char *) &tmp, 4 );
			if ( ELFfile.fail() )
        			cerr << "Write failed during fixup" << endl;
		}
	}

	ELFfile.close();
	IMEMfile.close();
	DMEMfile.close();
	lineFile.close();
	return 0;
}