OpenCores
URL https://opencores.org/ocsvn/forwardcom/forwardcom/trunk

Subversion Repositories forwardcom

[/] [forwardcom/] [bintools/] [linker1.cpp] - Blame information for rev 144

Go to most recent revision | Details | Compare with Previous | View Log

Line No. Rev Author Line
1 61 Agner
/****************************  linker.cpp  ***********************************
2
* Author:        Agner Fog
3
* date created:  2017-11-14
4
* Last modified: 2021-05-28
5
* Version:       1.11
6
* Project:       Binary tools for ForwardCom instruction set
7
* Description:
8
* This module contains the linker.
9
*
10
* Copyright 2017-2021 GNU General Public License v. 3 http://www.gnu.org/licenses
11
*****************************************************************************/
12
 
13
/*     Overview of data structures used during linking process
14
       -------------------------------------------------------
15
symbolImports:    List of imported symbols that need to be resolved.
16
                  Includes symbol name and source module
17
symbolExports:    List of public symbols that can be targets for symbolImports.
18
                  Includes symbol name and module or library
19
libraries:        Library files to include in symbol search
20
libmodules:       List of library modules that will be extracted as object files
21
modules1:         Metabuffer containing all the object files to add
22
modules2:         Same. Also includes object files extracted from libraries
23
sections:         Index to sections to be extracted from object files and library modules.
24
                  Sorted in the order in which they should occur in the executable file
25
sections2:        Same as sections. Sorted by module and section index. Used for re-finding a section
26
communalSections: List of communal sections. Some of these will be copied to sections and
27
                  sections2 when needed
28
symbolXref:       Cross reference between module-local symbol indexes and indexes in relinkable executable file
29
unresWeakSym:     List of unresolved weak symbols. Includes indexes in relinkable executable file
30
eventData:        List of event records
31
 
32
Each of the elements in modules1/2 is a complete CELF object containing its own data structures,
33
including sectionHeaders, symbols, stringBuffer, and relocations.
34
 
35
outFile is also a complete CELF object containing its own data structures, including
36
programHeaders, sectionHeaders, symbols, stringBuffer, and relocations.
37
 
38
*/
39
 
40
#include "stdafx.h"
41
 
42
// define code of dummy function for unresolved weak externals 
43
// and unresolved functions of incomplete executable file:
44
static const uint32_t unresolvedFunctionN = 2;
45
static const uint32_t unresolvedFunction[unresolvedFunctionN] = {
46
    0x79800200,         // tiny instructions: int64 r0 = 0; double v0 = 0
47
//  0x78000200,         // tiny instructions: int64 r0 = 0; v0 = clear()
48
    0x67C00000          // instruction: return
49
};
50
static const uint32_t unresolvedReguse1 = 1;
51
static const uint32_t unresolvedReguse2 = 1;
52
 
53
// run the linker
54
void CLinker::go() {
55
    // write text on stdout
56
    feedBackText1();
57
 
58
    if (cmd.job == CMDL_JOB_RELINK) {
59
        // read pre-existing executable file
60
        loadExeFile();
61
        relinkable = true;  relinking = true;
62
        if (err.number()) return;
63
    }
64
 
65
    // read specified object files and library files
66
    fillBuffers();
67
    if (err.number()) return;
68
 
69
    // make list of imported and exported symbols
70
    makeSymbolList();
71
    if (err.number()) return;
72
 
73
    // match lists of imported and exported symbols
74
    matchSymbols();
75
    if (err.number()) return;
76
 
77
    // search libraries for imported symbols
78
    librarySearch();
79
    if (err.number()) return;
80
 
81
    // write feedback to console
82
    feedBackText2();
83
 
84
    // check for duplicate symbols
85
    checkDuplicateSymbols();
86
    if (err.number()) return;
87
 
88
    // get imported library modules into modules2 buffer
89
    readLibraryModules();
90
    if (err.number()) return;
91
 
92
    // make list of all sections
93
    makeSectionList();
94
    if (err.number()) return;
95
 
96
    // make program headers and assign addresses to sections
97
    makeProgramHeaders();
98
    if (err.number()) return;
99
 
100
    // put values into all cross references
101
    relocate();
102
    if (err.number()) return;
103
 
104
    // make sorted event list
105
    makeEventList();
106
 
107
    // copy sections to output file
108
    copySections();
109
 
110
    // copy symbols to output file
111
    copySymbols();
112
 
113
    // copy relocation records to output file if needed
114
    copyRelocations();
115
    if (err.number()) return;
116
 
117
    // make executable file header
118
    makeFileHeader();
119
 
120
    // join sections into executable file
121
    outFile.join(&fileHeader);
122
    if (err.number()) return;
123
 
124
    // make link map
125
    if (cmd.outputListFile) {
126
        CELF exefile;
127
        exefile.copy(outFile);
128
        exefile.parseFile();
129
        const char * listfilename = cmd.getFilename(cmd.outputListFile);
130
        FILE * fp = fopen(listfilename, "w");
131
        fprintf(fp, "\nLink map of %s\n", cmd.getFilename(cmd.outputFile));
132
        exefile.makeLinkMap(fp);
133
        fclose(fp);
134
    }
135
 
136
    if (cmd.outputType == FILETYPE_FWC_HEX) {
137
        // make hexadecimal file
138
        CFileBuffer hexfile;
139
        outFile.makeHexBuffer() >> hexfile;
140
        hexfile.write(cmd.getFilename(cmd.outputFile));
141
    }
142
    else {
143
        // write output file
144
        outFile.write(cmd.getFilename(cmd.outputFile));
145
    }
146
}
147
 
148
CLinker::CLinker() {
149
    // Constructor
150
    zeroAllMembers(fileHeader); // initialize file header
151
    relinking = false;
152
    relinkable = (cmd.fileOptions & CMDL_FILE_RELINKABLE) != 0;
153
    symbolNameBuffer.pushString("");  // make sure name = 0 gives empty string
154
}
155
 
156
// write feedback text on stdout
157
void CLinker::feedBackText1() {
158
    if (cmd.verbose) {  // tell what we are doing
159
        if (cmd.verbose > 1) printf("\nForwardCom linker v. %i.%02i", FORWARDCOM_VERSION, FORWARDCOM_SUBVERSION);
160
        if (cmd.job == CMDL_JOB_LINK) {
161
            printf("\nLinking file %s", cmd.getFilename(cmd.outputFile));
162
        }
163
        else {
164
            printf("\nRelinking file %s to file %s", cmd.getFilename(cmd.inputFile), cmd.getFilename(cmd.outputFile));
165
        }
166
    }
167
}
168
 
169
// load specified object files and library files into buffers
170
void CLinker::fillBuffers() {
171
    uint32_t i;                                  // loop counter
172
    const char * fname;                          // file name
173
 
174
    // count number of modules and libraries on command line, and number of relinkable modules and libraries
175
    countModules();
176
 
177
    // allocate metabuffers
178
    modules1.setSize(numRelinkObjects + numObjects);
179
    libraries.setSize(numLibraries + numRelinkLibraries + 1); // libraries[0] is not used
180
 
181
    // get preserved modules if relinking
182
    if (cmd.job == CMDL_JOB_RELINK) getRelinkObjects();
183
 
184
    // read files into these buffers
185
    uint32_t iObject = numRelinkObjects;         // object file index
186
    uint32_t iLibrary = 0;                       // library file index
187
 
188
    if (cmd.verbose && numObjects) printf("\nAdding object files:");
189
 
190
    // loop through commands. get object files and libraries
191
    for (i = 0; i < cmd.lcommands.numEntries(); i++) {
192
        if ((cmd.lcommands[i].command & 0xFF) == CMDL_LINK_ADDMODULE) {
193
            // name of object file
194
            fname = cmd.getFilename(cmd.lcommands[i].filename);
195
            // write name
196
            if (cmd.verbose) printf(" %s", fname);
197
            // read object file
198
            modules1[iObject].read(fname);
199
            modules1[iObject].moduleName = cmd.fileNameBuffer.pushString(removePath(fname));
200
            modules1[iObject].library = 0;
201
            modules1[iObject].relinkable = (cmd.lcommands[i].command & CMDL_LINK_RELINKABLE) != 0;
202
 
203
            // remove colons from name
204
            char *nm = &cmd.fileNameBuffer.get<char>(modules1[iObject].moduleName);
205
            for (int s = 0; s < (int)strlen(nm); s++) {
206
                if (nm[s] == ':' || nm[s] <= ' ') nm[s] = '_';
207
            }
208
            if (err.number()) continue;
209
            // check type
210
            if (modules1[iObject].getFileType() != FILETYPE_FWC) {
211
                err.submit(ERR_LINK_FILE_TYPE, fname);
212
                return;
213
            }
214
            iObject++;
215
        }
216
        else if ((cmd.lcommands[i].command & 0xFF) == CMDL_LINK_ADDLIBRARY) {
217
            iLibrary++;
218
            // name of library file
219
            fname = cmd.getFilename(cmd.lcommands[i].filename);
220
            // read library file
221
            libraries[iLibrary].read(fname);
222
            libraries[iLibrary].relinkable = (cmd.lcommands[i].command & CMDL_LINK_RELINKABLE) != 0;
223
            libraries[iLibrary].libraryName = cmd.fileNameBuffer.pushString(removePath(fname));
224
 
225
            // remove colons and whitespace from name
226
            char *nm = &cmd.fileNameBuffer.get<char>(libraries[iLibrary].libraryName);
227
            for (int s = 0; s < (int)strlen(nm); s++) {
228
                if (nm[s] == ':' || nm[s] <= ' ') nm[s] = '_';
229
            }
230
            if (err.number()) continue;
231
            // check type
232
            uint32_t ftype = libraries[iLibrary].getFileType();
233
            if ((ftype != FILETYPE_LIBRARY && ftype != FILETYPE_FWC_LIB) || !libraries[iLibrary].isForwardCom()) {
234
                err.submit(ERR_LINK_FILE_TYPE_LIB, fname);
235
                return;
236
            }
237
        }
238
        else if ((cmd.lcommands[i].command & 0xFF) == CMDL_LINK_ADDLIBMODULE) {
239
            // add module explicitly from library
240
 
241
            // name of module
242
            fname = cmd.getFilename(cmd.lcommands[i].filename);
243
 
244
            // extract module from last library
245
            if (iLibrary == 0) {  // no library specified
246
                err.submit(ERR_LINK_MODULE_NOT_FOUND, fname, "none");
247
                continue;
248
            }
249
            // library name
250
            const char * libName = cmd.getFilename(libraries[iLibrary].libraryName);
251
            // find module
252
            uint32_t moduleOs = libraries[iLibrary].findMember(cmd.lcommands[i].filename);
253
            if (moduleOs == 0) { // module not found in library
254
                err.submit(ERR_LINK_MODULE_NOT_FOUND, fname, libName);
255
                continue;
256
            }
257
            // write name
258
            if (cmd.verbose) printf(" %s:%s", libName, fname);
259
 
260
            // read object file
261
            modules1[iObject].push(libraries[iLibrary].buf() + moduleOs + (uint32_t)sizeof(SUNIXLibraryHeader),
262
                libraries[iLibrary].getMemberSize(moduleOs));
263
            modules1[iObject].moduleName = cmd.lcommands[i].filename;
264
            modules1[iObject].library = iLibrary;
265
            modules1[iObject].relinkable = (cmd.lcommands[i].command & CMDL_LINK_RELINKABLE) != 0;
266
            iObject++;
267
        }
268
    }
269
 
270
    // get recovered libraries if relinking
271
    if (numRelinkLibraries) getRelinkLibraries();
272
}
273
 
274
// count number of modules and libraries to add
275
void CLinker::countModules() {
276
    uint32_t i;                                  // loop counter
277
    int32_t  j;                                  // loop counter
278
    const char * fname;                          // file name
279
    numObjects = 0;                              // number of object files
280
    numLibraries = 0;                            // number of libraries
281
 
282
    // count number of object files and library files on command line
283
    for (i = 0; i < cmd.lcommands.numEntries(); i++) {
284
        if ((uint8_t)cmd.lcommands[i].command == CMDL_LINK_ADDMODULE || (uint8_t)cmd.lcommands[i].command == CMDL_LINK_ADDLIBRARY) {
285
            // name of module
286
            fname = cmd.getFilename(cmd.lcommands[i].filename);
287
            // is it a library?
288
            for (j = (int32_t)strlen(fname) - 1; j > 0; j--) {
289
                if (fname[j] == '.') break;
290
            }
291
            if ((j > 0 && strncasecmp_(fname + j, ".li", 3) == 0 ) || (fname[j+1] == 'a' && fname[j+2] == 0)) {
292
                // this is a library
293
                numLibraries++;
294
                cmd.lcommands[i].command = CMDL_LINK_ADDLIBRARY | (cmd.lcommands[i].command & CMDL_LINK_RELINKABLE);
295
            }
296
            else {
297
                // assume that this is an object file
298
                numObjects++;
299
            }
300
        }
301
        if ((cmd.lcommands[i].command & 0xFF) == CMDL_LINK_ADDLIBMODULE) {
302
            // object module from library file
303
            numObjects++;
304
        }
305
        if (cmd.lcommands[i].command & CMDL_LINK_RELINKABLE) {
306
            // output file is relinkable
307
            relinkable = true;
308
        }
309
    }
310
    // count number of object files and libraries to reuse if relinking
311
    countReusedModules();
312
}
313
 
314
// make list of imported and exported symbols
315
void CLinker::makeSymbolList() {
316
    uint32_t modul;                              // module index
317
    SSymbolEntry sym;                            // symbol record
318
    zeroAllMembers(sym);
319
    unresolvedWeak = 0;           // unresolved weak imports: 1: constant, 2: readonly ip data, 4: writeable datap data, 8: function
320
    unresolvedWeakNum = 0;        // number of unresolved weak imports for writeable data
321
 
322
    // loop through modules
323
    for (modul = 0; modul < modules1.numEntries(); modul++) {
324
        if (modules1[modul].dataSize() == 0) continue;
325
        // get exported symbols
326
        modules1[modul].listSymbols(&symbolNameBuffer, &symbolExports, modul, 0, 1);
327
        // get imported symbols
328
        modules1[modul].listSymbols(&symbolNameBuffer, &symbolImports, modul, 0, 2);
329
    }
330
    // add special symbols as weak. value will be set later
331
    sym.name = symbolNameBuffer.pushString("__ip_base");
332
    sym.st_bind = STB_WEAK;
333
    sym.library = 0xFFFFFFFE;
334
    sym.st_other = SHF_IP;
335
    sym.symindex = 1;
336
    sym.member = 0;
337
    sym.status = 3;
338
    symbolExports.push(sym);
339
    symbolImports.push(sym);
340
    sym.name = symbolNameBuffer.pushString("__datap_base");
341
    sym.st_other = SHF_DATAP;
342
    sym.symindex = 2;
343
    symbolExports.push(sym);
344
    symbolImports.push(sym);
345
    sym.name = symbolNameBuffer.pushString("__threadp_base");
346
    sym.st_other = SHF_THREADP;
347
    sym.symindex = 3;
348
    symbolExports.push(sym);
349
    symbolImports.push(sym);
350
    sym.name = symbolNameBuffer.pushString("__event_table");
351
    sym.st_other = SHF_IP;
352
    sym.symindex = 4;
353
    symbolExports.push(sym);
354
    symbolImports.push(sym);
355
    sym.name = symbolNameBuffer.pushString("__event_table_num");
356
    sym.st_other = 0;
357
    sym.symindex = 5;
358
    symbolExports.push(sym);
359
    symbolImports.push(sym);
360
    // make import symbol __entry_point
361
    sym.name = symbolNameBuffer.pushString("__entry_point");
362
    sym.st_other = 0;
363
    sym.symindex = 6;
364
    sym.status = 0;
365
    sym.st_bind = STB_GLOBAL;
366
    symbolImports.push(sym);
367
    // sort symbols by name for easy search
368
    symbolExports.sort();
369
#if 0  // debug: list exported symbols
370
    for (uint32_t s = 0; s < symbolExports.numEntries(); s++) {
371
        printf("\n>%s", symbolNameBuffer.buf() + symbolExports[s].name);
372
    }
373
#endif
374
}
375
 
376
// match lists of imported and exported symbols
377
void CLinker::matchSymbols() {
378
    uint32_t sym;                               // symbol index
379
    int32_t found;
380
    for (sym = 0; sym < symbolImports.numEntries(); sym++) {
381
        // imported symbol name
382
        if (!(symbolImports[sym].status & 2)) {
383
            // symbol name not already resolved
384
            // search for this name in list of exported symbols
385
            SSymbolEntry sym1 = symbolImports[sym];
386
            sym1.st_bind = STB_IGNORE;    // ignore weak/strong difference
387
            found = symbolExports.findFirst(sym1);
388
            if (found >= 0) symbolImports[sym].status |= 2; // symbol has been matched
389
        }
390
    }
391
}
392
 
393
// search libraries for imported symbols
394
void CLinker::librarySearch() {
395
    bool newImports = true;                      // new modules have additional imports to resolve
396
    uint32_t sym;                                // symbol index
397
    uint32_t lib;                                // library index
398
    uint32_t m;                                  // module index
399
    const char * symname = 0;                    // name of symbol to find
400
    uint32_t moduleOs;                           // offset to module in library
401
    SLibraryModule modul;                        // identifyer of library module to add
402
    // repeat search as long as new modules have additional imports to resolve
403
    while (newImports) {
404
        // loop through symbols
405
        for (sym = 0; sym < symbolImports.numEntries(); sym++) {
406
            if ((symbolImports[sym].status & 6) == 0 && !(symbolImports[sym].st_bind & STB_WEAK)) {
407
                // symbol name
408
                symname = symbolNameBuffer.getString(symbolImports[sym].name);
409
                // symbol is unresolved and not weak. search for it in all libraries
410
                for (lib = 1; lib < libraries.numEntries(); lib++) {
411
                    moduleOs = libraries[lib].findSymbol(symname);
412
                    if (moduleOs) {
413
                        // symbol found. add module to list if it is not already there
414
                        symbolImports[sym].status = 2;
415
                        modul.library = lib;
416
                        modul.offset = moduleOs;
417
                        libmodules.addUnique(modul);
418
                        break;
419
                    }
420
                }
421
                if (lib == libraries.numEntries()) {
422
                    // strong symbol not found. make error message
423
                    // get module name
424
                    const char * moduleName = "[fixed]";
425
                    uint32_t modul = symbolImports[sym].member;
426
                    if (modul > 0 && modul < modules1.numEntries()) {
427
                        uint32_t mn = modules1[modul].moduleName;
428
                        moduleName = cmd.getFilename(mn);
429
                    }
430
                    symbolImports[sym].status |= 4;  // avoid reporting same unresolved symbol more than once
431
                    symbolImports[sym].st_bind = STB_UNRESOLVED;
432
                    fileHeader.e_flags |= EF_INCOMPLETE;  // file is incomplete when there are unresolved symbols
433
                    if (cmd.fileOptions & CMDL_FILE_INCOMPLETE) { //incomplete file allowed. warn only
434
                        err.submit(ERR_LINK_UNRESOLVED_WARN, symname, moduleName);
435
                    }
436
                    else {  //incomplete file not allowed. fatal error
437
                        err.submit(ERR_LINK_UNRESOLVED, symname, moduleName);
438
                    }
439
                }
440
            }
441
        }
442
 
443
        // loop through new library modules
444
        newImports = false;
445
        for (m = 0; m < libmodules.numEntries(); m++) {
446
            if (!(libmodules[m].library & 0x80000000)) {
447
                // this module has not been added before                
448
                libmodules[m].library |= 0x80000000;
449
                // library and offset
450
                lib = libmodules[m].library & 0x7FFFFFFF;
451
                moduleOs = libmodules[m].offset;
452
                // put member into buffer in order to extract symbols
453
                memberBuffer.setSize(0);
454
                memberBuffer.push(libraries[lib].buf() + moduleOs + (uint32_t)sizeof(SUNIXLibraryHeader),
455
                    libraries[lib].getMemberSize(moduleOs));
456
                // check if this is a ForwardCom object file
457
                int fileType = memberBuffer.getFileType();
458
                if (fileType != FILETYPE_FWC) {
459
                    err.submit(ERR_LIBRARY_MEMBER_TYPE,
460
                        libraries[lib].getMemberName(moduleOs),
461
                        CFileBuffer::getFileFormatName(fileType));
462
                    return;
463
                }
464
                memberBuffer.relinkable = libraries[lib].relinkable;
465
                // get names of exported symbols from ELF file            
466
                memberBuffer.listSymbols(&symbolNameBuffer, &symbolExports, moduleOs, lib, 1);
467
                uint32_t numImports = symbolImports.numEntries();
468
                // get names of imported symbols from ELF file            
469
                memberBuffer.listSymbols(&symbolNameBuffer, &symbolImports, moduleOs, lib, 2);
470
                if (symbolImports.numEntries() > numImports) {
471
                    // this library module has new imports to resolve
472
                    newImports = true;
473
                }
474
            }
475
        }
476
        if (err.number()) return;
477
        // new symbols have been added. sort list again
478
        symbolExports.sort();
479
        // match all new symbol exports to imports
480
        matchSymbols();
481
    }
482
    // search for unresolved weak imports
483
    for (sym = 0; sym < symbolImports.numEntries(); sym++) {
484
        if ((symbolImports[sym].status & 3) == 0 && (symbolImports[sym].st_bind & STB_WEAK)) {
485
            // weak symbol not resolved. make a zero dummy for it
486
            symbolImports[sym].status |= 1;  // avoid counting same unresolved symbol more than once
487
            // unresolved weak imports: 
488
            // 1: constant, 2: readonly ip data, 4: writeable datap data, 
489
            // 8: threadp, 0x10: function
490
            switch (symbolImports[sym].st_other & (SHF_BASEPOINTER | STV_EXEC)) {
491
            case 0:                   // constant
492
                unresolvedWeak |= 1;  break;
493
            case STV_IP:
494
                unresolvedWeak |= 2;  break;
495
            case STV_DATAP:
496
                unresolvedWeak |= 4;  unresolvedWeakNum++;
497
                break;
498
            case STV_THREADP:
499
                unresolvedWeak |= 8;  break;
500
            case STV_IP | STV_EXEC:
501
                unresolvedWeak |= 0x10;  break;
502
            }
503
        }
504
    }
505
    // remove check bit
506
    for (m = 0; m < libmodules.numEntries(); m++) {
507
        libmodules[m].library &= 0x7FFFFFFF;
508
    }
509
    symbolImports.sort();
510
}
511
 
512
// check for duplicate public symbols, except weak symbols
513
void CLinker::checkDuplicateSymbols() {
514
    uint32_t sym1, sym2;                         // index into symbolExports
515
    uint32_t text;                               // index to text in cmd.fileNameBuffer
516
    const char * name1, * name2;                 // library and module names
517
    for (sym1 = 0; sym1 < symbolExports.numEntries(); sym1++) {
518
        if (!(symbolExports[sym1].st_bind & STB_WEAK)) {
519
            sym2 = sym1 + 1;
520
            while (sym2 < symbolExports.numEntries() && symbolExports[sym2] == symbolExports[sym1]) {
521
                // symbol 2 has same name
522
                if (!(symbolExports[sym2].st_bind & STB_WEAK)) {
523
                    // name clash. make complete list of modules containing this symbol name
524
                    text = cmd.fileNameBuffer.dataSize();
525
                    uint32_t num = symbolExports.findAll(0, symbolExports[sym1]);
526
                    for (sym2 = sym1; sym2 < sym1 + num; sym2++) {
527
                        if (!(symbolExports[sym2].st_bind & STB_WEAK)) {
528
                            if (sym2 != sym1) {
529
                                cmd.fileNameBuffer.push(", ", 2);  // insert comma, except before first name
530
                            }
531
                            if (symbolExports[sym2].library) {
532
                                // symbol is in a library. get library name
533
                                uint32_t lib = symbolExports[sym2].library; // library number
534
                                name1 = cmd.getFilename(libraries[lib].libraryName);
535
                                cmd.fileNameBuffer.push(name1, (uint32_t)strlen(name1));
536
                                cmd.fileNameBuffer.push(":", 1);
537
                                // get module name
538
                                name2 = libraries[lib].getMemberName(symbolExports[sym2].member);
539
                                cmd.fileNameBuffer.push(name2, (uint32_t)strlen(name2));
540
                            }
541
                            else {
542
                                // object module. get name
543
                                uint32_t m = symbolExports[sym2].member;
544
                                if (m < modules2.numEntries()) {
545
                                    name2 = cmd.getFilename(modules2[m].moduleName);
546
                                    cmd.fileNameBuffer.push(name2, (uint32_t)strlen(name2));
547
                                }
548
                                else if (m < modules1.numEntries()) {
549
                                    name2 = cmd.getFilename(modules1[m].moduleName);
550
                                    cmd.fileNameBuffer.push(name2, (uint32_t)strlen(name2));
551
                                }
552
                            }
553
                        }
554
                    }
555
                    const char * symname = symbolNameBuffer.getString(symbolExports[sym1].name);
556
                    err.submit(ERR_LINK_DUPLICATE_SYMBOL, symname, cmd.getFilename(text));
557
                    // we are finished with this symbol name
558
                    sym1 += num - 1;             // skip the rest in the for loop
559
                    break;                       // skip while sym2 loop
560
                }
561
                sym2++;                          // while sym2
562
            }
563
        }
564
    }
565
}
566
 
567
 
568
// get imported library modules into modules2 buffer
569
void CLinker::readLibraryModules() {
570
    uint32_t m1;                                 // object file index
571
    uint32_t m2;                                 // library module index
572
    uint32_t lib;                                // library index
573
    uint32_t moduleOs;                           // offset to library module
574
 
575
    // modules1 contains object files, libmodules contains index to library modules.
576
    // we want to join these into the same buffer named modules2.
577
    // The total number of object files and library modules is
578
    uint32_t numModules = modules1.numEntries() + libmodules.numEntries();
579
    // we cannot change the size of a metabuffer, so we will make a new 
580
    // bigger metabuffer and transfer everything from modules1 to modules2:
581
    modules2.setSize(numModules);
582
    for (m1 = 0; m1 < modules1.numEntries(); m1++) {
583
        modules2[m1] << modules1[m1];
584
    }
585
    // now get the library modules
586
    for (m2 = 0; m2 < libmodules.numEntries(); m2++) {
587
        // library and offset
588
        lib = libmodules[m2].library & 0x7FFFFFFF;
589
        moduleOs = libmodules[m2].offset;
590
        // put member into its own buffer
591
        modules2[m1+m2].push(libraries[lib].buf() + moduleOs + (uint32_t)sizeof(SUNIXLibraryHeader),
592
            libraries[lib].getMemberSize(moduleOs));
593
        modules2[m1+m2].moduleName = cmd.fileNameBuffer.pushString(libraries[lib].getMemberName(moduleOs));
594
        modules2[m1+m2].library = lib;
595
        modules2[m1+m2].relinkable = libraries[lib].relinkable;
596
 
597
        // put new module index into libmodules record
598
        libmodules[m2].modul = m1 + m2;
599
    }
600
}
601
 
602
// make list of all sections
603
void CLinker::makeSectionList() {
604
    uint32_t m;                                  // module index
605
    uint32_t sh;                                 // section header index
606
    uint32_t sh_type;                            // section type
607
    uint32_t secStringTableLen = 0;              // length of section string table
608
    const char * secStringTable = 0;             // section string table in ELF module
609
    const char * secName = 0;                    // section name
610
    SLinkSection section;                        // section record
611
    zeroAllMembers(section);                     // initialize
612
    eventDataSize = 0;                           // total size of all event data sections
613
    sections.push(section);
614
 
615
    // loop through all modules to get all sections
616
    for (m = 0; m < modules2.numEntries(); m++) {
617
        if (modules2[m].dataSize() == 0) continue;
618
        modules2[m].split();                     // split module into components
619
        secStringTable = (char*)modules2[m].stringBuffer.buf();
620
        secStringTableLen = modules2[m].stringBuffer.dataSize();
621
        for (sh = 0; sh < modules2[m].sectionHeaders.numEntries(); sh++) {
622
            sh_type = modules2[m].sectionHeaders[sh].sh_type;
623
            if (sh_type & (SHT_ALLOCATED | SHT_LIST)) {
624
                section.sh_type = sh_type;
625
                section.sh_flags = modules2[m].sectionHeaders[sh].sh_flags;
626
                section.sh_size = modules2[m].sectionHeaders[sh].sh_size;
627
                section.sh_align = modules2[m].sectionHeaders[sh].sh_align;
628
                uint32_t namei = modules2[m].sectionHeaders[sh].sh_name;
629
                if (namei >= secStringTableLen) secName = "?";
630
                else secName = secStringTable + namei;
631
                section.name = cmd.fileNameBuffer.pushString(secName);
632
                section.sh_module = m;
633
                section.sectioni = sh;
634
                if (modules2[m].relinkable) section.sh_flags |= SHF_RELINK;
635
                if (section.sh_flags & SHF_EVENT_HND) {
636
                    // check event data sections
637
                    eventDataSize += (uint32_t)section.sh_size;
638
                    // unsorted lists are preserved in executable file but not loaded into memory:
639
                    section.sh_type = SHT_LIST;
640
                }
641
                if (sh_type == SHT_COMDAT) {
642
                    communalSections.push(section);  // communal section. sections with same name joined
643
                }
644
                else {
645
                    sections.push(section);          // normal code, data, or bss section
646
                }
647
            }
648
        }
649
    }
650
    // join communal sections with same name and add them to the sections list
651
    joinCommunalSections();
652
 
653
    // make dummy sections for unresolved weak external symbols
654
    makeDummySections();
655
 
656
    // sort the two section lists by the order in which it should occur in the executable
657
    sortSections();
658
 
659
    // add final index
660
    for (uint32_t ix = 0; ix < sections.numEntries(); ix++) {
661
        sections[ix].sectionx = ix + 1;
662
    }
663
    // copy the list
664
    sections2.copy(sections);
665
    // 'sections2' is sorted by module and section index for the purpose of finding back to the original
666
    sections2.sort();
667
}
668
 
669
// sort sections in the order in which they should occur in the executable file
670
void CLinker::sortSections() {
671
    uint32_t s;                                  // section index
672
    uint32_t order;                              // section sort order
673
    uint32_t flags;                              // section flags
674
    uint32_t type;                               // section type
675
 
676
    /* The order is as listed below.
677
       The base pointers are set to the limits where order changes from even to odd.
678
                  SHF_ALLOC:
679
    0x02000002       SHT_ALLOCATED:
680
    0x02000002          SHF_IP:
681
    0x02101002             SHF_EVENT_HND
682
    0x02202002             SHF_EXCEPTION_HND
683
    0x02303002             SHF_DEBUG_INFO
684
    0x02404002             SHF_COMMENT
685
    0x02500002             SHF_WRITE
686
    0x02600002             SHF_READ only !SHF_WRITE !SHF_EXEC  (const)
687
    0x02601002                SHF_AUTOGEN
688
    0x02602002                SHF_RELINK
689
    0x02603002                !SHF_RELINK !SHF_FIXED
690
    0x02604002                SHF_FIXED
691
                           SHF_EXEC  (code)  (set ip_base)
692
    0x02701003                SHF_FIXED !SHF_RELINK
693
    0x02702003                !SHF_RELINK
694
    0x02703003                SHF_RELINK
695
    0x02704003                SHF_AUTOGEN
696
    0x02800004          SHF_DATAP
697
                           SHT_PROGBITS  (data)
698
    0x02801004                SHF_RELINK
699
    0x02802004                !SHF_FIXED
700
    0x02803004                SHF_FIXED
701
                           SHT_NOBITS   (bss)  (set datap_base)
702
    0x02806005                SHF_FIXED
703
    0x02807005                !SHF_RELINK
704
    0x02808005                SHF_RELINK
705
    0x02809005                SHF_AUTOGEN
706
    0x02A00006          SHF_THREADP
707
                           SHT_PROGBITS  (data)
708
    0x02A01006                SHF_RELINK
709
    0x02A02006                !SHF_FIXED
710
    0x02A03006                SHF_FIXED
711
                           SHT_NOBITS   (bss)  (set threadp_base)
712
    0x02A06007                SHF_FIXED
713
    0x02A07007                !SHF_RELINK
714
    0x02A08007                SHF_RELINK
715
    0x08000000       !SHT_ALLOCATED:
716
    0x08100000    !SHF_ALLOC:
717
    0x08110000       SHT_RELA
718
    0x08120000       SHT_SYMTAB
719
    0x08130000       SHT_STRTAB
720
    0x08160000       other
721
    */
722
 
723
    for (s = 0; s < sections.numEntries(); s++) {
724
        flags = sections[s].sh_flags;
725
        type  = sections[s].sh_type;
726
        if (flags & SHF_ALLOC) {
727
            if (type & SHT_ALLOCATED) {
728
                order = 0x02000000;
729
                if (flags & SHF_IP) {
730
                    order = 0x02000002;
731
                    if (flags & SHF_EVENT_HND) order = 0x02101002;
732
                    else if (flags & SHF_EXCEPTION_HND) order = 0x02202002;
733
                    else if (flags & SHF_DEBUG_INFO) order = 0x02303002;
734
                    else if (flags & SHF_COMMENT) order = 0x02404002;
735
                    else if (flags & SHF_WRITE) order = 0x02500002;
736
                    else if ((flags & SHF_READ) && !(flags & SHF_EXEC)) {
737
                        order = 0x02600002;
738
                        if (flags & SHF_AUTOGEN) order = 0x02601002;
739
                        else if (flags & SHF_RELINK) order = 0x02602002;
740
                        else if (!(flags & SHF_FIXED)) order = 0x02603002;
741
                        else order = 0x02604002;
742
                    }
743
                    else if (flags & SHF_EXEC) {
744
                        if (!(flags & SHF_AUTOGEN)) {
745
                            if ((flags & SHF_FIXED) || !(flags & SHF_RELINK)) order = 0x02701003;
746
                            else if (!(flags & SHF_RELINK)) order = 0x02702003;
747
                            else order = 0x02703003;
748
                        }
749
                        else {
750
                            order = 0x02704003; // SHF_AUTOGEN
751
                        }
752
                    }
753
                }
754
                else if (flags & (SHF_DATAP | SHF_THREADP)) {
755
                    order = 0x02800004;
756
                    if (flags & SHF_THREADP) order = 0x02A00006;
757
                    if (type != SHT_NOBITS) {
758
                        if (flags & SHF_RELINK) order |= 0x1000;
759
                        else if (!(flags & SHF_FIXED)) order |= 0x2000;
760
                        else  order |= 0x3000;
761
                    }
762
                    else {  // SHT_NOBITS
763
                        order |= 1;
764
                        if (!(flags & SHF_AUTOGEN)) {
765
                            if (flags & SHF_FIXED) order |= 0x6000;
766
                            else if (!(flags & SHF_RELINK)) order |= 0x7000;
767
                            else  order |= 0x8000;
768
                        }
769
                        else {  // SHF_AUTOGEN 
770
                            order |= 0x9000;
771
                        }
772
                    }
773
                }
774
            }
775
            else { // !SHT_ALLOCATED
776
                order = 0x08000000;
777
            }
778
        }
779
        else {  // !SHF_ALLOC
780
            switch (type) {
781
            case SHT_RELA:
782
                order = 0x08110000;  break;
783
            case SHT_SYMTAB:
784
                order = 0x08120000;  break;
785
            case SHT_STRTAB:
786
                order = 0x08130000;  break;
787
            default:
788
                order = 0x08160000;  break;
789
            }
790
        }
791
        sections[s].order = order;
792
    }
793
    sections.sort();
794
 
795
#if 0  // debug: list sections
796
    for (s = 0; s < sections.numEntries(); s++) {
797
        printf("\n* %8X  %s", sections[s].order, cmd.getFilename(sections[s].name));
798
    }
799
#endif
800
}
801
 
802
// join communal sections with same name
803
void CLinker::joinCommunalSections() {
804
    uint32_t m;                                  // module index
805
    uint32_t s1 = 0, s2, s3, s4;                 // index into communalSections
806
    uint32_t sym;                                // symbol index in module
807
    uint32_t rel;                                // relocation index in module
808
    const char * comname;                        // name of communal section
809
    bool symbolsRemoved = false;                 // symbols in removed communal sections
810
 
811
    communalSections.sort();
812
    while (s1 < communalSections.numEntries()) {
813
        comname = cmd.getFilename(communalSections[s1].name);
814
        // find last entry with same name
815
        s4 = s2 = s1;
816
        while (s2 + 1 < communalSections.numEntries()
817
            && strcmp(comname, cmd.getFilename(communalSections[s2+1].name)) == 0) {
818
            s2++;
819
        }
820
 
821
        // check that communal sections with same name have same size
822
        bool differentSize = false;
823
        for (s3 = s1+1; s3 <= s2; s3++) {
824
            // a non-linkable communal section takes precedence
825
            if (!(communalSections[s3].sh_flags & SHF_RELINK) && (communalSections[s4].sh_flags & SHF_RELINK)) {
826
                s4 = s3;
827
            }
828
            else if (communalSections[s3].sh_size != communalSections[s1].sh_size) {
829
                differentSize = true;
830
                // find the biggest
831
                if (communalSections[s3].sh_size > communalSections[s4].sh_size) s4 = s3;
832
            }
833
        }
834
        if (differentSize) {
835
            // make error message
836
            CMemoryBuffer joinNames;                     // join section names for error message
837
            joinNames.setSize(0);
838
            m = communalSections[s1].sh_module;
839
            const char * mname = cmd.getFilename(modules2[m].moduleName);
840
            joinNames.push(mname, (uint32_t)strlen(mname));
841
            for (s3 = s1 + 1; s3 <= s2; s3++) {
842
                m = communalSections[s3].sh_module;
843
                mname = cmd.getFilename(modules2[m].moduleName);
844
                joinNames.push(", ", 2);
845
                joinNames.push(mname, (uint32_t)strlen(mname));
846
            }
847
            err.submit(ERR_LINK_COMMUNAL, comname, (char*)joinNames.buf());
848
        }
849
        // check if there is any reference to this section. if not, purge it, except when debug level 2
850
        bool keepSection = true;
851
        if (cmd.debugOptions < 2) {
852
            keepSection = false;
853
            m = communalSections[s4].sh_module;
854
            CELF * modul = &modules2[m];
855
            // find symbols in this section
856
            for (sym = 0; sym < modul->symbols.numEntries(); sym++) {
857
                if (modul->symbols[sym].st_section == communalSections[s4].sectioni) {
858
                    const char * symname = (char*)modul->stringBuffer.buf() + modul->symbols[sym].st_name;
859
                    // search for this symbol name in symbolImports
860
                    SSymbolEntry symsearch;
861
                    symsearch.name = symbolNameBuffer.pushString(symname);
862
                    symsearch.st_bind = STB_IGNORE;
863
                    int32_t s = symbolImports.findFirst(symsearch);
864
                    if (s >= 0) {
865
                        keepSection = true;      // there is a reference to this section. keep it
866
                        if (!(communalSections[s4].sh_flags & SHF_RELINK)) {
867
                            // communal section is not relinkable. Make the symbol non-weak
868
                            if (modul->symbols[sym].st_bind & STB_WEAK) {
869
                                modul->symbols[sym].st_bind = STB_GLOBAL;
870
                            }
871
                        }
872
                        break;
873
                    }
874
                }
875
            }
876
        }
877
        if (keepSection) {
878
            // save one instance of the communal section
879
            sections.push(communalSections[s4]);
880
        }
881
        // remove symbols and relocations from removed sections
882
        for (s3 = s1; s3 <= s2; s3++) {
883
            if (s3 != s4 || !keepSection) {
884
                // this section is removed
885
                m = communalSections[s3].sh_module;
886
                CELF * modul = &modules2[m];
887
                for (sym = 0; sym < modul->symbols.numEntries(); sym++) {
888
                    if (modul->symbols[sym].st_section == communalSections[s3].sectioni) {
889
                        const char * symname = (char*)modul->stringBuffer.buf() + modul->symbols[sym].st_name;
890
                        // search for this symbol name in symbolExports
891
                        SSymbolEntry symsearch;
892
                        symsearch.name = symbolNameBuffer.pushString(symname);
893
                        symsearch.st_bind = STB_IGNORE;
894
                        uint32_t firstMatch = 0;
895
                        uint32_t n = symbolExports.findAll(&firstMatch, symsearch);
896
                        // search through all symbols with this name
897
                        for (uint32_t i = firstMatch; i < firstMatch + n; i++) {
898
                            if (symbolExports[i].library == 0) {
899
                                if (symbolExports[i].member == m
900
                                && symbolExports[i].sectioni == communalSections[s3].sectioni) {
901
                                    // removed symbol found
902
                                    symbolExports[i].name = 0;
903
                                    symbolExports[i].st_bind = 0;
904
                                    symbolsRemoved = true;
905
                                    break;
906
                                }
907
                            }
908
                            else {
909
                                uint32_t m2 = findModule(symbolExports[i].library, symbolExports[i].member);
910
                                if (m2 == m && symbolExports[i].sectioni == communalSections[s4].sectioni) {
911
                                    symbolExports[i].library = 0;
912
                                    symbolExports[i].name = 0;
913
                                    symbolExports[i].st_bind = 0;
914
                                    symbolsRemoved = true;
915
                                    break;
916
                                }
917
                            }
918
                        }
919
                    }
920
                }
921
                // search for relocations in removed section
922
                for (rel = 0; rel < modul->relocations.numEntries(); rel++) {
923
                    if (modul->relocations[rel].r_section == communalSections[s3].sectioni) {
924
                        modul->relocations[rel].r_type = 0;
925
                    }
926
                }
927
            }
928
        }
929
        // continue with next communal name
930
        s1 = s2 + 1;
931
    }
932
    if (symbolsRemoved) {
933
        // entries have been removed from symbolExports. sort it again
934
        symbolExports.sort();
935
    }
936
}
937
 
938
// make dummy segments for event handler table and for unresolved weak externals
939
void CLinker::makeDummySections() {
940
    SLinkSection section;
941
    zeroAllMembers(section);
942
    section.sh_type = SHT_PROGBITS;
943
    section.sh_align = 3;
944
 
945
    if (eventDataSize) {
946
        section.sh_size = eventDataSize;
947
        section.sh_flags = SHF_READ | SHF_IP | SHF_ALLOC | SHF_EVENT_HND | SHF_RELINK | SHF_AUTOGEN;
948
        section.name = cmd.fileNameBuffer.pushString("eventhandlers_sorted");
949
        section.sh_module = 0xFFFFFFF8;
950
        sections.push(section);
951
    }
952
 
953
    // unresolved weak imports indicated by unresolvedWeak: 
954
    // 1: constant, 2: readonly ip data, 4: writeable datap data, 
955
    // 8: threadp, 0x10: function
956
    if (unresolvedWeak & 2) {
957
        section.sh_size = 8;
958
        section.sh_flags = SHF_READ | SHF_IP | SHF_ALLOC | SHF_RELINK | SHF_AUTOGEN;
959
        section.name = cmd.fileNameBuffer.pushString("zdummyconst");
960
        section.sh_module = 0xFFFFFFF1;
961
        sections.push(section);
962
    }
963
    if (unresolvedWeak & 4) {
964
        section.sh_size = 8 * unresolvedWeakNum;
965
        section.sh_flags = SHF_READ | SHF_WRITE | SHF_DATAP | SHF_ALLOC | SHF_RELINK | SHF_AUTOGEN;
966
        section.name = cmd.fileNameBuffer.pushString("zdummydata");
967
        section.sh_module = 0xFFFFFFF2;
968
        sections.push(section);
969
    }
970
    if (unresolvedWeak & 8) {
971
        section.sh_size = 8;
972
        section.sh_flags = SHF_READ | SHF_WRITE | SHF_THREADP | SHF_ALLOC | SHF_RELINK | SHF_AUTOGEN;
973
        section.name = cmd.fileNameBuffer.pushString("zdummythreaddata");
974
        section.sh_module = 0xFFFFFFF3;
975
        sections.push(section);
976
    }
977
    if (unresolvedWeak & 0x10) {
978
        section.sh_size = 8;
979
        section.sh_flags = SHF_EXEC | SHF_IP | SHF_ALLOC | SHF_RELINK | SHF_AUTOGEN;
980
        section.name = cmd.fileNameBuffer.pushString("zdummyfunc");
981
        section.sh_module = 0xFFFFFFF4;
982
        sections.push(section);
983
    }
984
}
985
 
986
// make sorted list of events
987
void CLinker::makeEventList() {
988
    uint32_t sec;                                // section
989
 
990
    // find event handler sections
991
    for (sec = 0; sec < sections.numEntries(); sec++) {
992
        if (sections[sec].sh_flags & SHF_EVENT_HND) {
993
            uint32_t m = sections[sec].sh_module;
994
            if (m < modules2.numEntries()) {
995
                CELF * modul = &modules2[sections[sec].sh_module]; // find module
996
                uint32_t offset = uint32_t(modul->sectionHeaders[sections[sec].sectioni].sh_offset);
997
                uint32_t size = uint32_t(modul->sectionHeaders[sections[sec].sectioni].sh_size);
998
                if (size & (sizeof(ElfFwcEvent)-1)) {
999
                    // event section size not divisible by event record size
1000
                    err.submit(ERR_EVENT_SIZE, cmd.getFilename(modul->moduleName));
1001
                    return;
1002
                }
1003
                // copy all event records
1004
                for (uint32_t index = 0; index < size; index += sizeof(ElfFwcEvent)) {
1005
                    eventData.push(modul->dataBuffer.get<ElfFwcEvent>(offset + index));
1006
                }
1007
            }
1008
        }
1009
    }
1010
    // sort event list
1011
    eventData.sort();
1012
}
1013
 
1014
 
1015
// make program headers and assign addresses to sections
1016
void CLinker::makeProgramHeaders() {
1017
    // Each program header can cover multiple sections with the same base pointer and
1018
    // the same read/write/execute permissions
1019
    uint32_t sec;                      // section index
1020
    uint32_t ph;                       // program header index
1021
    uint32_t lastFlags = 0;            // p_flags of last program header
1022
    uint64_t offset = 0;               // address relative to begin of section group
1023
    uint64_t * pBasePonter = 0;        // pointer to base pointer
1024
    uint32_t secOrder;                 // indicates 'order' as defined in sortSections()
1025
                                       // secOrder & 0xF00000 indicates program header
1026
                                       // secOrder & 0x0E indicates base pointer
1027
                                       // Even values may have negative index relative to the base pointer,
1028
                                       // odd values have positive index relative to the base pointer
1029
    uint32_t lastSecOrder = 0;         // secOrder of previous section
1030
    uint64_t align;                    // section alignment
1031
    uint8_t  maxAlign = 0;             // maximum alignment of all sections in group = (1 << maxAlign)
1032
    bool basePointerAssigned = false;  // a base pointer has been assigned for this group
1033
    ElfFwcPhdr pHeader;               // program header = segment definition
1034
    zeroAllMembers(pHeader);           // initialize
1035
 
1036
    // initialize pointer bases. may change later
1037
    ip_base = datap_base = threadp_base = 0;
1038
    event_table = event_table_num = 0;
1039
 
1040
    // loop through sections to assign sections to program headers, and 
1041
    // find the maximum alignment for each program header
1042
    for (sec = 0; sec < sections.numEntries(); sec++) {
1043
        // section order as defined by sortSections()
1044
        secOrder = sections[sec].order;
1045
        if (secOrder == 0 || !(sections[sec].sh_type & SHT_ALLOCATED)) {
1046
            // relocation tables, symbol tables, string tables, etc. need no program header.
1047
            // set address to zero
1048
            sections[sec].sh_addr = 0;
1049
            uint32_t mod = sections[sec].sh_module;
1050
            uint32_t seci = sections[sec].sectioni;
1051
            if (mod < modules2.numEntries() && seci < modules2[mod].sectionHeaders.numEntries()) {
1052
                // find section header
1053
                ElfFwcShdr & sectionHeader = modules2[mod].sectionHeaders[seci];
1054
                sectionHeader.sh_addr = 0;
1055
            }
1056
            continue;  // don't put in program header
1057
        }
1058
 
1059
        if ((secOrder & 0xF00000) != (lastSecOrder & 0xF00000)) {
1060
            // new program header. save last program header
1061
            if (pHeader.p_type != 0) {
1062
                // finished with previous section group
1063
                // check if alignment needs to be increased
1064
                if (maxAlign > pHeader.p_align) {
1065
                    pHeader.p_align = maxAlign;
1066
                }
1067
                outFile.programHeaders.push(pHeader);
1068
            }
1069
            // start making new program header
1070
            zeroAllMembers(pHeader);
1071
            pHeader.p_type = PT_LOAD;
1072
            pHeader.p_flags = sections[sec].sh_flags;
1073
            maxAlign = sections[sec].sh_align;
1074
            if (((sections[sec].sh_flags ^ lastFlags) & SHF_PERMISSIONS) || (secOrder & 0xE) != (lastSecOrder & 0xE)) {
1075
                // different permissions or different base pointer. must align by at least 1 << MEMORY_MAP_ALIGN
1076
                if (maxAlign < MEMORY_MAP_ALIGN) maxAlign = MEMORY_MAP_ALIGN;
1077
            }
1078
            // use low 32 bits of p_paddr to store index into sections and 
1079
            // high 32 bits to store number of sections
1080
            pHeader.p_paddr = sec;
1081
        }
1082
        lastSecOrder = secOrder;
1083
        lastFlags = sections[sec].sh_flags;
1084
        // find the section with the highest alignment
1085
        if (maxAlign < sections[sec].sh_align) maxAlign = sections[sec].sh_align;
1086
        // count sections covered by this header
1087
        pHeader.p_paddr += (uint64_t)1 << 32;
1088
    }
1089
    // finish last program header
1090
    if (pHeader.p_type != 0) {
1091
        // check if alignment needs to be increased
1092
        if (maxAlign > pHeader.p_align) {
1093
            pHeader.p_align = maxAlign;
1094
        }
1095
        // save last program header
1096
        outFile.programHeaders.push(pHeader);
1097
    }
1098
 
1099
    // Divide program headers into groups of headers with the same base pointer and align the start of each
1100
    // group with the maximum alignment for the group
1101
    maxAlign = 0;
1102
    uint32_t last_flags = 0;
1103
    uint32_t group_ph = 0xFFFFFFFF;   // first program header in group og program headers with same base pointer
1104
 
1105
    // loop through program headers to find maximum alignment for each base pointer
1106
    for (ph = 0; ph < outFile.programHeaders.numEntries(); ph++) {
1107
        ElfFwcPhdr & rHeader = outFile.programHeaders[ph];  // reference to current program header
1108
        if ((rHeader.p_flags ^ last_flags) & SHF_BASEPOINTER) {
1109
            // new base pointer
1110
            if (group_ph != 0xFFFFFFFF) {
1111
                outFile.programHeaders[group_ph].p_align = maxAlign;  // save maximum alignment to first program header in group
1112
            }
1113
            // start new header group
1114
            group_ph = ph;
1115
            maxAlign = 0;
1116
            last_flags = rHeader.p_flags;
1117
        }
1118
        if (rHeader.p_align > maxAlign) maxAlign = rHeader.p_align;
1119
    }
1120
 
1121
    // loop through sections covered by each program header and assign addresses
1122
    lastFlags = 0;  offset = 0;
1123
    for (ph = 0; ph < outFile.programHeaders.numEntries(); ph++) {
1124
        ElfFwcPhdr & rHeader = outFile.programHeaders[ph];  // reference to current program header
1125
        uint32_t fistSection = (uint32_t)rHeader.p_paddr;
1126
        uint32_t numSections = (uint32_t)(rHeader.p_paddr >> 32);
1127
 
1128
        if ((rHeader.p_flags ^ lastFlags) & SHF_BASEPOINTER) {
1129
            // base pointer is different from last header. restart addressing
1130
            offset = 0;  basePointerAssigned = false;
1131
            // get base pointer
1132
            switch (rHeader.p_flags & SHF_BASEPOINTER) {
1133
            case SHF_IP: // ip
1134
                pBasePonter = &ip_base;
1135
                break;
1136
            case SHF_DATAP: // datap
1137
                pBasePonter = &datap_base;
1138
                break;
1139
            case SHF_THREADP: // threadp
1140
                pBasePonter = &threadp_base;
1141
                break;
1142
            default:
1143
                pBasePonter = 0;
1144
            }
1145
        }
1146
        // align start of segment
1147
        align = (uint64_t)1 << rHeader.p_align;
1148
        offset = (offset + align - 1) & -(int64_t)align;
1149
        rHeader.p_vaddr = offset;
1150
 
1151
        // find event_table
1152
        if ((outFile.programHeaders[ph].p_flags & SHF_EVENT_HND) && !(lastFlags & SHF_EVENT_HND)) {
1153
            event_table = (uint32_t)offset;
1154
            event_table_num = uint32_t(sections[fistSection].sh_size / sizeof(ElfFwcEvent));
1155
        }
1156
 
1157
        // loop through sections covered by this program header
1158
        for (sec = fistSection; sec < fistSection + numSections; sec++) {
1159
            // get section start address
1160
            if (relinking
1161
                && (sections[sec].sh_flags & SHF_FIXED)
1162
                && basePointerAssigned) {
1163
                // this section belongs to the non-relinkable part of a relinkable file.
1164
                // the address must be the same as in the input file, relative to the base pointer
1165
                uint64_t offset2 = sections[sec].sh_addr + *pBasePonter;
1166
                if (offset2 - offset > MAX_ALIGN) {
1167
                    err.submit(ERR_INDEX_OUT_OF_RANGE);
1168
                    return;
1169
                }
1170
                offset = offset2;
1171
            }
1172
            else {
1173
                // align start of section
1174
                align = (uint64_t)1 << sections[sec].sh_align;
1175
                offset = (offset + align - 1) & -(int64_t)align;
1176
            }
1177
            // find base pointer
1178
            if (!basePointerAssigned && pBasePonter) {
1179
                if (relinking && (sections[sec].sh_flags & SHF_FIXED)) {
1180
                    // this section is the first in a the non-relinkable part of a relinkable file.
1181
                    // Place base pointer at the same position relative to this section as in the original
1182
                    *pBasePonter = offset - sections[sec].sh_addr;
1183
                    basePointerAssigned = true;
1184
                    if (int64_t(*pBasePonter) < 0) {
1185
                        err.submit(ERR_INDEX_OUT_OF_RANGE);
1186
                        return;
1187
                    }
1188
                }
1189
                else if (sections[sec].order & 1) {
1190
                    // changing from const to executable or from data to bss. place base pointer here
1191
                    offset = (offset + MEMORY_MAP_ALIGN - 1) & int64_t(-MEMORY_MAP_ALIGN);
1192
                    *pBasePonter = offset;
1193
                    basePointerAssigned = true;
1194
                }
1195
                else if (sec + 1 >= sections.numEntries() //fistSection + numSections
1196
                || uint8_t(sections[sec+1].order) >> 1 != uint8_t(sections[sec].order) >> 1) {
1197
                    // last section with this base pointer. place base pointer here
1198
                    // (alternatively, place base pointer at the end of this section)
1199
                    offset = (offset + MEMORY_MAP_ALIGN - 1) & int64_t(-MEMORY_MAP_ALIGN);
1200
                    *pBasePonter = offset;
1201
                    basePointerAssigned = true;
1202
                }
1203
            }
1204
            // save address
1205
            sections[sec].sh_addr = offset;
1206
 
1207
            if (sections[sec].sh_module < 0xFFFFFFF0) {
1208
                // find section header
1209
                ElfFwcShdr & sectionHeader = modules2[sections[sec].sh_module].sectionHeaders[sections[sec].sectioni];
1210
                sectionHeader.sh_addr = offset;
1211
                offset += sectionHeader.sh_size;
1212
            }
1213
            else {
1214
                // dummy section for unresolved weak externals
1215
                switch (sections[sec].sh_module) {
1216
                case 0xFFFFFFF1:
1217
                    dummyConst = (uint32_t)offset;  break;
1218
                case 0xFFFFFFF2:
1219
                    dummyData = (uint32_t)offset;  break;
1220
                case 0xFFFFFFF3:
1221
                    dummyThreadData = (uint32_t)offset;  break;
1222
                case 0xFFFFFFF4:
1223
                    dummyFunc = (uint32_t)offset;  break;
1224
                }
1225
                offset += sections[sec].sh_size;
1226
            }
1227
            // align position in ELF file
1228
            offset = (offset + (1<<FILE_DATA_ALIGN)-1) & -(1<<FILE_DATA_ALIGN);
1229
            if ((rHeader.p_flags & SHF_READ) && ph+1 < outFile.programHeaders.numEntries()
1230
                && !(outFile.programHeaders[ph+1].p_flags & SHF_READ)
1231
                && rHeader.p_memsz <= rHeader.p_filesz) {
1232
                // readable section followed by non-readable section. Add empty space
1233
                offset += DATA_EXTRA_SPACE;
1234
            }
1235
            // update program header
1236
            rHeader.p_memsz = offset - rHeader.p_vaddr;
1237
            if (sections[sec].sh_type != SHT_NOBITS) {
1238
                rHeader.p_filesz = rHeader.p_memsz;
1239
            }
1240
        }
1241
        lastFlags = rHeader.p_flags;
1242
    }
1243
 
1244
    // check if special symbols have been overridden
1245
    specialSymbolsOverride();
1246
}
1247
 
1248
 
1249
// check if automatic symbols have been overridden
1250
void CLinker::specialSymbolsOverride() {
1251
    uint64_t addr;
1252
    bool basePointerChanged = false;
1253
    addr = findSymbolAddress("__ip_base");
1254
    if ((int64_t)addr >= 0) {
1255
        if (ip_base != addr) basePointerChanged = true;
1256
        ip_base = addr;
1257
    }
1258
    addr = findSymbolAddress("__datap_base");
1259
    if ((int64_t)addr >= 0) {
1260
        if (datap_base != addr) basePointerChanged = true;
1261
        datap_base = addr;
1262
    }
1263
    addr = findSymbolAddress("__threadp_base");
1264
    if ((int64_t)addr >= 0) {
1265
        if (threadp_base != addr) basePointerChanged = true;
1266
        threadp_base = addr;
1267
    }
1268
    if (relinking && basePointerChanged && modules2[0].sectionHeaders.numEntries()) {
1269
        // base pointer has been changed during relinking and there are fixed sections that 
1270
        // may contain addresses relative to the old value of the base pointers
1271
        err.submit(ERR_RELINK_BASE_POINTER_MOD);
1272
    }
1273
 
1274
    // find entry point
1275
    addr = findSymbolAddress("__entry_point");
1276
    if ((int64_t)addr >= 0) entry_point = addr;
1277
    else entry_point = ip_base;
1278
}
1279
 
1280
// find a module from a record in symbolExports.
1281
// the return value is an index into modules2
1282
int32_t CLinker::findModule(uint32_t library, uint32_t memberos) {
1283
    if (library == 0) return memberos;           // module not in a library
1284
    if (library == 0xFFFFFFFE) return -2;        // special symbol, not in any module
1285
    SLibraryModule modu;                         // module is in a library
1286
    modu.library = library;
1287
    modu.offset = memberos;
1288
    int32_t i = libmodules.findFirst(modu);
1289
    if (i >= 0) return libmodules[i].modul;
1290
    return -1;
1291
}
1292
 
1293
 
1294
// put values into all cross references
1295
void CLinker::relocate() {
1296
    uint32_t modu;                               // module index
1297
    uint32_t r;                                  // relocation loop counter
1298
    ElfFwcReloc * reloc;                        // relocation record
1299
    uint32_t sourcePos;                          // relocation source position in file
1300
    ElfFwcSym * targetSym;                      // target symbol record
1301
    ElfFwcSym * externTargetSym;                // external target symbol record
1302
    ElfFwcSym * refSym;                         // reference symbol record
1303
    uint64_t targetAddress;                      // address of target symbol
1304
    uint64_t referenceAddress;                   // address of reference symbol
1305
    int64_t  value;                              // value of relocation
1306
    uint32_t targetModule;                       // module containing target symbol
1307
    uint32_t refsymModule;                       // module containing reference symbol
1308
    SReloc2  rel2;                               // relocation record for executable file
1309
    bool     relink;                             // copy relocation to relinkable executable file
1310
 
1311
    // loop through all modules to get all relocation records
1312
    for (modu = 0; modu < modules2.numEntries(); modu++) {
1313
        if (modules2[modu].dataSize() == 0) continue;
1314
        relink = modules2[modu].relinkable;
1315
        for (r = 0; r < modules2[modu].relocations.numEntries(); r++) {
1316
            // loop through relocations
1317
            reloc = &modules2[modu].relocations[r];
1318
            if (reloc->r_type == 0) continue;              // removed relocation
1319
            // find source address
1320
            if (reloc->r_section > modules2[modu].nSections) {
1321
                err.submit(ERR_ELF_INDEX_RANGE); continue;
1322
            }
1323
            // source address in executable file
1324
            // uint64_t sourceAddr = modules2[modu].sectionHeaders[reloc->r_section].sh_addr + reloc->r_offset;
1325
            // source address in local module. This is where the binary data are currently stored
1326
            sourcePos = uint32_t(modules2[modu].sectionHeaders[reloc->r_section].sh_offset + reloc->r_offset);
1327
            if (sourcePos >= modules2[modu].dataBuffer.dataSize()) {
1328
                err.submit(ERR_ELF_INDEX_RANGE); continue;
1329
            }
1330
            // find target symbol
1331
            targetSym = &modules2[modu].symbols[reloc->r_sym];
1332
            externTargetSym = findSymbolAddress(&targetAddress, &targetModule, targetSym, modu);
1333
            if (externTargetSym == 0) {
1334
                err.submit(ERR_ELF_INDEX_RANGE); continue;
1335
            }
1336
            // check if target symbol is in relinkable section
1337
            if (externTargetSym->st_other & STV_RELINK) relink = true;
1338
            if (relink) {
1339
                // copy symbol records to executable file if necessary
1340
                if (targetSym->st_section || (targetSym->st_bind & STB_WEAK)) {
1341
                    targetSym->st_bind |= STB_EXE;
1342
                }
1343
            }
1344
 
1345
            // check register use
1346
            checkRegisterUse(targetSym, externTargetSym, targetModule);
1347
 
1348
            // find reference symbol
1349
            if (reloc->r_refsym && (reloc->r_type & R_FORW_RELTYPEMASK) == R_FORW_REFP) {
1350
                refSym = &modules2[modu].symbols[reloc->r_refsym];
1351
                refSym = findSymbolAddress(&referenceAddress, &refsymModule, refSym, modu);
1352
                if (refSym->st_other & STV_RELINK) relink = true;
1353
            }
1354
            else {
1355
                refSym = 0;
1356
                referenceAddress = 0;
1357
                refsymModule = 0;
1358
            }
1359
            value = int64_t(targetAddress - referenceAddress);
1360
 
1361
            // select relocation type
1362
            switch (reloc->r_type >> 16 & 0xFF) {
1363
            case R_FORW_ABS >> 16:  // absolute symbol or absolute address
1364
                if (externTargetSym->st_type != STT_CONSTANT && externTargetSym->st_type != 0) {
1365
                    // this is an absolute address to insert at load time. the code is not position-independent
1366
                    // char * nm =  (char*)modules2[modu].stringBuffer.buf() + targetSym->st_name;
1367
                    reloc->r_type |= R_FORW_LOADTIME;
1368
                    fileHeader.e_flags |= EF_RELOCATE | EF_POSITION_DEPENDENT;
1369
                }
1370
                break;
1371
            case R_FORW_SELFREL >> 16:
1372
                value = int64_t(targetAddress - reloc->r_offset - modules2[modu].sectionHeaders[reloc->r_section].sh_addr);
1373
                if ((modules2[modu].sectionHeaders[reloc->r_section].sh_flags
1374
                    ^ externTargetSym->st_other) & SHF_BASEPOINTER) {
1375
                    // different base pointers
1376
                DIFFERENTBASEPOINTERS:
1377
                    err.submit(ERR_LINK_DIFFERENT_BASE,
1378
                        cmd.getFilename(modules2[modu].moduleName),
1379
                        (char*)modules2[modu].stringBuffer.buf() + externTargetSym->st_name,
1380
                        cmd.getFilename(modules2[targetModule].moduleName));
1381
                }
1382
                break;
1383
            case R_FORW_IP_BASE >> 16:
1384
                value = int64_t(targetAddress - ip_base);
1385
                if (!(externTargetSym->st_other & STV_IP)) goto DIFFERENTBASEPOINTERS;
1386
                break;
1387
            case R_FORW_DATAP >> 16:
1388
                value = int64_t(targetAddress - datap_base);
1389
                if (!(externTargetSym->st_other & STV_DATAP)) goto DIFFERENTBASEPOINTERS;
1390
                break;
1391
            case R_FORW_THREADP >> 16:
1392
                if (!(externTargetSym->st_other & STV_THREADP)) goto DIFFERENTBASEPOINTERS;
1393
                break;
1394
            case R_FORW_REFP >> 16:
1395
                if (refSym == 0 || ((externTargetSym->st_other ^ refSym->st_other) & SHF_BASEPOINTER)) {
1396
                    goto DIFFERENTBASEPOINTERS;
1397
                }
1398
                break;
1399
            case R_FORW_SYSFUNC:
1400
            case R_FORW_SYSMODUL:
1401
            case R_FORW_SYSCALL:
1402
                // system function ID inserted at load time
1403
                reloc->r_type |= R_FORW_LOADTIME;
1404
                fileHeader.e_flags |= EF_RELOCATE;
1405
                break;
1406
            }
1407
            // add addend (sign extended)
1408
            value += reloc->r_addend;
1409
            // scale
1410
            uint32_t scale = reloc->r_type & R_FORW_RELSCALEMASK;
1411
            // check if divisible by scale
1412
            if (value & ((1 << scale) - 1)) {
1413
                // misaligned target. scaling of reference failed
1414
                err.submit(ERR_LINK_MISALIGNED_TARGET,
1415
                    cmd.getFilename(modules2[modu].moduleName),
1416
                    (char*)modules2[modu].stringBuffer.buf() + externTargetSym->st_name,
1417
                    cmd.getFilename(modules2[targetModule].moduleName));
1418
            }
1419
            value >>= scale;
1420
 
1421
            // check if overflow and insert value
1422
            switch ((reloc->r_type >> 8) & 0xFF) {
1423
            case R_FORW_8 >> 8:
1424
                modules2[modu].dataBuffer.get<int8_t>((uint32_t)sourcePos) = (int8_t)value;
1425
                if (value > 0x7F || value < -0x80) {
1426
                RELOCATIONOVERFLOW:
1427
                    err.submit(ERR_LINK_OVERFLOW,
1428
                        cmd.getFilename(modules2[modu].moduleName),
1429
                        (char*)modules2[modu].stringBuffer.buf() + externTargetSym->st_name,
1430
                        cmd.getFilename(modules2[targetModule].moduleName));
1431
                }
1432
                break;
1433
            case R_FORW_16 >> 8:
1434
                modules2[modu].dataBuffer.get<int16_t>((uint32_t)sourcePos) = (int16_t)value;
1435
                if (value > 0x7FFF || value < -0x8000) goto RELOCATIONOVERFLOW;
1436
                break;
1437
            case R_FORW_24 >> 8:
1438
                modules2[modu].dataBuffer.get<int16_t>((uint32_t)sourcePos) = (int16_t)value;
1439
                modules2[modu].dataBuffer.get<int8_t>((uint32_t)sourcePos + 2) = (int8_t)(value >> 16);
1440
                if (value > 0x7FFFFF || value < -0x800000)  goto RELOCATIONOVERFLOW;
1441
                break;
1442
            case R_FORW_32 >> 8:
1443
                modules2[modu].dataBuffer.get<int32_t>((uint32_t)sourcePos) = (int32_t)value;
1444
                if (value > 0x7FFFFFFF || value < -((int64_t)1 << 31))  goto RELOCATIONOVERFLOW;
1445
                break;
1446
            case R_FORW_32LO >> 8:
1447
                modules2[modu].dataBuffer.get<int16_t>((uint32_t)sourcePos) = (int16_t)value;
1448
                if (value > 0x7FFFFFFF || value < -((int64_t)1 << 31))  goto RELOCATIONOVERFLOW;
1449
                break;
1450
            case R_FORW_32HI >> 8:
1451
                if (value > 0x7FFFFFFF || value < -((int64_t)1 << 31))  goto RELOCATIONOVERFLOW;
1452
                modules2[modu].dataBuffer.get<int16_t>((uint32_t)sourcePos) = (int16_t)(value >> 16);
1453
                if (value > 0x7FFFFFFF || value < -((int64_t)1 << 31))  goto RELOCATIONOVERFLOW;
1454
                break;
1455
            case R_FORW_64 >> 8:
1456
                modules2[modu].dataBuffer.get<int64_t>((uint32_t)sourcePos) = value;
1457
                break;
1458
            case R_FORW_64LO >> 8:
1459
                modules2[modu].dataBuffer.get<int32_t>((uint32_t)sourcePos) = (int32_t)value;
1460
                break;
1461
            case R_FORW_64HI >> 8:
1462
                modules2[modu].dataBuffer.get<int32_t>((uint32_t)sourcePos) = (int32_t)(value >> 32);
1463
                break;
1464
            }
1465
            // mark reference to unresolved and autogenerated symbols for copy to executable
1466
            if (relinkable) {
1467
                if (externTargetSym->st_section == 0 && (externTargetSym->st_bind & STB_WEAK)) relink = true;
1468
                if (refSym && refSym->st_section == 0 && (refSym->st_bind & STB_WEAK)) relink = true;
1469
                if (externTargetSym->st_other & STV_AUTOGEN) relink = true;
1470
                if (refSym && refSym->st_other & STV_AUTOGEN) relink = true;
1471
            }
1472
            // copy symbols and relocation record to executable file if target symbol or reference symbol are in relinkable sections
1473
            if (relink || (reloc->r_type & R_FORW_LOADTIME)) {
1474
                externTargetSym->st_bind |= STB_EXE;
1475
                if (refSym) refSym->st_bind |= STB_EXE;
1476
                memcpy(&rel2, reloc, sizeof(ElfFwcReloc));
1477
                rel2.modul = modu;
1478
                rel2.symLocal = (targetModule == modu)        // symbol is local
1479
                    || ((targetSym->st_bind & STB_EXE) && targetSym->st_section == 0); // keep local record for weak external so that it can be replaced by relinking
1480
                rel2.refSymLocal = (refsymModule == modu);
1481
                relocations2.push(rel2);
1482
            }
1483
        }
1484
    }
1485
}
1486
 
1487
// Check if external function call has compatible register use
1488
void CLinker::checkRegisterUse(ElfFwcSym * sym1, ElfFwcSym * sym2, uint32_t modul) {
1489
    if ((sym1->st_other | sym1->st_other) & STV_REGUSE) {
1490
        // register use specified for source or target or both
1491
        uint32_t tregusea1 = sym1->st_reguse1;
1492
        uint32_t tregusea2 = sym1->st_reguse2;
1493
        uint32_t treguseb1 = sym2->st_reguse1;
1494
        uint32_t treguseb2 = sym2->st_reguse2;
1495
        if (!(sym1->st_other & STV_REGUSE)) {
1496
            tregusea1 = tregusea2 = 0x0000FFFF; // register use not specified for source. assume default
1497
        }
1498
        if (sym1 == sym2 && sym1->st_section == 0 && (sym1->st_bind & STB_WEAK)) {
1499
            // unresolved weak. will set r0 = 0 and v0 = 0
1500
            treguseb1 = unresolvedReguse1;
1501
            treguseb2 = unresolvedReguse2;
1502
        }
1503
        else if (!(sym2->st_other & STV_REGUSE)) {
1504
            // register use not specified for external target. assume default
1505
            treguseb1 = treguseb2 = 0x0000FFFF;
1506
        }
1507
        uint32_t tregusem1 = treguseb1 & ~tregusea1;  // registers in target and not in source
1508
        uint32_t tregusem2 = treguseb2 & ~tregusea2;
1509
        if (tregusem1 | tregusem2) {
1510
            // mismatched register use
1511
            const char * symname = modules2[modul].stringBuffer.getString(sym2->st_name);
1512
            char text[30];
1513
            sprintf(text, "0x%X, 0x%X", tregusem1, tregusem2);
1514
            err.submit(ERR_LINK_REGUSE, cmd.getFilename(modules2[modul].moduleName), symname,text);
1515
            // avoid reporting multiple times if there are multiple references from a module to the same symbol
1516
            sym1->st_reguse1 = treguseb1;
1517
            sym1->st_reguse2 = treguseb2;
1518
        }
1519
    }
1520
}
1521
 
1522
// find a symbol and its address
1523
// the return value is a pointer to a remote symbol record. The address is returned in 'a'
1524
ElfFwcSym * CLinker::findSymbolAddress(uint64_t * a, uint32_t * targetMod, ElfFwcSym * sym, uint32_t modul) {
1525
    if (targetMod) *targetMod = modul;
1526
    if (sym->st_section && (sym->st_bind & ~STB_EXE) != STB_WEAK2) {
1527
        // target is in same module
1528
        if (sym->st_type == STT_CONSTANT) {
1529
            // absolute symbol
1530
            *a = sym->st_value;
1531
        }
1532
        else if (sym->st_section >= modules2[modul].nSections) {
1533
            err.submit(ERR_ELF_INDEX_RANGE); return sym;
1534
        }
1535
        else { // section address + offset into section
1536
            // check if section is included in exe file. 
1537
            // This will fail if there is a reference to a non-weak symbol in a replaced local communal section
1538
            SLinkSection2 secSearch;
1539
            secSearch.sh_module = modul;
1540
            secSearch.sectioni = sym->st_section;
1541
            int32_t x = sections2.findFirst(secSearch);
1542
            if (x < 0) {
1543
                const char * symname = (char*)modules2[modul].stringBuffer.buf() + sym->st_name;
1544
                err.submit(ERR_LINK_UNRESOLVED, symname, "(relocation)");
1545
                return sym;
1546
            }
1547
            *a = modules2[modul].sectionHeaders[sym->st_section].sh_addr + sym->st_value;
1548
        }
1549
        return sym;
1550
    }
1551
    else {
1552
        // target is external. find it in symbolExports
1553
        SSymbolEntry symSearch;                      // record for searching for symbol
1554
        zeroAllMembers(symSearch);                   // initialize
1555
        if (sym->st_name > modules2[modul].stringBuffer.dataSize()) {
1556
            err.submit(ERR_ELF_INDEX_RANGE); return sym;
1557
        }
1558
        const char * symname = (char*)modules2[modul].stringBuffer.buf() + sym->st_name;
1559
        symSearch.name = symbolNameBuffer.pushString(symname);
1560
        symSearch.st_bind = STB_IGNORE;          // find both strong and weak symbols
1561
        uint32_t firstMatch = 0;
1562
        uint32_t numMatch = symbolExports.findAll(&firstMatch, symSearch);
1563
        if (numMatch == 0) {
1564
            // symbol name not found
1565
            if (!(sym->st_bind & STB_WEAK)) {
1566
                sym->st_bind = STB_UNRESOLVED;   // not weak. mark as unresolved
1567
                if (sym->st_type == STT_FUNC) sym->st_other |= SHF_EXEC;
1568
            }
1569
            // give it a dummy
1570
            *targetMod = 0;
1571
            switch (sym->st_other & (SHF_BASEPOINTER | SHF_EXEC)) {
1572
            case 0:                   // constant
1573
                *a = 0;  break;
1574
            case STV_IP:              // read-only data
1575
                *a = dummyConst;  break;
1576
            case STV_DATAP:           // writeable data. Make one address for each unresolved reference
1577
                *a = dummyData + (--unresolvedWeakNum) * 8;
1578
                break;
1579
            case STV_THREADP:         // thread-local. this is rare
1580
                *a = dummyThreadData;  break;
1581
            case STV_IP | STV_EXEC:   // unresolved function
1582
                *a = dummyFunc;  break;
1583
            }
1584
            return sym;
1585
        }
1586
 
1587
        // one or more matching symbols found
1588
        int32_t targetModule = findModule(symbolExports[firstMatch].library, symbolExports[firstMatch].member);
1589
        if (targetModule == -2) {
1590
            // special symbol
1591
            switch (symbolExports[firstMatch].symindex) {
1592
            case 1:
1593
                *a = ip_base;  break;
1594
            case 2:
1595
                *a = datap_base;  break;
1596
            case 3:
1597
                *a = threadp_base;  break;
1598
            case 4:
1599
                *a = event_table;  break;
1600
            case 5:
1601
                *a = event_table_num;  break;
1602
            default:
1603
                err.submit(ERR_LINK_UNRESOLVED, symname, "relocation");
1604
            }
1605
            sym->st_other |= STV_AUTOGEN;        // symbol is autogenerated
1606
            return sym;
1607
        }
1608
        if (targetMod) *targetMod = targetModule;
1609
        if (targetModule < 0) {
1610
            // unexpected error 
1611
            err.submit(ERR_LINK_UNRESOLVED, symname, "relocation");
1612
            return sym;
1613
        }
1614
        // find external target symbol
1615
        ElfFwcSym * targetSym = &modules2[targetModule].symbols[symbolExports[firstMatch].symindex];
1616
        if (modules2[targetModule].relinkable) {
1617
            targetSym->st_other |= STV_RELINK;
1618
        }
1619
        if (targetSym->st_type == STT_CONSTANT) {
1620
            // absolute symbol
1621
            *a = targetSym->st_value;
1622
        }
1623
        else if (targetSym->st_section >= modules2[targetModule].nSections) {
1624
            err.submit(ERR_ELF_INDEX_RANGE); return sym;
1625
        }
1626
        else { // section address + offset into section
1627
            // check if target section is included in exe file. This will fail only if there is a reference to a non-weak symbol in a replaced local communal section
1628
            SLinkSection2 secSearch;
1629
            secSearch.sh_module = targetModule;
1630
            secSearch.sectioni = targetSym->st_section;
1631
            int32_t x = sections2.findFirst(secSearch);
1632
            if (x < 0) {
1633
                const char * symname = (char*)modules2[modul].stringBuffer.buf() + sym->st_name;
1634
                err.submit(ERR_LINK_UNRESOLVED, symname, "(removed)");
1635
                return sym;
1636
            }
1637
            *a = modules2[targetModule].sectionHeaders[targetSym->st_section].sh_addr + targetSym->st_value;
1638
        }
1639
        return targetSym;
1640
    }
1641
}
1642
 
1643
// find the final address of a symbol from its name
1644
uint64_t CLinker::findSymbolAddress(const char * name) {
1645
    SSymbolEntry symSearch;                      // record for symbol search
1646
    int32_t symi;                                // symbol index
1647
    int32_t modul;                               // module containing symbol
1648
    ElfFwcSym * sym;                            // pointer to symbol record
1649
    uint64_t addr = 0xFFFFFFFFFFFFFFFF;          // return value
1650
    symSearch.name = symbolNameBuffer.pushString(name);
1651
    symSearch.st_bind = STB_GLOBAL;              // search for strong symbols only
1652
    symi = symbolExports.findFirst(symSearch);
1653
    if (symi >= 0) {                             // strong symbol found
1654
        modul = findModule(symbolExports[symi].library, symbolExports[symi].member);
1655
        if (modul >= 0) {
1656
            sym = &modules2[modul].symbols[symbolExports[symi].symindex];
1657
            findSymbolAddress(&addr, 0, sym, modul);
1658
        }
1659
    }
1660
    return addr;
1661
}
1662
 
1663
// copy sections to output file
1664
void CLinker::copySections() {
1665
    ElfFwcShdr header;                          // section header
1666
    zeroAllMembers(header);                      // initialize
1667
    uint32_t s;                                  // section index
1668
    CELF * modul;                                // module containing section
1669
    uint32_t sectionx = 0;                       // section index in executable file
1670
    uint32_t progheadi = 0;                      // program header index
1671
    uint32_t lastprogheadi = 0xFFFFFFFF;         // program header index of previous section
1672
    CMemoryBuffer dummyBuffer;                   // buffer for dummy symbols
1673
    CMemoryBuffer * dataBuf;                     // pointer to data buffer
1674
    uint64_t dummyValue;                         // value of unresolved weak external symbols
1675
    uint32_t lastFlags = 0;                      // previous section flags
1676
    uint8_t type, lastType = 0;                  // section type
1677
    uint32_t pHfistSection = 0;                  // first section covered by program header
1678
    uint32_t pHlastSection = 0;                  // last section covered by program header
1679
    uint32_t pHnumSections = 0;                  // number of sections covered by program header
1680
    ElfFwcPhdr * pPHead = 0;                     // pointer to program header
1681
 
1682
    // find program header
1683
    if (outFile.programHeaders.numEntries()) {
1684
        pPHead = &outFile.programHeaders[progheadi];
1685
        pHfistSection = (uint32_t)pPHead->p_paddr;
1686
        pHnumSections = (uint32_t)(pPHead->p_paddr >> 32);
1687
    }
1688
 
1689
    // loop through sections
1690
    for (s = 0; s < sections.numEntries(); s++) {
1691
        // make section header
1692
        header.sh_type = sections[s].sh_type;
1693
        if (header.sh_type == 0) continue;
1694
        header.sh_name = sections[s].name;
1695
        header.sh_flags = sections[s].sh_flags;
1696
        header.sh_size = sections[s].sh_size;
1697
        header.sh_align = sections[s].sh_align;
1698
        header.sh_module = sections[s].sh_module;
1699
        if (header.sh_module < modules2.numEntries()) {
1700
            modul = &modules2[sections[s].sh_module]; // find module
1701
            header.sh_library = modul->library;
1702
            header.sh_offset = modul->sectionHeaders[sections[s].sectioni].sh_offset;
1703
            header.sh_addr = modul->sectionHeaders[sections[s].sectioni].sh_addr;
1704
            dataBuf = &modul->dataBuffer;
1705
        }
1706
        else {
1707
            header.sh_library = 0;
1708
            // make section for dummy symbol
1709
            switch (sections[s].sh_module) {
1710
            case 0xFFFFFFF1: default:            // read only data
1711
                dummyValue = 0;
1712
                header.sh_offset = dummyBuffer.push(&dummyValue, 8);
1713
                header.sh_addr = dummyConst;
1714
                break;
1715
            case 0xFFFFFFF2:                     // writeable data
1716
                dummyValue = 0;
1717
                header.sh_offset = dummyBuffer.dataSize();
1718
                header.sh_addr = dummyData;
1719
                for (uint32_t i = 0; i < unresolvedWeakNum; i++) dummyBuffer.push(&dummyValue, 8);
1720
                break;
1721
            case 0xFFFFFFF3:                     // thread-local data 
1722
                dummyValue = 0;
1723
                header.sh_offset = dummyBuffer.push(&dummyValue, 8);
1724
                header.sh_addr = dummyThreadData;
1725
                break;
1726
            case 0xFFFFFFF4:                     // unresolved weak function. return zero
1727
                header.sh_addr = dummyFunc;
1728
                header.sh_offset = dummyBuffer.dataSize();
1729
                for (uint32_t i = 0; i < unresolvedFunctionN; i++) {
1730
                    dummyBuffer.push(&unresolvedFunction[i], 4);
1731
                }
1732
                break;
1733
            case 0xFFFFFFF8:                     // event list
1734
                header.sh_offset = dummyBuffer.push(eventData.buf(), eventData.dataSize());
1735
                break;
1736
            }
1737
            dataBuf = &dummyBuffer;
1738
        }
1739
        // find correcponding program header, if any
1740
        while (s >= pHfistSection + pHnumSections && progheadi+1 < outFile.programHeaders.numEntries()) {
1741
            progheadi++;
1742
            pPHead = &outFile.programHeaders[progheadi];
1743
            pHfistSection = (uint32_t)pPHead->p_paddr;
1744
            pHnumSections = (uint32_t)(pPHead->p_paddr >> 32);
1745
        }
1746
        // is this section covered by a program header?
1747
        bool hasProgHead = s >= pHfistSection && s < pHfistSection + pHnumSections;
1748
 
1749
        if (hasProgHead && progheadi == lastprogheadi && s > 0 && sections[s].sh_type != SHT_NOBITS) {
1750
            // this section is covered by same program header as last section
1751
            // insert any necessary filler
1752
            uint64_t fill = sections[s].sh_addr - (sections[s-1].sh_addr + sections[s-1].sh_size);
1753
            if (fill > MAX_ALIGN) err.submit(ERR_LINK_OVERFLOW, "","","");
1754
            if (fill > 0) {
1755
                // insert alignment filler in dataBuffer               
1756
                outFile.insertFiller(fill);
1757
            }
1758
        }
1759
        type = header.sh_type;
1760
        if (type == SHT_COMDAT) type = SHT_PROGBITS;  // communal and normal data can be joined together
1761
 
1762
        // add section to outFile
1763
        if (hasProgHead
1764
        && progheadi == lastprogheadi
1765
        && type == lastType
1766
        && !cmd.debugOptions
1767
        && !(header.sh_flags & SHF_RELINK)
1768
        && !(lastFlags & SHF_RELINK)
1769
        && sections[s].sh_module < 0xFFFFFFF0) {
1770
            outFile.extendSection(header, *dataBuf);
1771
        }
1772
        else {
1773
            sectionx = outFile.addSection(header, cmd.fileNameBuffer, *dataBuf);
1774
        }
1775
        // remember new section index
1776
        sections[s].sectionx = sectionx;
1777
        lastprogheadi = progheadi;
1778
        lastType = type;
1779
        lastFlags = header.sh_flags;
1780
 
1781
#if 0   // testing only: list sections
1782
        ElfFwcShdr header3 = outFile.sectionHeaders[sectionx];
1783
        printf("\n%2i %X os=%X, sz=%X %s", outFile.sectionHeaders.numEntries(), header3.sh_type, header3.sh_offset, header3.sh_size, cmd.getFilename(header.sh_name));
1784
#endif
1785
    }
1786
 
1787
    // update section indexes in segment headers.
1788
    // indexes may have changed if some sections are joined together.
1789
    // p_paddr contains first section index and number of sections
1790
    for (uint32_t ph = 0; ph < outFile.programHeaders.numEntries(); ph++) {
1791
        pHfistSection = (uint32_t)outFile.programHeaders[ph].p_paddr;
1792
        pHnumSections = (uint32_t)(outFile.programHeaders[ph].p_paddr >> 32);
1793
        pHlastSection = pHfistSection + pHnumSections - 1;
1794
        if (pHlastSection < sections.numEntries()) {
1795
            uint32_t sx1 = sections[pHfistSection].sectionx;  // first new section index
1796
            uint32_t sx2 = sections[pHlastSection].sectionx;  // last new section index
1797
            uint32_t numsx = sx2 - sx1 + 1;                   // number of new sections
1798
            outFile.programHeaders[ph].p_paddr = sx1 | (uint64_t)numsx << 32;
1799
        }
1800
    }
1801
 
1802
    // sections list has been modified. update sections2
1803
    sections2.copy(sections);
1804
    sections2.sort();
1805
 
1806
    // make lists of module names and library names
1807
    CDynamicArray<uint32_t> moduleNames, libraryNames;
1808
    moduleNames.setNum(modules2.numEntries());
1809
    for (uint32_t m = 0; m < modules2.numEntries(); m++) {
1810
        moduleNames[m] = modules2[m].moduleName;
1811
    }
1812
    libraryNames.setNum(libraries.numEntries());
1813
    for (uint32_t lib = 0; lib < libraries.numEntries(); lib++) {
1814
        libraryNames[lib] = libraries[lib].libraryName;
1815
    }
1816
 
1817
    // copy module names and library names to relinkable sections
1818
    outFile.addModuleNames(moduleNames, libraryNames);
1819
}
1820
 
1821
// copy symbols to output file
1822
void CLinker::copySymbols() {
1823
    uint32_t s;                                  // symbol index
1824
    ElfFwcSym sym;                               // symbol record
1825
    uint32_t modul;                              // module containing symbol
1826
    SSymbolXref2 xref;                           // symbol cross reference record
1827
    SLinkSection2 searchSection;                 // record to search for section
1828
    char const * name;                           // symbol name
1829
    int32_t sx;                                  // section index in sections2
1830
    char text[12];                               // temporary text
1831
    CDynamicArray<SSymbolXref2> xreflist;        // list of cross reference records, sorted by name
1832
    // make symbol number 0 empty
1833
    zeroAllMembers(sym);
1834
    outFile.addSymbol(sym, cmd.fileNameBuffer);
1835
 
1836
    for (s = 0; s < symbolExports.numEntries(); s++) {
1837
        // skip weak public symbols if overridden and not relinkable
1838
        while (s+1 < symbolExports.numEntries() && symbolExports[s] == symbolExports[s+1]) {
1839
            // next symbol has same name
1840
            modul = findModule(symbolExports[s].library, symbolExports[s].member);
1841
            if (modules2[modul].relinkable) break;  // relinkable. preserve both symbols
1842
            if (symbolExports[s+1].st_bind & STB_WEAK) {
1843
                modul = findModule(symbolExports[s+1].library, symbolExports[s+1].member);
1844
                modules2[modul].symbols[symbolExports[s+1].symindex].st_bind |= STB_IGNORE;
1845
            }
1846
            s++;
1847
        }
1848
        // if (symbolExports[s].library == 0xFFFFFFFE) 
1849
        // The special symbols __ip_base, etc are not copied to the executable file.        
1850
        // If we want them then we need to find the corresponding sections        
1851
    }
1852
 
1853
    // loop through all modules to get all symbols
1854
    for (modul = 0; modul < modules2.numEntries(); modul++) {
1855
        for (s = 0; s < modules2[modul].symbols.numEntries(); s++) {
1856
            sym = modules2[modul].symbols[s];
1857
            if (sym.st_section || (sym.st_bind & STB_EXE)) {
1858
                if ((sym.st_bind & (STB_EXE | STB_IGNORE)) == STB_EXE
1859
                || ((sym.st_bind & (STB_GLOBAL | STB_WEAK)))
1860
                || (cmd.debugOptions && sym.st_bind != STB_IGNORE)) {
1861
                    name = (char*)modules2[modul].stringBuffer.buf() + modules2[modul].symbols[s].st_name;
1862
                    xref.modul = modul;
1863
                    xref.name = symbolNameBuffer.pushString(name);
1864
                    xref.symi = s;
1865
                    xref.symx = 0;
1866
                    xref.isPublic = sym.st_section != 0;
1867
                    xref.isWeak = (sym.st_bind & STB_WEAK) != 0;
1868
                    xreflist.push(xref);
1869
                }
1870
            }
1871
        }
1872
    }
1873
    // sort by name
1874
    xreflist.sort();
1875
    bool changed = false;
1876
    // remove any $$number and subsequent text from all symbol names
1877
    for (s = 0; s < xreflist.numEntries(); s++) {
1878
        char * name1 = (char*)symbolNameBuffer.buf() + xreflist[s].name;
1879
        char * p = strchr(name1, '$');
1880
        if (p && p[1] == '$' && p[2] >= '0' && p[2] <= '9') {
1881
            *p = 0;
1882
            changed = true;
1883
        }
1884
    }
1885
    // sort again
1886
    if (changed) xreflist.sort();
1887
 
1888
    // search for duplicate names
1889
    for (s = 0; s < xreflist.numEntries(); s++) {
1890
        uint32_t num = 0;
1891
        name = symbolNameBuffer.getString(xreflist[s].name);
1892
        if (xreflist[s].isPublic && !xreflist[s].isWeak) {
1893
            // local or public non-weak symbol. check if duplicate names
1894
            while (s+1 < xreflist.numEntries() && !(xreflist[s] < xreflist[s+1])) {
1895
                // next symbol has same name
1896
                s++;
1897
                if (xreflist[s].isPublic && !xreflist[s].isWeak) {
1898
                    // this symbol is local or public and non-weak. there is a name clash
1899
                    // change duplicate name to name$$number
1900
                    xreflist[s].name = symbolNameBuffer.push(name, (uint32_t)strlen(name));
1901
                    sprintf(text, "$$%u", ++num);
1902
                    symbolNameBuffer.pushString(text);
1903
                    const char * name2 = symbolNameBuffer.getString(xreflist[s].name);
1904
                    // also change name of original symbol
1905
                    SSymbolXref2 & x2 = xreflist[s];
1906
                    ElfFwcSym & s2 = modules2[x2.modul].symbols[x2.symi];
1907
                    s2.st_name = modules2[x2.modul].stringBuffer.pushString(name2);
1908
                }
1909
            }
1910
        }
1911
    }
1912
    // sort cross references by module
1913
    symbolXref << xreflist;
1914
    symbolXref.sort();
1915
 
1916
    // copy symbols to outFile
1917
    for (s = 0; s < symbolXref.numEntries(); s++) {
1918
        modul = symbolXref[s].modul;
1919
        sym = modules2[modul].symbols[symbolXref[s].symi];
1920
        if (sym.st_section != 0) {
1921
            // translate local section index to final section index
1922
            searchSection.sh_module = modul;
1923
            searchSection.sectioni = sym.st_section;
1924
            sx = sections2.findFirst(searchSection);
1925
            if (sx < 0) {
1926
                continue;  // symbol is in a discarded communal section. drop it
1927
            }
1928
            // adjust address
1929
            uint32_t newsection = sections2[sx].sectionx;
1930
            sym.st_value += sections2[sx].sh_addr - outFile.sectionHeaders[newsection].sh_addr;
1931
            sym.st_section = newsection;
1932
        }
1933
        sym.st_bind &= ~ STB_EXE;
1934
        symbolXref[s].symx = outFile.addSymbol(sym, modules2[modul].stringBuffer);
1935
    }
1936
    // make records for unresolved weak symbols
1937
    if (relinkable) {
1938
        zeroAllMembers(sym);
1939
        for (s = 0; s < symbolImports.numEntries(); s++) {
1940
            if ((symbolImports[s].status & 5) && (symbolImports[s].st_bind & STB_WEAK)) {
1941
                // unresolved weak. make a symbol record
1942
                sym.st_name = symbolImports[s].name;
1943
                sym.st_type = symbolImports[s].st_type;
1944
                sym.st_bind = symbolImports[s].st_bind;
1945
                sym.st_other = symbolImports[s].st_other;
1946
                // skip any additional unresolved symbols with same name
1947
                while (s+1 < symbolImports.numEntries() && symbolImports[s] == symbolImports[s+1]) s++;
1948
                // put record in output file
1949
                xref.symx = outFile.addSymbol(sym, symbolNameBuffer);
1950
                xref.name = sym.st_name;
1951
                xref.modul = symbolImports[s].library;
1952
                xref.symi = symbolImports[s].symindex;
1953
                // put new index into list of unresolved weak symbols
1954
                unresWeakSym.push(xref);  // this list will be sorted by name because symbolImports is sorted by name
1955
            }
1956
        }
1957
    }
1958
}
1959
 
1960
// copy relocation records to output file if needed
1961
void CLinker::copyRelocations() {
1962
    uint32_t r;                                  // relocation index
1963
    int32_t s;                                   // symbol index
1964
    SReloc2  rel2;                               // extended relocation record
1965
    SSymbolXref symx;                            // record for searching for symbol in symbolXref
1966
    CDynamicArray<SReloc2> relocations3;         // extended relocation records. load-time relocations first
1967
    relocations3.setSize(relocations2.dataSize());
1968
 
1969
    // get load-time relocations first
1970
    for (r = 0; r < relocations2.numEntries(); r++) {
1971
        if (relocations2[r].r_type & R_FORW_LOADTIME) {
1972
            relocations3.push(relocations2[r]);
1973
        }
1974
    }
1975
    // get remaining relocations, used only for relinking
1976
    for (r = 0; r < relocations2.numEntries(); r++) {
1977
        if (!(relocations2[r].r_type & R_FORW_LOADTIME)) {
1978
            relocations3.push(relocations2[r]);
1979
        }
1980
    }
1981
 
1982
    // relocations3 contains list of relocations that need to be copied to executable file
1983
    for (r = 0; r < relocations3.numEntries(); r++) {
1984
        rel2 = relocations3[r];
1985
        if (rel2.r_type == 0) continue;          // removed
1986
        if (rel2.modul >= modules2.numEntries()) {
1987
            err.submit(ERR_ELF_INDEX_RANGE);  continue;
1988
        }
1989
        // translate section index
1990
        SLinkSection2 secSearch;
1991
        secSearch.sh_module = rel2.modul;
1992
        secSearch.sectioni = rel2.r_section;
1993
        int32_t x = sections2.findFirst(secSearch);
1994
        if (x < 0) continue;                     // section not found. ignore
1995
        rel2.r_section = sections2[x].sectionx;
1996
        // adjust offset
1997
        rel2.r_offset += sections2[x].sh_addr - outFile.sectionHeaders[rel2.r_section].sh_addr;
1998
 
1999
        // translate symbol index
2000
        if (rel2.symLocal) {
2001
            // symbol is local. reference by ID
2002
            symx.modul = rel2.modul;
2003
            symx.symi = rel2.r_sym;
2004
            s = symbolXref.findFirst(symx);
2005
            if (s < 0) {
2006
                // unresolved weak
2007
                rel2.r_sym = resolveRelocationTarget(rel2.modul, rel2.r_sym);
2008
            }
2009
            else  rel2.r_sym = symbolXref[s].symx;
2010
        }
2011
        else {
2012
            // symbol is remote. search by name
2013
            rel2.r_sym = resolveRelocationTarget(rel2.modul, rel2.r_sym);
2014
        }
2015
 
2016
        // translate reference symbol index
2017
        if (rel2.r_refsym) {
2018
            if (rel2.refSymLocal) {
2019
                // reference symbol is local. reference by ID
2020
                symx.modul = rel2.modul;
2021
                symx.symi = rel2.r_refsym;
2022
                s = symbolXref.findFirst(symx);
2023
                if (s < 0) {
2024
                    rel2.r_refsym = resolveRelocationTarget(rel2.modul, rel2.r_refsym);
2025
                }
2026
                else rel2.r_refsym = symbolXref[s].symx;
2027
            }
2028
            else {
2029
                // reference symbol is remote. search by name
2030
                rel2.r_refsym = resolveRelocationTarget(rel2.modul, rel2.r_refsym);
2031
            }
2032
        }
2033
        // put relocation in outFile
2034
        outFile.addRelocation(rel2);
2035
    }
2036
}
2037
 
2038
// resolve relocation target for executable file record
2039
uint32_t CLinker::resolveRelocationTarget(uint32_t modul, uint32_t symi) {
2040
    CELF * modulp;                               // pointer to module
2041
    const char * symname;                        // symbol name
2042
    int32_t ie;                                  // index into symbolExports 
2043
    int32_t iu;                                  // index into unresWeakSym 
2044
    int32_t is;                                  // index into symbolXref 
2045
    uint32_t modt;                               // target module
2046
    SSymbolEntry syms;                           // record for searching for symbol in symbolExports
2047
    SSymbolXref2 symu;                           // record for searching for symbol in unresWeakSym
2048
    SSymbolXref symx;                            // record for searching for symbol in symbolXref
2049
 
2050
    modulp = &modules2[modul];                   // module
2051
    // search by name
2052
    if (symi >= modulp->symbols.numEntries()) {
2053
        err.submit(ERR_ELF_INDEX_RANGE);  return 0;
2054
    }
2055
    symname = (char*)modulp->stringBuffer.buf() + modulp->symbols[symi].st_name;
2056
    syms.name = symbolNameBuffer.pushString(symname);
2057
    syms.st_bind = STB_IGNORE;          // find both strong and weak symbols
2058
    ie = symbolExports.findFirst(syms);
2059
    if (ie < 0) {
2060
        // symbol name not found
2061
        if (modulp->symbols[symi].st_bind & STB_WEAK) {
2062
            // weak symbol not found
2063
            symu.name = symbolNameBuffer.pushString(symname);
2064
            iu = unresWeakSym.findFirst(symu);
2065
            if (iu >= 0) {
2066
                return unresWeakSym[iu].symx;
2067
            }
2068
            // strong symbol not found
2069
            err.submit(ERR_REL_SYMBOL_NOT_FOUND);  return 0;  // should not occur
2070
        }
2071
    }
2072
    if (symbolExports[ie].library > 0xFFFFFFF0) {
2073
        symu.name = symbolNameBuffer.pushString(symname);
2074
        iu = unresWeakSym.findFirst(symu);
2075
        if (iu >= 0) {
2076
            return unresWeakSym[iu].symx;
2077
        }
2078
    }
2079
    // module containing target symbol
2080
    modt = symbolExports[ie].member;
2081
    uint32_t symlib = symbolExports[ie].library;
2082
    if (symlib != 0 && symlib < 0xFFFFFFF0) {
2083
        modt = (uint32_t)findModule(symbolExports[ie].library, modt);
2084
        if ((int32_t)modt < 0) {
2085
            err.submit(ERR_REL_SYMBOL_NOT_FOUND);  return 0;  // should not occur
2086
        }
2087
    }
2088
    else if (symlib) {
2089
        modt = symlib;
2090
    }
2091
    symx.modul = modt;
2092
    symx.symi = symbolExports[ie].symindex;
2093
    // find new index for this symbol
2094
    is = symbolXref.findFirst(symx);
2095
    if (is < 0) {
2096
        err.submit(ERR_REL_SYMBOL_NOT_FOUND);  return 0;  // should not occur
2097
    }
2098
    return symbolXref[is].symx;
2099
}
2100
 
2101
// make executable file header
2102
void CLinker::makeFileHeader() {
2103
    fileHeader.e_type = ET_EXEC;                 // executable file
2104
    fileHeader.e_ip_base = ip_base;              // __ip_base relative to first ip based segment
2105
    fileHeader.e_datap_base = datap_base;        // __datap_base relative to first datap based segment
2106
    fileHeader.e_threadp_base = 0;               // __threadp_base relative to first threadp based segment
2107
    fileHeader.e_entry = entry_point;            // entry point for startup code
2108
    if (relinkable) fileHeader.e_flags |= EF_RELINKABLE; // relinking allowed
2109
}

powered by: WebSVN 2.1.0

© copyright 1999-2024 OpenCores.org, equivalent to Oliscience, all rights reserved. OpenCores®, registered trademark.