-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathlinker1.cpp
More file actions
2109 lines (1988 loc) · 98.1 KB
/
linker1.cpp
File metadata and controls
2109 lines (1988 loc) · 98.1 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
/**************************** linker.cpp ***********************************
* Author: Agner Fog
* date created: 2017-11-14
* Last modified: 2021-05-28
* Version: 1.13
* Project: Binary tools for ForwardCom instruction set
* Description:
* This module contains the linker.
*
* Copyright 2017-2024 GNU General Public License v. 3 http://www.gnu.org/licenses
*****************************************************************************/
/* Overview of data structures used during linking process
-------------------------------------------------------
symbolImports: List of imported symbols that need to be resolved.
Includes symbol name and source module
symbolExports: List of public symbols that can be targets for symbolImports.
Includes symbol name and module or library
libraries: Library files to include in symbol search
libmodules: List of library modules that will be extracted as object files
modules1: Metabuffer containing all the object files to add
modules2: Same. Also includes object files extracted from libraries
sections: Index to sections to be extracted from object files and library modules.
Sorted in the order in which they should occur in the executable file
sections2: Same as sections. Sorted by module and section index. Used for re-finding a section
communalSections: List of communal sections. Some of these will be copied to sections and
sections2 when needed
symbolXref: Cross reference between module-local symbol indexes and indexes in relinkable executable file
unresWeakSym: List of unresolved weak symbols. Includes indexes in relinkable executable file
eventData: List of event records
Each of the elements in modules1/2 is a complete CELF object containing its own data structures,
including sectionHeaders, symbols, stringBuffer, and relocations.
outFile is also a complete CELF object containing its own data structures, including
programHeaders, sectionHeaders, symbols, stringBuffer, and relocations.
*/
#include "stdafx.h"
// define code of dummy function for unresolved weak externals
// and unresolved functions of incomplete executable file:
static const uint32_t unresolvedFunctionN = 2;
static const uint32_t unresolvedFunction[unresolvedFunctionN] = {
0x79800200, // tiny instructions: int64 r0 = 0; double v0 = 0
// 0x78000200, // tiny instructions: int64 r0 = 0; v0 = clear()
0x67C00000 // instruction: return
};
static const uint32_t unresolvedReguse1 = 1;
static const uint32_t unresolvedReguse2 = 1;
// run the linker
void CLinker::go() {
// write text on stdout
feedBackText1();
if (cmd.job == CMDL_JOB_RELINK) {
// read pre-existing executable file
loadExeFile();
relinkable = true; relinking = true;
if (err.number()) return;
}
// read specified object files and library files
fillBuffers();
if (err.number()) return;
// make list of imported and exported symbols
makeSymbolList();
if (err.number()) return;
// match lists of imported and exported symbols
matchSymbols();
if (err.number()) return;
// search libraries for imported symbols
librarySearch();
if (err.number()) return;
// write feedback to console
feedBackText2();
// check for duplicate symbols
checkDuplicateSymbols();
if (err.number()) return;
// get imported library modules into modules2 buffer
readLibraryModules();
if (err.number()) return;
// make list of all sections
makeSectionList();
if (err.number()) return;
// make program headers and assign addresses to sections
makeProgramHeaders();
if (err.number()) return;
// put values into all cross references
relocate();
if (err.number()) return;
// make sorted event list
makeEventList();
// copy sections to output file
copySections();
// copy symbols to output file
copySymbols();
// copy relocation records to output file if needed
copyRelocations();
if (err.number()) return;
// make executable file header
makeFileHeader();
// join sections into executable file
outFile.join(&fileHeader);
if (err.number()) return;
// make link map
if (cmd.outputListFile) {
CELF exefile;
exefile.copy(outFile);
exefile.parseFile();
const char * listfilename = cmd.getFilename(cmd.outputListFile);
FILE * fp = fopen(listfilename, "w");
fprintf(fp, "\nLink map of %s\n", cmd.getFilename(cmd.outputFile));
exefile.makeLinkMap(fp);
fclose(fp);
}
if (cmd.outputType == FILETYPE_FWC_HEX) {
// make hexadecimal file
CFileBuffer hexfile;
outFile.makeHexBuffer() >> hexfile;
hexfile.write(cmd.getFilename(cmd.outputFile));
}
else {
// write output file
outFile.write(cmd.getFilename(cmd.outputFile));
}
}
CLinker::CLinker() {
// Constructor
zeroAllMembers(fileHeader); // initialize file header
relinking = false;
relinkable = (cmd.fileOptions & CMDL_FILE_RELINKABLE) != 0;
symbolNameBuffer.pushString(""); // make sure name = 0 gives empty string
}
// write feedback text on stdout
void CLinker::feedBackText1() {
if (cmd.verbose) { // tell what we are doing
if (cmd.verbose > 1) printf("\nForwardCom linker v. %i.%02i", FORWARDCOM_VERSION, FORWARDCOM_SUBVERSION);
if (cmd.job == CMDL_JOB_LINK) {
printf("\nLinking file %s", cmd.getFilename(cmd.outputFile));
}
else {
printf("\nRelinking file %s to file %s", cmd.getFilename(cmd.inputFile), cmd.getFilename(cmd.outputFile));
}
}
}
// load specified object files and library files into buffers
void CLinker::fillBuffers() {
uint32_t i; // loop counter
const char * fname; // file name
// count number of modules and libraries on command line, and number of relinkable modules and libraries
countModules();
// allocate metabuffers
modules1.setSize(numRelinkObjects + numObjects);
libraries.setSize(numLibraries + numRelinkLibraries + 1); // libraries[0] is not used
// get preserved modules if relinking
if (cmd.job == CMDL_JOB_RELINK) getRelinkObjects();
// read files into these buffers
uint32_t iObject = numRelinkObjects; // object file index
uint32_t iLibrary = 0; // library file index
if (cmd.verbose && numObjects) printf("\nAdding object files:");
// loop through commands. get object files and libraries
for (i = 0; i < cmd.lcommands.numEntries(); i++) {
if ((cmd.lcommands[i].command & 0xFF) == CMDL_LINK_ADDMODULE) {
// name of object file
fname = cmd.getFilename(cmd.lcommands[i].filename);
// write name
if (cmd.verbose) printf(" %s", fname);
// read object file
modules1[iObject].read(fname);
modules1[iObject].moduleName = cmd.fileNameBuffer.pushString(removePath(fname));
modules1[iObject].library = 0;
modules1[iObject].relinkable = (cmd.lcommands[i].command & CMDL_LINK_RELINKABLE) != 0;
// remove colons from name
char *nm = &cmd.fileNameBuffer.get<char>(modules1[iObject].moduleName);
for (int s = 0; s < (int)strlen(nm); s++) {
if (nm[s] == ':' || nm[s] <= ' ') nm[s] = '_';
}
if (err.number()) continue;
// check type
if (modules1[iObject].getFileType() != FILETYPE_FWC) {
err.submit(ERR_LINK_FILE_TYPE, fname);
return;
}
iObject++;
}
else if ((cmd.lcommands[i].command & 0xFF) == CMDL_LINK_ADDLIBRARY) {
iLibrary++;
// name of library file
fname = cmd.getFilename(cmd.lcommands[i].filename);
// read library file
libraries[iLibrary].read(fname);
libraries[iLibrary].relinkable = (cmd.lcommands[i].command & CMDL_LINK_RELINKABLE) != 0;
libraries[iLibrary].libraryName = cmd.fileNameBuffer.pushString(removePath(fname));
// remove colons and whitespace from name
char *nm = &cmd.fileNameBuffer.get<char>(libraries[iLibrary].libraryName);
for (int s = 0; s < (int)strlen(nm); s++) {
if (nm[s] == ':' || nm[s] <= ' ') nm[s] = '_';
}
if (err.number()) continue;
// check type
uint32_t ftype = libraries[iLibrary].getFileType();
if ((ftype != FILETYPE_LIBRARY && ftype != FILETYPE_FWC_LIB) || !libraries[iLibrary].isForwardCom()) {
err.submit(ERR_LINK_FILE_TYPE_LIB, fname);
return;
}
}
else if ((cmd.lcommands[i].command & 0xFF) == CMDL_LINK_ADDLIBMODULE) {
// add module explicitly from library
// name of module
fname = cmd.getFilename(cmd.lcommands[i].filename);
// extract module from last library
if (iLibrary == 0) { // no library specified
err.submit(ERR_LINK_MODULE_NOT_FOUND, fname, "none");
continue;
}
// library name
const char * libName = cmd.getFilename(libraries[iLibrary].libraryName);
// find module
uint32_t moduleOs = libraries[iLibrary].findMember(cmd.lcommands[i].filename);
if (moduleOs == 0) { // module not found in library
err.submit(ERR_LINK_MODULE_NOT_FOUND, fname, libName);
continue;
}
// write name
if (cmd.verbose) printf(" %s:%s", libName, fname);
// read object file
modules1[iObject].push(libraries[iLibrary].buf() + moduleOs + (uint32_t)sizeof(SUNIXLibraryHeader),
libraries[iLibrary].getMemberSize(moduleOs));
modules1[iObject].moduleName = cmd.lcommands[i].filename;
modules1[iObject].library = iLibrary;
modules1[iObject].relinkable = (cmd.lcommands[i].command & CMDL_LINK_RELINKABLE) != 0;
iObject++;
}
}
// get recovered libraries if relinking
if (numRelinkLibraries) getRelinkLibraries();
}
// count number of modules and libraries to add
void CLinker::countModules() {
uint32_t i; // loop counter
int32_t j; // loop counter
const char * fname; // file name
numObjects = 0; // number of object files
numLibraries = 0; // number of libraries
// count number of object files and library files on command line
for (i = 0; i < cmd.lcommands.numEntries(); i++) {
if ((uint8_t)cmd.lcommands[i].command == CMDL_LINK_ADDMODULE || (uint8_t)cmd.lcommands[i].command == CMDL_LINK_ADDLIBRARY) {
// name of module
fname = cmd.getFilename(cmd.lcommands[i].filename);
// is it a library?
for (j = (int32_t)strlen(fname) - 1; j > 0; j--) {
if (fname[j] == '.') break;
}
if ((j > 0 && strncasecmp_(fname + j, ".li", 3) == 0 ) || (fname[j+1] == 'a' && fname[j+2] == 0)) {
// this is a library
numLibraries++;
cmd.lcommands[i].command = CMDL_LINK_ADDLIBRARY | (cmd.lcommands[i].command & CMDL_LINK_RELINKABLE);
}
else {
// assume that this is an object file
numObjects++;
}
}
if ((cmd.lcommands[i].command & 0xFF) == CMDL_LINK_ADDLIBMODULE) {
// object module from library file
numObjects++;
}
if (cmd.lcommands[i].command & CMDL_LINK_RELINKABLE) {
// output file is relinkable
relinkable = true;
}
}
// count number of object files and libraries to reuse if relinking
countReusedModules();
}
// make list of imported and exported symbols
void CLinker::makeSymbolList() {
uint32_t modul; // module index
SSymbolEntry sym; // symbol record
zeroAllMembers(sym);
unresolvedWeak = 0; // unresolved weak imports: 1: constant, 2: readonly ip data, 4: writeable datap data, 8: function
unresolvedWeakNum = 0; // number of unresolved weak imports for writeable data
// loop through modules
for (modul = 0; modul < modules1.numEntries(); modul++) {
if (modules1[modul].dataSize() == 0) continue;
// get exported symbols
modules1[modul].listSymbols(&symbolNameBuffer, &symbolExports, modul, 0, 1);
// get imported symbols
modules1[modul].listSymbols(&symbolNameBuffer, &symbolImports, modul, 0, 2);
}
// add special symbols as weak. value will be set later
sym.name = symbolNameBuffer.pushString("__ip_base");
sym.st_bind = STB_WEAK;
sym.library = 0xFFFFFFFE;
sym.st_other = SHF_IP;
sym.symindex = 1;
sym.member = 0;
sym.status = 3;
symbolExports.push(sym);
symbolImports.push(sym);
sym.name = symbolNameBuffer.pushString("__datap_base");
sym.st_other = SHF_DATAP;
sym.symindex = 2;
symbolExports.push(sym);
symbolImports.push(sym);
sym.name = symbolNameBuffer.pushString("__threadp_base");
sym.st_other = SHF_THREADP;
sym.symindex = 3;
symbolExports.push(sym);
symbolImports.push(sym);
sym.name = symbolNameBuffer.pushString("__event_table");
sym.st_other = SHF_IP;
sym.symindex = 4;
symbolExports.push(sym);
symbolImports.push(sym);
sym.name = symbolNameBuffer.pushString("__event_table_num");
sym.st_other = 0;
sym.symindex = 5;
symbolExports.push(sym);
symbolImports.push(sym);
// make import symbol __entry_point
sym.name = symbolNameBuffer.pushString("__entry_point");
sym.st_other = 0;
sym.symindex = 6;
sym.status = 0;
sym.st_bind = STB_GLOBAL;
symbolImports.push(sym);
// sort symbols by name for easy search
symbolExports.sort();
#if 0 // debug: list exported symbols
for (uint32_t s = 0; s < symbolExports.numEntries(); s++) {
printf("\n>%s", symbolNameBuffer.buf() + symbolExports[s].name);
}
#endif
}
// match lists of imported and exported symbols
void CLinker::matchSymbols() {
uint32_t sym; // symbol index
int32_t found;
for (sym = 0; sym < symbolImports.numEntries(); sym++) {
// imported symbol name
if (!(symbolImports[sym].status & 2)) {
// symbol name not already resolved
// search for this name in list of exported symbols
SSymbolEntry sym1 = symbolImports[sym];
sym1.st_bind = STB_IGNORE; // ignore weak/strong difference
found = symbolExports.findFirst(sym1);
if (found >= 0) symbolImports[sym].status |= 2; // symbol has been matched
}
}
}
// search libraries for imported symbols
void CLinker::librarySearch() {
bool newImports = true; // new modules have additional imports to resolve
uint32_t sym; // symbol index
uint32_t lib; // library index
uint32_t m; // module index
const char * symname = 0; // name of symbol to find
uint32_t moduleOs; // offset to module in library
SLibraryModule modul; // identifyer of library module to add
// repeat search as long as new modules have additional imports to resolve
while (newImports) {
// loop through symbols
for (sym = 0; sym < symbolImports.numEntries(); sym++) {
if ((symbolImports[sym].status & 6) == 0 && !(symbolImports[sym].st_bind & STB_WEAK)) {
// symbol name
symname = symbolNameBuffer.getString(symbolImports[sym].name);
// symbol is unresolved and not weak. search for it in all libraries
for (lib = 1; lib < libraries.numEntries(); lib++) {
moduleOs = libraries[lib].findSymbol(symname);
if (moduleOs) {
// symbol found. add module to list if it is not already there
symbolImports[sym].status = 2;
modul.library = lib;
modul.offset = moduleOs;
libmodules.addUnique(modul);
break;
}
}
if (lib == libraries.numEntries()) {
// strong symbol not found. make error message
// get module name
const char * moduleName = "[fixed]";
uint32_t modul = symbolImports[sym].member;
if (modul > 0 && modul < modules1.numEntries()) {
uint32_t mn = modules1[modul].moduleName;
moduleName = cmd.getFilename(mn);
}
symbolImports[sym].status |= 4; // avoid reporting same unresolved symbol more than once
symbolImports[sym].st_bind = STB_UNRESOLVED;
fileHeader.e_flags |= EF_INCOMPLETE; // file is incomplete when there are unresolved symbols
if (cmd.fileOptions & CMDL_FILE_INCOMPLETE) { //incomplete file allowed. warn only
err.submit(ERR_LINK_UNRESOLVED_WARN, symname, moduleName);
}
else { //incomplete file not allowed. fatal error
err.submit(ERR_LINK_UNRESOLVED, symname, moduleName);
}
}
}
}
// loop through new library modules
newImports = false;
for (m = 0; m < libmodules.numEntries(); m++) {
if (!(libmodules[m].library & 0x80000000)) {
// this module has not been added before
libmodules[m].library |= 0x80000000;
// library and offset
lib = libmodules[m].library & 0x7FFFFFFF;
moduleOs = libmodules[m].offset;
// put member into buffer in order to extract symbols
memberBuffer.setSize(0);
memberBuffer.push(libraries[lib].buf() + moduleOs + (uint32_t)sizeof(SUNIXLibraryHeader),
libraries[lib].getMemberSize(moduleOs));
// check if this is a ForwardCom object file
int fileType = memberBuffer.getFileType();
if (fileType != FILETYPE_FWC) {
err.submit(ERR_LIBRARY_MEMBER_TYPE,
libraries[lib].getMemberName(moduleOs),
CFileBuffer::getFileFormatName(fileType));
return;
}
memberBuffer.relinkable = libraries[lib].relinkable;
// get names of exported symbols from ELF file
memberBuffer.listSymbols(&symbolNameBuffer, &symbolExports, moduleOs, lib, 1);
uint32_t numImports = symbolImports.numEntries();
// get names of imported symbols from ELF file
memberBuffer.listSymbols(&symbolNameBuffer, &symbolImports, moduleOs, lib, 2);
if (symbolImports.numEntries() > numImports) {
// this library module has new imports to resolve
newImports = true;
}
}
}
if (err.number()) return;
// new symbols have been added. sort list again
symbolExports.sort();
// match all new symbol exports to imports
matchSymbols();
}
// search for unresolved weak imports
for (sym = 0; sym < symbolImports.numEntries(); sym++) {
if ((symbolImports[sym].status & 3) == 0 && (symbolImports[sym].st_bind & STB_WEAK)) {
// weak symbol not resolved. make a zero dummy for it
symbolImports[sym].status |= 1; // avoid counting same unresolved symbol more than once
// unresolved weak imports:
// 1: constant, 2: readonly ip data, 4: writeable datap data,
// 8: threadp, 0x10: function
switch (symbolImports[sym].st_other & (SHF_BASEPOINTER | STV_EXEC)) {
case 0: // constant
unresolvedWeak |= 1; break;
case STV_IP:
unresolvedWeak |= 2; break;
case STV_DATAP:
unresolvedWeak |= 4; unresolvedWeakNum++;
break;
case STV_THREADP:
unresolvedWeak |= 8; break;
case STV_IP | STV_EXEC:
unresolvedWeak |= 0x10; break;
}
}
}
// remove check bit
for (m = 0; m < libmodules.numEntries(); m++) {
libmodules[m].library &= 0x7FFFFFFF;
}
symbolImports.sort();
}
// check for duplicate public symbols, except weak symbols
void CLinker::checkDuplicateSymbols() {
uint32_t sym1, sym2; // index into symbolExports
uint32_t text; // index to text in cmd.fileNameBuffer
const char * name1, * name2; // library and module names
for (sym1 = 0; sym1 < symbolExports.numEntries(); sym1++) {
if (!(symbolExports[sym1].st_bind & STB_WEAK)) {
sym2 = sym1 + 1;
while (sym2 < symbolExports.numEntries() && symbolExports[sym2] == symbolExports[sym1]) {
// symbol 2 has same name
if (!(symbolExports[sym2].st_bind & STB_WEAK)) {
// name clash. make complete list of modules containing this symbol name
text = cmd.fileNameBuffer.dataSize();
uint32_t num = symbolExports.findAll(0, symbolExports[sym1]);
for (sym2 = sym1; sym2 < sym1 + num; sym2++) {
if (!(symbolExports[sym2].st_bind & STB_WEAK)) {
if (sym2 != sym1) {
cmd.fileNameBuffer.push(", ", 2); // insert comma, except before first name
}
if (symbolExports[sym2].library) {
// symbol is in a library. get library name
uint32_t lib = symbolExports[sym2].library; // library number
name1 = cmd.getFilename(libraries[lib].libraryName);
cmd.fileNameBuffer.push(name1, (uint32_t)strlen(name1));
cmd.fileNameBuffer.push(":", 1);
// get module name
name2 = libraries[lib].getMemberName(symbolExports[sym2].member);
cmd.fileNameBuffer.push(name2, (uint32_t)strlen(name2));
}
else {
// object module. get name
uint32_t m = symbolExports[sym2].member;
if (m < modules2.numEntries()) {
name2 = cmd.getFilename(modules2[m].moduleName);
cmd.fileNameBuffer.push(name2, (uint32_t)strlen(name2));
}
else if (m < modules1.numEntries()) {
name2 = cmd.getFilename(modules1[m].moduleName);
cmd.fileNameBuffer.push(name2, (uint32_t)strlen(name2));
}
}
}
}
const char * symname = symbolNameBuffer.getString(symbolExports[sym1].name);
err.submit(ERR_LINK_DUPLICATE_SYMBOL, symname, cmd.getFilename(text));
// we are finished with this symbol name
sym1 += num - 1; // skip the rest in the for loop
break; // skip while sym2 loop
}
sym2++; // while sym2
}
}
}
}
// get imported library modules into modules2 buffer
void CLinker::readLibraryModules() {
uint32_t m1; // object file index
uint32_t m2; // library module index
uint32_t lib; // library index
uint32_t moduleOs; // offset to library module
// modules1 contains object files, libmodules contains index to library modules.
// we want to join these into the same buffer named modules2.
// The total number of object files and library modules is
uint32_t numModules = modules1.numEntries() + libmodules.numEntries();
// we cannot change the size of a metabuffer, so we will make a new
// bigger metabuffer and transfer everything from modules1 to modules2:
modules2.setSize(numModules);
for (m1 = 0; m1 < modules1.numEntries(); m1++) {
modules2[m1] << modules1[m1];
}
// now get the library modules
for (m2 = 0; m2 < libmodules.numEntries(); m2++) {
// library and offset
lib = libmodules[m2].library & 0x7FFFFFFF;
moduleOs = libmodules[m2].offset;
// put member into its own buffer
modules2[m1+m2].push(libraries[lib].buf() + moduleOs + (uint32_t)sizeof(SUNIXLibraryHeader),
libraries[lib].getMemberSize(moduleOs));
modules2[m1+m2].moduleName = cmd.fileNameBuffer.pushString(libraries[lib].getMemberName(moduleOs));
modules2[m1+m2].library = lib;
modules2[m1+m2].relinkable = libraries[lib].relinkable;
// put new module index into libmodules record
libmodules[m2].modul = m1 + m2;
}
}
// make list of all sections
void CLinker::makeSectionList() {
uint32_t m; // module index
uint32_t sh; // section header index
uint32_t sh_type; // section type
uint32_t secStringTableLen = 0; // length of section string table
const char * secStringTable = 0; // section string table in ELF module
const char * secName = 0; // section name
SLinkSection section; // section record
zeroAllMembers(section); // initialize
eventDataSize = 0; // total size of all event data sections
sections.push(section);
// loop through all modules to get all sections
for (m = 0; m < modules2.numEntries(); m++) {
if (modules2[m].dataSize() == 0) continue;
modules2[m].split(); // split module into components
secStringTable = (char*)modules2[m].stringBuffer.buf();
secStringTableLen = modules2[m].stringBuffer.dataSize();
for (sh = 0; sh < modules2[m].sectionHeaders.numEntries(); sh++) {
sh_type = modules2[m].sectionHeaders[sh].sh_type;
if (sh_type & (SHT_ALLOCATED | SHT_LIST)) {
section.sh_type = sh_type;
section.sh_flags = modules2[m].sectionHeaders[sh].sh_flags;
section.sh_size = modules2[m].sectionHeaders[sh].sh_size;
section.sh_align = modules2[m].sectionHeaders[sh].sh_align;
uint32_t namei = modules2[m].sectionHeaders[sh].sh_name;
if (namei >= secStringTableLen) secName = "?";
else secName = secStringTable + namei;
section.name = cmd.fileNameBuffer.pushString(secName);
section.sh_module = m;
section.sectioni = sh;
if (modules2[m].relinkable) section.sh_flags |= SHF_RELINK;
if (section.sh_flags & SHF_EVENT_HND) {
// check event data sections
eventDataSize += (uint32_t)section.sh_size;
// unsorted lists are preserved in executable file but not loaded into memory:
section.sh_type = SHT_LIST;
}
if (sh_type == SHT_COMDAT) {
communalSections.push(section); // communal section. sections with same name joined
}
else {
sections.push(section); // normal code, data, or bss section
}
}
}
}
// join communal sections with same name and add them to the sections list
joinCommunalSections();
// make dummy sections for unresolved weak external symbols
makeDummySections();
// sort the two section lists by the order in which it should occur in the executable
sortSections();
// add final index
for (uint32_t ix = 0; ix < sections.numEntries(); ix++) {
sections[ix].sectionx = ix + 1;
}
// copy the list
sections2.copy(sections);
// 'sections2' is sorted by module and section index for the purpose of finding back to the original
sections2.sort();
}
// sort sections in the order in which they should occur in the executable file
void CLinker::sortSections() {
uint32_t s; // section index
uint32_t order; // section sort order
uint32_t flags; // section flags
uint32_t type; // section type
/* The order is as listed below.
The base pointers are set to the limits where order changes from even to odd.
SHF_ALLOC:
0x02000002 SHT_ALLOCATED:
0x02000002 SHF_IP:
0x02101002 SHF_EVENT_HND
0x02202002 SHF_EXCEPTION_HND
0x02303002 SHF_DEBUG_INFO
0x02404002 SHF_COMMENT
0x02500002 SHF_WRITE
0x02600002 SHF_READ only !SHF_WRITE !SHF_EXEC (const)
0x02601002 SHF_AUTOGEN
0x02602002 SHF_RELINK
0x02603002 !SHF_RELINK !SHF_FIXED
0x02604002 SHF_FIXED
SHF_EXEC (code) (set ip_base)
0x02701003 SHF_FIXED !SHF_RELINK
0x02702003 !SHF_RELINK
0x02703003 SHF_RELINK
0x02704003 SHF_AUTOGEN
0x02800004 SHF_DATAP
SHT_PROGBITS (data)
0x02801004 SHF_RELINK
0x02802004 !SHF_FIXED
0x02803004 SHF_FIXED
SHT_NOBITS (bss) (set datap_base)
0x02806005 SHF_FIXED
0x02807005 !SHF_RELINK
0x02808005 SHF_RELINK
0x02809005 SHF_AUTOGEN
0x02A00006 SHF_THREADP
SHT_PROGBITS (data)
0x02A01006 SHF_RELINK
0x02A02006 !SHF_FIXED
0x02A03006 SHF_FIXED
SHT_NOBITS (bss) (set threadp_base)
0x02A06007 SHF_FIXED
0x02A07007 !SHF_RELINK
0x02A08007 SHF_RELINK
0x08000000 !SHT_ALLOCATED:
0x08100000 !SHF_ALLOC:
0x08110000 SHT_RELA
0x08120000 SHT_SYMTAB
0x08130000 SHT_STRTAB
0x08160000 other
*/
for (s = 0; s < sections.numEntries(); s++) {
flags = sections[s].sh_flags;
type = sections[s].sh_type;
if (flags & SHF_ALLOC) {
if (type & SHT_ALLOCATED) {
order = 0x02000000;
if (flags & SHF_IP) {
order = 0x02000002;
if (flags & SHF_EVENT_HND) order = 0x02101002;
else if (flags & SHF_EXCEPTION_HND) order = 0x02202002;
else if (flags & SHF_DEBUG_INFO) order = 0x02303002;
else if (flags & SHF_COMMENT) order = 0x02404002;
else if (flags & SHF_WRITE) order = 0x02500002;
else if ((flags & SHF_READ) && !(flags & SHF_EXEC)) {
order = 0x02600002;
if (flags & SHF_AUTOGEN) order = 0x02601002;
else if (flags & SHF_RELINK) order = 0x02602002;
else if (!(flags & SHF_FIXED)) order = 0x02603002;
else order = 0x02604002;
}
else if (flags & SHF_EXEC) {
if (!(flags & SHF_AUTOGEN)) {
if ((flags & SHF_FIXED) || !(flags & SHF_RELINK)) order = 0x02701003;
else if (!(flags & SHF_RELINK)) order = 0x02702003;
else order = 0x02703003;
}
else {
order = 0x02704003; // SHF_AUTOGEN
}
}
}
else if (flags & (SHF_DATAP | SHF_THREADP)) {
order = 0x02800004;
if (flags & SHF_THREADP) order = 0x02A00006;
if (type != SHT_NOBITS) {
if (flags & SHF_RELINK) order |= 0x1000;
else if (!(flags & SHF_FIXED)) order |= 0x2000;
else order |= 0x3000;
}
else { // SHT_NOBITS
order |= 1;
if (!(flags & SHF_AUTOGEN)) {
if (flags & SHF_FIXED) order |= 0x6000;
else if (!(flags & SHF_RELINK)) order |= 0x7000;
else order |= 0x8000;
}
else { // SHF_AUTOGEN
order |= 0x9000;
}
}
}
}
else { // !SHT_ALLOCATED
order = 0x08000000;
}
}
else { // !SHF_ALLOC
switch (type) {
case SHT_RELA:
order = 0x08110000; break;
case SHT_SYMTAB:
order = 0x08120000; break;
case SHT_STRTAB:
order = 0x08130000; break;
default:
order = 0x08160000; break;
}
}
sections[s].order = order;
}
sections.sort();
#if 0 // debug: list sections
for (s = 0; s < sections.numEntries(); s++) {
printf("\n* %8X %s", sections[s].order, cmd.getFilename(sections[s].name));
}
#endif
}
// join communal sections with same name
void CLinker::joinCommunalSections() {
uint32_t m; // module index
uint32_t s1 = 0, s2, s3, s4; // index into communalSections
uint32_t sym; // symbol index in module
uint32_t rel; // relocation index in module
const char * comname; // name of communal section
bool symbolsRemoved = false; // symbols in removed communal sections
communalSections.sort();
while (s1 < communalSections.numEntries()) {
comname = cmd.getFilename(communalSections[s1].name);
// find last entry with same name
s4 = s2 = s1;
while (s2 + 1 < communalSections.numEntries()
&& strcmp(comname, cmd.getFilename(communalSections[s2+1].name)) == 0) {
s2++;
}
// check that communal sections with same name have same size
bool differentSize = false;
for (s3 = s1+1; s3 <= s2; s3++) {
// a non-linkable communal section takes precedence
if (!(communalSections[s3].sh_flags & SHF_RELINK) && (communalSections[s4].sh_flags & SHF_RELINK)) {
s4 = s3;
}
else if (communalSections[s3].sh_size != communalSections[s1].sh_size) {
differentSize = true;
// find the biggest
if (communalSections[s3].sh_size > communalSections[s4].sh_size) s4 = s3;
}
}
if (differentSize) {
// make error message
CMemoryBuffer joinNames; // join section names for error message
joinNames.setSize(0);
m = communalSections[s1].sh_module;
const char * mname = cmd.getFilename(modules2[m].moduleName);
joinNames.push(mname, (uint32_t)strlen(mname));
for (s3 = s1 + 1; s3 <= s2; s3++) {
m = communalSections[s3].sh_module;
mname = cmd.getFilename(modules2[m].moduleName);
joinNames.push(", ", 2);
joinNames.push(mname, (uint32_t)strlen(mname));
}
err.submit(ERR_LINK_COMMUNAL, comname, (char*)joinNames.buf());
}
// check if there is any reference to this section. if not, purge it, except when debug level 2
bool keepSection = true;
if (cmd.debugOptions < 2) {
keepSection = false;
m = communalSections[s4].sh_module;
CELF * modul = &modules2[m];
// find symbols in this section
for (sym = 0; sym < modul->symbols.numEntries(); sym++) {
if (modul->symbols[sym].st_section == communalSections[s4].sectioni) {
const char * symname = (char*)modul->stringBuffer.buf() + modul->symbols[sym].st_name;
// search for this symbol name in symbolImports
SSymbolEntry symsearch;
symsearch.name = symbolNameBuffer.pushString(symname);
symsearch.st_bind = STB_IGNORE;
int32_t s = symbolImports.findFirst(symsearch);
if (s >= 0) {
keepSection = true; // there is a reference to this section. keep it
if (!(communalSections[s4].sh_flags & SHF_RELINK)) {
// communal section is not relinkable. Make the symbol non-weak
if (modul->symbols[sym].st_bind & STB_WEAK) {
modul->symbols[sym].st_bind = STB_GLOBAL;
}
}
break;
}
}
}
}
if (keepSection) {
// save one instance of the communal section
sections.push(communalSections[s4]);
}
// remove symbols and relocations from removed sections
for (s3 = s1; s3 <= s2; s3++) {
if (s3 != s4 || !keepSection) {
// this section is removed
m = communalSections[s3].sh_module;
CELF * modul = &modules2[m];
for (sym = 0; sym < modul->symbols.numEntries(); sym++) {
if (modul->symbols[sym].st_section == communalSections[s3].sectioni) {
const char * symname = (char*)modul->stringBuffer.buf() + modul->symbols[sym].st_name;
// search for this symbol name in symbolExports
SSymbolEntry symsearch;
symsearch.name = symbolNameBuffer.pushString(symname);
symsearch.st_bind = STB_IGNORE;
uint32_t firstMatch = 0;
uint32_t n = symbolExports.findAll(&firstMatch, symsearch);
// search through all symbols with this name
for (uint32_t i = firstMatch; i < firstMatch + n; i++) {
if (symbolExports[i].library == 0) {
if (symbolExports[i].member == m
&& symbolExports[i].sectioni == communalSections[s3].sectioni) {
// removed symbol found
symbolExports[i].name = 0;
symbolExports[i].st_bind = 0;
symbolsRemoved = true;
break;
}
}
else {
uint32_t m2 = findModule(symbolExports[i].library, symbolExports[i].member);
if (m2 == m && symbolExports[i].sectioni == communalSections[s4].sectioni) {
symbolExports[i].library = 0;
symbolExports[i].name = 0;
symbolExports[i].st_bind = 0;
symbolsRemoved = true;
break;
}
}
}
}
}
// search for relocations in removed section
for (rel = 0; rel < modul->relocations.numEntries(); rel++) {
if (modul->relocations[rel].r_section == communalSections[s3].sectioni) {
modul->relocations[rel].r_type = 0;
}
}
}
}
// continue with next communal name
s1 = s2 + 1;
}
if (symbolsRemoved) {
// entries have been removed from symbolExports. sort it again
symbolExports.sort();
}
}
// make dummy segments for event handler table and for unresolved weak externals
void CLinker::makeDummySections() {
SLinkSection section;
zeroAllMembers(section);
section.sh_type = SHT_PROGBITS;
section.sh_align = 3;
if (eventDataSize) {
section.sh_size = eventDataSize;
section.sh_flags = SHF_READ | SHF_IP | SHF_ALLOC | SHF_EVENT_HND | SHF_RELINK | SHF_AUTOGEN;
section.name = cmd.fileNameBuffer.pushString("eventhandlers_sorted");
section.sh_module = 0xFFFFFFF8;
sections.push(section);
}
// unresolved weak imports indicated by unresolvedWeak:
// 1: constant, 2: readonly ip data, 4: writeable datap data,
// 8: threadp, 0x10: function
if (unresolvedWeak & 2) {
section.sh_size = 8;
section.sh_flags = SHF_READ | SHF_IP | SHF_ALLOC | SHF_RELINK | SHF_AUTOGEN;
section.name = cmd.fileNameBuffer.pushString("zdummyconst");
section.sh_module = 0xFFFFFFF1;
sections.push(section);
}
if (unresolvedWeak & 4) {
section.sh_size = 8 * unresolvedWeakNum;
section.sh_flags = SHF_READ | SHF_WRITE | SHF_DATAP | SHF_ALLOC | SHF_RELINK | SHF_AUTOGEN;
section.name = cmd.fileNameBuffer.pushString("zdummydata");
section.sh_module = 0xFFFFFFF2;
sections.push(section);
}
if (unresolvedWeak & 8) {
section.sh_size = 8;
section.sh_flags = SHF_READ | SHF_WRITE | SHF_THREADP | SHF_ALLOC | SHF_RELINK | SHF_AUTOGEN;
section.name = cmd.fileNameBuffer.pushString("zdummythreaddata");
section.sh_module = 0xFFFFFFF3;
sections.push(section);
}
if (unresolvedWeak & 0x10) {
section.sh_size = 8;
section.sh_flags = SHF_EXEC | SHF_IP | SHF_ALLOC | SHF_RELINK | SHF_AUTOGEN;
section.name = cmd.fileNameBuffer.pushString("zdummyfunc");
section.sh_module = 0xFFFFFFF4;
sections.push(section);
}
}
// make sorted list of events
void CLinker::makeEventList() {
uint32_t sec; // section
// find event handler sections
for (sec = 0; sec < sections.numEntries(); sec++) {
if (sections[sec].sh_flags & SHF_EVENT_HND) {
uint32_t m = sections[sec].sh_module;
if (m < modules2.numEntries()) {
CELF * modul = &modules2[sections[sec].sh_module]; // find module
uint32_t offset = uint32_t(modul->sectionHeaders[sections[sec].sectioni].sh_offset);
uint32_t size = uint32_t(modul->sectionHeaders[sections[sec].sectioni].sh_size);
if (size & (sizeof(ElfFwcEvent)-1)) {
// event section size not divisible by event record size
err.submit(ERR_EVENT_SIZE, cmd.getFilename(modul->moduleName));