-
Notifications
You must be signed in to change notification settings - Fork 17.8k
/
Copy pathlib.go
3022 lines (2748 loc) · 91.8 KB
/
lib.go
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
// Inferno utils/8l/asm.c
// https://bitbucket.org/inferno-os/inferno-os/src/master/utils/8l/asm.c
//
// Copyright © 1994-1999 Lucent Technologies Inc. All rights reserved.
// Portions Copyright © 1995-1997 C H Forsyth ([email protected])
// Portions Copyright © 1997-1999 Vita Nuova Limited
// Portions Copyright © 2000-2007 Vita Nuova Holdings Limited (www.vitanuova.com)
// Portions Copyright © 2004,2006 Bruce Ellis
// Portions Copyright © 2005-2007 C H Forsyth ([email protected])
// Revisions Copyright © 2000-2007 Lucent Technologies Inc. and others
// Portions Copyright © 2009 The Go Authors. All rights reserved.
//
// 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.
package ld
import (
"bytes"
"debug/elf"
"debug/macho"
"encoding/base64"
"encoding/binary"
"fmt"
"internal/buildcfg"
"io"
"log"
"os"
"os/exec"
"path/filepath"
"runtime"
"slices"
"sort"
"strings"
"sync"
"time"
"cmd/internal/bio"
"cmd/internal/goobj"
"cmd/internal/hash"
"cmd/internal/objabi"
"cmd/internal/sys"
"cmd/link/internal/loadelf"
"cmd/link/internal/loader"
"cmd/link/internal/loadmacho"
"cmd/link/internal/loadpe"
"cmd/link/internal/loadxcoff"
"cmd/link/internal/sym"
)
// Data layout and relocation.
// Derived from Inferno utils/6l/l.h
// https://bitbucket.org/inferno-os/inferno-os/src/master/utils/6l/l.h
//
// Copyright © 1994-1999 Lucent Technologies Inc. All rights reserved.
// Portions Copyright © 1995-1997 C H Forsyth ([email protected])
// Portions Copyright © 1997-1999 Vita Nuova Limited
// Portions Copyright © 2000-2007 Vita Nuova Holdings Limited (www.vitanuova.com)
// Portions Copyright © 2004,2006 Bruce Ellis
// Portions Copyright © 2005-2007 C H Forsyth ([email protected])
// Revisions Copyright © 2000-2007 Lucent Technologies Inc. and others
// Portions Copyright © 2009 The Go Authors. All rights reserved.
//
// 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.
// ArchSyms holds a number of architecture specific symbols used during
// relocation. Rather than allowing them universal access to all symbols,
// we keep a subset for relocation application.
type ArchSyms struct {
Rel loader.Sym
Rela loader.Sym
RelPLT loader.Sym
RelaPLT loader.Sym
LinkEditGOT loader.Sym
LinkEditPLT loader.Sym
TOC loader.Sym
DotTOC []loader.Sym // for each version
GOT loader.Sym
PLT loader.Sym
GOTPLT loader.Sym
Tlsg loader.Sym
Tlsoffset int
Dynamic loader.Sym
DynSym loader.Sym
DynStr loader.Sym
unreachableMethod loader.Sym
// Symbol containing a list of all the inittasks that need
// to be run at startup.
mainInittasks loader.Sym
}
// mkArchSym is a helper for setArchSyms, to set up a special symbol.
func (ctxt *Link) mkArchSym(name string, ver int, ls *loader.Sym) {
*ls = ctxt.loader.LookupOrCreateSym(name, ver)
ctxt.loader.SetAttrReachable(*ls, true)
}
// mkArchSymVec is similar to setArchSyms, but operates on elements within
// a slice, where each element corresponds to some symbol version.
func (ctxt *Link) mkArchSymVec(name string, ver int, ls []loader.Sym) {
ls[ver] = ctxt.loader.LookupOrCreateSym(name, ver)
ctxt.loader.SetAttrReachable(ls[ver], true)
}
// setArchSyms sets up the ArchSyms structure, and must be called before
// relocations are applied.
func (ctxt *Link) setArchSyms() {
ctxt.mkArchSym(".got", 0, &ctxt.GOT)
ctxt.mkArchSym(".plt", 0, &ctxt.PLT)
ctxt.mkArchSym(".got.plt", 0, &ctxt.GOTPLT)
ctxt.mkArchSym(".dynamic", 0, &ctxt.Dynamic)
ctxt.mkArchSym(".dynsym", 0, &ctxt.DynSym)
ctxt.mkArchSym(".dynstr", 0, &ctxt.DynStr)
ctxt.mkArchSym("runtime.unreachableMethod", abiInternalVer, &ctxt.unreachableMethod)
if ctxt.IsPPC64() {
ctxt.mkArchSym("TOC", 0, &ctxt.TOC)
ctxt.DotTOC = make([]loader.Sym, ctxt.MaxVersion()+1)
for i := 0; i <= ctxt.MaxVersion(); i++ {
if i >= sym.SymVerABICount && i < sym.SymVerStatic { // these versions are not used currently
continue
}
ctxt.mkArchSymVec(".TOC.", i, ctxt.DotTOC)
}
}
if ctxt.IsElf() {
ctxt.mkArchSym(".rel", 0, &ctxt.Rel)
ctxt.mkArchSym(".rela", 0, &ctxt.Rela)
ctxt.mkArchSym(".rel.plt", 0, &ctxt.RelPLT)
ctxt.mkArchSym(".rela.plt", 0, &ctxt.RelaPLT)
}
if ctxt.IsDarwin() {
ctxt.mkArchSym(".linkedit.got", 0, &ctxt.LinkEditGOT)
ctxt.mkArchSym(".linkedit.plt", 0, &ctxt.LinkEditPLT)
}
}
type Arch struct {
Funcalign int
Maxalign int
Minalign int
Dwarfregsp int
Dwarfreglr int
// Threshold of total text size, used for trampoline insertion. If the total
// text size is smaller than TrampLimit, we won't need to insert trampolines.
// It is pretty close to the offset range of a direct CALL machine instruction.
// We leave some room for extra stuff like PLT stubs.
TrampLimit uint64
// Empty spaces between codeblocks will be padded with this value.
// For example an architecture might want to pad with a trap instruction to
// catch wayward programs. Architectures that do not define a padding value
// are padded with zeros.
CodePad []byte
// Plan 9 variables.
Plan9Magic uint32
Plan9_64Bit bool
Adddynrel func(*Target, *loader.Loader, *ArchSyms, loader.Sym, loader.Reloc, int) bool
Archinit func(*Link)
// Archreloc is an arch-specific hook that assists in relocation processing
// (invoked by 'relocsym'); it handles target-specific relocation tasks.
// Here "rel" is the current relocation being examined, "sym" is the symbol
// containing the chunk of data to which the relocation applies, and "off"
// is the contents of the to-be-relocated data item (from sym.P). Return
// value is the appropriately relocated value (to be written back to the
// same spot in sym.P), number of external _host_ relocations needed (i.e.
// ELF/Mach-O/etc. relocations, not Go relocations, this must match ELF.Reloc1,
// etc.), and a boolean indicating success/failure (a failing value indicates
// a fatal error).
Archreloc func(*Target, *loader.Loader, *ArchSyms, loader.Reloc, loader.Sym,
int64) (relocatedOffset int64, nExtReloc int, ok bool)
// Archrelocvariant is a second arch-specific hook used for
// relocation processing; it handles relocations where r.Type is
// insufficient to describe the relocation (r.Variant !=
// sym.RV_NONE). Here "rel" is the relocation being applied, "sym"
// is the symbol containing the chunk of data to which the
// relocation applies, and "off" is the contents of the
// to-be-relocated data item (from sym.P). Return is an updated
// offset value.
Archrelocvariant func(target *Target, ldr *loader.Loader, rel loader.Reloc,
rv sym.RelocVariant, sym loader.Sym, offset int64, data []byte) (relocatedOffset int64)
// Generate a trampoline for a call from s to rs if necessary. ri is
// index of the relocation.
Trampoline func(ctxt *Link, ldr *loader.Loader, ri int, rs, s loader.Sym)
// Assembling the binary breaks into two phases, writing the code/data/
// dwarf information (which is rather generic), and some more architecture
// specific work like setting up the elf headers/dynamic relocations, etc.
// The phases are called "Asmb" and "Asmb2". Asmb2 needs to be defined for
// every architecture, but only if architecture has an Asmb function will
// it be used for assembly. Otherwise a generic assembly Asmb function is
// used.
Asmb func(*Link, *loader.Loader)
Asmb2 func(*Link, *loader.Loader)
// Extreloc is an arch-specific hook that converts a Go relocation to an
// external relocation. Return the external relocation and whether it is
// needed.
Extreloc func(*Target, *loader.Loader, loader.Reloc, loader.Sym) (loader.ExtReloc, bool)
Gentext func(*Link, *loader.Loader) // Generate text before addressing has been performed.
Machoreloc1 func(*sys.Arch, *OutBuf, *loader.Loader, loader.Sym, loader.ExtReloc, int64) bool
MachorelocSize uint32 // size of an Mach-O relocation record, must match Machoreloc1.
PEreloc1 func(*sys.Arch, *OutBuf, *loader.Loader, loader.Sym, loader.ExtReloc, int64) bool
Xcoffreloc1 func(*sys.Arch, *OutBuf, *loader.Loader, loader.Sym, loader.ExtReloc, int64) bool
// Generate additional symbols for the native symbol table just prior to
// code generation.
GenSymsLate func(*Link, *loader.Loader)
// TLSIEtoLE converts a TLS Initial Executable relocation to
// a TLS Local Executable relocation.
//
// This is possible when a TLS IE relocation refers to a local
// symbol in an executable, which is typical when internally
// linking PIE binaries.
TLSIEtoLE func(P []byte, off, size int)
// optional override for assignAddress
AssignAddress func(ldr *loader.Loader, sect *sym.Section, n int, s loader.Sym, va uint64, isTramp bool) (*sym.Section, int, uint64)
// ELF specific information.
ELF ELFArch
}
var (
thearch Arch
lcSize int32
rpath Rpath
spSize int32
symSize int32
)
// Symbol version of ABIInternal symbols. It is sym.SymVerABIInternal if ABI wrappers
// are used, 0 otherwise.
var abiInternalVer = sym.SymVerABIInternal
// DynlinkingGo reports whether we are producing Go code that can live
// in separate shared libraries linked together at runtime.
func (ctxt *Link) DynlinkingGo() bool {
if !ctxt.Loaded {
panic("DynlinkingGo called before all symbols loaded")
}
return ctxt.BuildMode == BuildModeShared || ctxt.linkShared || ctxt.BuildMode == BuildModePlugin || ctxt.canUsePlugins
}
// CanUsePlugins reports whether a plugins can be used
func (ctxt *Link) CanUsePlugins() bool {
if !ctxt.Loaded {
panic("CanUsePlugins called before all symbols loaded")
}
return ctxt.canUsePlugins
}
// NeedCodeSign reports whether we need to code-sign the output binary.
func (ctxt *Link) NeedCodeSign() bool {
return ctxt.IsDarwin() && ctxt.IsARM64()
}
var (
dynlib []string
ldflag []string
havedynamic int
Funcalign int
iscgo bool
elfglobalsymndx int
interpreter string
debug_s bool // backup old value of debug['s']
HEADR int32
nerrors int
liveness int64 // size of liveness data (funcdata), printed if -v
// See -strictdups command line flag.
checkStrictDups int // 0=off 1=warning 2=error
strictDupMsgCount int
)
var (
Segtext sym.Segment
Segrodata sym.Segment
Segrelrodata sym.Segment
Segdata sym.Segment
Segdwarf sym.Segment
Segpdata sym.Segment // windows-only
Segxdata sym.Segment // windows-only
Segments = []*sym.Segment{&Segtext, &Segrodata, &Segrelrodata, &Segdata, &Segdwarf, &Segpdata, &Segxdata}
)
const pkgdef = "__.PKGDEF"
var (
// externalobj is set to true if we see an object compiled by
// the host compiler that is not from a package that is known
// to support internal linking mode.
externalobj = false
// dynimportfail is a list of packages for which generating
// the dynimport file, _cgo_import.go, failed. If there are
// any of these objects, we must link externally. Issue 52863.
dynimportfail []string
// preferlinkext is a list of packages for which the Go command
// noticed use of peculiar C flags. If we see any of these,
// default to linking externally unless overridden by the
// user. See issues #58619, #58620, and #58848.
preferlinkext []string
// unknownObjFormat is set to true if we see an object whose
// format we don't recognize.
unknownObjFormat = false
theline string
)
func Lflag(ctxt *Link, arg string) {
ctxt.Libdir = append(ctxt.Libdir, arg)
}
/*
* Unix doesn't like it when we write to a running (or, sometimes,
* recently run) binary, so remove the output file before writing it.
* On Windows 7, remove() can force a subsequent create() to fail.
* S_ISREG() does not exist on Plan 9.
*/
func mayberemoveoutfile() {
if fi, err := os.Lstat(*flagOutfile); err == nil && !fi.Mode().IsRegular() {
return
}
os.Remove(*flagOutfile)
}
func libinit(ctxt *Link) {
Funcalign = thearch.Funcalign
// add goroot to the end of the libdir list.
suffix := ""
suffixsep := ""
if *flagInstallSuffix != "" {
suffixsep = "_"
suffix = *flagInstallSuffix
} else if *flagRace {
suffixsep = "_"
suffix = "race"
} else if *flagMsan {
suffixsep = "_"
suffix = "msan"
} else if *flagAsan {
suffixsep = "_"
suffix = "asan"
}
if buildcfg.GOROOT != "" {
Lflag(ctxt, filepath.Join(buildcfg.GOROOT, "pkg", fmt.Sprintf("%s_%s%s%s", buildcfg.GOOS, buildcfg.GOARCH, suffixsep, suffix)))
}
mayberemoveoutfile()
if err := ctxt.Out.Open(*flagOutfile); err != nil {
Exitf("cannot create %s: %v", *flagOutfile, err)
}
if *flagEntrySymbol == "" {
switch ctxt.BuildMode {
case BuildModeCShared, BuildModeCArchive:
*flagEntrySymbol = fmt.Sprintf("_rt0_%s_%s_lib", buildcfg.GOARCH, buildcfg.GOOS)
case BuildModeExe, BuildModePIE:
*flagEntrySymbol = fmt.Sprintf("_rt0_%s_%s", buildcfg.GOARCH, buildcfg.GOOS)
case BuildModeShared, BuildModePlugin:
// No *flagEntrySymbol for -buildmode=shared and plugin
default:
Errorf("unknown *flagEntrySymbol for buildmode %v", ctxt.BuildMode)
}
}
}
func exitIfErrors() {
if nerrors != 0 || checkStrictDups > 1 && strictDupMsgCount > 0 {
mayberemoveoutfile()
Exit(2)
}
}
func errorexit() {
exitIfErrors()
Exit(0)
}
func loadinternal(ctxt *Link, name string) *sym.Library {
zerofp := goobj.FingerprintType{}
if ctxt.linkShared && ctxt.PackageShlib != nil {
if shlib := ctxt.PackageShlib[name]; shlib != "" {
return addlibpath(ctxt, "internal", "internal", "", name, shlib, zerofp)
}
}
if ctxt.PackageFile != nil {
if pname := ctxt.PackageFile[name]; pname != "" {
return addlibpath(ctxt, "internal", "internal", pname, name, "", zerofp)
}
ctxt.Logf("loadinternal: cannot find %s\n", name)
return nil
}
for _, libdir := range ctxt.Libdir {
if ctxt.linkShared {
shlibname := filepath.Join(libdir, name+".shlibname")
if ctxt.Debugvlog != 0 {
ctxt.Logf("searching for %s.a in %s\n", name, shlibname)
}
if _, err := os.Stat(shlibname); err == nil {
return addlibpath(ctxt, "internal", "internal", "", name, shlibname, zerofp)
}
}
pname := filepath.Join(libdir, name+".a")
if ctxt.Debugvlog != 0 {
ctxt.Logf("searching for %s.a in %s\n", name, pname)
}
if _, err := os.Stat(pname); err == nil {
return addlibpath(ctxt, "internal", "internal", pname, name, "", zerofp)
}
}
if name == "runtime" {
Exitf("error: unable to find runtime.a")
}
ctxt.Logf("warning: unable to find %s.a\n", name)
return nil
}
// extld returns the current external linker.
func (ctxt *Link) extld() []string {
if len(flagExtld) == 0 {
// Return the default external linker for the platform.
// This only matters when link tool is called directly without explicit -extld,
// go tool already passes the correct linker in other cases.
switch buildcfg.GOOS {
case "darwin", "freebsd", "openbsd":
flagExtld = []string{"clang"}
default:
flagExtld = []string{"gcc"}
}
}
return flagExtld
}
// findLibPathCmd uses cmd command to find gcc library libname.
// It returns library full path if found, or "none" if not found.
func (ctxt *Link) findLibPathCmd(cmd, libname string) string {
extld := ctxt.extld()
name, args := extld[0], extld[1:]
args = append(args, hostlinkArchArgs(ctxt.Arch)...)
args = append(args, cmd)
if ctxt.Debugvlog != 0 {
ctxt.Logf("%s %v\n", extld, args)
}
out, err := exec.Command(name, args...).Output()
if err != nil {
if ctxt.Debugvlog != 0 {
ctxt.Logf("not using a %s file because compiler failed\n%v\n%s\n", libname, err, out)
}
return "none"
}
return strings.TrimSpace(string(out))
}
// findLibPath searches for library libname.
// It returns library full path if found, or "none" if not found.
func (ctxt *Link) findLibPath(libname string) string {
return ctxt.findLibPathCmd("--print-file-name="+libname, libname)
}
func (ctxt *Link) loadlib() {
var flags uint32
if *flagCheckLinkname {
flags |= loader.FlagCheckLinkname
}
switch *FlagStrictDups {
case 0:
// nothing to do
case 1, 2:
flags |= loader.FlagStrictDups
default:
log.Fatalf("invalid -strictdups flag value %d", *FlagStrictDups)
}
ctxt.loader = loader.NewLoader(flags, &ctxt.ErrorReporter.ErrorReporter)
ctxt.ErrorReporter.SymName = func(s loader.Sym) string {
return ctxt.loader.SymName(s)
}
// ctxt.Library grows during the loop, so not a range loop.
i := 0
for ; i < len(ctxt.Library); i++ {
lib := ctxt.Library[i]
if lib.Shlib == "" {
if ctxt.Debugvlog > 1 {
ctxt.Logf("autolib: %s (from %s)\n", lib.File, lib.Objref)
}
loadobjfile(ctxt, lib)
}
}
// load internal packages, if not already
if *flagRace {
loadinternal(ctxt, "runtime/race")
}
if *flagMsan {
loadinternal(ctxt, "runtime/msan")
}
if *flagAsan {
loadinternal(ctxt, "runtime/asan")
}
loadinternal(ctxt, "runtime")
for ; i < len(ctxt.Library); i++ {
lib := ctxt.Library[i]
if lib.Shlib == "" {
loadobjfile(ctxt, lib)
}
}
// At this point, the Go objects are "preloaded". Not all the symbols are
// added to the symbol table (only defined package symbols are). Looking
// up symbol by name may not get expected result.
iscgo = ctxt.LibraryByPkg["runtime/cgo"] != nil
// Plugins a require cgo support to function. Similarly, plugins may require additional
// internal linker support on some platforms which may not be implemented.
ctxt.canUsePlugins = ctxt.LibraryByPkg["plugin"] != nil && iscgo
// We now have enough information to determine the link mode.
determineLinkMode(ctxt)
if ctxt.LinkMode == LinkExternal && !iscgo && !(buildcfg.GOOS == "darwin" && ctxt.BuildMode != BuildModePlugin && ctxt.Arch.Family == sys.AMD64) {
// This indicates a user requested -linkmode=external.
// The startup code uses an import of runtime/cgo to decide
// whether to initialize the TLS. So give it one. This could
// be handled differently but it's an unusual case.
if lib := loadinternal(ctxt, "runtime/cgo"); lib != nil && lib.Shlib == "" {
if ctxt.BuildMode == BuildModeShared || ctxt.linkShared {
Exitf("cannot implicitly include runtime/cgo in a shared library")
}
for ; i < len(ctxt.Library); i++ {
lib := ctxt.Library[i]
if lib.Shlib == "" {
loadobjfile(ctxt, lib)
}
}
}
}
// Add non-package symbols and references of externally defined symbols.
ctxt.loader.LoadSyms(ctxt.Arch)
// Load symbols from shared libraries, after all Go object symbols are loaded.
for _, lib := range ctxt.Library {
if lib.Shlib != "" {
if ctxt.Debugvlog > 1 {
ctxt.Logf("autolib: %s (from %s)\n", lib.Shlib, lib.Objref)
}
ldshlibsyms(ctxt, lib.Shlib)
}
}
// Process cgo directives (has to be done before host object loading).
ctxt.loadcgodirectives()
// Conditionally load host objects, or setup for external linking.
hostobjs(ctxt)
hostlinksetup(ctxt)
if ctxt.LinkMode == LinkInternal && len(hostobj) != 0 {
// If we have any undefined symbols in external
// objects, try to read them from the libgcc file.
any := false
undefs, froms := ctxt.loader.UndefinedRelocTargets(1)
if len(undefs) > 0 {
any = true
if ctxt.Debugvlog > 1 {
ctxt.Logf("loadlib: first unresolved is %s [%d] from %s [%d]\n",
ctxt.loader.SymName(undefs[0]), undefs[0],
ctxt.loader.SymName(froms[0]), froms[0])
}
}
if any {
if *flagLibGCC == "" {
*flagLibGCC = ctxt.findLibPathCmd("--print-libgcc-file-name", "libgcc")
}
if runtime.GOOS == "freebsd" && strings.HasPrefix(filepath.Base(*flagLibGCC), "libclang_rt.builtins") {
// On newer versions of FreeBSD, libgcc is returned as something like
// /usr/lib/clang/18/lib/freebsd/libclang_rt.builtins-x86_64.a.
// Unfortunately this ends up missing a bunch of symbols we need from
// libcompiler_rt.
*flagLibGCC = ctxt.findLibPathCmd("--print-file-name=libcompiler_rt.a", "libcompiler_rt")
}
if runtime.GOOS == "openbsd" && *flagLibGCC == "libgcc.a" {
// On OpenBSD `clang --print-libgcc-file-name` returns "libgcc.a".
// In this case we fail to load libgcc.a and can encounter link
// errors - see if we can find libcompiler_rt.a instead.
*flagLibGCC = ctxt.findLibPathCmd("--print-file-name=libcompiler_rt.a", "libcompiler_rt")
}
if ctxt.HeadType == objabi.Hwindows {
loadWindowsHostArchives(ctxt)
}
if *flagLibGCC != "none" {
hostArchive(ctxt, *flagLibGCC)
}
// For glibc systems, the linker setup used by GCC
// looks like
//
// GROUP ( /lib/x86_64-linux-gnu/libc.so.6
// /usr/lib/x86_64-linux-gnu/libc_nonshared.a
// AS_NEEDED ( /lib64/ld-linux-x86-64.so.2 ) )
//
// where libc_nonshared.a contains a small set of
// symbols including "__stack_chk_fail_local" and a
// few others. Thus if we are doing internal linking
// and "__stack_chk_fail_local" is unresolved (most
// likely due to the use of -fstack-protector), try
// loading libc_nonshared.a to resolve it.
//
// On Alpine Linux (musl-based), the library providing
// this symbol is called libssp_nonshared.a.
isunresolved := symbolsAreUnresolved(ctxt, []string{"__stack_chk_fail_local"})
if isunresolved[0] {
if p := ctxt.findLibPath("libc_nonshared.a"); p != "none" {
hostArchive(ctxt, p)
}
if p := ctxt.findLibPath("libssp_nonshared.a"); p != "none" {
hostArchive(ctxt, p)
}
}
}
}
loadfips(ctxt)
// We've loaded all the code now.
ctxt.Loaded = true
strictDupMsgCount = ctxt.loader.NStrictDupMsgs()
}
// loadWindowsHostArchives loads in host archives and objects when
// doing internal linking on windows. Older toolchains seem to require
// just a single pass through the various archives, but some modern
// toolchains when linking a C program with mingw pass library paths
// multiple times to the linker, e.g. "... -lmingwex -lmingw32 ...
// -lmingwex -lmingw32 ...". To accommodate this behavior, we make two
// passes over the host archives below.
func loadWindowsHostArchives(ctxt *Link) {
any := true
for i := 0; any && i < 2; i++ {
// Link crt2.o (if present) to resolve "atexit" when
// using LLVM-based compilers.
isunresolved := symbolsAreUnresolved(ctxt, []string{"atexit"})
if isunresolved[0] {
if p := ctxt.findLibPath("crt2.o"); p != "none" {
hostObject(ctxt, "crt2", p)
}
}
if *flagRace {
if p := ctxt.findLibPath("libsynchronization.a"); p != "none" {
hostArchive(ctxt, p)
}
}
if p := ctxt.findLibPath("libmingwex.a"); p != "none" {
hostArchive(ctxt, p)
}
if p := ctxt.findLibPath("libmingw32.a"); p != "none" {
hostArchive(ctxt, p)
}
// Link libmsvcrt.a to resolve '__acrt_iob_func' symbol
// (see https://golang.org/issue/23649 for details).
if p := ctxt.findLibPath("libmsvcrt.a"); p != "none" {
hostArchive(ctxt, p)
}
any = false
undefs, froms := ctxt.loader.UndefinedRelocTargets(1)
if len(undefs) > 0 {
any = true
if ctxt.Debugvlog > 1 {
ctxt.Logf("loadWindowsHostArchives: remaining unresolved is %s [%d] from %s [%d]\n",
ctxt.loader.SymName(undefs[0]), undefs[0],
ctxt.loader.SymName(froms[0]), froms[0])
}
}
}
// If needed, create the __CTOR_LIST__ and __DTOR_LIST__
// symbols (referenced by some of the mingw support library
// routines). Creation of these symbols is normally done by the
// linker if not already present.
want := []string{"__CTOR_LIST__", "__DTOR_LIST__"}
isunresolved := symbolsAreUnresolved(ctxt, want)
for k, w := range want {
if isunresolved[k] {
sb := ctxt.loader.CreateSymForUpdate(w, 0)
sb.SetType(sym.SDATA)
sb.AddUint64(ctxt.Arch, 0)
sb.SetReachable(true)
ctxt.loader.SetAttrSpecial(sb.Sym(), true)
}
}
// Fix up references to DLL import symbols now that we're done
// pulling in new objects.
if err := loadpe.PostProcessImports(); err != nil {
Errorf("%v", err)
}
// TODO: maybe do something similar to peimporteddlls to collect
// all lib names and try link them all to final exe just like
// libmingwex.a and libmingw32.a:
/*
for:
#cgo windows LDFLAGS: -lmsvcrt -lm
import:
libmsvcrt.a libm.a
*/
}
// loadcgodirectives reads the previously discovered cgo directives, creating
// symbols in preparation for host object loading or use later in the link.
func (ctxt *Link) loadcgodirectives() {
l := ctxt.loader
hostObjSyms := make(map[loader.Sym]struct{})
for _, d := range ctxt.cgodata {
setCgoAttr(ctxt, d.file, d.pkg, d.directives, hostObjSyms)
}
ctxt.cgodata = nil
if ctxt.LinkMode == LinkInternal {
// Drop all the cgo_import_static declarations.
// Turns out we won't be needing them.
for symIdx := range hostObjSyms {
if l.SymType(symIdx) == sym.SHOSTOBJ {
// If a symbol was marked both
// cgo_import_static and cgo_import_dynamic,
// then we want to make it cgo_import_dynamic
// now.
su := l.MakeSymbolUpdater(symIdx)
if l.SymExtname(symIdx) != "" && l.SymDynimplib(symIdx) != "" && !(l.AttrCgoExportStatic(symIdx) || l.AttrCgoExportDynamic(symIdx)) {
su.SetType(sym.SDYNIMPORT)
} else {
su.SetType(0)
}
}
}
}
}
// Set up flags and special symbols depending on the platform build mode.
// This version works with loader.Loader.
func (ctxt *Link) linksetup() {
switch ctxt.BuildMode {
case BuildModeCShared, BuildModePlugin:
symIdx := ctxt.loader.LookupOrCreateSym("runtime.islibrary", 0)
sb := ctxt.loader.MakeSymbolUpdater(symIdx)
sb.SetType(sym.SNOPTRDATA)
sb.AddUint8(1)
case BuildModeCArchive:
symIdx := ctxt.loader.LookupOrCreateSym("runtime.isarchive", 0)
sb := ctxt.loader.MakeSymbolUpdater(symIdx)
sb.SetType(sym.SNOPTRDATA)
sb.AddUint8(1)
}
// Recalculate pe parameters now that we have ctxt.LinkMode set.
if ctxt.HeadType == objabi.Hwindows {
Peinit(ctxt)
}
if ctxt.LinkMode == LinkExternal {
// When external linking, we are creating an object file. The
// absolute address is irrelevant.
*FlagTextAddr = 0
}
// If there are no dynamic libraries needed, gcc disables dynamic linking.
// Because of this, glibc's dynamic ELF loader occasionally (like in version 2.13)
// assumes that a dynamic binary always refers to at least one dynamic library.
// Rather than be a source of test cases for glibc, disable dynamic linking
// the same way that gcc would.
//
// Exception: on OS X, programs such as Shark only work with dynamic
// binaries, so leave it enabled on OS X (Mach-O) binaries.
// Also leave it enabled on Solaris which doesn't support
// statically linked binaries.
if ctxt.BuildMode == BuildModeExe {
if havedynamic == 0 && ctxt.HeadType != objabi.Hdarwin && ctxt.HeadType != objabi.Hsolaris {
*FlagD = true
}
}
if ctxt.LinkMode == LinkExternal && ctxt.Arch.Family == sys.PPC64 && buildcfg.GOOS != "aix" {
toc := ctxt.loader.LookupOrCreateSym(".TOC.", 0)
sb := ctxt.loader.MakeSymbolUpdater(toc)
sb.SetType(sym.SDYNIMPORT)
}
// The Android Q linker started to complain about underalignment of the our TLS
// section. We don't actually use the section on android, so don't
// generate it.
if buildcfg.GOOS != "android" {
tlsg := ctxt.loader.LookupOrCreateSym("runtime.tlsg", 0)
sb := ctxt.loader.MakeSymbolUpdater(tlsg)
// runtime.tlsg is used for external linking on platforms that do not define
// a variable to hold g in assembly (currently only intel).
if sb.Type() == 0 {
sb.SetType(sym.STLSBSS)
sb.SetSize(int64(ctxt.Arch.PtrSize))
} else if sb.Type() != sym.SDYNIMPORT {
Errorf("runtime declared tlsg variable %v", sb.Type())
}
ctxt.loader.SetAttrReachable(tlsg, true)
ctxt.Tlsg = tlsg
}
var moduledata loader.Sym
var mdsb *loader.SymbolBuilder
if ctxt.BuildMode == BuildModePlugin {
moduledata = ctxt.loader.LookupOrCreateSym("local.pluginmoduledata", 0)
mdsb = ctxt.loader.MakeSymbolUpdater(moduledata)
ctxt.loader.SetAttrLocal(moduledata, true)
} else {
moduledata = ctxt.loader.LookupOrCreateSym("runtime.firstmoduledata", 0)
mdsb = ctxt.loader.MakeSymbolUpdater(moduledata)
}
if mdsb.Type() != 0 && mdsb.Type() != sym.SDYNIMPORT {
// If the module (toolchain-speak for "executable or shared
// library") we are linking contains the runtime package, it
// will define the runtime.firstmoduledata symbol and we
// truncate it back to 0 bytes so we can define its entire
// contents in symtab.go:symtab().
mdsb.SetSize(0)
// In addition, on ARM, the runtime depends on the linker
// recording the value of GOARM.
if ctxt.Arch.Family == sys.ARM {
goarm := ctxt.loader.LookupOrCreateSym("runtime.goarm", 0)
sb := ctxt.loader.MakeSymbolUpdater(goarm)
sb.SetType(sym.SNOPTRDATA)
sb.SetSize(0)
sb.AddUint8(uint8(buildcfg.GOARM.Version))
goarmsoftfp := ctxt.loader.LookupOrCreateSym("runtime.goarmsoftfp", 0)
sb2 := ctxt.loader.MakeSymbolUpdater(goarmsoftfp)
sb2.SetType(sym.SNOPTRDATA)
sb2.SetSize(0)
if buildcfg.GOARM.SoftFloat {
sb2.AddUint8(1)
} else {
sb2.AddUint8(0)
}
}
// Set runtime.disableMemoryProfiling bool if
// runtime.memProfileInternal is not retained in the binary after
// deadcode (and we're not dynamically linking).
memProfile := ctxt.loader.Lookup("runtime.memProfileInternal", abiInternalVer)
if memProfile != 0 && !ctxt.loader.AttrReachable(memProfile) && !ctxt.DynlinkingGo() {
memProfSym := ctxt.loader.LookupOrCreateSym("runtime.disableMemoryProfiling", 0)
sb := ctxt.loader.MakeSymbolUpdater(memProfSym)
sb.SetType(sym.SNOPTRDATA)
sb.SetSize(0)
sb.AddUint8(1) // true bool
}
} else {
// If OTOH the module does not contain the runtime package,
// create a local symbol for the moduledata.
moduledata = ctxt.loader.LookupOrCreateSym("local.moduledata", 0)
mdsb = ctxt.loader.MakeSymbolUpdater(moduledata)
ctxt.loader.SetAttrLocal(moduledata, true)
}
// In all cases way we mark the moduledata as noptrdata to hide it from
// the GC.
mdsb.SetType(sym.SNOPTRDATA)
ctxt.loader.SetAttrReachable(moduledata, true)
ctxt.Moduledata = moduledata
if ctxt.Arch == sys.Arch386 && ctxt.HeadType != objabi.Hwindows {
if (ctxt.BuildMode == BuildModeCArchive && ctxt.IsELF) || ctxt.BuildMode == BuildModeCShared || ctxt.BuildMode == BuildModePIE || ctxt.DynlinkingGo() {
got := ctxt.loader.LookupOrCreateSym("_GLOBAL_OFFSET_TABLE_", 0)
sb := ctxt.loader.MakeSymbolUpdater(got)
sb.SetType(sym.SDYNIMPORT)
ctxt.loader.SetAttrReachable(got, true)
}
}
// DWARF-gen and other phases require that the unit Textp slices
// be populated, so that it can walk the functions in each unit.
// Call into the loader to do this (requires that we collect the
// set of internal libraries first). NB: might be simpler if we
// moved isRuntimeDepPkg to cmd/internal and then did the test in
// loader.AssignTextSymbolOrder.
ctxt.Library = postorder(ctxt.Library)
intlibs := []bool{}
for _, lib := range ctxt.Library {
intlibs = append(intlibs, isRuntimeDepPkg(lib.Pkg))
}
ctxt.Textp = ctxt.loader.AssignTextSymbolOrder(ctxt.Library, intlibs, ctxt.Textp)
}
// mangleTypeSym shortens the names of symbols that represent Go types
// if they are visible in the symbol table.
//
// As the names of these symbols are derived from the string of
// the type, they can run to many kilobytes long. So we shorten
// them using a SHA-1 when the name appears in the final binary.
// This also removes characters that upset external linkers.
//
// These are the symbols that begin with the prefix 'type.' and
// contain run-time type information used by the runtime and reflect
// packages. All Go binaries contain these symbols, but only
// those programs loaded dynamically in multiple parts need these
// symbols to have entries in the symbol table.
func (ctxt *Link) mangleTypeSym() {
if ctxt.BuildMode != BuildModeShared && !ctxt.linkShared && ctxt.BuildMode != BuildModePlugin && !ctxt.CanUsePlugins() {
return
}
ldr := ctxt.loader
for s := loader.Sym(1); s < loader.Sym(ldr.NSym()); s++ {
if !ldr.AttrReachable(s) && !ctxt.linkShared {
// If -linkshared, the gc mask generation code may need to reach
// out to the shared library for the type descriptor's data, even
// the type descriptor itself is not actually needed at run time
// (therefore not reachable). We still need to mangle its name,
// so it is consistent with the one stored in the shared library.
continue
}
name := ldr.SymName(s)
newName := typeSymbolMangle(name)
if newName != name {
ldr.SetSymExtname(s, newName)
// When linking against a shared library, the Go object file may
// have reference to the original symbol name whereas the shared
// library provides a symbol with the mangled name. We need to
// copy the payload of mangled to original.
// XXX maybe there is a better way to do this.
dup := ldr.Lookup(newName, ldr.SymVersion(s))
if dup != 0 {
st := ldr.SymType(s)
dt := ldr.SymType(dup)
if st == sym.Sxxx && dt != sym.Sxxx {
ldr.CopySym(dup, s)
}
}
}
}
}