forked from golang/go
/
lib.go
2289 lines (2050 loc) · 62 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/default/utils/8l/asm.c
//
// Copyright © 1994-1999 Lucent Technologies Inc. All rights reserved.
// Portions Copyright © 1995-1997 C H Forsyth (forsyth@terzarima.net)
// 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 (forsyth@terzarima.net)
// 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 (
"bufio"
"bytes"
"cmd/internal/bio"
"cmd/internal/objabi"
"cmd/internal/sys"
"cmd/link/internal/loadelf"
"cmd/link/internal/loadmacho"
"cmd/link/internal/loadpe"
"cmd/link/internal/objfile"
"cmd/link/internal/sym"
"crypto/sha1"
"debug/elf"
"encoding/base64"
"encoding/binary"
"encoding/hex"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"sync"
)
// Data layout and relocation.
// Derived from Inferno utils/6l/l.h
// https://bitbucket.org/inferno-os/inferno-os/src/default/utils/6l/l.h
//
// Copyright © 1994-1999 Lucent Technologies Inc. All rights reserved.
// Portions Copyright © 1995-1997 C H Forsyth (forsyth@terzarima.net)
// 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 (forsyth@terzarima.net)
// 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.
type Arch struct {
Funcalign int
Maxalign int
Minalign int
Dwarfregsp int
Dwarfreglr int
Linuxdynld string
Freebsddynld string
Netbsddynld string
Openbsddynld string
Dragonflydynld string
Solarisdynld string
Adddynrel func(*Link, *sym.Symbol, *sym.Reloc) bool
Archinit func(*Link)
Archreloc func(*Link, *sym.Reloc, *sym.Symbol, *int64) bool
Archrelocvariant func(*Link, *sym.Reloc, *sym.Symbol, int64) int64
Trampoline func(*Link, *sym.Reloc, *sym.Symbol)
Asmb func(*Link)
Elfreloc1 func(*Link, *sym.Reloc, int64) bool
Elfsetupplt func(*Link)
Gentext func(*Link)
Machoreloc1 func(*sys.Arch, *OutBuf, *sym.Symbol, *sym.Reloc, int64) bool
PEreloc1 func(*sys.Arch, *OutBuf, *sym.Symbol, *sym.Reloc, int64) bool
// 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(s *sym.Symbol, off, size int)
}
var (
thearch Arch
Lcsize int32
rpath Rpath
Spsize int32
Symsize int32
)
const (
MINFUNC = 16 // minimum size for a function
)
// DynlinkingGo returns 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 returns whether a plugins can be used
func (ctxt *Link) CanUsePlugins() bool {
return ctxt.Syms.ROLookup("plugin.Open", 0) != nil
}
// UseRelro returns whether to make use of "read only relocations" aka
// relro.
func (ctxt *Link) UseRelro() bool {
switch ctxt.BuildMode {
case BuildModeCArchive, BuildModeCShared, BuildModeShared, BuildModePIE, BuildModePlugin:
return ctxt.IsELF
default:
return ctxt.linkShared
}
}
var (
dynexp []*sym.Symbol
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
)
var (
Segtext sym.Segment
Segrodata sym.Segment
Segrelrodata sym.Segment
Segdata sym.Segment
Segdwarf sym.Segment
)
const pkgdef = "__.PKGDEF"
var (
// Set 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
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"
}
Lflag(ctxt, filepath.Join(objabi.GOROOT, "pkg", fmt.Sprintf("%s_%s%s%s", objabi.GOOS, objabi.GOARCH, suffixsep, suffix)))
mayberemoveoutfile()
f, err := os.OpenFile(*flagOutfile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0775)
if err != nil {
Exitf("cannot create %s: %v", *flagOutfile, err)
}
ctxt.Out.w = bufio.NewWriter(f)
ctxt.Out.f = f
if *flagEntrySymbol == "" {
switch ctxt.BuildMode {
case BuildModeCShared, BuildModeCArchive:
*flagEntrySymbol = fmt.Sprintf("_rt0_%s_%s_lib", objabi.GOARCH, objabi.GOOS)
case BuildModeExe, BuildModePIE:
*flagEntrySymbol = fmt.Sprintf("_rt0_%s_%s", objabi.GOARCH, objabi.GOOS)
case BuildModeShared, BuildModePlugin:
// No *flagEntrySymbol for -buildmode=shared and plugin
default:
Errorf(nil, "unknown *flagEntrySymbol for buildmode %v", ctxt.BuildMode)
}
}
}
func errorexit() {
if nerrors != 0 {
Exit(2)
}
Exit(0)
}
func loadinternal(ctxt *Link, name string) *sym.Library {
if ctxt.linkShared && ctxt.PackageShlib != nil {
if shlib := ctxt.PackageShlib[name]; shlib != "" {
return addlibpath(ctxt, "internal", "internal", "", name, shlib)
}
}
if ctxt.PackageFile != nil {
if pname := ctxt.PackageFile[name]; pname != "" {
return addlibpath(ctxt, "internal", "internal", pname, name, "")
}
ctxt.Logf("loadinternal: cannot find %s\n", name)
return nil
}
for i := 0; i < len(ctxt.Libdir); i++ {
if ctxt.linkShared {
shlibname := filepath.Join(ctxt.Libdir[i], 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)
}
}
pname := filepath.Join(ctxt.Libdir[i], 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, "")
}
}
ctxt.Logf("warning: unable to find %s.a\n", name)
return nil
}
// 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 {
if *flagExtld == "" {
*flagExtld = "gcc"
}
args := hostlinkArchArgs(ctxt.Arch)
args = append(args, cmd)
if ctxt.Debugvlog != 0 {
ctxt.Logf("%s %v\n", *flagExtld, args)
}
out, err := exec.Command(*flagExtld, 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() {
switch ctxt.BuildMode {
case BuildModeCShared, BuildModePlugin:
s := ctxt.Syms.Lookup("runtime.islibrary", 0)
s.Attr |= sym.AttrDuplicateOK
s.AddUint8(1)
case BuildModeCArchive:
s := ctxt.Syms.Lookup("runtime.isarchive", 0)
s.Attr |= sym.AttrDuplicateOK
s.AddUint8(1)
}
loadinternal(ctxt, "runtime")
if ctxt.Arch.Family == sys.ARM {
loadinternal(ctxt, "math")
}
if *flagRace {
loadinternal(ctxt, "runtime/race")
}
if *flagMsan {
loadinternal(ctxt, "runtime/msan")
}
// ctxt.Library grows during the loop, so not a range loop.
for i := 0; i < len(ctxt.Library); i++ {
lib := ctxt.Library[i]
if lib.Shlib == "" {
if ctxt.Debugvlog > 1 {
ctxt.Logf("%5.2f autolib: %s (from %s)\n", Cputime(), lib.File, lib.Objref)
}
loadobjfile(ctxt, lib)
}
}
for _, lib := range ctxt.Library {
if lib.Shlib != "" {
if ctxt.Debugvlog > 1 {
ctxt.Logf("%5.2f autolib: %s (from %s)\n", Cputime(), lib.Shlib, lib.Objref)
}
ldshlibsyms(ctxt, lib.Shlib)
}
}
iscgo = ctxt.Syms.ROLookup("x_cgo_init", 0) != nil
// We now have enough information to determine the link mode.
determineLinkMode(ctxt)
// Recalculate pe parameters now that we have ctxt.LinkMode set.
if ctxt.HeadType == objabi.Hwindows {
Peinit(ctxt)
}
if ctxt.HeadType == objabi.Hdarwin && ctxt.LinkMode == LinkExternal {
*FlagTextAddr = 0
}
if ctxt.LinkMode == LinkExternal && ctxt.Arch.Family == sys.PPC64 {
toc := ctxt.Syms.Lookup(".TOC.", 0)
toc.Type = sym.SDYNIMPORT
}
if ctxt.LinkMode == LinkExternal && !iscgo && ctxt.LibraryByPkg["runtime/cgo"] == nil {
// 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 {
if lib.Shlib != "" {
ldshlibsyms(ctxt, lib.Shlib)
} else {
if ctxt.BuildMode == BuildModeShared || ctxt.linkShared {
Exitf("cannot implicitly include runtime/cgo in a shared library")
}
loadobjfile(ctxt, lib)
}
}
}
if ctxt.LinkMode == LinkInternal {
// Drop all the cgo_import_static declarations.
// Turns out we won't be needing them.
for _, s := range ctxt.Syms.Allsym {
if s.Type == 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.
if s.Extname != "" && s.Dynimplib != "" && !s.Attr.CgoExport() {
s.Type = sym.SDYNIMPORT
} else {
s.Type = 0
}
}
}
}
tlsg := ctxt.Syms.Lookup("runtime.tlsg", 0)
// runtime.tlsg is used for external linking on platforms that do not define
// a variable to hold g in assembly (currently only intel).
if tlsg.Type == 0 {
tlsg.Type = sym.STLSBSS
tlsg.Size = int64(ctxt.Arch.PtrSize)
} else if tlsg.Type != sym.SDYNIMPORT {
Errorf(nil, "runtime declared tlsg variable %v", tlsg.Type)
}
tlsg.Attr |= sym.AttrReachable
ctxt.Tlsg = tlsg
var moduledata *sym.Symbol
if ctxt.BuildMode == BuildModePlugin {
moduledata = ctxt.Syms.Lookup("local.pluginmoduledata", 0)
moduledata.Attr |= sym.AttrLocal
} else {
moduledata = ctxt.Syms.Lookup("runtime.firstmoduledata", 0)
}
if moduledata.Type != 0 && moduledata.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().
moduledata.Size = 0
// In addition, on ARM, the runtime depends on the linker
// recording the value of GOARM.
if ctxt.Arch.Family == sys.ARM {
s := ctxt.Syms.Lookup("runtime.goarm", 0)
s.Type = sym.SDATA
s.Size = 0
s.AddUint8(uint8(objabi.GOARM))
}
if objabi.Framepointer_enabled(objabi.GOOS, objabi.GOARCH) {
s := ctxt.Syms.Lookup("runtime.framepointer_enabled", 0)
s.Type = sym.SDATA
s.Size = 0
s.AddUint8(1)
}
} else {
// If OTOH the module does not contain the runtime package,
// create a local symbol for the moduledata.
moduledata = ctxt.Syms.Lookup("local.moduledata", 0)
moduledata.Attr |= sym.AttrLocal
}
// In all cases way we mark the moduledata as noptrdata to hide it from
// the GC.
moduledata.Type = sym.SNOPTRDATA
moduledata.Attr |= sym.AttrReachable
ctxt.Moduledata = moduledata
// Now that we know the link mode, trim the dynexp list.
x := sym.AttrCgoExportDynamic
if ctxt.LinkMode == LinkExternal {
x = sym.AttrCgoExportStatic
}
w := 0
for i := 0; i < len(dynexp); i++ {
if dynexp[i].Attr&x != 0 {
dynexp[w] = dynexp[i]
w++
}
}
dynexp = dynexp[:w]
// In internal link mode, read the host object files.
if ctxt.LinkMode == LinkInternal {
hostobjs(ctxt)
// If we have any undefined symbols in external
// objects, try to read them from the libgcc file.
any := false
for _, s := range ctxt.Syms.Allsym {
for _, r := range s.R {
if r.Sym != nil && r.Sym.Type == sym.SXREF && r.Sym.Name != ".got" {
any = true
break
}
}
}
if any {
if *flagLibGCC == "" {
*flagLibGCC = ctxt.findLibPathCmd("--print-libgcc-file-name", "libgcc")
}
if *flagLibGCC != "none" {
hostArchive(ctxt, *flagLibGCC)
}
if ctxt.HeadType == objabi.Hwindows {
if p := ctxt.findLibPath("libmingwex.a"); p != "none" {
hostArchive(ctxt, p)
}
if p := ctxt.findLibPath("libmingw32.a"); p != "none" {
hostArchive(ctxt, p)
}
// 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
*/
}
}
} else {
hostlinksetup(ctxt)
}
// We've loaded all the code now.
ctxt.Loaded = true
// 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 type. symbols are visible in the symbol table, rename them
// using a SHA-1 prefix. This reduces binary size (the full
// string of a type symbol can be multiple kilobytes) and removes
// characters that upset external linkers.
//
// Keep the type.. prefix, which parts of the linker (like the
// DWARF generator) know means the symbol is not decodable.
//
// Leave type.runtime. symbols alone, because other parts of
// the linker manipulates them, and also symbols whose names
// would not be shortened by this process.
if typeSymbolMangling(ctxt) {
*FlagW = true // disable DWARF generation
for _, s := range ctxt.Syms.Allsym {
newName := typeSymbolMangle(s.Name)
if newName != s.Name {
ctxt.Syms.Rename(s.Name, newName, int(s.Version))
}
}
}
// If package versioning is required, generate a hash of the
// packages used in the link.
if ctxt.BuildMode == BuildModeShared || ctxt.BuildMode == BuildModePlugin || ctxt.CanUsePlugins() {
for _, lib := range ctxt.Library {
if lib.Shlib == "" {
genhash(ctxt, lib)
}
}
}
if ctxt.Arch == sys.Arch386 {
if (ctxt.BuildMode == BuildModeCArchive && ctxt.IsELF) || (ctxt.BuildMode == BuildModeCShared && ctxt.HeadType != objabi.Hwindows) || ctxt.BuildMode == BuildModePIE || ctxt.DynlinkingGo() {
got := ctxt.Syms.Lookup("_GLOBAL_OFFSET_TABLE_", 0)
got.Type = sym.SDYNIMPORT
got.Attr |= sym.AttrReachable
}
}
importcycles()
// put symbols into Textp
// do it in postorder so that packages are laid down in dependency order
// internal first, then everything else
ctxt.Library = postorder(ctxt.Library)
for _, doInternal := range [2]bool{true, false} {
for _, lib := range ctxt.Library {
if isRuntimeDepPkg(lib.Pkg) != doInternal {
continue
}
ctxt.Textp = append(ctxt.Textp, lib.Textp...)
for _, s := range lib.DupTextSyms {
if !s.Attr.OnList() {
ctxt.Textp = append(ctxt.Textp, s)
s.Attr |= sym.AttrOnList
// dupok symbols may be defined in multiple packages. its
// associated package is chosen sort of arbitrarily (the
// first containing package that the linker loads). canonicalize
// it here to the package with which it will be laid down
// in text.
s.File = objabi.PathToPrefix(lib.Pkg)
}
}
}
}
if len(ctxt.Shlibs) > 0 {
// We might have overwritten some functions above (this tends to happen for the
// autogenerated type equality/hashing functions) and we don't want to generated
// pcln table entries for these any more so remove them from Textp.
textp := make([]*sym.Symbol, 0, len(ctxt.Textp))
for _, s := range ctxt.Textp {
if s.Type != sym.SDYNIMPORT {
textp = append(textp, s)
}
}
ctxt.Textp = textp
}
}
// typeSymbolMangling reports whether the linker should shorten the
// names of symbols that represent Go types.
//
// 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.
//
// 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 only
// those programs loaded dynamically in multiple parts need these
// symbols to have entries in the symbol table.
func typeSymbolMangling(ctxt *Link) bool {
return ctxt.BuildMode == BuildModeShared || ctxt.linkShared || ctxt.BuildMode == BuildModePlugin || ctxt.Syms.ROLookup("plugin.Open", 0) != nil
}
// typeSymbolMangle mangles the given symbol name into something shorter.
func typeSymbolMangle(name string) string {
if !strings.HasPrefix(name, "type.") {
return name
}
if strings.HasPrefix(name, "type.runtime.") {
return name
}
if len(name) <= 14 && !strings.Contains(name, "@") { // Issue 19529
return name
}
hash := sha1.Sum([]byte(name))
prefix := "type."
if name[5] == '.' {
prefix = "type.."
}
return prefix + base64.StdEncoding.EncodeToString(hash[:6])
}
/*
* look for the next file in an archive.
* adapted from libmach.
*/
func nextar(bp *bio.Reader, off int64, a *ArHdr) int64 {
if off&1 != 0 {
off++
}
bp.Seek(off, 0)
var buf [SAR_HDR]byte
if n, err := io.ReadFull(bp, buf[:]); err != nil {
if n == 0 && err != io.EOF {
return -1
}
return 0
}
a.name = artrim(buf[0:16])
a.date = artrim(buf[16:28])
a.uid = artrim(buf[28:34])
a.gid = artrim(buf[34:40])
a.mode = artrim(buf[40:48])
a.size = artrim(buf[48:58])
a.fmag = artrim(buf[58:60])
arsize := atolwhex(a.size)
if arsize&1 != 0 {
arsize++
}
return arsize + SAR_HDR
}
func genhash(ctxt *Link, lib *sym.Library) {
f, err := bio.Open(lib.File)
if err != nil {
Errorf(nil, "cannot open file %s for hash generation: %v", lib.File, err)
return
}
defer f.Close()
var magbuf [len(ARMAG)]byte
if _, err := io.ReadFull(f, magbuf[:]); err != nil {
Exitf("file %s too short", lib.File)
}
if string(magbuf[:]) != ARMAG {
Exitf("%s is not an archive file", lib.File)
}
var arhdr ArHdr
l := nextar(f, f.Offset(), &arhdr)
if l <= 0 {
Errorf(nil, "%s: short read on archive file symbol header", lib.File)
return
}
if arhdr.name != pkgdef {
Errorf(nil, "%s: missing package data entry", lib.File)
return
}
h := sha1.New()
// To compute the hash of a package, we hash the first line of
// __.PKGDEF (which contains the toolchain version and any
// GOEXPERIMENT flags) and the export data (which is between
// the first two occurrences of "\n$$").
pkgDefBytes := make([]byte, atolwhex(arhdr.size))
_, err = io.ReadFull(f, pkgDefBytes)
if err != nil {
Errorf(nil, "%s: error reading package data: %v", lib.File, err)
return
}
firstEOL := bytes.IndexByte(pkgDefBytes, '\n')
if firstEOL < 0 {
Errorf(nil, "cannot parse package data of %s for hash generation, no newline found", lib.File)
return
}
firstDoubleDollar := bytes.Index(pkgDefBytes, []byte("\n$$"))
if firstDoubleDollar < 0 {
Errorf(nil, "cannot parse package data of %s for hash generation, no \\n$$ found", lib.File)
return
}
secondDoubleDollar := bytes.Index(pkgDefBytes[firstDoubleDollar+1:], []byte("\n$$"))
if secondDoubleDollar < 0 {
Errorf(nil, "cannot parse package data of %s for hash generation, only one \\n$$ found", lib.File)
return
}
h.Write(pkgDefBytes[0:firstEOL])
h.Write(pkgDefBytes[firstDoubleDollar : firstDoubleDollar+secondDoubleDollar])
lib.Hash = hex.EncodeToString(h.Sum(nil))
}
func loadobjfile(ctxt *Link, lib *sym.Library) {
pkg := objabi.PathToPrefix(lib.Pkg)
if ctxt.Debugvlog > 1 {
ctxt.Logf("%5.2f ldobj: %s (%s)\n", Cputime(), lib.File, pkg)
}
f, err := bio.Open(lib.File)
if err != nil {
Exitf("cannot open file %s: %v", lib.File, err)
}
defer f.Close()
defer func() {
if pkg == "main" && !lib.Main {
Exitf("%s: not package main", lib.File)
}
// Ideally, we'd check that *all* object files within
// the archive were marked safe, but here we settle
// for *any*.
//
// Historically, cmd/link only checked the __.PKGDEF
// file, which in turn came from the first object
// file, typically produced by cmd/compile. The
// remaining object files are normally produced by
// cmd/asm, which doesn't support marking files as
// safe anyway. So at least in practice, this matches
// how safe mode has always worked.
if *flagU && !lib.Safe {
Exitf("%s: load of unsafe package %s", lib.File, pkg)
}
}()
for i := 0; i < len(ARMAG); i++ {
if c, err := f.ReadByte(); err == nil && c == ARMAG[i] {
continue
}
/* load it as a regular file */
l := f.Seek(0, 2)
f.Seek(0, 0)
ldobj(ctxt, f, lib, l, lib.File, lib.File)
return
}
/*
* load all the object files from the archive now.
* this gives us sequential file access and keeps us
* from needing to come back later to pick up more
* objects. it breaks the usual C archive model, but
* this is Go, not C. the common case in Go is that
* we need to load all the objects, and then we throw away
* the individual symbols that are unused.
*
* loading every object will also make it possible to
* load foreign objects not referenced by __.PKGDEF.
*/
var arhdr ArHdr
off := f.Offset()
for {
l := nextar(f, off, &arhdr)
if l == 0 {
break
}
if l < 0 {
Exitf("%s: malformed archive", lib.File)
}
off += l
// __.PKGDEF isn't a real Go object file, and it's
// absent in -linkobj builds anyway. Skipping it
// ensures consistency between -linkobj and normal
// build modes.
if arhdr.name == pkgdef {
continue
}
pname := fmt.Sprintf("%s(%s)", lib.File, arhdr.name)
l = atolwhex(arhdr.size)
ldobj(ctxt, f, lib, l, pname, lib.File)
}
}
type Hostobj struct {
ld func(*Link, *bio.Reader, string, int64, string)
pkg string
pn string
file string
off int64
length int64
}
var hostobj []Hostobj
// These packages can use internal linking mode.
// Others trigger external mode.
var internalpkg = []string{
"crypto/x509",
"net",
"os/user",
"runtime/cgo",
"runtime/race",
"runtime/msan",
}
func ldhostobj(ld func(*Link, *bio.Reader, string, int64, string), headType objabi.HeadType, f *bio.Reader, pkg string, length int64, pn string, file string) *Hostobj {
isinternal := false
for i := 0; i < len(internalpkg); i++ {
if pkg == internalpkg[i] {
isinternal = true
break
}
}
// DragonFly declares errno with __thread, which results in a symbol
// type of R_386_TLS_GD or R_X86_64_TLSGD. The Go linker does not
// currently know how to handle TLS relocations, hence we have to
// force external linking for any libraries that link in code that
// uses errno. This can be removed if the Go linker ever supports
// these relocation types.
if headType == objabi.Hdragonfly {
if pkg == "net" || pkg == "os/user" {
isinternal = false
}
}
if !isinternal {
externalobj = true
}
hostobj = append(hostobj, Hostobj{})
h := &hostobj[len(hostobj)-1]
h.ld = ld
h.pkg = pkg
h.pn = pn
h.file = file
h.off = f.Offset()
h.length = length
return h
}
func hostobjs(ctxt *Link) {
var h *Hostobj
for i := 0; i < len(hostobj); i++ {
h = &hostobj[i]
f, err := bio.Open(h.file)
if err != nil {
Exitf("cannot reopen %s: %v", h.pn, err)
}
f.Seek(h.off, 0)
h.ld(ctxt, f, h.pkg, h.length, h.pn)
f.Close()
}
}
// provided by lib9
func rmtemp() {
os.RemoveAll(*flagTmpdir)
}
func hostlinksetup(ctxt *Link) {
if ctxt.LinkMode != LinkExternal {
return
}
// For external link, record that we need to tell the external linker -s,
// and turn off -s internally: the external linker needs the symbol
// information for its final link.
debug_s = *FlagS
*FlagS = false
// create temporary directory and arrange cleanup
if *flagTmpdir == "" {
dir, err := ioutil.TempDir("", "go-link-")
if err != nil {
log.Fatal(err)
}
*flagTmpdir = dir
AtExit(rmtemp)
}
// change our output to temporary object file
ctxt.Out.f.Close()
mayberemoveoutfile()
p := filepath.Join(*flagTmpdir, "go.o")
var err error
f, err := os.OpenFile(p, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0775)
if err != nil {
Exitf("cannot create %s: %v", p, err)
}
ctxt.Out.w = bufio.NewWriter(f)
ctxt.Out.f = f
ctxt.Out.off = 0
}
// hostobjCopy creates a copy of the object files in hostobj in a
// temporary directory.
func hostobjCopy() (paths []string) {
var wg sync.WaitGroup
sema := make(chan struct{}, runtime.NumCPU()) // limit open file descriptors
for i, h := range hostobj {
h := h
dst := filepath.Join(*flagTmpdir, fmt.Sprintf("%06d.o", i))
paths = append(paths, dst)
wg.Add(1)
go func() {
sema <- struct{}{}
defer func() {
<-sema
wg.Done()
}()
f, err := os.Open(h.file)
if err != nil {
Exitf("cannot reopen %s: %v", h.pn, err)
}
if _, err := f.Seek(h.off, 0); err != nil {
Exitf("cannot seek %s: %v", h.pn, err)
}
w, err := os.Create(dst)
if err != nil {
Exitf("cannot create %s: %v", dst, err)
}
if _, err := io.CopyN(w, f, h.length); err != nil {
Exitf("cannot write %s: %v", dst, err)
}
if err := w.Close(); err != nil {
Exitf("cannot close %s: %v", dst, err)
}
}()
}