...
Run Format

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

Documentation: cmd/link/internal/ld

     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  	"bytes"
    11  	"cmd/internal/bio"
    12  	"cmd/internal/objabi"
    13  	"cmd/link/internal/sym"
    14  	"encoding/json"
    15  	"fmt"
    16  	"io"
    17  	"os"
    18  	"strings"
    19  )
    20  
    21  // go-specific code shared across loaders (5l, 6l, 8l).
    22  
    23  // replace all "". with pkg.
    24  func expandpkg(t0 string, pkg string) string {
    25  	return strings.Replace(t0, `"".`, pkg+".", -1)
    26  }
    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  		if *flagU {
    41  			errorexit()
    42  		}
    43  		return
    44  	}
    45  
    46  	bdata := make([]byte, length)
    47  	if _, err := io.ReadFull(f, bdata); err != nil {
    48  		fmt.Fprintf(os.Stderr, "%s: short pkg read %s\n", os.Args[0], filename)
    49  		if *flagU {
    50  			errorexit()
    51  		}
    52  		return
    53  	}
    54  	data := string(bdata)
    55  
    56  	// process header lines
    57  	for data != "" {
    58  		var line string
    59  		if i := strings.Index(data, "\n"); i >= 0 {
    60  			line, data = data[:i], data[i+1:]
    61  		} else {
    62  			line, data = data, ""
    63  		}
    64  		if line == "safe" {
    65  			lib.Safe = true
    66  		}
    67  		if line == "main" {
    68  			lib.Main = true
    69  		}
    70  		if line == "" {
    71  			break
    72  		}
    73  	}
    74  
    75  	// look for cgo section
    76  	p0 := strings.Index(data, "\n$$  // cgo")
    77  	var p1 int
    78  	if p0 >= 0 {
    79  		p0 += p1
    80  		i := strings.IndexByte(data[p0+1:], '\n')
    81  		if i < 0 {
    82  			fmt.Fprintf(os.Stderr, "%s: found $$ // cgo but no newline in %s\n", os.Args[0], filename)
    83  			if *flagU {
    84  				errorexit()
    85  			}
    86  			return
    87  		}
    88  		p0 += 1 + i
    89  
    90  		p1 = strings.Index(data[p0:], "\n$$")
    91  		if p1 < 0 {
    92  			p1 = strings.Index(data[p0:], "\n!\n")
    93  		}
    94  		if p1 < 0 {
    95  			fmt.Fprintf(os.Stderr, "%s: cannot find end of // cgo section in %s\n", os.Args[0], filename)
    96  			if *flagU {
    97  				errorexit()
    98  			}
    99  			return
   100  		}
   101  		p1 += p0
   102  
   103  		loadcgo(ctxt, filename, objabi.PathToPrefix(lib.Pkg), data[p0:p1])
   104  	}
   105  }
   106  
   107  func loadcgo(ctxt *Link, file string, pkg string, p string) {
   108  	var directives [][]string
   109  	if err := json.NewDecoder(strings.NewReader(p)).Decode(&directives); err != nil {
   110  		fmt.Fprintf(os.Stderr, "%s: %s: failed decoding cgo directives: %v\n", os.Args[0], file, err)
   111  		nerrors++
   112  		return
   113  	}
   114  
   115  	for _, f := range directives {
   116  		switch f[0] {
   117  		case "cgo_import_dynamic":
   118  			if len(f) < 2 || len(f) > 4 {
   119  				break
   120  			}
   121  
   122  			local := f[1]
   123  			remote := local
   124  			if len(f) > 2 {
   125  				remote = f[2]
   126  			}
   127  			lib := ""
   128  			if len(f) > 3 {
   129  				lib = f[3]
   130  			}
   131  
   132  			if *FlagD {
   133  				fmt.Fprintf(os.Stderr, "%s: %s: cannot use dynamic imports with -d flag\n", os.Args[0], file)
   134  				nerrors++
   135  				return
   136  			}
   137  
   138  			if local == "_" && remote == "_" {
   139  				// allow #pragma dynimport _ _ "foo.so"
   140  				// to force a link of foo.so.
   141  				havedynamic = 1
   142  
   143  				if ctxt.HeadType == objabi.Hdarwin {
   144  					machoadddynlib(lib, ctxt.LinkMode)
   145  				} else {
   146  					dynlib = append(dynlib, lib)
   147  				}
   148  				continue
   149  			}
   150  
   151  			local = expandpkg(local, pkg)
   152  			q := ""
   153  			if i := strings.Index(remote, "#"); i >= 0 {
   154  				remote, q = remote[:i], remote[i+1:]
   155  			}
   156  			s := ctxt.Syms.Lookup(local, 0)
   157  			if s.Type == 0 || s.Type == sym.SXREF || s.Type == sym.SHOSTOBJ {
   158  				s.SetDynimplib(lib)
   159  				s.Extname = remote
   160  				s.SetDynimpvers(q)
   161  				if s.Type != sym.SHOSTOBJ {
   162  					s.Type = sym.SDYNIMPORT
   163  				}
   164  				havedynamic = 1
   165  			}
   166  			continue
   167  
   168  		case "cgo_import_static":
   169  			if len(f) != 2 {
   170  				break
   171  			}
   172  			local := f[1]
   173  
   174  			s := ctxt.Syms.Lookup(local, 0)
   175  			s.Type = sym.SHOSTOBJ
   176  			s.Size = 0
   177  			continue
   178  
   179  		case "cgo_export_static", "cgo_export_dynamic":
   180  			if len(f) < 2 || len(f) > 3 {
   181  				break
   182  			}
   183  			local := f[1]
   184  			remote := local
   185  			if len(f) > 2 {
   186  				remote = f[2]
   187  			}
   188  			local = expandpkg(local, pkg)
   189  
   190  			s := ctxt.Syms.Lookup(local, 0)
   191  
   192  			switch ctxt.BuildMode {
   193  			case BuildModeCShared, BuildModeCArchive, BuildModePlugin:
   194  				if s == ctxt.Syms.Lookup("main", 0) {
   195  					continue
   196  				}
   197  			}
   198  
   199  			// export overrides import, for openbsd/cgo.
   200  			// see issue 4878.
   201  			if s.Dynimplib() != "" {
   202  				s.ResetDyninfo()
   203  				s.Extname = ""
   204  				s.Type = 0
   205  			}
   206  
   207  			if !s.Attr.CgoExport() {
   208  				s.Extname = remote
   209  				dynexp = append(dynexp, s)
   210  			} else if s.Extname != remote {
   211  				fmt.Fprintf(os.Stderr, "%s: conflicting cgo_export directives: %s as %s and %s\n", os.Args[0], s.Name, s.Extname, remote)
   212  				nerrors++
   213  				return
   214  			}
   215  
   216  			if f[0] == "cgo_export_static" {
   217  				s.Attr |= sym.AttrCgoExportStatic
   218  			} else {
   219  				s.Attr |= sym.AttrCgoExportDynamic
   220  			}
   221  			continue
   222  
   223  		case "cgo_dynamic_linker":
   224  			if len(f) != 2 {
   225  				break
   226  			}
   227  
   228  			if *flagInterpreter == "" {
   229  				if interpreter != "" && interpreter != f[1] {
   230  					fmt.Fprintf(os.Stderr, "%s: conflict dynlinker: %s and %s\n", os.Args[0], interpreter, f[1])
   231  					nerrors++
   232  					return
   233  				}
   234  
   235  				interpreter = f[1]
   236  			}
   237  			continue
   238  
   239  		case "cgo_ldflag":
   240  			if len(f) != 2 {
   241  				break
   242  			}
   243  			ldflag = append(ldflag, f[1])
   244  			continue
   245  		}
   246  
   247  		fmt.Fprintf(os.Stderr, "%s: %s: invalid cgo directive: %q\n", os.Args[0], file, f)
   248  		nerrors++
   249  	}
   250  }
   251  
   252  var seenlib = make(map[string]bool)
   253  
   254  func adddynlib(ctxt *Link, lib string) {
   255  	if seenlib[lib] || ctxt.LinkMode == LinkExternal {
   256  		return
   257  	}
   258  	seenlib[lib] = true
   259  
   260  	if ctxt.IsELF {
   261  		s := ctxt.Syms.Lookup(".dynstr", 0)
   262  		if s.Size == 0 {
   263  			Addstring(s, "")
   264  		}
   265  		Elfwritedynent(ctxt, ctxt.Syms.Lookup(".dynamic", 0), DT_NEEDED, uint64(Addstring(s, lib)))
   266  	} else {
   267  		Errorf(nil, "adddynlib: unsupported binary format")
   268  	}
   269  }
   270  
   271  func Adddynsym(ctxt *Link, s *sym.Symbol) {
   272  	if s.Dynid >= 0 || ctxt.LinkMode == LinkExternal {
   273  		return
   274  	}
   275  
   276  	if ctxt.IsELF {
   277  		elfadddynsym(ctxt, s)
   278  	} else if ctxt.HeadType == objabi.Hdarwin {
   279  		Errorf(s, "adddynsym: missed symbol (Extname=%s)", s.Extname)
   280  	} else if ctxt.HeadType == objabi.Hwindows {
   281  		// already taken care of
   282  	} else {
   283  		Errorf(s, "adddynsym: unsupported binary format")
   284  	}
   285  }
   286  
   287  func fieldtrack(ctxt *Link) {
   288  	// record field tracking references
   289  	var buf bytes.Buffer
   290  	for _, s := range ctxt.Syms.Allsym {
   291  		if strings.HasPrefix(s.Name, "go.track.") {
   292  			s.Attr |= sym.AttrSpecial // do not lay out in data segment
   293  			s.Attr |= sym.AttrNotInSymbolTable
   294  			if s.Attr.Reachable() {
   295  				buf.WriteString(s.Name[9:])
   296  				for p := ctxt.Reachparent[s]; p != nil; p = ctxt.Reachparent[p] {
   297  					buf.WriteString("\t")
   298  					buf.WriteString(p.Name)
   299  				}
   300  				buf.WriteString("\n")
   301  			}
   302  
   303  			s.Type = sym.SCONST
   304  			s.Value = 0
   305  		}
   306  	}
   307  
   308  	if *flagFieldTrack == "" {
   309  		return
   310  	}
   311  	s := ctxt.Syms.ROLookup(*flagFieldTrack, 0)
   312  	if s == nil || !s.Attr.Reachable() {
   313  		return
   314  	}
   315  	s.Type = sym.SDATA
   316  	addstrdata(ctxt, *flagFieldTrack, buf.String())
   317  }
   318  
   319  func (ctxt *Link) addexport() {
   320  	if ctxt.HeadType == objabi.Hdarwin {
   321  		return
   322  	}
   323  
   324  	for _, exp := range dynexp {
   325  		Adddynsym(ctxt, exp)
   326  	}
   327  	for _, lib := range dynlib {
   328  		adddynlib(ctxt, lib)
   329  	}
   330  }
   331  
   332  type Pkg struct {
   333  	mark    bool
   334  	checked bool
   335  	path    string
   336  	impby   []*Pkg
   337  }
   338  
   339  var pkgall []*Pkg
   340  
   341  func (p *Pkg) cycle() *Pkg {
   342  	if p.checked {
   343  		return nil
   344  	}
   345  
   346  	if p.mark {
   347  		nerrors++
   348  		fmt.Printf("import cycle:\n")
   349  		fmt.Printf("\t%s\n", p.path)
   350  		return p
   351  	}
   352  
   353  	p.mark = true
   354  	for _, q := range p.impby {
   355  		if bad := q.cycle(); bad != nil {
   356  			p.mark = false
   357  			p.checked = true
   358  			fmt.Printf("\timports %s\n", p.path)
   359  			if bad == p {
   360  				return nil
   361  			}
   362  			return bad
   363  		}
   364  	}
   365  
   366  	p.checked = true
   367  	p.mark = false
   368  	return nil
   369  }
   370  
   371  func importcycles() {
   372  	for _, p := range pkgall {
   373  		p.cycle()
   374  	}
   375  }
   376  

View as plain text