forked from rui314/mold
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpasses.cc
3142 lines (2671 loc) · 99.8 KB
/
passes.cc
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
#include "mold.h"
#include <fstream>
#include <functional>
#include <map>
#include <optional>
#include <regex>
#include <shared_mutex>
#include <tbb/parallel_for_each.h>
#include <tbb/parallel_sort.h>
#include <tbb/partitioner.h>
#include <unordered_set>
namespace mold::elf {
// Since elf_main is a template, we can't run it without a type parameter.
// We speculatively run elf_main with X86_64, and if the speculation was
// wrong, re-run it with an actual machine type.
template <typename E>
int redo_main(Context<E> &ctx, int argc, char **argv) {
std::string_view target = ctx.arg.emulation;
if (target == I386::target_name)
return elf_main<I386>(argc, argv);
if (target == ARM64::target_name)
return elf_main<ARM64>(argc, argv);
if (target == ARM32::target_name)
return elf_main<ARM32>(argc, argv);
if (target == RV64LE::target_name)
return elf_main<RV64LE>(argc, argv);
if (target == RV64BE::target_name)
return elf_main<RV64BE>(argc, argv);
if (target == RV32LE::target_name)
return elf_main<RV32LE>(argc, argv);
if (target == RV32BE::target_name)
return elf_main<RV32BE>(argc, argv);
if (target == PPC32::target_name)
return elf_main<PPC32>(argc, argv);
if (target == PPC64V1::target_name)
return elf_main<PPC64V1>(argc, argv);
if (target == PPC64V2::target_name)
return elf_main<PPC64V2>(argc, argv);
if (target == S390X::target_name)
return elf_main<S390X>(argc, argv);
if (target == SPARC64::target_name)
return elf_main<SPARC64>(argc, argv);
if (target == M68K::target_name)
return elf_main<M68K>(argc, argv);
if (target == SH4::target_name)
return elf_main<SH4>(argc, argv);
if (target == ALPHA::target_name)
return elf_main<ALPHA>(argc, argv);
if (target == LOONGARCH32::target_name)
return elf_main<LOONGARCH32>(argc, argv);
if (target == LOONGARCH64::target_name)
return elf_main<LOONGARCH64>(argc, argv);
unreachable();
}
template <typename E>
void apply_exclude_libs(Context<E> &ctx) {
Timer t(ctx, "apply_exclude_libs");
if (ctx.arg.exclude_libs.empty())
return;
std::unordered_set<std::string_view> set(ctx.arg.exclude_libs.begin(),
ctx.arg.exclude_libs.end());
for (ObjectFile<E> *file : ctx.objs)
if (!file->archive_name.empty())
if (set.contains("ALL") ||
set.contains(filepath(file->archive_name).filename().string()))
file->exclude_libs = true;
}
template <typename E>
static bool has_debug_info_section(Context<E> &ctx) {
for (ObjectFile<E> *file : ctx.objs)
if (file->debug_info)
return true;
return false;
}
template <typename E>
void create_synthetic_sections(Context<E> &ctx) {
auto push = [&](auto *x) {
ctx.chunks.push_back(x);
ctx.chunk_pool.emplace_back(x);
return x;
};
if (!ctx.arg.oformat_binary) {
auto find = [&](std::string_view name) {
for (SectionOrder &ord : ctx.arg.section_order)
if (ord.type == SectionOrder::SECTION && ord.name == name)
return true;
return false;
};
if (ctx.arg.section_order.empty() || find("EHDR"))
ctx.ehdr = push(new OutputEhdr<E>(SHF_ALLOC));
else
ctx.ehdr = push(new OutputEhdr<E>(0));
if (ctx.arg.section_order.empty() || find("PHDR"))
ctx.phdr = push(new OutputPhdr<E>(SHF_ALLOC));
else
ctx.phdr = push(new OutputPhdr<E>(0));
if (ctx.arg.z_sectionheader)
ctx.shdr = push(new OutputShdr<E>);
}
ctx.got = push(new GotSection<E>);
if constexpr (!is_sparc<E>)
ctx.gotplt = push(new GotPltSection<E>(ctx));
ctx.reldyn = push(new RelDynSection<E>);
ctx.relplt = push(new RelPltSection<E>);
if (ctx.arg.pack_dyn_relocs_relr)
ctx.relrdyn = push(new RelrDynSection<E>);
ctx.strtab = push(new StrtabSection<E>);
ctx.plt = push(new PltSection<E>);
ctx.pltgot = push(new PltGotSection<E>);
ctx.symtab = push(new SymtabSection<E>);
ctx.dynsym = push(new DynsymSection<E>);
ctx.dynstr = push(new DynstrSection<E>);
ctx.eh_frame = push(new EhFrameSection<E>);
ctx.copyrel = push(new CopyrelSection<E>(false));
ctx.copyrel_relro = push(new CopyrelSection<E>(true));
if (ctx.shdr)
ctx.shstrtab = push(new ShstrtabSection<E>);
if (!ctx.arg.dynamic_linker.empty())
ctx.interp = push(new InterpSection<E>);
if (ctx.arg.build_id.kind != BuildId::NONE)
ctx.buildid = push(new BuildIdSection<E>);
if (ctx.arg.eh_frame_hdr)
ctx.eh_frame_hdr = push(new EhFrameHdrSection<E>);
if (ctx.arg.gdb_index && has_debug_info_section(ctx))
ctx.gdb_index = push(new GdbIndexSection<E>);
if (ctx.arg.z_relro && ctx.arg.section_order.empty() &&
ctx.arg.z_separate_code != SEPARATE_LOADABLE_SEGMENTS)
ctx.relro_padding = push(new RelroPaddingSection<E>);
if (ctx.arg.hash_style_sysv)
ctx.hash = push(new HashSection<E>);
if (ctx.arg.hash_style_gnu)
ctx.gnu_hash = push(new GnuHashSection<E>);
if (!ctx.arg.version_definitions.empty())
ctx.verdef = push(new VerdefSection<E>);
if (ctx.arg.emit_relocs)
ctx.eh_frame_reloc = push(new EhFrameRelocSection<E>);
if (ctx.arg.shared || !ctx.dsos.empty() || ctx.arg.pie) {
ctx.dynamic = push(new DynamicSection<E>(ctx));
// If .dynamic exists, .dynsym and .dynstr must exist as well
// since .dynamic refers to them.
ctx.dynstr->shdr.sh_size = 1;
ctx.dynsym->symbols.resize(1);
}
ctx.versym = push(new VersymSection<E>);
ctx.verneed = push(new VerneedSection<E>);
ctx.note_package = push(new NotePackageSection<E>);
ctx.note_property = push(new NotePropertySection<E>);
if constexpr (is_riscv<E>)
ctx.extra.riscv_attributes = push(new RiscvAttributesSection<E>);
if constexpr (is_ppc64v1<E>)
ctx.extra.opd = push(new PPC64OpdSection);
if constexpr (is_ppc64v2<E>)
ctx.extra.save_restore = push(new PPC64SaveRestoreSection);
if constexpr (is_sparc<E>) {
if (ctx.arg.is_static)
ctx.extra.tls_get_addr_sec = push(new SparcTlsGetAddrSection);
ctx.extra.tls_get_addr_sym = get_symbol(ctx, "__tls_get_addr");
}
if constexpr (is_alpha<E>)
ctx.extra.got = push(new AlphaGotSection);
}
template <typename E>
static void mark_live_objects(Context<E> &ctx) {
for (Symbol<E> *sym : ctx.arg.undefined)
if (sym->file)
sym->file->is_alive = true;
for (Symbol<E> *sym : ctx.arg.require_defined)
if (sym->file)
sym->file->is_alive = true;
if (!ctx.arg.undefined_glob.empty()) {
tbb::parallel_for_each(ctx.objs, [&](ObjectFile<E> *file) {
if (!file->is_alive) {
for (Symbol<E> *sym : file->get_global_syms()) {
if (sym->file == file && ctx.arg.undefined_glob.find(sym->name())) {
file->is_alive = true;
sym->gc_root = true;
break;
}
}
}
});
}
std::vector<InputFile<E> *> roots;
for (InputFile<E> *file : ctx.objs)
if (file->is_alive)
roots.push_back(file);
for (InputFile<E> *file : ctx.dsos)
if (file->is_alive)
roots.push_back(file);
tbb::parallel_for_each(roots, [&](InputFile<E> *file,
tbb::feeder<InputFile<E> *> &feeder) {
file->mark_live_objects(ctx, [&](InputFile<E> *obj) { feeder.add(obj); });
});
}
template <typename E>
static void clear_symbols(Context<E> &ctx) {
std::vector<InputFile<E> *> files;
append(files, ctx.objs);
append(files, ctx.dsos);
tbb::parallel_for_each(files, [](InputFile<E> *file) {
for (Symbol<E> *sym : file->get_global_syms()) {
if (__atomic_load_n(&sym->file, __ATOMIC_ACQUIRE) == file) {
sym->origin = 0;
sym->value = -1;
sym->sym_idx = -1;
sym->ver_idx = VER_NDX_UNSPECIFIED;
sym->is_weak = false;
sym->is_imported = false;
sym->is_exported = false;
__atomic_store_n(&sym->file, nullptr, __ATOMIC_RELEASE);
}
}
});
}
template <typename E>
void do_resolve_symbols(Context<E> &ctx) {
std::vector<InputFile<E> *> files;
append(files, ctx.objs);
append(files, ctx.dsos);
// Due to legacy reasons, archive members will only get included in the final
// binary if they satisfy one of the undefined symbols in a non-archive object
// file. This is called archive extraction. In finalize_archive_extraction,
// this is processed as follows:
//
// 1. Do preliminary symbol resolution assuming all archive members
// are included. This matches the undefined symbols with ones to be
// extracted from archives.
//
// 2. Do a mark & sweep pass to eliminate unneeded archive members.
//
// Note that the symbol resolution inside finalize_archive_extraction uses a
// different rule. In order to prevent extracting archive members that can be
// satisfied by either non-archive object files or DSOs, the archive members
// are given a lower priority. This is not correct for the general case, where
// *extracted* object files have precedence over DSOs and even non-archive
// files that are passed earlier in the command line. Hence, the symbol
// resolution is thrown away once we determine which archive members to
// extract, and redone later with the formal rule.
{
Timer t(ctx, "extract_archive_members");
// Register symbols
tbb::parallel_for_each(files, [&](InputFile<E> *file) {
file->resolve_symbols(ctx);
});
// Mark reachable objects to decide which files to include into an output.
// This also merges symbol visibility.
mark_live_objects(ctx);
// Cleanup. The rule used for archive extraction isn't accurate for the
// general case of symbol extraction, so reset the resolution to be redone
// later.
clear_symbols(ctx);
// Now that the symbol references are gone, remove the eliminated files from
// the file list.
std::erase_if(files, [](InputFile<E> *file) { return !file->is_alive; });
std::erase_if(ctx.objs, [](InputFile<E> *file) { return !file->is_alive; });
std::erase_if(ctx.dsos, [](InputFile<E> *file) { return !file->is_alive; });
}
// COMDAT elimination needs to happen exactly here.
//
// It needs to be after archive extraction, otherwise we might assign COMDAT
// leader to an archive member that is not supposed to be extracted.
//
// It needs to happen before symbol resolution, otherwise we could eliminate
// a symbol that is already resolved to and cause dangling references.
{
Timer t(ctx, "eliminate_comdats");
tbb::parallel_for_each(ctx.objs, [](ObjectFile<E> *file) {
for (ComdatGroupRef<E> &ref : file->comdat_groups)
update_minimum(ref.group->owner, file->priority);
});
tbb::parallel_for_each(ctx.objs, [](ObjectFile<E> *file) {
for (ComdatGroupRef<E> &ref : file->comdat_groups)
if (ref.group->owner != file->priority)
for (u32 i : ref.members)
if (file->sections[i])
file->sections[i]->kill();
});
}
// Since we have turned on object files live bits, their symbols
// may now have higher priority than before. So run the symbol
// resolution pass again to get the final resolution result.
tbb::parallel_for_each(files, [&](InputFile<E> *file) {
file->resolve_symbols(ctx);
});
}
template <typename E>
void resolve_symbols(Context<E> &ctx) {
Timer t(ctx, "resolve_symbols");
std::vector<ObjectFile<E> *> objs = ctx.objs;
std::vector<SharedFile<E> *> dsos = ctx.dsos;
do_resolve_symbols(ctx);
bool has_lto_obj = false;
for (ObjectFile<E> *file : objs)
if (file->is_alive && (file->is_lto_obj || file->is_gcc_offload_obj))
has_lto_obj = true;
if (has_lto_obj) {
// Do link-time optimization. We pass all IR object files to the
// compiler backend to compile them into a few ELF object files.
//
// The compiler backend needs to know how symbols are resolved,
// so compute symbol visibility, import/export bits, etc early.
mark_live_objects(ctx);
apply_version_script(ctx);
parse_symbol_version(ctx);
compute_import_export(ctx);
// Do LTO. It compiles IR object files into a few big ELF files.
std::vector<ObjectFile<E> *> lto_objs = do_lto(ctx);
// do_resolve_symbols() have removed unreferenced files. Restore the
// original files here because some of them may have to be resurrected
// because they are referenced by the ELF files returned from do_lto().
ctx.objs = objs;
ctx.dsos = dsos;
append(ctx.objs, lto_objs);
// Redo name resolution from scratch.
clear_symbols(ctx);
// Remove IR object files.
for (ObjectFile<E> *file : ctx.objs)
if (file->is_lto_obj)
file->is_alive = false;
std::erase_if(ctx.objs, [](ObjectFile<E> *file) { return file->is_lto_obj; });
do_resolve_symbols(ctx);
}
}
// .eh_frame sections are parsed and regenerated by the linker for the purpose
// of deduplication and garbage collection. As such, the input sections should
// not be copied over.
//
// However, in very rare cases (e.g. GCC CRT compiled with LTO) we might need
// to resolve cross-object .eh_frame section references (they only point to
// begin or end and don't depend on the actual section contents).
// Therefore, the sections are "killed" after symbol resolution as a separate
// pass.
template <typename E>
void kill_eh_frame_sections(Context<E> &ctx) {
Timer t(ctx, "kill_eh_frame_sections");
for (ObjectFile<E> *file : ctx.objs)
for (InputSection<E> *sec : file->eh_frame_sections)
sec->is_alive = false;
}
template <typename E>
void split_section_pieces(Context<E> &ctx) {
Timer t(ctx, "split_section_pieces");
tbb::parallel_for_each(ctx.objs, [&](ObjectFile<E> *file) {
file->initialize_mergeable_sections(ctx);
});
}
template <typename E>
void resolve_section_pieces(Context<E> &ctx) {
Timer t(ctx, "resolve_section_pieces");
// We aim 2/3 occupation ratio
for (std::unique_ptr<MergedSection<E>> &sec : ctx.merged_sections)
sec->map.resize(sec->estimator.get_cardinality() * 3 / 2);
tbb::parallel_for_each(ctx.objs, [&](ObjectFile<E> *file) {
file->resolve_section_pieces(ctx);
});
}
template <typename E>
void convert_common_symbols(Context<E> &ctx) {
Timer t(ctx, "convert_common_symbols");
tbb::parallel_for_each(ctx.objs, [&](ObjectFile<E> *file) {
file->convert_common_symbols(ctx);
});
}
template <typename E>
static std::string get_cmdline_args(Context<E> &ctx) {
std::stringstream ss;
ss << ctx.cmdline_args[1];
for (i64 i = 2; i < ctx.cmdline_args.size(); i++)
ss << " " << ctx.cmdline_args[i];
return ss.str();
}
template <typename E>
void add_comment_string(Context<E> &ctx, std::string str) {
MergedSection<E> *sec =
MergedSection<E>::get_instance(ctx, ".comment", SHT_PROGBITS,
SHF_MERGE | SHF_STRINGS, 1, 1);
if (sec->map.nbuckets == 0)
sec->map.resize(4096);
std::string_view buf = save_string(ctx, str);
std::string_view data(buf.data(), buf.size() + 1);
sec->insert(ctx, data, hash_string(data), 0);
}
template <typename E>
void compute_merged_section_sizes(Context<E> &ctx) {
Timer t(ctx, "compute_merged_section_sizes");
// Add an identification string to .comment.
if (!ctx.arg.oformat_binary)
add_comment_string(ctx, get_mold_version());
// Embed command line arguments for debugging.
if (char *env = getenv("MOLD_DEBUG"); env && env[0])
add_comment_string(ctx, "mold command line: " + get_cmdline_args(ctx));
tbb::parallel_for_each(ctx.merged_sections,
[&](std::unique_ptr<MergedSection<E>> &sec) {
sec->assign_offsets(ctx);
});
}
template <typename T>
static std::vector<std::span<T>> split(std::vector<T> &input, i64 unit) {
std::span<T> span(input);
std::vector<std::span<T>> vec;
while (span.size() >= unit) {
vec.push_back(span.subspan(0, unit));
span = span.subspan(unit);
}
if (!span.empty())
vec.push_back(span);
return vec;
}
template <typename E>
static bool has_ctors_and_init_array(Context<E> &ctx) {
bool x = false;
bool y = false;
for (ObjectFile<E> *file : ctx.objs) {
x |= file->has_ctors;
y |= file->has_init_array;
}
return x && y;
}
template <typename E>
static u64 canonicalize_type(std::string_view name, u64 type) {
// Some old assemblers don't recognize these section names and
// create them as SHT_PROGBITS.
if (type == SHT_PROGBITS) {
if (name == ".init_array" || name.starts_with(".init_array."))
return SHT_INIT_ARRAY;
if (name == ".fini_array" || name.starts_with(".fini_array."))
return SHT_FINI_ARRAY;
}
// The x86-64 psABI defines SHT_X86_64_UNWIND for .eh_frame, allowing
// the linker to recognize the section not by name but by section type.
// However, that spec change was generally considered a mistake; it has
// just complicated the situation. As a result, .eh_frame on x86-64 may
// be either SHT_PROGBITS or SHT_X86_64_UNWIND. We use SHT_PROGBITS
// consistently.
if constexpr (is_x86_64<E>)
if (type == SHT_X86_64_UNWIND)
return SHT_PROGBITS;
return type;
}
struct OutputSectionKey {
bool operator==(const OutputSectionKey &) const = default;
std::string_view name;
u64 type;
struct Hash {
size_t operator()(const OutputSectionKey &k) const {
return combine_hash(hash_string(k.name), std::hash<u64>{}(k.type));
}
};
};
template <typename E>
static std::string_view
get_output_name(Context<E> &ctx, std::string_view name, u64 flags) {
if (ctx.arg.relocatable && !ctx.arg.relocatable_merge_sections)
return name;
if (ctx.arg.unique && ctx.arg.unique->match(name))
return name;
if (flags & SHF_MERGE)
return name;
if constexpr (is_arm32<E>) {
if (name.starts_with(".ARM.exidx"))
return ".ARM.exidx";
if (name.starts_with(".ARM.extab"))
return ".ARM.extab";
}
if constexpr (is_alpha<E>) {
if (name.starts_with(".sdata."))
return ".sdata";
if (name.starts_with(".sbss."))
return ".sbss";
}
if (ctx.arg.z_keep_text_section_prefix) {
static std::string_view prefixes[] = {
".text.hot.", ".text.unknown.", ".text.unlikely.", ".text.startup.",
".text.exit."
};
for (std::string_view prefix : prefixes) {
std::string_view stem = prefix.substr(0, prefix.size() - 1);
if (name == stem || name.starts_with(prefix))
return stem;
}
}
static std::string_view prefixes[] = {
".text.", ".data.rel.ro.", ".data.", ".rodata.", ".bss.rel.ro.", ".bss.",
".init_array.", ".fini_array.", ".tbss.", ".tdata.", ".gcc_except_table.",
".ctors.", ".dtors.", ".gnu.warning.", ".openbsd.randomdata.",
};
for (std::string_view prefix : prefixes) {
std::string_view stem = prefix.substr(0, prefix.size() - 1);
if (name == stem || name.starts_with(prefix))
return stem;
}
return name;
}
template <typename E>
static OutputSectionKey
get_output_section_key(Context<E> &ctx, InputSection<E> &isec,
bool ctors_in_init_array) {
// If .init_array/.fini_array exist, .ctors/.dtors must be merged
// with them.
//
// CRT object files contain .ctors/.dtors sections without any
// relocations. They contain sentinel values, 0 and -1, to mark the
// beginning and the end of the initializer/finalizer pointer arrays.
// We do not place them into .init_array/.fini_array because such
// invalid pointer values would simply make the program to crash.
if (ctors_in_init_array && !isec.get_rels(ctx).empty()) {
std::string_view name = isec.name();
if (name == ".ctors" || name.starts_with(".ctors."))
return {".init_array", SHT_INIT_ARRAY};
if (name == ".dtors" || name.starts_with(".dtors."))
return {".fini_array", SHT_FINI_ARRAY};
}
const ElfShdr<E> &shdr = isec.shdr();
std::string_view name = get_output_name(ctx, isec.name(), shdr.sh_flags);
u64 type = canonicalize_type<E>(name, shdr.sh_type);
return {name, type};
}
template <typename E>
static bool is_relro(OutputSection<E> &osec) {
// PT_GNU_RELRO segment is a security mechanism to make more pages
// read-only than we could have done without it.
//
// Traditionally, sections are either read-only or read-write. If a
// section contains dynamic relocations, it must have been put into a
// read-write segment so that the program loader can mutate its
// contents in memory, even if no one will write to it at runtime.
//
// RELRO segment allows us to make such pages writable only when a
// program is being loaded. After that, the page becomes read-only.
//
// Some sections, such as .init, .fini, .got, .dynamic, contain
// dynamic relocations but doesn't have to be writable at runtime,
// so they are put into a RELRO segment.
u32 type = osec.shdr.sh_type;
u32 flags = osec.shdr.sh_flags;
return osec.name == ".toc" || osec.name.ends_with(".rel.ro") ||
type == SHT_INIT_ARRAY || type == SHT_FINI_ARRAY ||
type == SHT_PREINIT_ARRAY || (flags & SHF_TLS);
}
// Create output sections for input sections.
template <typename E>
void create_output_sections(Context<E> &ctx) {
Timer t(ctx, "create_output_sections");
using MapType = std::unordered_map<OutputSectionKey, OutputSection<E> *,
OutputSectionKey::Hash>;
MapType map;
std::shared_mutex mu;
i64 size = ctx.osec_pool.size();
bool ctors_in_init_array = has_ctors_and_init_array(ctx);
// Instantiate output sections
tbb::parallel_for_each(ctx.objs, [&](ObjectFile<E> *file) {
// Make a per-thread cache of the main map to avoid lock contention.
// It makes a noticeable difference if we have millions of input sections.
MapType cache;
{
std::shared_lock lock(mu);
cache = map;
}
for (std::unique_ptr<InputSection<E>> &isec : file->sections) {
if (!isec || !isec->is_alive)
continue;
const ElfShdr<E> &shdr = isec->shdr();
u32 sh_flags = shdr.sh_flags & ~SHF_MERGE & ~SHF_STRINGS &
~SHF_COMPRESSED & ~SHF_GNU_RETAIN;
if (ctx.arg.relocatable && (sh_flags & SHF_GROUP)) {
OutputSection<E> *osec = new OutputSection<E>(isec->name(), shdr.sh_type);
osec->sh_flags = sh_flags;
isec->output_section = osec;
ctx.osec_pool.emplace_back(osec);
continue;
}
auto get_or_insert = [&] {
OutputSectionKey key =
get_output_section_key(ctx, *isec, ctors_in_init_array);
if (auto it = cache.find(key); it != cache.end())
return it->second;
{
std::shared_lock lock(mu);
if (auto it = map.find(key); it != map.end()) {
cache.insert({key, it->second});
return it->second;
}
}
std::unique_ptr<OutputSection<E>> osec =
std::make_unique<OutputSection<E>>(key.name, key.type);
std::unique_lock lock(mu);
auto [it, inserted] = map.insert({key, osec.get()});
if (inserted)
ctx.osec_pool.emplace_back(std::move(osec));
cache.insert({key, it->second});
return it->second;
};
OutputSection<E> *osec = get_or_insert();
sh_flags &= ~SHF_GROUP;
if ((osec->sh_flags & sh_flags) != sh_flags)
osec->sh_flags |= sh_flags;
isec->output_section = osec;
}
});
for (std::unique_ptr<OutputSection<E>> &osec : ctx.osec_pool) {
osec->shdr.sh_flags = osec->sh_flags;
osec->is_relro = is_relro(*osec);
}
// Add input sections to output sections
std::vector<Chunk<E> *> chunks;
for (i64 i = size; i < ctx.osec_pool.size(); i++)
chunks.push_back(ctx.osec_pool[i].get());
for (ObjectFile<E> *file : ctx.objs)
for (std::unique_ptr<InputSection<E>> &isec : file->sections)
if (isec && isec->is_alive)
isec->output_section->members.push_back(isec.get());
// Add output sections and mergeable sections to ctx.chunks
for (std::unique_ptr<MergedSection<E>> &osec : ctx.merged_sections)
if (osec->shdr.sh_size)
chunks.push_back(osec.get());
// Sections are added to the section lists in an arbitrary order
// because they are created in parallel. Sort them to to make the
// output deterministic.
tbb::parallel_sort(chunks.begin(), chunks.end(), [](Chunk<E> *x, Chunk<E> *y) {
return std::tuple(x->name, x->shdr.sh_type, x->shdr.sh_flags) <
std::tuple(y->name, y->shdr.sh_type, y->shdr.sh_flags);
});
append(ctx.chunks, chunks);
}
// Create a dummy object file containing linker-synthesized
// symbols.
template <typename E>
void create_internal_file(Context<E> &ctx) {
ObjectFile<E> *obj = new ObjectFile<E>;
ctx.obj_pool.emplace_back(obj);
ctx.internal_obj = obj;
ctx.objs.push_back(obj);
// Create linker-synthesized symbols.
ctx.internal_esyms.resize(1);
obj->symbols.push_back(new Symbol<E>);
obj->first_global = 1;
obj->is_alive = true;
obj->priority = 1;
auto add = [&](Symbol<E> *sym) {
obj->symbols.push_back(sym);
// An actual value will be set to a linker-synthesized symbol by
// fix_synthetic_symbols(). Until then, `value` doesn't have a valid
// value. 0xdeadbeef is a unique dummy value to make debugging easier
// if the field is accidentally used before it gets a valid one.
sym->value = 0xdeadbeef;
ElfSym<E> esym;
memset(&esym, 0, sizeof(esym));
esym.st_type = STT_NOTYPE;
esym.st_shndx = SHN_ABS;
esym.st_bind = STB_GLOBAL;
esym.st_visibility = STV_DEFAULT;
ctx.internal_esyms.push_back(esym);
};
// Add --defsym'd symbols
for (i64 i = 0; i < ctx.arg.defsyms.size(); i++)
add(ctx.arg.defsyms[i].first);
// Add --section-order symbols
for (SectionOrder &ord : ctx.arg.section_order)
if (ord.type == SectionOrder::SYMBOL)
add(get_symbol(ctx, ord.name));
obj->elf_syms = ctx.internal_esyms;
obj->has_symver.resize(ctx.internal_esyms.size() - 1);
}
template <typename E>
static std::optional<std::string>
get_start_stop_name(Context<E> &ctx, Chunk<E> &chunk) {
if ((chunk.shdr.sh_flags & SHF_ALLOC) && !chunk.name.empty()) {
if (is_c_identifier(chunk.name))
return std::string(chunk.name);
if (ctx.arg.start_stop) {
auto isalnum = [](char c) {
return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') ||
('0' <= c && c <= '9');
};
std::string s{chunk.name};
if (s.starts_with('.'))
s = s.substr(1);
for (i64 i = 0; i < s.size(); i++)
if (!isalnum(s[i]))
s[i] = '_';
return s;
}
}
return {};
}
template <typename E>
void add_synthetic_symbols(Context<E> &ctx) {
ObjectFile<E> &obj = *ctx.internal_obj;
auto add = [&](std::string_view name, u32 type = STT_NOTYPE) {
ElfSym<E> esym;
memset(&esym, 0, sizeof(esym));
esym.st_type = type;
esym.st_shndx = SHN_ABS;
esym.st_bind = STB_GLOBAL;
esym.st_visibility = STV_HIDDEN;
ctx.internal_esyms.push_back(esym);
Symbol<E> *sym = get_symbol(ctx, name);
sym->value = 0xdeadbeef; // unique dummy value
obj.symbols.push_back(sym);
return sym;
};
ctx.__ehdr_start = add("__ehdr_start");
ctx.__init_array_start = add("__init_array_start");
ctx.__init_array_end = add("__init_array_end");
ctx.__fini_array_start = add("__fini_array_start");
ctx.__fini_array_end = add("__fini_array_end");
ctx.__preinit_array_start = add("__preinit_array_start");
ctx.__preinit_array_end = add("__preinit_array_end");
ctx._DYNAMIC = add("_DYNAMIC");
ctx._GLOBAL_OFFSET_TABLE_ = add("_GLOBAL_OFFSET_TABLE_");
ctx._PROCEDURE_LINKAGE_TABLE_ = add("_PROCEDURE_LINKAGE_TABLE_");
ctx.__bss_start = add("__bss_start");
ctx._end = add("_end");
ctx._etext = add("_etext");
ctx._edata = add("_edata");
ctx.__executable_start = add("__executable_start");
ctx.__rel_iplt_start =
add(E::is_rela ? "__rela_iplt_start" : "__rel_iplt_start");
ctx.__rel_iplt_end =
add(E::is_rela ? "__rela_iplt_end" : "__rel_iplt_end");
if (ctx.arg.eh_frame_hdr)
ctx.__GNU_EH_FRAME_HDR = add("__GNU_EH_FRAME_HDR");
if (!get_symbol(ctx, "end")->file)
ctx.end = add("end");
if (!get_symbol(ctx, "etext")->file)
ctx.etext = add("etext");
if (!get_symbol(ctx, "edata")->file)
ctx.edata = add("edata");
if (!get_symbol(ctx, "__dso_handle")->file)
ctx.__dso_handle = add("__dso_handle");
if constexpr (supports_tlsdesc<E>)
ctx._TLS_MODULE_BASE_ = add("_TLS_MODULE_BASE_", STT_TLS);
if constexpr (is_riscv<E>) {
ctx.__global_pointer = add("__global_pointer$");
if (ctx.dynamic && !ctx.arg.shared)
ctx.__global_pointer->is_exported = true;
}
if constexpr (is_arm32<E>) {
ctx.__exidx_start = add("__exidx_start");
ctx.__exidx_end = add("__exidx_end");
}
if constexpr (is_ppc64<E>)
ctx.extra.TOC = add(".TOC.");
if constexpr (is_ppc32<E>)
ctx.extra._SDA_BASE_ = add("_SDA_BASE_");
auto add_start_stop = [&](std::string s) {
add(save_string(ctx, s));
if (ctx.arg.z_start_stop_visibility_protected)
get_symbol(ctx, save_string(ctx, s))->is_exported = true;
};
for (Chunk<E> *chunk : ctx.chunks) {
if (std::optional<std::string> name = get_start_stop_name(ctx, *chunk)) {
add_start_stop("__start_" + *name);
add_start_stop("__stop_" + *name);
if (ctx.arg.physical_image_base) {
add_start_stop("__phys_start_" + *name);
add_start_stop("__phys_stop_" + *name);
}
}
}
if constexpr (is_ppc64v2<E>)
for (std::pair<std::string_view, u32> p : ppc64_save_restore_insns)
if (std::string_view label = p.first; !label.empty())
add(label);
obj.elf_syms = ctx.internal_esyms;
obj.has_symver.resize(ctx.internal_esyms.size() - 1);
obj.resolve_symbols(ctx);
// Make all synthetic symbols relative ones by associating them to
// a dummy output section.
for (Symbol<E> *sym : obj.symbols) {
if (sym->file == &obj) {
sym->set_output_section(ctx.symtab);
sym->is_imported = false;
}
}
// Handle --defsym symbols.
for (i64 i = 0; i < ctx.arg.defsyms.size(); i++) {
Symbol<E> *sym1 = ctx.arg.defsyms[i].first;
std::variant<Symbol<E> *, u64> val = ctx.arg.defsyms[i].second;
if (Symbol<E> **ref = std::get_if<Symbol<E> *>(&val)) {
Symbol<E> *sym2 = *ref;
if (!sym2->file) {
Error(ctx) << "--defsym: undefined symbol: " << *sym2;
continue;
}
ElfSym<E> &esym = obj.elf_syms[i + 1];
esym.st_type = sym2->esym().st_type;
if constexpr (is_ppc64v2<E>)
esym.ppc_local_entry = sym2->esym().ppc_local_entry;
if (sym2->is_absolute())
sym1->origin = 0;
} else {
sym1->origin = 0;
}
}
}
template <typename E>
void apply_section_align(Context<E> &ctx) {
for (Chunk<E> *chunk : ctx.chunks)
if (OutputSection<E> *osec = chunk->to_osec())
if (auto it = ctx.arg.section_align.find(osec->name);
it != ctx.arg.section_align.end())
osec->shdr.sh_addralign = it->second;
}
template <typename E>
void check_cet_errors(Context<E> &ctx) {
bool warning = (ctx.arg.z_cet_report == CET_REPORT_WARNING);
assert(warning || ctx.arg.z_cet_report == CET_REPORT_ERROR);
auto has_feature = [](ObjectFile<E> *file, u32 feature) {
return std::any_of(file->gnu_properties.begin(), file->gnu_properties.end(),
[&](std::pair<u32, u32> kv) {
return kv.first == GNU_PROPERTY_X86_FEATURE_1_AND &&
(kv.second & feature);
});
};
for (ObjectFile<E> *file : ctx.objs) {
if (file == ctx.internal_obj)
continue;
if (!has_feature(file, GNU_PROPERTY_X86_FEATURE_1_IBT)) {
if (warning)
Warn(ctx) << *file << ": -cet-report=warning: "
<< "missing GNU_PROPERTY_X86_FEATURE_1_IBT";
else
Error(ctx) << *file << ": -cet-report=error: "
<< "missing GNU_PROPERTY_X86_FEATURE_1_IBT";
}
if (!has_feature(file, GNU_PROPERTY_X86_FEATURE_1_SHSTK)) {
if (warning)
Warn(ctx) << *file << ": -cet-report=warning: "
<< "missing GNU_PROPERTY_X86_FEATURE_1_SHSTK";
else
Error(ctx) << *file << ": -cet-report=error: "
<< "missing GNU_PROPERTY_X86_FEATURE_1_SHSTK";
}
}
}
template <typename E>
void print_dependencies(Context<E> &ctx) {
Out(ctx) <<
R"(# This is an output of the mold linker's --print-dependencies option.