forked from alexfru/SmallerC
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsmlrl.c
3961 lines (3564 loc) · 113 KB
/
smlrl.c
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
/*
Copyright (c) 2014-2021, Alexey Frunze
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*****************************************************************************/
/* */
/* Smaller C linker */
/* */
/* A simple linker for Smaller C compiler and NASM */
/* */
/* Consumes ELF32 x86 object files produced with NASM */
/* */
/* Produces: */
/* - 16/32-bit DOS executables */
/* (tiny model/.COM, small model/.EXE, */
/* huge model/.EXE, unreal model/.EXE, */
/* 32-bit DPMI/.EXE) */
/* - 32-bit PE/Windows executables */
/* - 32-bit ELF/Linux executables */
/* - 32-bit Mach-O/Mac OS X executables */
/* - 32-bit OMAGIC a.out executables */
/* - 16/32-bit flat executables */
/* */
/* Main file */
/* */
/*****************************************************************************/
#ifndef __SMALLER_C__
#include <limits.h>
#include <stdarg.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#else
#ifndef __SMALLER_C_32__
#error must be compiled for 32-bit or huge mode(l)
#endif
#define NULL 0
typedef void FILE;
#define EOF (-1)
#define SEEK_SET 0
#define SEEK_CUR 1
#define SEEK_END 2
#define CHAR_BIT 8
#define INT_MAX 0x7FFFFFFF
#define LONG_MAX 0x7FFFFFFF
typedef unsigned size_t;
char* strtok(char*, char*);
unsigned long strtoul(char*, char**, int);
void qsort(void*, size_t, size_t, int (*)(void*, void*));
#define EXIT_FAILURE 1
void exit(int);
size_t strlen(char*);
int strcmp(char*, char*);
int strncmp(char*, char*, size_t);
char* strncpy(char*, char*, size_t);
void* memmove(void*, void*, size_t);
void* memcpy(void*, void*, size_t);
void* memset(void*, int, size_t);
int memcmp(void*, void*, size_t);
FILE* fopen(char*, char*);
int fclose(FILE*);
int fgetc(FILE*);
int puts(char*);
int sprintf(char*, char*, ...);
//int vsprintf(char*, char*, va_list);
int vsprintf(char*, char*, void*);
int printf(char*, ...);
int fprintf(FILE*, char*, ...);
//int vprintf(char*, va_list);
int vprintf(char*, void*);
size_t fread(void*, size_t, size_t, FILE*);
size_t fwrite(void*, size_t, size_t, FILE*);
int fseek(FILE*, long, int);
long ftell(FILE*);
int remove(char*);
void* malloc(size_t);
void* realloc(void*, size_t);
void free(void*);
#endif
// By default don't support relocations with local symbols
// other than section symbols in DOS huge memory model.
// This is to conserve memory.
#ifndef SUPPORT_LOCAL_RELS
#ifdef __SMALLER_C__
#ifdef __HUGE__
#define SHOULDNT_SUPPORT_LOCAL_RELS
#endif
#endif
#ifndef SHOULDNT_SUPPORT_LOCAL_RELS
#define SUPPORT_LOCAL_RELS
#endif
#endif // SUPPORT_LOCAL_RELS
typedef unsigned char uchar, uint8;
typedef signed char schar, int8;
typedef unsigned short ushort, uint16;
typedef short int16;
#ifndef __SMALLER_C__
#if UINT_MAX >= 0xFFFFFFFF
typedef unsigned uint32;
typedef int int32;
#else
typedef unsigned long uint32;
typedef long int32;
#endif
#else
typedef unsigned uint32;
typedef int int32;
#endif
typedef unsigned uint;
typedef unsigned long ulong;
#ifndef __SMALLER_C_32__
#define C_ASSERT(expr) extern char CAssertExtern[(expr)?1:-1]
C_ASSERT(CHAR_BIT == 8);
C_ASSERT(sizeof(uint16) == 2);
C_ASSERT(sizeof(uint32) == 4);
C_ASSERT(sizeof(size_t) >= 4); // need a 32-bit compiler
#endif
typedef struct
{
uint8 e_ident[16];
#define ELFCLASS32 1
#define ELFDATA2LSB 1
uint16 e_type;
#define ET_REL 1
#define ET_EXEC 2
uint16 e_machine;
#define EM_386 3
uint32 e_version;
#define EV_CURRENT 1
uint32 e_entry;
uint32 e_phoff;
uint32 e_shoff;
uint32 e_flags;
uint16 e_ehsize;
uint16 e_phentsize;
uint16 e_phnum;
uint16 e_shentsize;
uint16 e_shnum;
uint16 e_shstrndx;
#define SHN_UNDEF 0
#define SHN_LORESERVE 0xFF00
#define SHN_COMMON 0xFFF2
} Elf32_Ehdr;
typedef struct
{
uint32 sh_name;
uint32 sh_type;
#define SHT_NULL 0
#define SHT_PROGBITS 1
#define SHT_SYMTAB 2
#define SHT_STRTAB 3
#define SHT_RELA 4
#define SHT_HASH 5
#define SHT_DYNAMIC 6
#define SHT_NOTE 7
#define SHT_NOBITS 8
#define SHT_REL 9
#define SHT_SHLIB 10
#define SHT_DYNSYM 11
uint32 sh_flags;
#define SHF_WRITE 1
#define SHF_ALLOC 2
#define SHF_EXECINSTR 4
uint32 sh_addr;
uint32 sh_offset;
uint32 sh_size;
uint32 sh_link;
uint32 sh_info;
uint32 sh_addralign;
uint32 sh_entsize;
} Elf32_Shd;
typedef struct
{
uint32 st_name;
#define STN_UNDEF 0
uint32 st_value;
uint32 st_size;
uint8 st_info;
#define STB_LOCAL 0
#define STB_GLOBAL 1
#define STB_WEAK 2
#define STT_NOTYPE 0
#define STT_OBJECT 1
#define STT_FUNC 2
#define STT_SECTION 3
#define STT_FILE 4
uint8 st_other;
uint16 st_shndx;
} Elf32_Sym;
typedef struct
{
uint32 r_offset;
uint32 r_info; // bits 0...7: relocation type, bits 8...31: index into the symbol table
// relocation section's sh_link is the section index of the symbol section to use
// relocation section's sh_info is the section index of the code/data section to make relocations in
// symbol section's sh_link is the section index of the string table section containing symbol names
// symbol section's sh_info is the number of all local symblols, others (global, weak, etc) follow local ones
// it's a pity that symbols referring to whole sections can be local and thus I can't simply ignore all
// local symbols
#define R_386_32 1
#define R_386_PC32 2
#define R_386_16 20
#define R_386_PC16 21
} Elf32_Rel;
typedef struct
{
uint32 r_offset;
uint32 r_info;
uint32 r_addend;
} Elf32_Rela;
typedef struct
{
uint32 p_type;
#define PT_NULL 0
#define PT_LOAD 1
#define PT_NOTE 4
#define PT_PHDR 6
uint32 p_offset;
uint32 p_vaddr;
uint32 p_paddr;
uint32 p_filesz;
uint32 p_memsz;
uint32 p_flags;
uint32 p_align;
} Elf32_Phdr;
#ifndef __SMALLER_C__
C_ASSERT(sizeof(Elf32_Ehdr) == 52);
C_ASSERT(sizeof(Elf32_Shd) == 40);
C_ASSERT(sizeof(Elf32_Sym) == 16);
C_ASSERT(sizeof(Elf32_Rel) == 8);
C_ASSERT(sizeof(Elf32_Rela) == 12);
C_ASSERT(sizeof(Elf32_Phdr) == 32);
#endif
typedef struct
{
#define MACH_MAGIC_32 0xfeedface
uint32 magic;
#define MACH_CPU_ARCH_ABI32 0x00000000
#define MACH_CPU_TYPE_I386 0x00000007
#define MACH_CPU_TYPE_X86 (MACH_CPU_ARCH_ABI32 | MACH_CPU_TYPE_I386)
uint32 cputype;
#define MACH_CPU_SUBTYPE_I386_ALL 0x00000003
uint32 cpusubtype;
#define MACH_EXECUTE 0x2
uint32 filetype;
uint32 ncmds;
uint32 sizeofcmds;
#define MACH_NOUNDEFS 0x1
uint32 flags;
} Mach32_Header;
typedef struct
{
#define MACH_LC_SEGMENT 0x1
#define MACH_LC_SYMTAB 0x2
#define MACH_LC_THREAD 0x4
#define MACH_LC_UNIXTHREAD 0x5
uint32 cmd;
uint32 cmdsize;
} Mach32_LoadCmd;
typedef struct
{
uint32 cmd;
uint32 cmdsize;
char segname[16];
uint32 vmaddr;
uint32 vmsize;
uint32 fileoff;
uint32 filesize;
#define MACH_VM_PROT_READ 0x1
#define MACH_VM_PROT_WRITE 0x2
#define MACH_VM_PROT_EXECUTE 0x4
uint32 maxprot;
uint32 initprot;
uint32 nsects;
uint32 flags;
} Mach32_SegmentCmd;
typedef struct
{
char sectname[16];
char segname[16];
uint32 addr;
uint32 size;
uint32 offset;
uint32 align;
uint32 reloff;
uint32 nreloc;
#define S_ATTR_PURE_INSTRUCTIONS 0x80000000
#define S_ATTR_SOME_INSTRUCTIONS 0x400
uint32 flags;
uint32 reserved1;
uint32 reserved2;
} Mach32_Section;
typedef struct
{
uint32 eax;
uint32 ebx;
uint32 ecx;
uint32 edx;
uint32 edi;
uint32 esi;
uint32 ebp;
uint32 esp;
uint32 ss;
uint32 eflags;
uint32 eip;
uint32 cs;
uint32 ds;
uint32 es;
uint32 fs;
uint32 gs;
} Mach32_ThreadState;
typedef struct
{
uint32 cmd; /* MACH_LC_THREAD or MACH_LC_UNIXTHREAD */
uint32 cmdsize; /* total size of this command */
#define MACH_X86_THREAD_STATE 0x1
uint32 flavor; /* flavor of thread state */
uint32 count; /* count of longs in thread state */
Mach32_ThreadState state;
} Mach32_ThreadCmd;
typedef struct
{
uint32 cmd;
uint32 cmdsize;
uint32 symoff;
uint32 nsyms;
uint32 stroff;
uint32 strsize;
} Mach32_SymtabCmd;
typedef struct
{
uint32 n_strx;
#define MACH_N_EXT 0x1
#define MACH_N_ABS 0x2
#define MACH_N_SECT 0xe
uint8 n_type;
uint8 n_sect;
#define MACH_REFERENCE_FLAG_UNDEFINED_NON_LAZY 0x00
#define MACH_REFERENCED_DYNAMICALLY 0x10
int16 n_desc;
uint32 n_value;
} Mach32_Nlist;
typedef struct
{
uint8 Signature[2];
uint16 PartPage;
uint16 PageCnt;
uint16 ReloCnt;
uint16 HdrSize;
uint16 MinAlloc;
uint16 MaxAlloc;
uint16 InitSs;
uint16 InitSp;
uint16 ChkSum;
uint16 InitIp;
uint16 InitCs;
uint16 ReloOff;
uint16 OverlayNo;
uint16 FirstRelo[2];
} tDosExeHeader;
#ifndef __SMALLER_C__
C_ASSERT(sizeof(tDosExeHeader) == 32);
#endif
typedef struct
{
uint16 Machine;
uint16 NumberOfSections;
uint32 TimeDateStamp;
uint32 PointerToSymbolTable;
uint32 NumberOfSymbols;
uint16 SizeOfOptionalHeader;
uint16 Characteristics;
} tPeImageFileHeader;
typedef struct
{
uint32 VirtualAddress;
uint32 Size;
} tPeImageDataDirectory;
typedef struct
{
uint16 Magic;
uint8 MajorLinkerVersion;
uint8 MinorLinkerVersion;
uint32 SizeOfCode;
uint32 SizeOfInitializedData;
uint32 SizeOfUninitializedData;
uint32 AddressOfEntryPoint;
uint32 BaseOfCode;
uint32 BaseOfData;
uint32 ImageBase;
uint32 SectionAlignment;
uint32 FileAlignment;
uint16 MajorOperatingSystemVersion;
uint16 MinorOperatingSystemVersion;
uint16 MajorImageVersion;
uint16 MinorImageVersion;
uint16 MajorSubsystemVersion;
uint16 MinorSubsystemVersion;
uint32 Win32VersionValue;
uint32 SizeOfImage;
uint32 SizeOfHeaders;
uint32 CheckSum;
uint16 Subsystem;
uint16 DllCharacteristics;
uint32 SizeOfStackReserve;
uint32 SizeOfStackCommit;
uint32 SizeOfHeapReserve;
uint32 SizeOfHeapCommit;
uint32 LoaderFlags;
uint32 NumberOfRvaAndSizes;
tPeImageDataDirectory DataDirectory[16];
} tPeImageOptionalHeader;
typedef struct
{
uint8 Name[8];
union
{
uint32 PhysicalAddress;
uint32 VirtualSize;
} Misc;
uint32 VirtualAddress;
uint32 SizeOfRawData;
uint32 PointerToRawData;
uint32 PointerToRelocations;
uint32 PointerToLinenumbers;
uint16 NumberOfRelocations;
uint16 NumberOfLinenumbers;
uint32 Characteristics;
} tPeImageSectionHeader;
typedef struct
{
union
{
uint32 Characteristics;
uint32 OrdinalFirstThunk;
} u;
uint32 TimeDateStamp;
uint32 ForwarderChain;
uint32 Name;
uint32 FirstThunk;
} tPeImageImportDescriptor;
#ifndef __SMALLER_C__
C_ASSERT(sizeof(tPeImageFileHeader) == 20);
C_ASSERT(sizeof(tPeImageDataDirectory) == 8);
C_ASSERT(sizeof(tPeImageOptionalHeader) == 224);
C_ASSERT(sizeof(tPeImageSectionHeader) == 40);
C_ASSERT(sizeof(tPeImageImportDescriptor) == 20);
#endif
typedef struct
{
uint32 magic; // machine ID and magic
#define OMAGIC 0x107
//#define NMAGIC 0x108
//#define ZMAGIC 0x10B
//#define QMAGIC 0x0CC
uint32 text;
uint32 data;
uint32 bss;
uint32 syms;
uint32 entry;
uint32 trsize;
uint32 drsize;
} tAout;
typedef struct
{
uint32 address;
uint32 info; // bit field:
// 0-23 symbolnum
#define N_UNDF 0
#define N_ABS 2
#define N_TEXT 4
#define N_DATA 6
#define N_BSS 8
// 24-24 pcrel
// 25-26 length: 0 for 8-bit relocations, 1 for 16-bit rel's, 2 for 32-bit rel's
// 27-27 extern
// 28-31 nothing
} tAoutRel;
#ifndef __SMALLER_C__
C_ASSERT(sizeof(tAout) == 32);
C_ASSERT(sizeof(tAoutRel) == 8);
#endif
typedef struct
{
char name[16];
char date[12];
char uid[6];
char gid[6];
char mode[8];
char size[10];
char fmag[2];
} tArchiveFileHeader;
#ifndef __SMALLER_C__
C_ASSERT(sizeof(tArchiveFileHeader) == 60);
#endif
typedef struct
{
void** Buf;
size_t Reserved;
size_t Used;
} tDynArr;
typedef struct
{
Elf32_Shd h;
union
{
void* pData;
char* pStr; // SHT_STRTAB
Elf32_Sym* pSym; // SHT_SYMTAB
Elf32_Rel* pRel; // SHT_REL
Elf32_Rela* pRela; // SHT_RELA
} d;
uint32 OutOffset;
uint32 OutFileOffset;
} tElfSection;
typedef struct
{
const char* ElfName;
uint32 ObjOffset;
char* pSectNames;
tElfSection* pSections;
uint32 SectionCnt;
int Needed;
} tElfMeta;
typedef struct
{
const char* pName;
int32 Attrs;
uint32 Start;
uint32 Stop;
} tSectDescr;
typedef struct
{
const char* pName;
uint32 SectIdx;
int IsStop;
} tDeferredSym;
#define FBUF_SIZE 1024
const char* OutName = "a.out";
const char* MapName;
const char* EntryPoint = "__start";
const char* StubName;
#define FormatDosComTiny 1
#define FormatDosExeSmall 2
#define FormatDosExeHuge 3
#define FormatDosExeUnreal 4
#define FormatFlat16 5
#define FormatFlat32 6
#define FormatWinPe32 7
#define FormatElf32 8
#define FormatAout 9
#define FormatMach32 10
int OutputFormat = 0;
int UseBss = 1;
int NoRelocations = 0;
int verbose = 0;
uint32 Origin = 0xFFFFFFFF; // 0xFFFFFFFF means unspecified
uint32 StackSize = 0xFFFFFFFF; // 0xFFFFFFFF means unspecified
uint32 MinHeap = 0xFFFFFFFF; // 0xFFFFFFFF means unspecified
uint32 MaxHeap = 0xFFFFFFFF; // 0xFFFFFFFF means unspecified
tDynArr OpenFiles;
uint32 ObjFileCnt;
tElfMeta* pMetas;
tSectDescr* pSectDescrs;
uint32 SectCnt;
tDeferredSym* pDeferredSyms;
uint32 DeferredSymCnt;
// Size of the .relod section generated by the linker for FormatDosExeUnreal
uint32 UnrealRelodSize;
#ifdef __SMALLER_C__
#ifdef DETERMINE_VA_LIST
// 2 if va_list is a one-element array containing a pointer
// (typical for x86 Open Watcom C/C++)
// 1 if va_list is a pointer
// (typical for Turbo C++, x86 gcc)
// 0 if va_list is something else, and
// the code may have long crashed by now
int VaListType = 0;
// Attempts to determine the type of va_list as
// expected by the standard library
void DetermineVaListType(void)
{
void* testptr[2];
// hopefully enough space to sprintf() 3 pointers using "%p"
char testbuf[3][CHAR_BIT * sizeof(void*) + 1];
// TBD!!! This is not good. Really need the va_something macros.
// Test whether va_list is a pointer to the first optional parameter or
// an array of one element containing said pointer
testptr[0] = &testptr[1];
testptr[1] = &testptr[0];
memset(testbuf, '\0', sizeof(testbuf));
sprintf(testbuf[0], "%p", testptr[0]);
sprintf(testbuf[1], "%p", testptr[1]);
vsprintf(testbuf[2], "%p", &testptr[0]);
if (!strcmp(testbuf[2], testbuf[0]))
{
// va_list is a pointer
VaListType = 1;
}
else if (!strcmp(testbuf[2], testbuf[1]))
{
// va_list is a one-element array containing a pointer
VaListType = 2;
}
else
{
// va_list is something else, and
// the code may have long crashed by now
printf("Internal error: Indeterminate underlying type of va_list\n");
exit(EXIT_FAILURE);
}
}
#endif // DETERMINE_VA_LIST
#endif // __SMALLER_C__
size_t StrAnyOf(const char* s, const char* ss)
{
size_t idx = 1, slen;
if (!s || !*s || !ss)
return 0;
slen = strlen(s);
for (;;)
{
size_t sslen = strlen(ss);
if (sslen == 0)
return 0;
if (slen == sslen && !memcmp(s, ss, slen))
return idx;
ss += sslen + 1;
idx++;
}
}
void error(char* format, ...)
{
size_t i;
#ifndef __SMALLER_C__
va_list vl;
va_start(vl, format);
#else
void* vl = &format + 1;
#endif
// Make sure all files get closed if linking fails (DOS doesn't like leaked file handles)
for (i = 0; i < OpenFiles.Reserved; i++)
if (OpenFiles.Buf[i])
fclose(OpenFiles.Buf[i]);
remove(OutName);
puts("");
#ifndef __SMALLER_C__
vprintf(format, vl);
#else
// TBD!!! This is not good. Really need the va_something macros.
#ifdef DETERMINE_VA_LIST
if (VaListType == 2)
{
// va_list is a one-element array containing a pointer
vprintf(format, &vl);
}
else // if (VaListType == 1)
// fallthrough
#endif // DETERMINE_VA_LIST
{
// va_list is a pointer
vprintf(format, vl);
}
#endif // __SMALLER_C__
#ifndef __SMALLER_C__
va_end(vl);
#endif
exit(EXIT_FAILURE);
}
void errInternal(int n)
{
error("%d (internal)\n", n);
}
void errMem(void)
{
error("Out of memory\n");
}
void errSectTooBig(void)
{
error("Too much code (or data) or too big origin\n");
}
void errStackTooSmall(void)
{
error("Too small stack\n");
}
void errStackTooBig(void)
{
error("Too big stack or too much data (or code)\n");
}
void errArchive(void)
{
error("Corrupted archive\n");
}
void* Malloc(size_t size)
{
void* p = malloc(size);
if (!p)
errMem();
return p;
}
void* Realloc(void* ptr, size_t size)
{
void* p = realloc(ptr, size);
if (!p)
errMem();
return p;
}
void** DynArrFindSpot(tDynArr* pArr)
{
size_t i, oldcnt, oldsz, newcnt, newsz;
void* p = NULL;
if (pArr->Used < pArr->Reserved)
for (i = 0; i < pArr->Reserved; i++)
if (!pArr->Buf[i])
return pArr->Buf + i;
oldcnt = pArr->Reserved;
oldsz = oldcnt * sizeof pArr->Buf[0];
newcnt = oldcnt ? oldcnt * 2 : 1;
newsz = newcnt * sizeof pArr->Buf[0];
if (newcnt < oldcnt ||
newsz / sizeof pArr->Buf[0] != newcnt ||
!(p = realloc(pArr->Buf, newsz)))
errMem();
pArr->Buf = p;
pArr->Reserved = newcnt;
memset(pArr->Buf + oldcnt, 0, newsz - oldsz);
return pArr->Buf + oldcnt;
}
void DynArrFillSpot(tDynArr* pArr, void** spot, void* p)
{
*spot = p;
pArr->Used++;
}
void DynArrVacateSpot(tDynArr* pArr, void* p)
{
size_t i;
for (i = 0; i < pArr->Reserved; i++)
if (pArr->Buf[i] == p)
{
pArr->Buf[i] = NULL;
pArr->Used--;
break;
}
}
FILE* Fopen(const char* filename, const char* mode)
{
void** spot = DynArrFindSpot(&OpenFiles);
FILE* stream = fopen(filename, mode);
if (!stream)
error("Can't open/create file '%s'\n", filename);
DynArrFillSpot(&OpenFiles, spot, stream);
return stream;
}
void Fclose(FILE* stream)
{
DynArrVacateSpot(&OpenFiles, stream);
if (fclose(stream))
error("Can't close a file\n");
}
void Fseek(FILE* stream, long offset, int whence)
{
int r = fseek(stream, offset, whence);
if (r)
error("Can't seek a file\n");
}
void Fread(void* ptr, size_t size, FILE* stream)
{
size_t r = fread(ptr, 1, size, stream);
if (r != size)
error("Can't read a file\n");
}
void Fwrite(const void* ptr, size_t size, FILE* stream)
{
size_t r = fwrite(ptr, 1, size, stream);
if (r != size)
error("Can't write a file\n");
}
void FillWithByte(unsigned char byte, size_t size, FILE* stream)
{
static unsigned char buf[FBUF_SIZE];
memset(buf, byte, FBUF_SIZE);
while (size)
{
size_t csz = size;
if (csz > FBUF_SIZE)
csz = FBUF_SIZE;
Fwrite(buf, csz, stream);
size -= csz;
}
}
uint32 AlignTo(uint32 ofs, uint32 align)
{
return (ofs + align - 1) / align * align;
}
int RelCmp(const void* p1_, const void* p2_)
{
const Elf32_Rel *p1 = (const Elf32_Rel*)p1_, *p2 = (const Elf32_Rel*)p2_;
if (p1->r_offset < p2->r_offset)
return -1;
if (p1->r_offset > p2->r_offset)
return +1;
return 0;
}
// TBD??? Thoroughly validate ELF object files, specifically sections
void loadElfObj(tElfMeta* pMeta, const char* ElfName, FILE* file, uint32 objOfs)
{
Elf32_Ehdr elfHdr;
Elf32_Shd sectHdr;
uint32 sectIdx;
int unsupported = 0;
memset(pMeta, 0, sizeof *pMeta);
pMeta->ElfName = ElfName;
pMeta->ObjOffset = objOfs;
if (verbose)
printf("File %s:\n\n", ElfName);
Fseek(file, objOfs, SEEK_SET);
Fread(&elfHdr, sizeof elfHdr, file);
if (memcmp(elfHdr.e_ident, "\x7F""ELF", 4))
error("Not an ELF file\n");
if (elfHdr.e_ident[6] != EV_CURRENT)
error("Not a v1 ELF file\n");
if (elfHdr.e_ehsize != sizeof elfHdr)
error("Unexpected ELF header size\n");
if (elfHdr.e_shentsize != sizeof sectHdr)
error("Unexpected ELF section size\n");
if (elfHdr.e_ident[4] != ELFCLASS32)
error("Not a 32-bit file\n");
if (elfHdr.e_ident[5] != ELFDATA2LSB)
error("Not a little-endian file\n");
if (elfHdr.e_type != ET_REL)
error("Not a relocatable file\n");
if (elfHdr.e_machine != EM_386)
error("Not an x86 file\n");
if (elfHdr.e_shoff == 0 || elfHdr.e_shstrndx == 0)
error("Invalid file\n");
Fseek(file, objOfs + elfHdr.e_shoff + elfHdr.e_shstrndx * sizeof sectHdr, SEEK_SET);
Fread(§Hdr, sizeof sectHdr, file);
pMeta->pSectNames = Malloc(sectHdr.sh_size);
Fseek(file, objOfs + sectHdr.sh_offset, SEEK_SET);
Fread(pMeta->pSectNames, sectHdr.sh_size, file);
pMeta->pSections = Malloc((elfHdr.e_shnum + 1) * sizeof(tElfSection));
if (verbose)
printf(" # Type XAW FileOffs Align Size Link Info EnSz Name\n");
for (sectIdx = 0; sectIdx < elfHdr.e_shnum; sectIdx++)
{
const char* typeName = "????????";
static const char* const typeNames[] =
{
"NULL",
"PROGBITS",
"SYMTAB",
"STRTAB",
"RELA",
"HASH",
"DYNAMIC",
"NOTE",
"NOBITS",
"REL",
"SHLIB",
"DYNSYM",
};
const char* name = "";