-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathld.c
More file actions
5970 lines (5201 loc) · 173 KB
/
ld.c
File metadata and controls
5970 lines (5201 loc) · 173 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* The MIT License (MIT)
* Copyright (C) 2016 ZongXian Shen <andy.zsshen@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include "minux.h"
#include "elf.h"
#define EXIT_FAILURE 1
#ifndef STT_NOTYPE
#define STT_NOTYPE 0
#endif
#ifndef STT_OBJECT
#define STT_OBJECT 1
#endif
#ifndef STT_FUNC
#define STT_FUNC 2
#endif
#ifndef STB_LOCAL
#define STB_LOCAL 0
#endif
#ifndef STB_GLOBAL
#define STB_GLOBAL 1
#endif
#ifndef STB_WEAK
#define STB_WEAK 2
#endif
#ifndef ELF64_ST_TYPE
#define ELF64_ST_TYPE(i) ((i) & 0xf)
#endif
#ifndef ELF64_ST_BIND
#define ELF64_ST_BIND(i) ((i) >> 4)
#endif
#ifndef ELF64_ST_INFO
#define ELF64_ST_INFO(bind, type) (((bind) << 4) + ((type) & 0xf))
#endif
#define DEBUG_LINKER 1
#define SYMBOL_FLAG_GOT_TP 0x1
#define SYMBOL_FLAG_GOT 0x2
#define SYMBOL_FLAG_SYMTAB 0x4
#define max_(a, b) ((a) > (b) ? (a) : (b))
#define max(a, b) ((a) > (b) ? (a) : (b))
#if DEBUG_LINKER
#define DBG(fmt, ...) do { fprintf(stderr, "[ld2] " fmt, ##__VA_ARGS__); fflush(stderr); } while (0)
#else
#define DBG(fmt, ...) do { } while (0)
#endif
#define uint64 uint64_t
#define uint32 uint32_t
#define ushort unsigned short
#define uint unsigned int
#define uchar unsigned char
static int DebugCountArgs(char** args)
{
if (args == NULL) {
return 0;
}
int count = 0;
while (args[count] != NULL) {
count++;
}
return count;
}
typedef unsigned (*HashMapHash) (void*);
typedef int (*HashMapCompare) (void*, void*);
typedef void (*HashMapCleanKey) (void*);
typedef void (*HashMapCleanValue) (void*);
typedef struct _Pair
{
void* key;
void* value;
} Pair;
typedef struct _SlotNode
{
Pair pair_;
struct _SlotNode* next_;
} SlotNode;
struct _HashMapData
{
int size_;
int idx_prime_;
unsigned num_slot_;
unsigned curr_limit_;
unsigned iter_slot_;
SlotNode** arr_slot_;
SlotNode* iter_node_;
HashMapHash func_hash_;
HashMapCompare func_cmp_;
HashMapCleanKey func_clean_key_;
HashMapCleanValue func_clean_val_;
};
typedef struct _HashMapData HashMapData;
typedef struct _HashMap
{
HashMapData *data;
bool (*put) (struct _HashMap*, void*, void*);
void* (*get) (struct _HashMap*, void*);
bool (*contain) (struct _HashMap*, void*);
bool (*remove) (struct _HashMap*, void*);
unsigned (*size) (struct _HashMap*);
void (*first) (struct _HashMap*);
Pair* (*next) (struct _HashMap*);
void (*set_hash) (struct _HashMap*, HashMapHash);
void (*set_compare) (struct _HashMap*, HashMapCompare);
void (*set_clean_key) (struct _HashMap*, HashMapCleanKey);
void (*set_clean_value) (struct _HashMap*, HashMapCleanValue);
} HashMap;
HashMap* HashMapInit();
void HashMapDeinit(HashMap* obj);
bool HashMapPut(HashMap* self, void* key, void* value);
void* HashMapGet(HashMap* self, void* key);
bool HashMapContain(HashMap* self, void* key);
bool HashMapRemove(HashMap* self, void* key);
unsigned HashMapSize(HashMap* self);
void HashMapFirst(HashMap* self);
Pair* HashMapNext(HashMap* self);
void HashMapSetHash(HashMap* self, HashMapHash func);
void HashMapSetCompare(HashMap* self, HashMapCompare func);
void HashMapSetCleanKey(HashMap* self, HashMapCleanKey func);
void HashMapSetCleanValue(HashMap* self, HashMapCleanValue func);
void HashMapClean(HashMap *self);
typedef unsigned (*HashSetHash) (void*);
typedef int (*HashSetCompare) (void*, void*);
typedef void (*HashSetCleanKey) (void*);
typedef struct _HashSetSlotNode
{
void* key_;
struct _HashSetSlotNode* next_;
} HashSetSlotNode;
struct _HashSetData
{
int idx_prime_;
unsigned size_;
unsigned num_slot_;
unsigned curr_limit_;
unsigned iter_slot_;
HashSetSlotNode** arr_slot_;
HashSetSlotNode* iter_node_;
HashSetHash func_hash_;
HashSetCompare func_cmp_;
HashSetCleanKey func_clean_key_;
};
typedef struct _HashSetData HashSetData;
typedef struct _HashSet
{
HashSetData* data;
bool (*add) (struct _HashSet*, void*);
bool (*find) (struct _HashSet*, void*);
bool (*remove) (struct _HashSet*, void*);
unsigned (*size) (struct _HashSet*);
void (*first) (struct _HashSet*);
void* (*next) (struct _HashSet*);
void (*set_hash) (struct _HashSet*, HashSetHash);
void (*set_compare) (struct _HashSet*, HashSetCompare);
void (*set_clean_key) (struct _HashSet*, HashSetCleanKey);
} HashSet;
HashSet* _HashSetInit(int idx_prime);
unsigned _HashSetHash(void* key);
int _HashSetCompare(void* lhs, void* rhs);
void _HashSetReHash(HashSetData* data);
HashSet* HashSetInit();
void HashSetDeinit(HashSet* obj);
bool HashSetAdd(HashSet* self, void* key);
bool HashSetFind(HashSet* self, void* key);
bool HashSetRemove(HashSet* self, void* key);
unsigned HashSetSize(HashSet* self);
void HashSetFirst(HashSet* self);
void* HashSetNext(HashSet* self);
void HashSetSetHash(HashSet* self, HashSetHash func);
void HashSetSetCompare(HashSet* self, HashSetCompare func);
void HashSetSetCleanKey(HashSet* self, HashSetCleanKey func);
HashSet* HashSetUnion(HashSet* lhs, HashSet* rhs);
HashSet* HashSetIntersect(HashSet* lhs, HashSet* rhs);
HashSet* HashSetDifference(HashSet* lhs, HashSet* rhs);
unsigned HashMurMur32(void* key, size_t size);
unsigned HashJenkins(void* key, size_t size);
unsigned HashDjb2(char* key);
unsigned _HashMapHash(void* key);
int _HashMapCompare(void* lhs, void* rhs);
void _HashMapReHash(HashMapData* data);
typedef struct File
{
char* Name;
char* Contents;
uint64_t contents_len; //由于有'\0',添加这个
struct File* Parent; //表示它来自于哪个.a文件 , 如果直接.o就是空
} File;
// Elf32_Ehdr Executable header type. One per ELF file.
typedef struct Ehdr_
{
uint8_t Ident[16]; //表示ELF文件的标识信息
uint16_t Type; //表示 ELF 文件的类型,比如可执行文件、共享库等
uint16_t Machine;
uint32_t Version;
uint64_t Entry ; //表示程序的入口地址
uint64_t PhOff ; //表示程序头表(Program Header Table)的偏移量
uint64_t ShOff ; //表示节表(Section Header Table)的偏移量
uint32_t Flags ; //表示 ELF 文件的标志信息
uint16_t EhSize; //表示 ELF 文件头部的大小 sizeof(Elf32_Ehdr);
uint16_t PhEntSize ; //表示program header table中每个表项的大小,每一个表项描述一个Segment信息
uint16_t PhNum ; //表示program header table中表项的数量
uint16_t ShEntSize; //Section header table中每个表项的大小sizeof(Elf32_Shdr)
uint16_t ShNum ; //num sections
uint16_t ShStrndx ; //表示节表中字符串表的索引,第多少个表项描述的是字符串表......
}Ehdr;
// Elf32_Shdr Section header
typedef struct
{
uint32_t Name; //section名称,是在字符串表节区的索引
uint32_t Type;
uint64_t Flags; //描述杂项属性
uint64_t Addr; //如果该section将出现在进程的内存映像中,则该成员给出该section的第一个字节应该驻留的地址。否则,该成员的值为0
uint64_t Offset; //该节在elf文件中偏移量
uint64_t Size; //该节的大小
uint32_t Link; //holds a section header table index link,表示当前节依赖于对应的节
uint32_t Info; //该节的附加信息, 如符号表节中存储的第一个global的信息
uint64_t AddrAlign; //该节的对齐方式
uint64_t EntSize; //某些节区中包含固定大小的项目,如符号表节中每个符号的大小,没有则是0
} Shdr;
typedef struct
{
uint32_t Name; //存储一个指向字符串表的索引来表示对应符号的名称
uint8_t Info;
uint8_t Other;
uint16_t Shndx; //每个符号都有属于的节,当前成员存储的就是对应节的索引
uint64_t Val; //存储对应符号的取值,具体值依赖于上下文,可能是一个指针地址,立即数等
uint64_t Size;
} ElfSym;
typedef struct
{
uint64_t Offset;
uint32_t Type;
uint32_t Sym;
int64_t Addend;
} Rela;
// [Section ] -> [ArHdr][ ][ArHdr][
typedef struct
{
char Name[16];
char Date[12];
char Uid[6];
char Gid[6];
char Mode[8];
char Size[10]; //即[ArHdr][这部分的size]
char Fmag[2];
} ArHdr;
typedef struct
{
uint32_t Type;
uint32_t Flags;
uint64_t Offset;
uint64_t VAddr;
uint64_t PAddr;
uint64_t FileSize;
uint64_t MemSize;
uint64_t Align;
} Phdr;
typedef uint8_t ChunkType;
struct ObjectFile_;
struct MergedSection_ ;
struct OutputEhdr_;
struct OutputShdr_;
struct OutputSection_;
struct OutputPhdr_;
struct GotSection_;
struct OutputShStrtab_;
struct OutputStrtab_;
struct OutputSymtab_;
struct Chunk_;
typedef struct ObjectFile_ ObjectFile;
typedef struct InputSection_ InputSection;
typedef struct InputFile_ InputFile;
typedef uint8_t MachineType;
typedef struct
{
char* Output;
MachineType Emulation;
char** LibraryPaths;
int LibraryPathsCount;
char* Entry; // -e ENTRY
} ContextArgs;
typedef struct SectionFragment_ SectionFragment;
typedef struct MergedSection_ MergedSection;
typedef struct
{
ContextArgs Args;
struct ObjectFile_** Objs;
int ObjsCount;
HashMap *SymbolMap; //char*,Symbol*
struct MergedSection_ **mergedSections;
int mergedSectionNum;
struct Chunk_ **chunk;
int chunkNum;
char* buf;
//链接器自己生成了,保存于此
struct OutputEhdr_* ehdr;
struct OutputShdr_* shdr;
struct OutputPhdr_* phdr;
struct GotSection_* got;
struct OutputShStrtab_* shstrtab;
struct OutputStrtab_* strtab;
struct OutputSymtab_* symtab;
struct OutputSection_** outputSections;
int outputSecNum;
uint64_t TpAddr;
uint64_t GpAddr;
uint16_t ShStrtabIndex;
} Context;
typedef struct Symbol_
{
ObjectFile *file;
char* name;
uint64_t value;
int32_t symIdx;
//union
InputSection * inputSection;
SectionFragment *sectionFragment;
int32_t gotIdx;
int32_t gotTpIdx;
uint32_t flags;
}Symbol;
typedef struct Chunk_
{
char* name;
Shdr shdr;
ChunkType chunkType;
int32_t rank;
struct {
struct InputSection_** members;
int memberNum;
uint32_t idx;
}outpuSec;
struct {
HashMap *map; //string - sectionFragment
}mergedSec;
struct {
Phdr *phdrs;
int phdrNum;
}phdrS;
struct {
Symbol ** GotTpSyms;
int TpSymNum;
Symbol ** GotSyms;
int GotSymNum;
}gotSec;
struct {
Shdr *entries;
size_t count;
}shdrTable;
}Chunk;
typedef struct OutputEhdr_
{
Chunk *chunk;
}OutputEhdr;
typedef struct OutputShdr_
{
Chunk *chunk;
}OutputShdr;
typedef struct OutputSection_
{
Chunk * chunk;
}OutputSection;
typedef struct OutputPhdr_
{
Chunk *chunk;
}OutputPhdr;
typedef struct GotSection_
{
Chunk *chunk;
}GotSection;
typedef struct OutputShStrtab_
{
Chunk *chunk;
char* data;
size_t size;
size_t capacity;
}OutputShStrtab;
typedef struct OutputStrtab_
{
Chunk *chunk;
char* data;
size_t size;
size_t capacity;
}OutputStrtab;
typedef struct SymtabEntry_
{
Symbol* sym;
Chunk* sectionChunk;
uint32_t nameOffset;
uint16_t shndx;
uint8_t info;
uint8_t other;
uint64_t size;
} SymtabEntry;
typedef struct OutputSymtab_
{
Chunk *chunk;
OutputStrtab* strtab;
SymtabEntry* entries;
size_t count;
size_t capacity;
size_t localCount;
}OutputSymtab;
// .got 表中的每个条目对应一个全局变量或函数的地址 , 针对tp_addr的偏移量
typedef struct GotEntry_
{
int64_t idx;
uint64_t val;
}GotEntry;
//合并后的section
struct MergedSection_
{
Chunk *chunk;
};
typedef struct Fragment_
{
char* key;
SectionFragment* val;
}Fragment;
//将merge-able section分成小的数据块
struct SectionFragment_
{
MergedSection* OutputSection; //进行一个双向关联吧
uint32_t Offset; //在section中的offset
uint32_t P2Align;
bool IsAlive;
int strslen; //保存这个sectionFragment的长度
} ;
//input section拆成一个(? y)包含多个sectionFragment的merge-able section , 再放入merged section
typedef struct MergeableSection
{
MergedSection * parent;
uint8_t p2align;
char** strs; //fragments的原始数据, 是数据,不一定是字符串 , 还有const原始数据
int strNum;
int* strslen;
uint32_t* fragOffsets;
int fragOffsetNum;
SectionFragment ** fragments;
int fragmentNum;
}MergeableSection;
struct ObjectFile_
{
InputFile *inputFile; //这样表示继承
Shdr *SymtabSec;
InputSection ** Sections;
int64_t isecNum;
uint32_t* SymtabShndxSec; //
MergeableSection **mergeableSections;
size_t mergeableSectionsNum;
};
struct InputSection_
{
struct ObjectFile_ *objectFile; //来自于某个文件
char* contents;
uint32_t shndx; //在section header数组中的下标值,为了找到它的section header信息
uint32_t shsize;
bool isAlive; //看看这个inputsection是否放到最终可执行文件中
uint8_t P2Align; //power to align , 等于log2的addrAlign
//在outputsection中的偏移
uint32_t offset; //这个inputsection在它对应的outputsection中的偏移
struct OutputSection_* outputSection; //记录一下这个input section属于哪个output section
uint32_t RelsecIdx;
Rela* rels;
int relNum;
};
// InputFile 包含obj file或so file, 作为一个基类
// 用于解析elf文件后存储信息用
struct InputFile_
{
File *file;
//ElfSyms 是一个 Sym 结构体的数组
Shdr* ElfSections;
int64_t sectionNum;
char* ShStrtab;
int64_t FirstGlobal;
ElfSym *ElfSyms;
int64_t ElfSymNum;
char* SymbolStrtab;
bool isAlive;
Symbol* Symbols; // all symbols
Symbol** LocalSymbols; // local symbols
int numLocalSymbols;
int64_t numSymbols;
};
#define ChunkTypeUnknown ((ChunkType)0)
#define ChunkTypeEhdr ((ChunkType)1)
#define ChunkTypeShdr ((ChunkType)2)
#define ChunkTypePhdr ((ChunkType)3)
#define ChunkTypeOutputSection ((ChunkType)4)
#define ChunkTypeMergedSection ((ChunkType)5)
#define ChunkTypeGotSection ((ChunkType)6)
#define ChunkTypeShStrtab ((ChunkType)7)
#define ChunkTypeSymtab ((ChunkType)8)
#define ChunkTypeStrtab ((ChunkType)9)
File** ReadArchiveMembers(File* file,int * fileCount);
ObjectFile *CreateObjectFile(Context *ctx,File* file,bool inLib);
void readFile(Context *ctx,File* file);
void ReadInputFiles(Context* ctx,char** remaining);
Chunk *NewChunk();
Shdr *GetShdr(Chunk* c);
void CopyBuf(Chunk* c,Context* ctx);
char* GetName(Chunk* c);
void Update(Chunk* c,Context* ctx);
//-------------ehdr
OutputEhdr *NewOutputEhdr();
void Ehdr_CopyBuf(Chunk *c,Context* ctx);
//----------------shdr
OutputShdr *NewOutputShdr();
void Shdr_UpdateShdr(Chunk* c,Context* ctx);
void Shdr_CopyBuf(Chunk* c,Context* ctx);
//--------------outputsection
OutputSection *GetOutputSection(Context* ctx,char* name,uint64_t typ,uint64_t flags);
OutputSection *NewOutputSection(char* name,uint32_t typ, uint64_t flags, uint32_t idx);
void OutputSec_CopyBuf(Chunk* c,Context* ctx);
//-------------------shstrtab
OutputShStrtab *NewOutputShStrtab();
void ShStrtab_CopyBuf(Chunk* c,Context* ctx);
//-------------------strtab
typedef struct OutputStrtab_ OutputStrtab;
OutputStrtab *NewOutputStrtab(const char* name);
uint32_t StrtabAppend(OutputStrtab* tab, const char* name);
void Strtab_CopyBuf(Chunk* c, Context* ctx);
//-------------------symtab
typedef struct OutputSymtab_ OutputSymtab;
OutputSymtab *NewOutputSymtab(OutputStrtab* strtab);
void BuildOutputSymtab(Context* ctx);
void Symtab_CopyBuf(Chunk* c, Context* ctx);
static bool ShouldEmitSectionHeader(Context* ctx, Chunk* chunk);
//-------------------phdr
OutputPhdr *NewOutputPhdr();
void Phdr_CopyBuf(Chunk* c,Context* ctx);
void Phdr_UpdateShdr(Chunk* c,Context* ctx);
//-------------------got section
GotSection *NewGotSection();
void AddGotTpSymbol(Chunk* chunk, Symbol* sym);
void AddGotSymbol(Chunk* chunk, Symbol* sym);
void GotSec_CopyBuf(Chunk* c,Context* ctx);
GotEntry *GetEntries(Chunk *chunk,Context* ctx,int* num);
uint64_t GetGotAddr(Context* ctx,Symbol* s);
void FinalizeGlobalPointer(Context* ctx);
void AssignOffsets(MergedSection* m);
void MergedSec_CopyBuf(Chunk* c,Context* ctx);
File* NewFile(const char* name);
File* OpenLibrary(const char* filepath);
File* FindLibrary(Context* ctx, const char* name);
Context* NewContext();
void appendLibraryPath(Context* ctx, char* arg);
//SectionFragment
SectionFragment* NewSectionFragment(MergedSection* m);
uint64_t SectionFragment_GetAddr(SectionFragment* s);
//mergedSection
MergedSection *NewMergedSection(char* name , uint64_t flags , uint32_t typ);
MergedSection *GetMergedSectionInstance(Context* ctx, char* name,uint32_t typ,uint64_t flags);
SectionFragment *Insert(MergedSection* m,char* key,uint32_t p2align,int strslen);
//mergeableSection
MergeableSection *NewMergeableSection();
//根据偏移,找到它属于哪个sectionFragment
SectionFragment* GetFragment(const MergeableSection* m, uint32_t offset, uint32_t* fragOffset);
#define MachineTypeNone ((MachineType)0)
#define MachineTypeRISCV64 ((MachineType)1)
const char* MachineType_String(MachineType m);
MachineType GetMachineTypeFromContents(const char* contents);
char* GetOutputName(char* name, uint64_t flags);
// Format of an ELF executable file
#define ELF_MAGIC 0x464C457FU // "\x7FELF" in little endian
// Values for Proghdr type
#define ELF_PROG_LOAD 1
// Flag bits for Proghdr flags
#define ELF_PROG_FLAG_EXEC 1
#define ELF_PROG_FLAG_WRITE 2
#define ELF_PROG_FLAG_READ 4
void MarkLiveObjects(Context* ctx);
void ResolveSymbols_pass(Context* ctx);
void RegisterSectionPieces(Context* ctx);
void CreateSyntheticSections(Context* ctx);
uint64_t SetOutputSectionOffsets(Context* ctx);
void BinSections(Context* ctx);
void CollectOutputSections(Context* ctx);
void ComputeSectionSizes(Context* ctx);
void SortOutputSections(Context* ctx);
bool isTbss(Chunk* chunk);
void ComputeMergedSectionSizes(Context* ctx);
void ScanRelocations(Context* ctx);
ObjectFile *NewObjectFile(File* file,bool isAlive);
void Parse(Context *ctx,ObjectFile* o);
void FillUpSymtabShndxSec(ObjectFile* o,Shdr* s);
void InitializeSections(ObjectFile* o,Context* ctx);
void InitializeSymbols(Context *ctx,ObjectFile* o);
void InitializeMergeableSections(ObjectFile * o,Context* ctx);
MergeableSection *splitSection(Context* ctx,InputSection* isec);
int64_t GetShndx(ObjectFile* o, ElfSym* esym, int idx);
void ResolveSymbols(ObjectFile* o);
//typedef void (*FeederFunc)(ObjectFile*);
void markLiveObjs(ObjectFile* o,ObjectFile*** roots,int *rootSize);
void ClearSymbols(ObjectFile* o);
void registerSectionPieces(ObjectFile* o);
void SkipEhframeSections(ObjectFile* o);
//-----------------------
void AddObjectFile(ObjectFile*** Objs, int* ObjsCount, ObjectFile* newObj);
//----------------inputsection
InputSection *NewInputSection(Context *ctx,char* name,ObjectFile* file,uint32_t shndx);
Shdr *shdr_(struct InputSection_* i);
char* Name(struct InputSection_* inputSection);
void WriteTo(struct InputSection_ *i,char* buf,Context* ctx);
Rela *GetRels(InputSection* i);
uint64_t InputSec_GetAddr(InputSection* i);
void ScanRelocations_(Context* ctx,ObjectFile* o);
void ApplyRelocAlloc(InputSection* i,Context* ctx,char* buf);
void writeItype(void* loc, uint32_t val);
void writeStype(void* loc, uint32_t val);
void writeBtype(void* loc, uint32_t val);
void writeUtype(void* loc, uint32_t val);
void writeJtype(void* loc, uint32_t val);
void setRs1(void* loc,uint32_t rs1);
Symbol *NewSymbol(char* name);
Symbol *GetSymbolByName(Context* ctx,char* name);
ElfSym *GetElfSymbol(Symbol* s);
void clear(Symbol* s);
uint64_t Symbol_GetAddr(Symbol* s);
uint64_t GetGotTpAddr(Context* ctx,Symbol* s);
InputFile* NewInputFile(File* file);
char* GetBytesFromIdx(InputFile* inputFile, int64_t idx);
char* GetBytesFromShdr(InputFile* inputFile, Shdr* shdr);
Shdr* FindSection(InputFile* f, uint32_t ty);
void FillUpElfSyms(InputFile* inputFile,Shdr* s);
Ehdr GetEhdr(InputFile* f);
void fatal(const char* format, ...);
char* ReadFile(const char* filename,uint64_t *len);
void Read(void* out, const void* data, size_t size);
char** appendToRemaining(char** remaining, const char* arg,bool l);
char* removePrefix(const char* s, const char* prefix);
bool hasPrefix(const char* s, const char* prefix);
int endsWith(const char *str, const char *suffix);
static unsigned hash_string_key(void* key);
static int compare_string_key(void* lhs, void* rhs);
uint64_t AlignTo(uint64_t val, uint64_t align);
void Write(void* data, size_t dataSize, void* element);
uint32_t Bit_32(uint32_t val, int pos);
uint32_t Bits_32(uint32_t val, uint32_t hi, uint32_t lo);
uint64_t SignExtend(uint64_t val,int size);
typedef uint8_t FileType;
#define FileTypeUnknown ((FileType)0)
#define FileTypeEmpty ((FileType)1)
#define FileTypeObject ((FileType)2)
#define FileTypeArchive ((FileType)3)
FileType GetFileType(const char* contents);
#define ELF_MAGIC 0x464C457FU // "\x7FELF" in little endian
bool CheckMagic(const char* contents);
void WriteMagic(uint8_t * contents);
char* ElfGetName(char* strTab, uint32_t offset);
int GetSize(const ArHdr* a);
bool IsAbs(const ElfSym* s);
bool IsUndef(const ElfSym* s);
bool IsCommon(const ElfSym* s);
bool HasPrefix(const ArHdr* a, const char* s);
bool IsStrtab(const ArHdr* a);
bool IsSymtab(const ArHdr* a);
char* ReadName(const ArHdr* a, char* strTab);
static const char* FileTypeToString(FileType type)
{
switch (type) {
case FileTypeEmpty:
return "empty";
case FileTypeObject:
return "object";
case FileTypeArchive:
return "archive";
case FileTypeUnknown:
default:
return "unknown";
}
}
ObjectFile** RemoveIf(ObjectFile** elems, int* count)
{
int num = *count;
size_t i = 0;
for (size_t j = 0; j < num; j++) {
if (!elems[j]->inputFile->isAlive) {
(*count)--;
continue;
}
elems[i] = elems[j];
i++;
}
return elems;
}
void ResolveSymbols_pass(Context* ctx)
{
DBG("ResolveSymbols_pass: start (objs=%d)\n", ctx->ObjsCount);
for(int i=0;i<ctx->ObjsCount;i++){
ObjectFile *objectFile = ctx->Objs[i];
DBG("ResolveSymbols_pass: resolving %s (alive=%d)\n",
objectFile->inputFile->file->Name,
objectFile->inputFile->isAlive);
ResolveSymbols(objectFile);
}
DBG("ResolveSymbols_pass: MarkLiveObjects start\n");
MarkLiveObjects(ctx);
DBG("ResolveSymbols_pass: MarkLiveObjects done\n");
for(int i=0;i<ctx->ObjsCount;i++){
ObjectFile *objectFile = ctx->Objs[i];
if(!objectFile->inputFile->isAlive) {
DBG("ResolveSymbols_pass: clearing symbols for %s\n",
objectFile->inputFile->file->Name);
ClearSymbols(objectFile);
}
}
ctx->Objs = RemoveIf(ctx->Objs,&ctx->ObjsCount);
DBG("ResolveSymbols_pass: done (objs=%d)\n", ctx->ObjsCount);
}
void MarkLiveObjects(Context* ctx)
{
ObjectFile **roots = NULL;
int rootSize = 0;
for (int i = 0; i < ctx->ObjsCount; i++) {
if (ctx->Objs[i]->inputFile->isAlive) {
roots = realloc(roots, (rootSize + 1) * sizeof(ObjectFile*));
roots[rootSize] = ctx->Objs[i];
rootSize++;
}
}
int num = 0;
int stuck_num = -1;
int stuck_count = 0;
DBG("MarkLiveObjects: rootSize=%d\n", rootSize);
while (num < rootSize) {
ObjectFile *file = roots[num];
DBG("MarkLiveObjects: visit root[%d/%d] %s alive=%d\n",
num, rootSize, file->inputFile->file->Name,
file->inputFile->isAlive);
if (!file->inputFile->isAlive) {
if (stuck_num == num) {
stuck_count++;
} else {
stuck_num = num;
stuck_count = 1;
}
if (stuck_count == 1 || stuck_count % 1000 == 0) {
DBG("MarkLiveObjects: root[%d] %s unexpectedly not alive (count=%d)\n",
num, file->inputFile->file->Name, stuck_count);
}
if (stuck_count > 100000) {
fatal("MarkLiveObjects stuck at root %d (%s)", num, file->inputFile->file->Name);
}
continue;
}
stuck_num = -1;
stuck_count = 0;
markLiveObjs(file, &roots, &rootSize);
DBG("MarkLiveObjects: after mark, rootSize=%d\n", rootSize);
num++;
}
}
void RegisterSectionPieces(Context* ctx)
{
for (int i = 0; i < ctx->ObjsCount; i++) {
ObjectFile *file = ctx->Objs[i];
registerSectionPieces(file);
}
}
uint64_t SetOutputSectionOffsets(Context* ctx)
{
uint64_t fileoff = 0;
int iter = 0;
while (1) {
uint64_t oldPhdrSize = ctx->phdr->chunk->shdr.Size;
uint64_t addr = 0x1000;
for (int idx = 0; idx < ctx->chunkNum; idx++) {
Chunk *chunk = ctx->chunk[idx];
if ((GetShdr(chunk)->Flags & SHF_ALLOC) == 0)
continue;
addr = AlignTo(addr, GetShdr(chunk)->AddrAlign);
GetShdr(chunk)->Addr = addr;
if (chunk->name && strcmp(chunk->name, ".got") == 0) {
DBG("SetOutputSectionOffsets: .got size=%lu addr=0x%lx\n",
(unsigned long)GetShdr(chunk)->Size,
(unsigned long)addr);
}
if (!isTbss(chunk)) {
addr += GetShdr(chunk)->Size;
}
}
size_t i = 0;
Chunk *first = ctx->chunk[0];
while (1) {
Shdr* shdr = GetShdr(ctx->chunk[i]);
// 偏移地址是当前虚拟地址减去起始虚拟地址
shdr->Offset = shdr->Addr - GetShdr(first)->Addr;
i++;
if (i >= ctx->chunkNum ||
((GetShdr(ctx->chunk[i])->Flags & SHF_ALLOC) == 0)) {
break;
}
}
Shdr *lastShdr = GetShdr(ctx->chunk[i-1]);
fileoff = lastShdr->Offset + lastShdr->Size;
for (; i < ctx->chunkNum; i++) {
fileoff = AlignTo(fileoff, ctx->chunk[i]->shdr.AddrAlign);
GetShdr(ctx->chunk[i])->Offset = fileoff;
fileoff += ctx->chunk[i]->shdr.Size;
}
// 算完值后重新更新 phdr;如果大小变化则重新迭代
Phdr_UpdateShdr(ctx->phdr->chunk, ctx);
Shdr_UpdateShdr(ctx->shdr->chunk, ctx);
if (ctx->phdr->chunk->shdr.Size == oldPhdrSize) {
return fileoff;
}
if (++iter > 4) {
fatal("SetOutputSectionOffsets: phdr size failed to converge");
}
}
}
// 创建自己合成的section
void CreateSyntheticSections(Context* ctx)
{
struct OutputEhdr_* outputEhdr = NewOutputEhdr();
ctx->ehdr = outputEhdr;
ctx->chunk = realloc(ctx->chunk,sizeof (Chunk*) * (ctx->chunkNum+1));
ctx->chunk[ctx->chunkNum] = outputEhdr->chunk;
ctx->chunkNum++;
struct OutputPhdr_* outputPhdr = NewOutputPhdr();
ctx->phdr = outputPhdr;
ctx->chunk = realloc(ctx->chunk,sizeof (Chunk*) * (ctx->chunkNum+1));
ctx->chunk[ctx->chunkNum] = outputPhdr->chunk;
ctx->chunkNum++;
struct OutputShdr_* outputShdr = NewOutputShdr();
ctx->shdr = outputShdr;
ctx->chunk = realloc(ctx->chunk,sizeof (Chunk*) * (ctx->chunkNum+1));
ctx->chunk[ctx->chunkNum] = outputShdr->chunk;
ctx->chunkNum++;
struct OutputShStrtab_* shstrtab = NewOutputShStrtab();
ctx->shstrtab = shstrtab;
ctx->chunk = realloc(ctx->chunk,sizeof (Chunk*) * (ctx->chunkNum+1));
ctx->chunk[ctx->chunkNum] = shstrtab->chunk;