Source file src/cmd/link/internal/ld/go.go

     1  // Copyright 2009 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // go-specific code shared across loaders (5l, 6l, 8l).
     6  
     7  package ld
     8  
     9  import (
    10  	"cmd/internal/bio"
    11  	"cmd/internal/obj"
    12  	"cmd/internal/objabi"
    13  	"cmd/internal/sys"
    14  	"cmd/link/internal/loader"
    15  	"cmd/link/internal/sym"
    16  	"debug/elf"
    17  	"encoding/json"
    18  	"fmt"
    19  	"io"
    20  	"os"
    21  	"sort"
    22  	"strconv"
    23  	"strings"
    24  )
    25  
    26  // go-specific code shared across loaders (5l, 6l, 8l).
    27  
    28  // TODO:
    29  //	generate debugging section in binary.
    30  //	once the dust settles, try to move some code to
    31  //		libmach, so that other linkers and ar can share.
    32  
    33  func ldpkg(ctxt *Link, f *bio.Reader, lib *sym.Library, length int64, filename string) {
    34  	if *flagG {
    35  		return
    36  	}
    37  
    38  	if int64(int(length)) != length {
    39  		fmt.Fprintf(os.Stderr, "%s: too much pkg data in %s\n", os.Args[0], filename)
    40  		return
    41  	}
    42  
    43  	bdata := make([]byte, length)
    44  	if _, err := io.ReadFull(f, bdata); err != nil {
    45  		fmt.Fprintf(os.Stderr, "%s: short pkg read %s\n", os.Args[0], filename)
    46  		return
    47  	}
    48  	data := string(bdata)
    49  
    50  	// process header lines
    51  	for data != "" {
    52  		var line string
    53  		line, data, _ = strings.Cut(data, "\n")
    54  		if line == "main" {
    55  			lib.Main = true
    56  		}
    57  		if line == "" {
    58  			break
    59  		}
    60  	}
    61  
    62  	// look for cgo section
    63  	p0 := strings.Index(data, "\n$$  // cgo")
    64  	var p1 int
    65  	if p0 >= 0 {
    66  		p0 += p1
    67  		i := strings.IndexByte(data[p0+1:], '\n')
    68  		if i < 0 {
    69  			fmt.Fprintf(os.Stderr, "%s: found $$ // cgo but no newline in %s\n", os.Args[0], filename)
    70  			return
    71  		}
    72  		p0 += 1 + i
    73  
    74  		p1 = strings.Index(data[p0:], "\n$$")
    75  		if p1 < 0 {
    76  			p1 = strings.Index(data[p0:], "\n!\n")
    77  		}
    78  		if p1 < 0 {
    79  			fmt.Fprintf(os.Stderr, "%s: cannot find end of // cgo section in %s\n", os.Args[0], filename)
    80  			return
    81  		}
    82  		p1 += p0
    83  		loadcgo(ctxt, filename, objabi.PathToPrefix(lib.Pkg), data[p0:p1])
    84  	}
    85  }
    86  
    87  func loadcgo(ctxt *Link, file string, pkg string, p string) {
    88  	var directives [][]string
    89  	if err := json.NewDecoder(strings.NewReader(p)).Decode(&directives); err != nil {
    90  		fmt.Fprintf(os.Stderr, "%s: %s: failed decoding cgo directives: %v\n", os.Args[0], file, err)
    91  		nerrors++
    92  		return
    93  	}
    94  
    95  	// Record the directives. We'll process them later after Symbols are created.
    96  	ctxt.cgodata = append(ctxt.cgodata, cgodata{file, pkg, directives})
    97  }
    98  
    99  // Set symbol attributes or flags based on cgo directives.
   100  // Any newly discovered HOSTOBJ syms are added to 'hostObjSyms'.
   101  func setCgoAttr(ctxt *Link, file string, pkg string, directives [][]string, hostObjSyms map[loader.Sym]struct{}) {
   102  	l := ctxt.loader
   103  	for _, f := range directives {
   104  		switch f[0] {
   105  		case "cgo_import_dynamic":
   106  			if len(f) < 2 || len(f) > 4 {
   107  				break
   108  			}
   109  
   110  			local := f[1]
   111  			remote := local
   112  			if len(f) > 2 {
   113  				remote = f[2]
   114  			}
   115  			lib := ""
   116  			if len(f) > 3 {
   117  				lib = f[3]
   118  			}
   119  
   120  			if strings.Contains(local, ",") || strings.Contains(remote, ",") {
   121  				fmt.Fprintf(os.Stderr, "%s: %s: invalid symbol in cgo_import_dynamic directive: %q\n", os.Args[0], file, f)
   122  				nerrors++
   123  				return
   124  			}
   125  
   126  			if *FlagD {
   127  				fmt.Fprintf(os.Stderr, "%s: %s: cannot use dynamic imports with -d flag\n", os.Args[0], file)
   128  				nerrors++
   129  				return
   130  			}
   131  
   132  			if local == "_" && remote == "_" {
   133  				// allow #pragma dynimport _ _ "foo.so"
   134  				// to force a link of foo.so.
   135  				havedynamic = 1
   136  
   137  				if ctxt.HeadType == objabi.Hdarwin {
   138  					machoadddynlib(lib, ctxt.LinkMode)
   139  				} else {
   140  					dynlib = append(dynlib, lib)
   141  				}
   142  				continue
   143  			}
   144  
   145  			q := ""
   146  			if before, after, found := strings.Cut(remote, "#"); found {
   147  				remote, q = before, after
   148  			}
   149  			s := l.LookupOrCreateSym(local, 0)
   150  			// export overrides import
   151  			if l.AttrCgoExportStatic(s) || l.AttrCgoExportDynamic(s) {
   152  				continue
   153  			}
   154  			st := l.SymType(s)
   155  			if st == 0 || st == sym.SXREF || st == sym.SBSS || st == sym.SNOPTRBSS || st == sym.SHOSTOBJ {
   156  				l.SetSymDynimplib(s, lib)
   157  				l.SetSymExtname(s, remote)
   158  				l.SetSymDynimpvers(s, q)
   159  				if st != sym.SHOSTOBJ {
   160  					su := l.MakeSymbolUpdater(s)
   161  					su.SetType(sym.SDYNIMPORT)
   162  				} else {
   163  					hostObjSyms[s] = struct{}{}
   164  				}
   165  				havedynamic = 1
   166  				if lib != "" && ctxt.IsDarwin() {
   167  					machoadddynlib(lib, ctxt.LinkMode)
   168  				}
   169  			}
   170  
   171  			continue
   172  
   173  		case "cgo_import_static":
   174  			if len(f) != 2 {
   175  				break
   176  			}
   177  			local := f[1]
   178  			if strings.Contains(local, ",") {
   179  				fmt.Fprintf(os.Stderr, "%s: %s: invalid symbol in cgo_import_static directive: %q\n", os.Args[0], file, f)
   180  				nerrors++
   181  				return
   182  			}
   183  
   184  			s := l.LookupOrCreateSym(local, 0)
   185  			su := l.MakeSymbolUpdater(s)
   186  			su.SetType(sym.SHOSTOBJ)
   187  			su.SetSize(0)
   188  			hostObjSyms[s] = struct{}{}
   189  			continue
   190  
   191  		case "cgo_export_static", "cgo_export_dynamic":
   192  			if len(f) < 2 || len(f) > 4 {
   193  				break
   194  			}
   195  			local := f[1]
   196  			remote := local
   197  			if len(f) > 2 {
   198  				remote = f[2]
   199  			}
   200  			if strings.Contains(local, ",") || strings.Contains(remote, ",") {
   201  				fmt.Fprintf(os.Stderr, "%s: %s: invalid symbol in %s directive: %q\n", os.Args[0], file, f[0], f)
   202  				nerrors++
   203  				return
   204  			}
   205  			// The compiler adds a fourth argument giving
   206  			// the definition ABI of function symbols.
   207  			abi := obj.ABI0
   208  			if len(f) > 3 {
   209  				var ok bool
   210  				abi, ok = obj.ParseABI(f[3])
   211  				if !ok {
   212  					fmt.Fprintf(os.Stderr, "%s: bad ABI in cgo_export directive %s\n", os.Args[0], f)
   213  					nerrors++
   214  					return
   215  				}
   216  			}
   217  
   218  			s := l.LookupOrCreateSym(local, sym.ABIToVersion(abi))
   219  
   220  			if l.SymType(s) == sym.SHOSTOBJ {
   221  				hostObjSyms[s] = struct{}{}
   222  			}
   223  
   224  			switch ctxt.BuildMode {
   225  			case BuildModeCShared, BuildModeCArchive, BuildModePlugin:
   226  				if s == l.Lookup("main", 0) {
   227  					continue
   228  				}
   229  			}
   230  
   231  			// If we saw a cgo_import_dynamic before this cgo_export, the
   232  			// export overrides the import (for example on openbsd/cgo, see
   233  			// issue 4878).
   234  			if l.SymDynimplib(s) != "" || l.SymType(s) == sym.SDYNIMPORT {
   235  				l.SetSymDynimplib(s, "")
   236  				l.SetSymDynimpvers(s, "")
   237  				l.SetSymExtname(s, "")
   238  				var su *loader.SymbolBuilder
   239  				su = l.MakeSymbolUpdater(s)
   240  				su.SetType(0)
   241  			}
   242  
   243  			if !(l.AttrCgoExportStatic(s) || l.AttrCgoExportDynamic(s)) {
   244  				l.SetSymExtname(s, remote)
   245  			} else if l.SymExtname(s) != remote {
   246  				fmt.Fprintf(os.Stderr, "%s: conflicting cgo_export directives: %s as %s and %s\n", os.Args[0], l.SymName(s), l.SymExtname(s), remote)
   247  				nerrors++
   248  				return
   249  			}
   250  
   251  			// Mark exported symbols and also add them to
   252  			// the lists used for roots in the deadcode pass.
   253  			if f[0] == "cgo_export_static" {
   254  				if ctxt.LinkMode == LinkExternal && !l.AttrCgoExportStatic(s) {
   255  					// Static cgo exports appear
   256  					// in the exported symbol table.
   257  					ctxt.dynexp = append(ctxt.dynexp, s)
   258  				}
   259  				if ctxt.LinkMode == LinkInternal {
   260  					// For internal linking, we're
   261  					// responsible for resolving
   262  					// relocations from host objects.
   263  					// Record the right Go symbol
   264  					// version to use.
   265  					l.AddCgoExport(s)
   266  				}
   267  				l.SetAttrCgoExportStatic(s, true)
   268  			} else {
   269  				if ctxt.LinkMode == LinkInternal && !l.AttrCgoExportDynamic(s) {
   270  					// Dynamic cgo exports appear
   271  					// in the exported symbol table.
   272  					ctxt.dynexp = append(ctxt.dynexp, s)
   273  				}
   274  				l.SetAttrCgoExportDynamic(s, true)
   275  			}
   276  
   277  			continue
   278  
   279  		case "cgo_dynamic_linker":
   280  			if len(f) != 2 {
   281  				break
   282  			}
   283  			if strings.Contains(f[1], ",") {
   284  				fmt.Fprintf(os.Stderr, "%s: %s: invalid path in cgo_dynamic_linker directive: %q\n", os.Args[0], file, f[1])
   285  				nerrors++
   286  				return
   287  			}
   288  
   289  			if *flagInterpreter == "" {
   290  				if interpreter != "" && interpreter != f[1] {
   291  					fmt.Fprintf(os.Stderr, "%s: conflict dynlinker: %s and %s\n", os.Args[0], interpreter, f[1])
   292  					nerrors++
   293  					return
   294  				}
   295  
   296  				interpreter = f[1]
   297  			}
   298  			continue
   299  
   300  		case "cgo_ldflag":
   301  			if len(f) != 2 {
   302  				break
   303  			}
   304  			ldflag = append(ldflag, f[1])
   305  			continue
   306  		}
   307  
   308  		fmt.Fprintf(os.Stderr, "%s: %s: invalid cgo directive: %q\n", os.Args[0], file, f)
   309  		nerrors++
   310  	}
   311  	return
   312  }
   313  
   314  // openbsdTrimLibVersion indicates whether a shared library is
   315  // versioned and if it is, returns the unversioned name. The
   316  // OpenBSD library naming scheme is lib<name>.so.<major>.<minor>
   317  func openbsdTrimLibVersion(lib string) (string, bool) {
   318  	parts := strings.Split(lib, ".")
   319  	if len(parts) != 4 {
   320  		return "", false
   321  	}
   322  	if parts[1] != "so" {
   323  		return "", false
   324  	}
   325  	if _, err := strconv.Atoi(parts[2]); err != nil {
   326  		return "", false
   327  	}
   328  	if _, err := strconv.Atoi(parts[3]); err != nil {
   329  		return "", false
   330  	}
   331  	return fmt.Sprintf("%s.%s", parts[0], parts[1]), true
   332  }
   333  
   334  // dedupLibrariesOpenBSD dedups a list of shared libraries, treating versioned
   335  // and unversioned libraries as equivalents. Versioned libraries are preferred
   336  // and retained over unversioned libraries. This avoids the situation where
   337  // the use of cgo results in a DT_NEEDED for a versioned library (for example,
   338  // libc.so.96.1), while a dynamic import specifies an unversioned library (for
   339  // example, libc.so) - this would otherwise result in two DT_NEEDED entries
   340  // for the same library, resulting in a failure when ld.so attempts to load
   341  // the Go binary.
   342  func dedupLibrariesOpenBSD(ctxt *Link, libs []string) []string {
   343  	libraries := make(map[string]string)
   344  	for _, lib := range libs {
   345  		if name, ok := openbsdTrimLibVersion(lib); ok {
   346  			// Record unversioned name as seen.
   347  			seenlib[name] = true
   348  			libraries[name] = lib
   349  		} else if _, ok := libraries[lib]; !ok {
   350  			libraries[lib] = lib
   351  		}
   352  	}
   353  
   354  	libs = nil
   355  	for _, lib := range libraries {
   356  		libs = append(libs, lib)
   357  	}
   358  	sort.Strings(libs)
   359  
   360  	return libs
   361  }
   362  
   363  func dedupLibraries(ctxt *Link, libs []string) []string {
   364  	if ctxt.Target.IsOpenbsd() {
   365  		return dedupLibrariesOpenBSD(ctxt, libs)
   366  	}
   367  	return libs
   368  }
   369  
   370  var seenlib = make(map[string]bool)
   371  
   372  func adddynlib(ctxt *Link, lib string) {
   373  	if seenlib[lib] || ctxt.LinkMode == LinkExternal {
   374  		return
   375  	}
   376  	seenlib[lib] = true
   377  
   378  	if ctxt.IsELF {
   379  		dsu := ctxt.loader.MakeSymbolUpdater(ctxt.DynStr)
   380  		if dsu.Size() == 0 {
   381  			dsu.Addstring("")
   382  		}
   383  		du := ctxt.loader.MakeSymbolUpdater(ctxt.Dynamic)
   384  		Elfwritedynent(ctxt.Arch, du, elf.DT_NEEDED, uint64(dsu.Addstring(lib)))
   385  	} else {
   386  		Errorf("adddynlib: unsupported binary format")
   387  	}
   388  }
   389  
   390  func Adddynsym(ldr *loader.Loader, target *Target, syms *ArchSyms, s loader.Sym) {
   391  	if ldr.SymDynid(s) >= 0 || target.LinkMode == LinkExternal {
   392  		return
   393  	}
   394  
   395  	if target.IsELF {
   396  		elfadddynsym(ldr, target, syms, s)
   397  	} else if target.HeadType == objabi.Hdarwin {
   398  		ldr.Errorf(s, "adddynsym: missed symbol (Extname=%s)", ldr.SymExtname(s))
   399  	} else if target.HeadType == objabi.Hwindows {
   400  		// already taken care of
   401  	} else {
   402  		ldr.Errorf(s, "adddynsym: unsupported binary format")
   403  	}
   404  }
   405  
   406  func fieldtrack(arch *sys.Arch, l *loader.Loader) {
   407  	var buf strings.Builder
   408  	for i := loader.Sym(1); i < loader.Sym(l.NSym()); i++ {
   409  		if name := l.SymName(i); strings.HasPrefix(name, "go:track.") {
   410  			if l.AttrReachable(i) {
   411  				l.SetAttrSpecial(i, true)
   412  				l.SetAttrNotInSymbolTable(i, true)
   413  				buf.WriteString(name[9:])
   414  				for p := l.Reachparent[i]; p != 0; p = l.Reachparent[p] {
   415  					buf.WriteString("\t")
   416  					buf.WriteString(l.SymName(p))
   417  				}
   418  				buf.WriteString("\n")
   419  			}
   420  		}
   421  	}
   422  	l.Reachparent = nil // we are done with it
   423  	if *flagFieldTrack == "" {
   424  		return
   425  	}
   426  	s := l.Lookup(*flagFieldTrack, 0)
   427  	if s == 0 || !l.AttrReachable(s) {
   428  		return
   429  	}
   430  	bld := l.MakeSymbolUpdater(s)
   431  	bld.SetType(sym.SDATA)
   432  	addstrdata(arch, l, *flagFieldTrack, buf.String())
   433  }
   434  
   435  func (ctxt *Link) addexport() {
   436  	// Track undefined external symbols during external link.
   437  	if ctxt.LinkMode == LinkExternal {
   438  		for _, s := range ctxt.Textp {
   439  			if ctxt.loader.AttrSpecial(s) || ctxt.loader.AttrSubSymbol(s) {
   440  				continue
   441  			}
   442  			relocs := ctxt.loader.Relocs(s)
   443  			for i := 0; i < relocs.Count(); i++ {
   444  				if rs := relocs.At(i).Sym(); rs != 0 {
   445  					if ctxt.loader.SymType(rs) == sym.Sxxx && !ctxt.loader.AttrLocal(rs) {
   446  						// sanity check
   447  						if len(ctxt.loader.Data(rs)) != 0 {
   448  							panic("expected no data on undef symbol")
   449  						}
   450  						su := ctxt.loader.MakeSymbolUpdater(rs)
   451  						su.SetType(sym.SUNDEFEXT)
   452  					}
   453  				}
   454  			}
   455  		}
   456  	}
   457  
   458  	// TODO(aix)
   459  	if ctxt.HeadType == objabi.Hdarwin || ctxt.HeadType == objabi.Haix {
   460  		return
   461  	}
   462  
   463  	// Add dynamic symbols.
   464  	for _, s := range ctxt.dynexp {
   465  		// Consistency check.
   466  		if !ctxt.loader.AttrReachable(s) {
   467  			panic("dynexp entry not reachable")
   468  		}
   469  
   470  		Adddynsym(ctxt.loader, &ctxt.Target, &ctxt.ArchSyms, s)
   471  	}
   472  
   473  	for _, lib := range dedupLibraries(ctxt, dynlib) {
   474  		adddynlib(ctxt, lib)
   475  	}
   476  }
   477  

View as plain text