forked from golang/go
/
lib.go
2213 lines (1962 loc) · 54.1 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
// http://code.google.com/p/inferno-os/source/browse/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/obj"
"cmd/internal/sys"
"crypto/sha1"
"debug/elf"
"encoding/binary"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"sync"
)
// Data layout and relocation.
// Derived from Inferno utils/6l/l.h
// http://code.google.com/p/inferno-os/source/browse/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(*LSym, *Reloc)
Archinit func()
Archreloc func(*Reloc, *LSym, *int64) int
Archrelocvariant func(*Reloc, *LSym, int64) int64
Asmb func()
Elfreloc1 func(*Reloc, int64) int
Elfsetupplt func()
Gentext func()
Machoreloc1 func(*Reloc, int64) int
PEreloc1 func(*Reloc, int64) bool
Wput func(uint16)
Lput func(uint32)
Vput func(uint64)
Append16 func(b []byte, v uint16) []byte
Append32 func(b []byte, v uint32) []byte
Append64 func(b []byte, v uint64) []byte
}
type Rpath struct {
set bool
val string
}
func (r *Rpath) Set(val string) error {
r.set = true
r.val = val
return nil
}
func (r *Rpath) String() string {
return r.val
}
var (
Thearch Arch
Debug [128]int
Lcsize int32
rpath Rpath
Spsize int32
Symsize int32
)
// Terrible but standard terminology.
// A segment describes a block of file to load into memory.
// A section further describes the pieces of that block for
// use in debuggers and such.
const (
MINFUNC = 16 // minimum size for a function
)
type Segment struct {
Rwx uint8 // permission as usual unix bits (5 = r-x etc)
Vaddr uint64 // virtual address
Length uint64 // length in memory
Fileoff uint64 // file offset
Filelen uint64 // length on disk
Sect *Section
}
type Section struct {
Rwx uint8
Extnum int16
Align int32
Name string
Vaddr uint64
Length uint64
Next *Section
Seg *Segment
Elfsect *ElfShdr
Reloff uint64
Rellen uint64
}
// DynlinkingGo returns whether we are producing Go code that can live
// in separate shared libraries linked together at runtime.
func DynlinkingGo() bool {
return Buildmode == BuildmodeShared || Linkshared
}
// UseRelro returns whether to make use of "read only relocations" aka
// relro.
func UseRelro() bool {
switch Buildmode {
case BuildmodeCShared, BuildmodeShared, BuildmodePIE:
return Iself
default:
return Linkshared
}
}
var (
SysArch *sys.Arch
outfile string
dynexp []*LSym
dynlib []string
ldflag []string
havedynamic int
Funcalign int
iscgo bool
elfglobalsymndx int
flag_dumpdep bool
flag_installsuffix string
flag_race int
flag_msan int
Buildmode BuildMode
Linkshared bool
tracksym string
interpreter string
tmpdir string
extld string
extldflags string
extar string
libgccfile string
debug_s int // backup old value of debug['s']
Ctxt *Link
HEADR int32
HEADTYPE int32
INITRND int32
INITTEXT int64
INITDAT int64
INITENTRY string /* entry point */
nerrors int
Linkmode int
liveness int64
)
var (
Segtext Segment
Segrodata Segment
Segdata Segment
Segdwarf Segment
)
/* set by call to mywhatsys() */
/* whence for ldpkg */
const (
FileObj = 0 + iota
ArchiveObj
Pkgdef
)
var (
headstring string
// buffered output
Bso *bufio.Writer
)
// TODO(dfc) outBuf duplicates bio.Writer
type outBuf struct {
w *bufio.Writer
f *os.File
off int64
}
func (w *outBuf) Write(p []byte) (n int, err error) {
n, err = w.w.Write(p)
w.off += int64(n)
return n, err
}
func (w *outBuf) WriteString(s string) (n int, err error) {
n, err = coutbuf.w.WriteString(s)
w.off += int64(n)
return n, err
}
var coutbuf outBuf
const pkgname = "__.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
goroot string
goarch string
goos string
theline string
)
func Lflag(arg string) {
Ctxt.Libdir = append(Ctxt.Libdir, arg)
}
// A BuildMode indicates the sort of object we are building:
// "exe": build a main package and everything it imports into an executable.
// "c-shared": build a main package, plus all packages that it imports, into a
// single C shared library. The only callable symbols will be those functions
// marked as exported.
// "shared": combine all packages passed on the command line, and their
// dependencies, into a single shared library that will be used when
// building with the -linkshared option.
type BuildMode uint8
const (
BuildmodeUnset BuildMode = iota
BuildmodeExe
BuildmodePIE
BuildmodeCArchive
BuildmodeCShared
BuildmodeShared
)
func (mode *BuildMode) Set(s string) error {
goos := obj.Getgoos()
goarch := obj.Getgoarch()
badmode := func() error {
return fmt.Errorf("buildmode %s not supported on %s/%s", s, goos, goarch)
}
switch s {
default:
return fmt.Errorf("invalid buildmode: %q", s)
case "exe":
*mode = BuildmodeExe
case "pie":
switch goos {
case "android", "linux":
default:
return badmode()
}
*mode = BuildmodePIE
case "c-archive":
switch goos {
case "darwin", "linux":
case "windows":
switch goarch {
case "amd64", "386":
default:
return badmode()
}
default:
return badmode()
}
*mode = BuildmodeCArchive
case "c-shared":
switch goarch {
case "386", "amd64", "arm", "arm64":
default:
return badmode()
}
*mode = BuildmodeCShared
case "shared":
switch goos {
case "linux":
switch goarch {
case "386", "amd64", "arm", "arm64", "ppc64le", "s390x":
default:
return badmode()
}
default:
return badmode()
}
*mode = BuildmodeShared
}
return nil
}
func (mode *BuildMode) String() string {
switch *mode {
case BuildmodeUnset:
return "" // avoid showing a default in usage message
case BuildmodeExe:
return "exe"
case BuildmodePIE:
return "pie"
case BuildmodeCArchive:
return "c-archive"
case BuildmodeCShared:
return "c-shared"
case BuildmodeShared:
return "shared"
}
return fmt.Sprintf("BuildMode(%d)", uint8(*mode))
}
/*
* 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(outfile); err == nil && !fi.Mode().IsRegular() {
return
}
os.Remove(outfile)
}
func libinit() {
Funcalign = Thearch.Funcalign
mywhatsys() // get goroot, goarch, goos
// add goroot to the end of the libdir list.
suffix := ""
suffixsep := ""
if flag_installsuffix != "" {
suffixsep = "_"
suffix = flag_installsuffix
} else if flag_race != 0 {
suffixsep = "_"
suffix = "race"
} else if flag_msan != 0 {
suffixsep = "_"
suffix = "msan"
}
Lflag(filepath.Join(goroot, "pkg", fmt.Sprintf("%s_%s%s%s", goos, goarch, suffixsep, suffix)))
mayberemoveoutfile()
f, err := os.OpenFile(outfile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0775)
if err != nil {
Exitf("cannot create %s: %v", outfile, err)
}
coutbuf.w = bufio.NewWriter(f)
coutbuf.f = f
if INITENTRY == "" {
switch Buildmode {
case BuildmodeCShared, BuildmodeCArchive:
INITENTRY = fmt.Sprintf("_rt0_%s_%s_lib", goarch, goos)
case BuildmodeExe, BuildmodePIE:
INITENTRY = fmt.Sprintf("_rt0_%s_%s", goarch, goos)
case BuildmodeShared:
// No INITENTRY for -buildmode=shared
default:
Diag("unknown INITENTRY for buildmode %v", Buildmode)
}
}
if !DynlinkingGo() {
Linklookup(Ctxt, INITENTRY, 0).Type = obj.SXREF
}
}
func Exitf(format string, a ...interface{}) {
fmt.Fprintf(os.Stderr, os.Args[0]+": "+format+"\n", a...)
if coutbuf.f != nil {
coutbuf.f.Close()
mayberemoveoutfile()
}
Exit(2)
}
func errorexit() {
if coutbuf.f != nil {
if nerrors != 0 {
Cflush()
}
// For rmtemp run at atexit time on Windows.
if err := coutbuf.f.Close(); err != nil {
Exitf("close: %v", err)
}
}
if nerrors != 0 {
if coutbuf.f != nil {
mayberemoveoutfile()
}
Exit(2)
}
Exit(0)
}
func loadinternal(name string) {
found := 0
for i := 0; i < len(Ctxt.Libdir); i++ {
if Linkshared {
shlibname := filepath.Join(Ctxt.Libdir[i], name+".shlibname")
if Debug['v'] != 0 {
fmt.Fprintf(Bso, "searching for %s.a in %s\n", name, shlibname)
}
if _, err := os.Stat(shlibname); err == nil {
addlibpath(Ctxt, "internal", "internal", "", name, shlibname)
found = 1
break
}
}
pname := filepath.Join(Ctxt.Libdir[i], name+".a")
if Debug['v'] != 0 {
fmt.Fprintf(Bso, "searching for %s.a in %s\n", name, pname)
}
if _, err := os.Stat(pname); err == nil {
addlibpath(Ctxt, "internal", "internal", pname, name, "")
found = 1
break
}
}
if found == 0 {
fmt.Fprintf(Bso, "warning: unable to find %s.a\n", name)
}
}
func loadlib() {
switch Buildmode {
case BuildmodeCShared:
s := Linklookup(Ctxt, "runtime.islibrary", 0)
s.Attr |= AttrDuplicateOK
Adduint8(Ctxt, s, 1)
case BuildmodeCArchive:
s := Linklookup(Ctxt, "runtime.isarchive", 0)
s.Attr |= AttrDuplicateOK
Adduint8(Ctxt, s, 1)
}
loadinternal("runtime")
if SysArch.Family == sys.ARM {
loadinternal("math")
}
if flag_race != 0 {
loadinternal("runtime/race")
}
if flag_msan != 0 {
loadinternal("runtime/msan")
}
var i int
for i = 0; i < len(Ctxt.Library); i++ {
iscgo = iscgo || Ctxt.Library[i].Pkg == "runtime/cgo"
if Ctxt.Library[i].Shlib == "" {
if Debug['v'] > 1 {
fmt.Fprintf(Bso, "%5.2f autolib: %s (from %s)\n", obj.Cputime(), Ctxt.Library[i].File, Ctxt.Library[i].Objref)
}
objfile(Ctxt.Library[i])
}
}
for i = 0; i < len(Ctxt.Library); i++ {
if Ctxt.Library[i].Shlib != "" {
if Debug['v'] > 1 {
fmt.Fprintf(Bso, "%5.2f autolib: %s (from %s)\n", obj.Cputime(), Ctxt.Library[i].Shlib, Ctxt.Library[i].Objref)
}
ldshlibsyms(Ctxt.Library[i].Shlib)
}
}
if Linkmode == LinkAuto {
if iscgo && externalobj {
Linkmode = LinkExternal
} else {
Linkmode = LinkInternal
}
// Force external linking for android.
if goos == "android" {
Linkmode = LinkExternal
}
// Force external linking for PIE executables, as
// internal linking does not support TLS_IE.
if Buildmode == BuildmodePIE {
Linkmode = LinkExternal
}
// cgo on Darwin must use external linking
// we can always use external linking, but then there will be circular
// dependency problems when compiling natively (external linking requires
// runtime/cgo, runtime/cgo requires cmd/cgo, but cmd/cgo needs to be
// compiled using external linking.)
if SysArch.InFamily(sys.ARM, sys.ARM64) && HEADTYPE == obj.Hdarwin && iscgo {
Linkmode = LinkExternal
}
// Force external linking for msan.
if flag_msan != 0 {
Linkmode = LinkExternal
}
}
// cmd/7l doesn't support cgo internal linking
// This is https://golang.org/issue/10373.
// mips64x doesn't support cgo internal linking either (golang.org/issue/14449)
if iscgo && (goarch == "arm64" || goarch == "mips64" || goarch == "mips64le") {
Linkmode = LinkExternal
}
if Linkmode == LinkExternal && !iscgo {
// 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.
loadinternal("runtime/cgo")
if i < len(Ctxt.Library) {
if Ctxt.Library[i].Shlib != "" {
ldshlibsyms(Ctxt.Library[i].Shlib)
} else {
if DynlinkingGo() {
Exitf("cannot implicitly include runtime/cgo in a shared library")
}
objfile(Ctxt.Library[i])
}
}
}
if Linkmode == LinkInternal {
// Drop all the cgo_import_static declarations.
// Turns out we won't be needing them.
for _, s := range Ctxt.Allsym {
if s.Type == obj.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 = obj.SDYNIMPORT
} else {
s.Type = 0
}
}
}
}
tlsg := Linklookup(Ctxt, "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 = obj.STLSBSS
tlsg.Size = int64(SysArch.PtrSize)
} else if tlsg.Type != obj.SDYNIMPORT {
Diag("internal error: runtime declared tlsg variable %d", tlsg.Type)
}
tlsg.Attr |= AttrReachable
Ctxt.Tlsg = tlsg
moduledata := Linklookup(Ctxt, "runtime.firstmoduledata", 0)
if moduledata.Type != 0 && moduledata.Type != obj.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 SysArch.Family == sys.ARM {
s := Linklookup(Ctxt, "runtime.goarm", 0)
s.Type = obj.SRODATA
s.Size = 0
Adduint8(Ctxt, s, uint8(Ctxt.Goarm))
}
if obj.Framepointer_enabled(obj.Getgoos(), obj.Getgoarch()) {
s := Linklookup(Ctxt, "runtime.framepointer_enabled", 0)
s.Type = obj.SRODATA
s.Size = 0
Adduint8(Ctxt, s, 1)
}
} else {
// If OTOH the module does not contain the runtime package,
// create a local symbol for the moduledata.
moduledata = Linklookup(Ctxt, "local.moduledata", 0)
moduledata.Attr |= AttrLocal
}
// In all cases way we mark the moduledata as noptrdata to hide it from
// the GC.
moduledata.Type = obj.SNOPTRDATA
moduledata.Attr |= AttrReachable
Ctxt.Moduledata = moduledata
// Now that we know the link mode, trim the dynexp list.
x := AttrCgoExportDynamic
if Linkmode == LinkExternal {
x = 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 Linkmode == LinkInternal {
hostobjs()
// If we have any undefined symbols in external
// objects, try to read them from the libgcc file.
any := false
for _, s := range Ctxt.Allsym {
for _, r := range s.R {
if r.Sym != nil && r.Sym.Type&obj.SMASK == obj.SXREF && r.Sym.Name != ".got" {
any = true
break
}
}
}
if any {
if libgccfile == "" {
if extld == "" {
extld = "gcc"
}
args := hostlinkArchArgs()
args = append(args, "--print-libgcc-file-name")
if Debug['v'] != 0 {
fmt.Fprintf(Bso, "%s %v\n", extld, args)
}
out, err := exec.Command(extld, args...).Output()
if err != nil {
if Debug['v'] != 0 {
fmt.Fprintln(Bso, "not using a libgcc file because compiler failed")
fmt.Fprintf(Bso, "%v\n%s\n", err, out)
}
libgccfile = "none"
} else {
libgccfile = strings.TrimSpace(string(out))
}
}
if libgccfile != "none" {
hostArchive(libgccfile)
}
}
} else {
hostlinksetup()
}
// We've loaded all the code now.
// 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.
switch Buildmode {
case BuildmodeExe, BuildmodePIE:
if havedynamic == 0 && HEADTYPE != obj.Hdarwin && HEADTYPE != obj.Hsolaris {
Debug['d'] = 1
}
}
importcycles()
}
/*
* 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 objfile(lib *Library) {
pkg := pathtoprefix(lib.Pkg)
if Debug['v'] > 1 {
fmt.Fprintf(Bso, "%5.2f ldobj: %s (%s)\n", obj.Cputime(), lib.File, pkg)
}
Bso.Flush()
f, err := bio.Open(lib.File)
if err != nil {
Exitf("cannot open file %s: %v", lib.File, err)
}
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(f, pkg, l, lib.File, lib.File, FileObj)
f.Close()
return
}
/* process __.PKGDEF */
off := f.Offset()
var arhdr ArHdr
l := nextar(f, off, &arhdr)
var pname string
if l <= 0 {
Diag("%s: short read on archive file symbol header", lib.File)
goto out
}
if !strings.HasPrefix(arhdr.name, pkgname) {
Diag("%s: cannot find package header", lib.File)
goto out
}
if Buildmode == BuildmodeShared {
before := f.Offset()
pkgdefBytes := make([]byte, atolwhex(arhdr.size))
if _, err := io.ReadFull(f, pkgdefBytes); err != nil {
Diag("%s: short read on archive file symbol header: %v", lib.File, err)
}
hash := sha1.Sum(pkgdefBytes)
lib.hash = hash[:]
f.Seek(before, 0)
}
off += l
ldpkg(f, pkg, atolwhex(arhdr.size), lib.File, Pkgdef)
/*
* 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.
*/
for {
l = nextar(f, off, &arhdr)
if l == 0 {
break
}
if l < 0 {
Exitf("%s: malformed archive", lib.File)
}
off += l
pname = fmt.Sprintf("%s(%s)", lib.File, arhdr.name)
l = atolwhex(arhdr.size)
ldobj(f, pkg, l, pname, lib.File, ArchiveObj)
}
out:
f.Close()
}
type Hostobj struct {
ld func(*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(*bio.Reader, string, int64, string), 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 == obj.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() {
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(f, h.pkg, h.length, h.pn)
f.Close()
}
}
// provided by lib9
func rmtemp() {
os.RemoveAll(tmpdir)
}
func hostlinksetup() {
if 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 = Debug['s']
Debug['s'] = 0
// create temporary directory and arrange cleanup
if tmpdir == "" {
dir, err := ioutil.TempDir("", "go-link-")
if err != nil {
log.Fatal(err)
}
tmpdir = dir
AtExit(rmtemp)
}
// change our output to temporary object file
coutbuf.f.Close()
mayberemoveoutfile()
p := filepath.Join(tmpdir, "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)
}
coutbuf.w = bufio.NewWriter(f)
coutbuf.f = f
}
// 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(tmpdir, fmt.Sprintf("%06d.o", i))
paths = append(paths, dst)
wg.Add(1)
go func() {
sema <- struct{}{}
defer func() {
<-sema
wg.Done()
}()