/
elfobj.d
3749 lines (3331 loc) · 117 KB
/
elfobj.d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Output to ELF object files
*
* http://www.sco.com/developers/gabi/2003-12-17/ch4.sheader.html
*
* Compiler implementation of the
* $(LINK2 https://www.dlang.org, D programming language).
*
* Copyright: Copyright (C) ?-1998 by Symantec
* Copyright (C) 2000-2024 by The D Language Foundation, All Rights Reserved
* Authors: $(LINK2 https://www.digitalmars.com, Walter Bright)
* License: $(LINK2 https://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
* Source: $(LINK2 https://github.com/dlang/dmd/blob/master/src/dmd/backend/elfobj.d, backend/elfobj.d)
*/
module dmd.backend.elfobj;
import core.stdc.stdio;
import core.stdc.stdlib;
import core.stdc.string;
// qsort is only nothrow in newer versions of druntime (since 2.081.0)
alias _compare_fp_t = extern(C) nothrow int function(const void*, const void*);
private extern(C) void qsort(scope void* base, size_t nmemb, size_t size, _compare_fp_t compar) nothrow @nogc;
import dmd.backend.barray;
import dmd.backend.cc;
import dmd.backend.cdef;
import dmd.backend.code;
import dmd.backend.code_x86;
import dmd.backend.dout : symbol_iscomdat2;
import dmd.backend.mem;
import dmd.backend.aarray;
import dmd.backend.dlist;
import dmd.backend.el;
import dmd.backend.global;
import dmd.backend.obj;
import dmd.backend.oper;
import dmd.backend.symtab;
import dmd.backend.ty;
import dmd.backend.type;
import dmd.common.outbuffer;
nothrow:
import dmd.backend.dwarf;
import dmd.backend.melf;
private __gshared OutBuffer *fobjbuf;
enum MATCH_SECTION = 1;
enum DEST_LEN = (IDMAX + IDOHD + 1);
// C++ name mangling is handled by front end
const(char)* cpp_mangle2(Symbol* s) { return &s.Sident[0]; }
void addSegmentToComdat(segidx_t seg, segidx_t comdatseg);
/**
* If set the compiler requires full druntime support of the new
* section registration.
*/
//version (DMDV2)
static if (1)
enum DMDV2 = true;
else
enum DMDV2 = false;
bool REQUIRE_DSO_REGISTRY()
{
return DMDV2 && (config.exe & (EX_LINUX | EX_LINUX64 | EX_FREEBSD | EX_FREEBSD64 | EX_DRAGONFLYBSD64));
}
/**
* If set, produce .init_array/.fini_array instead of legacy .ctors/.dtors .
* OpenBSD added the support in Aug 2016. Other supported platforms has
* supported .init_array for years.
*/
bool USE_INIT_ARRAY() { return !(config.exe & (EX_OPENBSD | EX_OPENBSD64)); }
/******
* FreeBSD uses ELF, but the linker crashes with Elf comdats with the following message:
* /usr/bin/ld: BFD 2.15 [FreeBSD] 2004-05-23 internal error, aborting at
* /usr/src/gnu/usr.bin/binutils/libbfd/../../../../contrib/binutils/bfd/elfcode.h
* line 213 in bfd_elf32_swap_symbol_out
* For the time being, just stick with Linux.
*/
bool ELF_COMDAT() { return (config.exe & (EX_LINUX | EX_LINUX64)) != 0; }
/***************************************************
* Correspondence of relocation types
* 386 32 bit in 64 64 in 64
* R_386_32 R_X86_64_32 R_X86_64_64
* R_386_GOTOFF R_X86_64_PC32 R_X86_64_
* R_386_GOTPC R_X86_64_ R_X86_64_
* R_386_GOT32 R_X86_64_ R_X86_64_
* R_386_TLS_GD R_X86_64_TLSGD R_X86_64_
* R_386_TLS_IE R_X86_64_GOTTPOFF R_X86_64_
* R_386_TLS_LE R_X86_64_TPOFF32 R_X86_64_
* R_386_PLT32 R_X86_64_PLT32 R_X86_64_
* R_386_PC32 R_X86_64_PC32 R_X86_64_
*/
alias reltype_t = uint;
/******************************************
*/
private __gshared Symbol *GOTsym; // global offset table reference
Symbol *ElfObj_getGOTsym()
{
if (!GOTsym)
{
GOTsym = symbol_name("_GLOBAL_OFFSET_TABLE_",SC.global,tspvoid);
}
return GOTsym;
}
void ElfObj_refGOTsym()
{
if (!GOTsym)
{
Symbol *s = ElfObj_getGOTsym();
ElfObj_external(s);
}
}
//private void objfile_write(FILE *fd, void *buffer, uint len);
// The object file is built is several separate pieces
// Non-repeatable section types have single output buffers
// Pre-allocated buffers are defined for:
// Section Names string table
// Section Headers table
// Symbol table
// String table
// Notes section
// Comment data
// Section Names - String table for section names only
private __gshared OutBuffer *section_names;
enum SEC_NAMES_INIT = 800;
enum SEC_NAMES_INC = 400;
// Hash table for section_names
__gshared AApair2 *section_names_hashtable;
__gshared int jmpseg;
/* ======================================================================== */
// String Table - String table for all other names
private __gshared OutBuffer *symtab_strings;
// Section Headers
__gshared Barray!(Elf32_Shdr) SecHdrTab; // section header table
const(char)* GET_SECTION_NAME(int secidx)
{
return cast(const(char)*)section_names.buf + SecHdrTab[secidx].sh_name;
}
// The relocation for text and data seems to get lost.
// Try matching the order gcc output them
// This means defining the sections and then removing them if they are
// not used.
enum
{
SHN_TEXT = 1,
SHN_RELTEXT = 2,
SHN_DATA = 3,
SHN_RELDATA = 4,
SHN_BSS = 5,
SHN_RODAT = 6,
SHN_STRINGS = 7,
SHN_SYMTAB = 8,
SHN_SECNAMES = 9,
SHN_COM = 10,
SHN_NOTE = 11,
SHN_GNUSTACK = 12,
SHN_CDATAREL = 13,
}
__gshared IDXSYM *mapsec2sym;
enum S2S_INC = 20;
private __gshared int symbol_idx; // Number of symbols in symbol table
private __gshared int local_cnt; // Number of symbols with STB_LOCAL
enum
{
STI_FILE = 1, // Where file symbol table entry is
STI_TEXT = 2,
STI_DATA = 3,
STI_BSS = 4,
STI_GCC = 5, // Where "gcc2_compiled" symbol is */
STI_RODAT = 6, // Symbol for readonly data
STI_NOTE = 7, // Where note symbol table entry is
STI_COM = 8,
STI_CDATAREL = 9, // Symbol for readonly data with relocations
}
// NOTE: There seems to be a requirement that the read-only data have the
// same symbol table index and section index. Use section NOTE as a place
// holder. When a read-only string section is required, swap to NOTE.
__gshared
{
struct ElfObj
{
// Symbol Table
Barray!Elf32_Sym SymbolTable;
Barray!Elf64_Sym SymbolTable64;
Barray!(Symbol*) resetSyms; // Keep pointers to reset symbols
}
private ElfObj elfobj;
// Extended section header indices
private OutBuffer *shndx_data;
private const IDXSEC secidx_shndx = SHN_HIRESERVE + 1;
// Notes data (note currently used)
private OutBuffer *note_data;
private IDXSEC secidx_note; // Final table index for note data
// Comment data for compiler version
private OutBuffer *comment_data;
// Each compiler segment is an elf section
// Predefined compiler segments CODE,DATA,CDATA,UDATA map to indexes
// into SegData[]
// An additionl index is reserved for comment data
// New compiler segments are added to end.
//
// There doesn't seem to be any way to get reserved data space in the
// same section as initialized data or code, so section offsets should
// be continuous when adding data. Fix-ups anywhere withing existing data.
enum COMD = CDATAREL+1;
enum
{
OB_SEG_SIZ = 10, // initial number of segments supported
OB_SEG_INC = 10, // increment for additional segments
OB_CODE_STR = 100_000, // initial size for code
OB_CODE_INC = 100_000, // increment for additional code
OB_DATA_STR = 100_000, // initial size for data
OB_DATA_INC = 100_000, // increment for additional data
OB_CDATA_STR = 1024, // initial size for data
OB_CDATA_INC = 1024, // increment for additional data
OB_COMD_STR = 256, // initial size for comments
// increment as needed
OB_XTRA_STR = 250, // initial size for extra segments
OB_XTRA_INC = 10_000, // increment size
}
IDXSEC MAP_SEG2SECIDX(int seg) { return SegData[seg].SDshtidx; }
extern (D)
IDXSYM MAP_SEG2SYMIDX(int seg) { return SegData[seg].SDsymidx; }
Elf32_Shdr* MAP_SEG2SEC(int seg) { return &SecHdrTab[MAP_SEG2SECIDX(seg)]; }
int MAP_SEG2TYP(int seg) { return MAP_SEG2SEC(seg).sh_flags & SHF_EXECINSTR ? CODE : DATA; }
extern (C++) extern Rarray!(seg_data*) SegData;
int seg_tlsseg = UNKNOWN;
int seg_tlsseg_bss = UNKNOWN;
}
/*******************************
* Output a string into a string table
* Input:
* strtab = string table for entry
* str = string to add
*
* Returns index into the specified string table.
*/
IDXSTR ElfObj_addstr(OutBuffer *strtab, const(char)* str)
{
//dbg_printf("ElfObj_addstr(strtab = x%x str = '%s')\n",strtab,str);
IDXSTR idx = cast(IDXSTR)strtab.length(); // remember starting offset
strtab.writeStringz(str);
//dbg_printf("\tidx %d, new size %d\n",idx,strtab.length());
return idx;
}
/*******************************
* Output a mangled string into the symbol string table
* Input:
* str = string to add
*
* Returns index into the table.
*/
private IDXSTR elf_addmangled(Symbol *s)
{
//printf("elf_addmangled(%s)\n", s.Sident.ptr);
char[DEST_LEN] dest = void;
IDXSTR namidx = cast(IDXSTR)symtab_strings.length();
size_t len;
char *destr = obj_mangle2(s, dest.ptr, &len);
const(char)* name = destr;
if (CPP && name[0] == '_' && name[1] == '_')
{
if (strncmp(name,"__ct__",6) == 0)
{
name += 4;
len -= 4;
}
static if (0)
{
switch(name[2])
{
case 'c':
if (strncmp(name,"__ct__",6) == 0)
name += 4;
break;
case 'd':
if (strcmp(name,"__dl__FvP") == 0)
name = "__builtin_delete";
break;
case 'v':
//if (strcmp(name,"__vec_delete__FvPiUIPi") == 0)
//name = "__builtin_vec_del";
//else
//if (strcmp(name,"__vn__FPUI") == 0)
//name = "__builtin_vec_new";
break;
case 'n':
if (strcmp(name,"__nw__FPUI") == 0)
name = "__builtin_new";
break;
default:
break;
}
}
}
else if (tyfunc(s.ty()) && s.Sfunc && s.Sfunc.Fredirect)
{
name = s.Sfunc.Fredirect;
len = strlen(name);
}
symtab_strings.write(name[0 .. len + 1]);
if (destr != dest.ptr) // if we resized result
mem_free(destr);
//dbg_printf("\telf_addmagled symtab_strings %s namidx %d len %d size %d\n",name, namidx,len,symtab_strings.length());
return namidx;
}
/*******************************
* Output a symbol into the symbol table
* Input:
* stridx = string table index for name
* val = value associated with symbol
* sz = symbol size
* typ = symbol type
* bind = symbol binding
* sec = index of section where symbol is defined
* visibility = visibility of symbol (STV_xxxx)
*
* Returns the symbol table index for the symbol
*/
private IDXSYM elf_addsym(IDXSTR nam, targ_size_t val, uint sz,
uint typ, uint bind, IDXSEC sec,
ubyte visibility = STV_DEFAULT)
{
//dbg_printf("elf_addsym(nam %d, val %d, sz %x, typ %x, bind %x, sec %d\n",
//nam,val,sz,typ,bind,sec);
/* We want globally defined data symbols to have a size because
* zero sized symbols break copy relocations for shared libraries.
*/
if(sz == 0 && (bind == STB_GLOBAL || bind == STB_WEAK) &&
(typ == STT_OBJECT || typ == STT_TLS) &&
sec != SHN_UNDEF)
sz = 1; // so fake it if it doesn't
if (sec > SHN_HIRESERVE)
{ // If the section index is too big we need to store it as
// extended section header index.
if (!shndx_data)
{
shndx_data = cast(OutBuffer*) calloc(1, OutBuffer.sizeof);
if (!shndx_data)
err_nomem();
shndx_data.reserve(50 * (Elf64_Word).sizeof);
}
// fill with zeros up to symbol_idx
const size_t shndx_idx = shndx_data.length() / Elf64_Word.sizeof;
shndx_data.writezeros(cast(uint)((symbol_idx - shndx_idx) * Elf64_Word.sizeof));
shndx_data.write32(sec);
sec = SHN_XINDEX;
}
if (I64)
{
Elf64_Sym* sym = elfobj.SymbolTable64.push();
sym.st_name = nam;
sym.st_value = val;
sym.st_size = sz;
sym.st_info = cast(ubyte)ELF64_ST_INFO(cast(ubyte)bind,cast(ubyte)typ);
sym.st_other = visibility;
sym.st_shndx = cast(ushort)sec;
}
else
{
Elf32_Sym* sym = elfobj.SymbolTable.push();
sym.st_name = nam;
sym.st_value = cast(uint)val;
sym.st_size = sz;
sym.st_info = ELF32_ST_INFO(cast(ubyte)bind,cast(ubyte)typ);
sym.st_other = visibility;
sym.st_shndx = cast(ushort)sec;
}
if (bind == STB_LOCAL)
local_cnt++;
//dbg_printf("\treturning symbol table index %d\n",symbol_idx);
return symbol_idx++;
}
/*******************************
* Create a new section header table entry.
*
* Input:
* name = section name
* suffix = suffix for name or null
* type = type of data in section sh_type
* flags = attribute flags sh_flags
* Output:
* assigned number for this section
* Note: Sections will be reordered on output
*/
private IDXSEC elf_newsection2(
Elf32_Word name,
Elf32_Word type,
Elf32_Word flags,
Elf32_Addr addr,
Elf32_Off offset,
Elf32_Word size,
Elf32_Word link,
Elf32_Word info,
Elf32_Word addralign,
Elf32_Word entsize)
{
Elf32_Shdr sec;
sec.sh_name = name;
sec.sh_type = type;
sec.sh_flags = flags;
sec.sh_addr = addr;
sec.sh_offset = offset;
sec.sh_size = size;
sec.sh_link = link;
sec.sh_info = info;
sec.sh_addralign = addralign;
sec.sh_entsize = entsize;
if (SecHdrTab.length == SHN_LORESERVE)
{ // insert dummy null sections to skip reserved section indices
foreach (i; SHN_LORESERVE .. SHN_HIRESERVE + 1)
SecHdrTab.push();
// shndx itself becomes the first section with an extended index
IDXSTR namidx = ElfObj_addstr(section_names, ".symtab_shndx");
elf_newsection2(namidx,SHT_SYMTAB_SHNDX,0,0,0,0,SHN_SYMTAB,0,4,4);
}
const si = SecHdrTab.length;
*SecHdrTab.push() = sec;
return cast(IDXSEC)si;
}
/**
Add a new section name or get the string table index of an existing entry.
Params:
name = name of section
suffix = append to name
padded = set to true when entry was newly added
Returns:
pointer to Pair, where the first field is the string index of the new or existing section name,
and the second field is its segment index
*/
private Pair* elf_addsectionname(const(char)* name, const(char)* suffix = null, bool *padded = null)
{
IDXSTR namidx = cast(IDXSTR)section_names.length();
section_names.writeStringz(name);
if (suffix)
{ // Append suffix string
section_names.setsize(cast(uint)section_names.length() - 1); // back up over terminating 0
section_names.writeStringz(suffix);
}
Pair* pidx = section_names_hashtable.get(namidx, cast(uint)section_names.length() - 1);
if (pidx.start)
{
// this section name already exists, remove addition
section_names.setsize(namidx);
return pidx;
}
if (padded)
*padded = true;
pidx.start = namidx;
return pidx;
}
private IDXSEC elf_newsection(const(char)* name, const(char)* suffix,
Elf32_Word type, Elf32_Word flags)
{
// dbg_printf("elf_newsection(%s,%s,type %d, flags x%x)\n",
// name?name:"",suffix?suffix:"",type,flags);
bool added = false;
Pair* pidx = elf_addsectionname(name, suffix, &added);
assert(added);
return elf_newsection2(pidx.start,type,flags,0,0,0,0,0,0,0);
}
/**************************
* Ouput read only data and generate a symbol for it.
*
*/
Symbol *ElfObj_sym_cdata(tym_t ty,char *p,int len)
{
Symbol *s;
static if (0)
{
if (OPT_IS_SET(OPTfwritable_strings))
{
alignOffset(DATA, tysize(ty));
s = symboldata(Offset(DATA), ty);
SegData[DATA].SDbuf.write(p[0 .. len]);
s.Sseg = DATA;
s.Soffset = Offset(DATA); // Remember its offset into DATA section
Offset(DATA) += len;
s.Sfl = /*(config.flags3 & CFG3pic) ? FLgotoff :*/ FLextern;
return s;
}
}
//printf("ElfObj_sym_cdata(ty = %x, p = %x, len = %d, Offset(CDATA) = %x)\n", ty, p, len, Offset(CDATA));
alignOffset(CDATA, tysize(ty));
s = symboldata(Offset(CDATA), ty);
ElfObj_bytes(CDATA, Offset(CDATA), len, p);
s.Sseg = CDATA;
s.Sfl = /*(config.flags3 & CFG3pic) ? FLgotoff :*/ FLextern;
return s;
}
/**************************
* Ouput read only data for data.
* Output:
* *pseg segment of that data
* Returns:
* offset of that data
*/
int ElfObj_data_readonly(char *p, int len, int *pseg)
{
int oldoff = cast(int)Offset(CDATA);
SegData[CDATA].SDbuf.reserve(len);
SegData[CDATA].SDbuf.writen(p,len);
Offset(CDATA) += len;
*pseg = CDATA;
return oldoff;
}
int ElfObj_data_readonly(char *p, int len)
{
int pseg;
return ElfObj_data_readonly(p, len, &pseg);
}
/******************************
* Get segment for readonly string literals.
* The linker will pool strings in this section.
* Params:
* sz = number of bytes per character (1, 2, or 4)
* Returns:
* segment index
*/
int ElfObj_string_literal_segment(uint sz)
{
/* Elf special sections:
* .rodata.strM.N - M is size of character
* N is alignment
* .rodata.cstN - N fixed size readonly constants N bytes in size,
* aligned to the same size
*/
static immutable char[4][3] name = [ "1.1", "2.2", "4.4" ];
const int i = (sz == 4) ? 2 : sz - 1;
// FIXME: can't use SHF_MERGE | SHF_STRINGS because of https://issues.dlang.org/show_bug.cgi?id=22483
const IDXSEC seg = ElfObj_getsegment(".rodata.str".ptr, name[i].ptr, SHT_PROGBITS, SHF_ALLOC, sz);
return seg;
}
/******************************
* Perform initialization that applies to all .o output files.
* Called before any other obj_xxx routines
* Called by Obj.initialize()
* Params:
* objbuf = where to write the object file data
* filename = source file name
* csegname = name for code segment
*/
Obj ElfObj_init(OutBuffer *objbuf, const(char)* filename, const(char)* csegname)
{
//printf("ElfObj_init(filename = %s, csegname = %s)\n",filename,csegname);
Obj obj = cast(Obj)mem_calloc(__traits(classInstanceSize, Obj));
cseg = CODE;
fobjbuf = objbuf;
mapsec2sym = null;
note_data = null;
secidx_note = 0;
comment_data = null;
seg_tlsseg = UNKNOWN;
seg_tlsseg_bss = UNKNOWN;
GOTsym = null;
// Initialize buffers
if (symtab_strings)
symtab_strings.setsize(1);
else
{
symtab_strings = cast(OutBuffer*) calloc(1, OutBuffer.sizeof);
if (!symtab_strings)
err_nomem();
symtab_strings.reserve(2048);
symtab_strings.writeByte(0);
}
SecHdrTab.reset();
enum NAMIDX : IDXSTR
{
NONE = 0,
SYMTAB = 1, // .symtab
STRTAB = 9, // .strtab
SHSTRTAB = 17, // .shstrtab
TEXT = 27, // .text
DATA = 33, // .data
BSS = 39, // .bss
NOTE = 44, // .note
COMMENT = 50, // .comment
RODATA = 59, // .rodata
GNUSTACK = 67, // .note.GNU-stack
CDATAREL = 83, // .data.rel.ro
RELTEXT = 96, // .rel.text and .rela.text
RELDATA = 106, // .rel.data
RELDATA64 = 107, // .rela.data
}
if (I64)
{
static immutable char[107 + 12] section_names_init64 =
"\0.symtab\0.strtab\0.shstrtab\0.text\0.data\0.bss\0.note" ~
"\0.comment\0.rodata\0.note.GNU-stack\0.data.rel.ro\0.rela.text\0.rela.data";
if (section_names)
section_names.setsize(section_names_init64.sizeof);
else
{
section_names = cast(OutBuffer*) calloc(1, OutBuffer.sizeof);
if (!section_names)
err_nomem();
section_names.reserve(1024);
section_names.writen(section_names_init64.ptr, section_names_init64.sizeof);
}
if (section_names_hashtable)
AApair2.destroy(section_names_hashtable);
section_names_hashtable = AApair2.create(section_names.bufptr);
// name,type,flags,addr,offset,size,link,info,addralign,entsize
elf_newsection2(0, SHT_NULL, 0, 0,0,0,0,0, 0,0);
elf_newsection2(NAMIDX.TEXT,SHT_PROGBITS,SHF_ALLOC|SHF_EXECINSTR,0,0,0,0,0, 4,0);
elf_newsection2(NAMIDX.RELTEXT,SHT_RELA, 0,0,0,0,SHN_SYMTAB, SHN_TEXT, 8,0x18);
elf_newsection2(NAMIDX.DATA,SHT_PROGBITS,SHF_ALLOC|SHF_WRITE, 0,0,0,0,0, 8,0);
elf_newsection2(NAMIDX.RELDATA64,SHT_RELA, 0,0,0,0,SHN_SYMTAB, SHN_DATA, 8,0x18);
elf_newsection2(NAMIDX.BSS, SHT_NOBITS,SHF_ALLOC|SHF_WRITE, 0,0,0,0,0, 16,0);
elf_newsection2(NAMIDX.RODATA,SHT_PROGBITS,SHF_ALLOC, 0,0,0,0,0, 16,0);
elf_newsection2(NAMIDX.STRTAB,SHT_STRTAB, 0, 0,0,0,0,0, 1,0);
elf_newsection2(NAMIDX.SYMTAB,SHT_SYMTAB, 0, 0,0,0,0,0, 8,0);
elf_newsection2(NAMIDX.SHSTRTAB,SHT_STRTAB, 0, 0,0,0,0,0, 1,0);
elf_newsection2(NAMIDX.COMMENT, SHT_PROGBITS,0, 0,0,0,0,0, 1,0);
elf_newsection2(NAMIDX.NOTE,SHT_NOTE, 0, 0,0,0,0,0, 1,0);
elf_newsection2(NAMIDX.GNUSTACK,SHT_PROGBITS,0, 0,0,0,0,0, 1,0);
elf_newsection2(NAMIDX.CDATAREL,SHT_PROGBITS,SHF_ALLOC|SHF_WRITE,0,0,0,0,0, 16,0);
foreach (idxname; __traits(allMembers, NAMIDX)[1 .. $])
{
NAMIDX idx = mixin("NAMIDX." ~ idxname);
section_names_hashtable.get(idx, cast(uint)section_names_init64.sizeof).start = idx;
}
}
else
{
static immutable char[106 + 12] section_names_init =
"\0.symtab\0.strtab\0.shstrtab\0.text\0.data\0.bss\0.note" ~
"\0.comment\0.rodata\0.note.GNU-stack\0.data.rel.ro\0.rel.text\0.rel.data";
if (section_names)
section_names.setsize(section_names_init.sizeof);
else
{
section_names = cast(OutBuffer*) calloc(1, OutBuffer.sizeof);
if (!section_names)
err_nomem();
section_names.reserve(100*1024);
section_names.writen(section_names_init.ptr, section_names_init.sizeof);
}
if (section_names_hashtable)
AApair2.destroy(section_names_hashtable);
section_names_hashtable = AApair2.create(section_names.bufptr);
// name,type,flags,addr,offset,size,link,info,addralign,entsize
elf_newsection2(0, SHT_NULL, 0, 0,0,0,0,0, 0,0);
elf_newsection2(NAMIDX.TEXT,SHT_PROGBITS,SHF_ALLOC|SHF_EXECINSTR,0,0,0,0,0, 16,0);
elf_newsection2(NAMIDX.RELTEXT,SHT_REL,SHF_INFO_LINK, 0,0,0,SHN_SYMTAB, SHN_TEXT, 4,8);
elf_newsection2(NAMIDX.DATA,SHT_PROGBITS,SHF_ALLOC|SHF_WRITE, 0,0,0,0,0, 4,0);
elf_newsection2(NAMIDX.RELDATA,SHT_REL,SHF_INFO_LINK ,0,0,0,SHN_SYMTAB, SHN_DATA, 4,8);
elf_newsection2(NAMIDX.BSS, SHT_NOBITS,SHF_ALLOC|SHF_WRITE, 0,0,0,0,0, 32,0);
elf_newsection2(NAMIDX.RODATA,SHT_PROGBITS,SHF_ALLOC, 0,0,0,0,0, 4,0);
elf_newsection2(NAMIDX.STRTAB,SHT_STRTAB, 0, 0,0,0,0,0, 1,0);
elf_newsection2(NAMIDX.SYMTAB,SHT_SYMTAB, 0, 0,0,0,0,0, 4,0);
elf_newsection2(NAMIDX.SHSTRTAB,SHT_STRTAB, 0, 0,0,0,0,0, 1,0);
elf_newsection2(NAMIDX.COMMENT, SHT_PROGBITS,0, 0,0,0,0,0, 1,0);
elf_newsection2(NAMIDX.NOTE,SHT_NOTE, 0, 0,0,0,0,0, 1,0);
elf_newsection2(NAMIDX.GNUSTACK,SHT_PROGBITS,0, 0,0,0,0,0, 1,0);
elf_newsection2(NAMIDX.CDATAREL,SHT_PROGBITS,SHF_ALLOC|SHF_WRITE,0,0,0,0,0, 1,0);
foreach (idxname; __traits(allMembers, NAMIDX)[1 .. $])
{
NAMIDX idx = mixin("NAMIDX." ~ idxname);
section_names_hashtable.get(idx, cast(uint)section_names_init.sizeof).start = idx;
}
}
elfobj.SymbolTable.reset();
elfobj.SymbolTable64.reset();
foreach (s; elfobj.resetSyms)
symbol_reset(s);
elfobj.resetSyms.reset();
if (shndx_data)
shndx_data.reset();
if (note_data)
note_data.reset();
if (comment_data)
comment_data.reset();
symbol_idx = 0;
local_cnt = 0;
// The symbols that every object file has
elf_addsym(0, 0, 0, STT_NOTYPE, STB_LOCAL, 0);
elf_addsym(0, 0, 0, STT_FILE, STB_LOCAL, SHN_ABS); // STI_FILE
elf_addsym(0, 0, 0, STT_SECTION, STB_LOCAL, SHN_TEXT); // STI_TEXT
elf_addsym(0, 0, 0, STT_SECTION, STB_LOCAL, SHN_DATA); // STI_DATA
elf_addsym(0, 0, 0, STT_SECTION, STB_LOCAL, SHN_BSS); // STI_BSS
elf_addsym(0, 0, 0, STT_NOTYPE, STB_LOCAL, SHN_TEXT); // STI_GCC
elf_addsym(0, 0, 0, STT_SECTION, STB_LOCAL, SHN_RODAT); // STI_RODAT
elf_addsym(0, 0, 0, STT_SECTION, STB_LOCAL, SHN_NOTE); // STI_NOTE
elf_addsym(0, 0, 0, STT_SECTION, STB_LOCAL, SHN_COM); // STI_COM
elf_addsym(0, 0, 0, STT_SECTION, STB_LOCAL, SHN_CDATAREL); // STI_CDATAREL
// Initialize output buffers for CODE, DATA and COMMENTS
// (NOTE not supported, BSS not required)
SegData.reset(); // recycle memory
SegData.push(); // element 0 is reserved
elf_addsegment2(SHN_TEXT, STI_TEXT, SHN_RELTEXT);
assert(SegData[CODE].SDseg == CODE);
elf_addsegment2(SHN_DATA, STI_DATA, SHN_RELDATA);
assert(SegData[DATA].SDseg == DATA);
elf_addsegment2(SHN_RODAT, STI_RODAT, 0);
assert(SegData[CDATA].SDseg == CDATA);
elf_addsegment2(SHN_BSS, STI_BSS, 0);
assert(SegData[UDATA].SDseg == UDATA);
elf_addsegment2(SHN_CDATAREL, STI_CDATAREL, 0);
assert(SegData[CDATAREL].SDseg == CDATAREL);
elf_addsegment2(SHN_COM, STI_COM, 0);
assert(SegData[COMD].SDseg == COMD);
dwarf_initfile(filename);
return obj;
}
/**************************
* Initialize the start of object output for this particular .o file.
* Called by Obj.initfile()
*
* Input:
* filename: Name of source file
* csegname: User specified default code segment name
*/
void ElfObj_initfile(const(char)* filename, const(char)* csegname, const(char)* modname)
{
//printf("ElfObj_initfile(filename = %s, modname = %s)\n",filename,modname);
IDXSTR name = ElfObj_addstr(symtab_strings, filename);
if (I64)
elfobj.SymbolTable64[STI_FILE].st_name = name;
else
elfobj.SymbolTable[STI_FILE].st_name = name;
static if (0)
{
// compiler flag for linker
if (I64)
elfobj.SymbolTable64[STI_GCC].st_name = ElfObj_addstr(symtab_strings,"gcc2_compiled.");
else
elfobj.SymbolTable[STI_GCC].st_name = ElfObj_addstr(symtab_strings,"gcc2_compiled.");
}
if (csegname && *csegname && strcmp(csegname,".text"))
{ // Define new section and make it the default for cseg segment
// NOTE: cseg is initialized to CODE
const newsecidx = elf_newsection(csegname,null,SHT_PROGBITS,SHF_ALLOC|SHF_EXECINSTR);
SecHdrTab[newsecidx].sh_addralign = 4;
SegData[cseg].SDshtidx = newsecidx;
SegData[cseg].SDsymidx = elf_addsym(0, 0, 0, STT_SECTION, STB_LOCAL, newsecidx);
}
if (config.fulltypes)
dwarf_initmodule(filename, modname);
}
/***************************
* Renumber symbols so they are
* ordered as locals, weak and then global
* Returns:
* sorted symbol table, caller must free with util_free()
*/
void *elf_renumbersyms()
{ void *symtab;
int nextlocal = 0;
int nextglobal = local_cnt;
SYMIDX *sym_map = cast(SYMIDX *)util_malloc(SYMIDX.sizeof,symbol_idx);
if (I64)
{
Elf64_Sym *oldsymtab = &elfobj.SymbolTable64[0];
Elf64_Sym *symtabend = oldsymtab+symbol_idx;
symtab = util_malloc(Elf64_Sym.sizeof,symbol_idx);
Elf64_Sym *sl = cast(Elf64_Sym *)symtab;
Elf64_Sym *sg = sl + local_cnt;
int old_idx = 0;
for(Elf64_Sym *s = oldsymtab; s != symtabend; s++)
{ // reorder symbol and map new #s to old
int bind = ELF64_ST_BIND(s.st_info);
if (bind == STB_LOCAL)
{
*sl++ = *s;
sym_map[old_idx] = nextlocal++;
}
else
{
*sg++ = *s;
sym_map[old_idx] = nextglobal++;
}
old_idx++;
}
}
else
{
Elf32_Sym *oldsymtab = &elfobj.SymbolTable[0];
Elf32_Sym *symtabend = oldsymtab+symbol_idx;
symtab = util_malloc(Elf32_Sym.sizeof,symbol_idx);
Elf32_Sym *sl = cast(Elf32_Sym *)symtab;
Elf32_Sym *sg = sl + local_cnt;
int old_idx = 0;
for(Elf32_Sym *s = oldsymtab; s != symtabend; s++)
{ // reorder symbol and map new #s to old
int bind = ELF32_ST_BIND(s.st_info);
if (bind == STB_LOCAL)
{
*sl++ = *s;
sym_map[old_idx] = nextlocal++;
}
else
{
*sg++ = *s;
sym_map[old_idx] = nextglobal++;
}
old_idx++;
}
}
// Reorder extended section header indices
if (shndx_data && shndx_data.length())
{
// fill with zeros up to symbol_idx
const size_t shndx_idx = shndx_data.length() / Elf64_Word.sizeof;
shndx_data.writezeros(cast(uint)((symbol_idx - shndx_idx) * Elf64_Word.sizeof));
Elf64_Word *old_buf = cast(Elf64_Word *)shndx_data.buf;
Elf64_Word *tmp_buf = cast(Elf64_Word *)util_malloc(Elf64_Word.sizeof, symbol_idx);
for (SYMIDX old_idx = 0; old_idx < symbol_idx; ++old_idx)
{
const SYMIDX new_idx = sym_map[old_idx];
tmp_buf[new_idx] = old_buf[old_idx];
}
memcpy(old_buf, tmp_buf, Elf64_Word.sizeof * symbol_idx);
util_free(tmp_buf);
}
// Renumber the relocations
for (int i = 1; i < SegData.length; i++)
{ // Map indicies in the segment table
seg_data *pseg = SegData[i];
pseg.SDsymidx = cast(uint) sym_map[pseg.SDsymidx];
if (SecHdrTab[pseg.SDshtidx].sh_type == SHT_GROUP)
{ // map symbol index of group section header
uint oidx = SecHdrTab[pseg.SDshtidx].sh_info;
assert(oidx < symbol_idx);
// we only have one symbol table
assert(SecHdrTab[pseg.SDshtidx].sh_link == SHN_SYMTAB);
SecHdrTab[pseg.SDshtidx].sh_info = cast(uint) sym_map[oidx];
}
if (pseg.SDrel)
{
if (I64)
{
Elf64_Rela *rel = cast(Elf64_Rela *) pseg.SDrel.buf;
for (int r = 0; r < pseg.SDrelcnt; r++)
{
uint t = ELF64_R_TYPE(rel.r_info);
uint si = ELF64_R_SYM(rel.r_info);
assert(si < symbol_idx);
rel.r_info = ELF64_R_INFO(sym_map[si],t);
rel++;
}
}
else
{
Elf32_Rel *rel = cast(Elf32_Rel *) pseg.SDrel.buf;
assert(pseg.SDrelcnt == pseg.SDrel.length() / Elf32_Rel.sizeof);
for (int r = 0; r < pseg.SDrelcnt; r++)
{
uint t = ELF32_R_TYPE(rel.r_info);
uint si = ELF32_R_SYM(rel.r_info);
assert(si < symbol_idx);
rel.r_info = ELF32_R_INFO(cast(uint) sym_map[si],t);
rel++;
}
}
}
}
return symtab;
}
/***************************
* Fixup and terminate object file.
* Pairs with ElfObj_initfile()