...
Run Format

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

Documentation: cmd/link/internal/ld

     1  // Derived from Inferno utils/6l/obj.c and utils/6l/span.c
     2  // https://bitbucket.org/inferno-os/inferno-os/src/default/utils/6l/obj.c
     3  // https://bitbucket.org/inferno-os/inferno-os/src/default/utils/6l/span.c
     4  //
     5  //	Copyright © 1994-1999 Lucent Technologies Inc.  All rights reserved.
     6  //	Portions Copyright © 1995-1997 C H Forsyth (forsyth@terzarima.net)
     7  //	Portions Copyright © 1997-1999 Vita Nuova Limited
     8  //	Portions Copyright © 2000-2007 Vita Nuova Holdings Limited (www.vitanuova.com)
     9  //	Portions Copyright © 2004,2006 Bruce Ellis
    10  //	Portions Copyright © 2005-2007 C H Forsyth (forsyth@terzarima.net)
    11  //	Revisions Copyright © 2000-2007 Lucent Technologies Inc. and others
    12  //	Portions Copyright © 2009 The Go Authors. All rights reserved.
    13  //
    14  // Permission is hereby granted, free of charge, to any person obtaining a copy
    15  // of this software and associated documentation files (the "Software"), to deal
    16  // in the Software without restriction, including without limitation the rights
    17  // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    18  // copies of the Software, and to permit persons to whom the Software is
    19  // furnished to do so, subject to the following conditions:
    20  //
    21  // The above copyright notice and this permission notice shall be included in
    22  // all copies or substantial portions of the Software.
    23  //
    24  // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    25  // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    26  // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
    27  // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    28  // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    29  // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    30  // THE SOFTWARE.
    31  
    32  package ld
    33  
    34  import (
    35  	"bytes"
    36  	"cmd/internal/gcprog"
    37  	"cmd/internal/objabi"
    38  	"cmd/internal/sys"
    39  	"cmd/link/internal/sym"
    40  	"compress/zlib"
    41  	"encoding/binary"
    42  	"fmt"
    43  	"log"
    44  	"os"
    45  	"sort"
    46  	"strconv"
    47  	"strings"
    48  	"sync"
    49  )
    50  
    51  // isRuntimeDepPkg returns whether pkg is the runtime package or its dependency
    52  func isRuntimeDepPkg(pkg string) bool {
    53  	switch pkg {
    54  	case "runtime",
    55  		"sync/atomic",      // runtime may call to sync/atomic, due to go:linkname
    56  		"internal/bytealg", // for IndexByte
    57  		"internal/cpu":     // for cpu features
    58  		return true
    59  	}
    60  	return strings.HasPrefix(pkg, "runtime/internal/") && !strings.HasSuffix(pkg, "_test")
    61  }
    62  
    63  // Estimate the max size needed to hold any new trampolines created for this function. This
    64  // is used to determine when the section can be split if it becomes too large, to ensure that
    65  // the trampolines are in the same section as the function that uses them.
    66  func maxSizeTrampolinesPPC64(s *sym.Symbol, isTramp bool) uint64 {
    67  	// If thearch.Trampoline is nil, then trampoline support is not available on this arch.
    68  	// A trampoline does not need any dependent trampolines.
    69  	if thearch.Trampoline == nil || isTramp {
    70  		return 0
    71  	}
    72  
    73  	n := uint64(0)
    74  	for ri := range s.R {
    75  		r := &s.R[ri]
    76  		if r.Type.IsDirectJump() {
    77  			n++
    78  		}
    79  	}
    80  	// Trampolines in ppc64 are 4 instructions.
    81  	return n * 16
    82  }
    83  
    84  // detect too-far jumps in function s, and add trampolines if necessary
    85  // ARM, PPC64 & PPC64LE support trampoline insertion for internal and external linking
    86  // On PPC64 & PPC64LE the text sections might be split but will still insert trampolines
    87  // where necessary.
    88  func trampoline(ctxt *Link, s *sym.Symbol) {
    89  	if thearch.Trampoline == nil {
    90  		return // no need or no support of trampolines on this arch
    91  	}
    92  
    93  	for ri := range s.R {
    94  		r := &s.R[ri]
    95  		if !r.Type.IsDirectJump() {
    96  			continue
    97  		}
    98  		if Symaddr(r.Sym) == 0 && r.Sym.Type != sym.SDYNIMPORT {
    99  			if r.Sym.File != s.File {
   100  				if !isRuntimeDepPkg(s.File) || !isRuntimeDepPkg(r.Sym.File) {
   101  					ctxt.ErrorUnresolved(s, r)
   102  				}
   103  				// runtime and its dependent packages may call to each other.
   104  				// they are fine, as they will be laid down together.
   105  			}
   106  			continue
   107  		}
   108  
   109  		thearch.Trampoline(ctxt, r, s)
   110  	}
   111  
   112  }
   113  
   114  // resolve relocations in s.
   115  func relocsym(ctxt *Link, s *sym.Symbol) {
   116  	for ri := int32(0); ri < int32(len(s.R)); ri++ {
   117  		r := &s.R[ri]
   118  		if r.Done {
   119  			// Relocation already processed by an earlier phase.
   120  			continue
   121  		}
   122  		r.Done = true
   123  		off := r.Off
   124  		siz := int32(r.Siz)
   125  		if off < 0 || off+siz > int32(len(s.P)) {
   126  			rname := ""
   127  			if r.Sym != nil {
   128  				rname = r.Sym.Name
   129  			}
   130  			Errorf(s, "invalid relocation %s: %d+%d not in [%d,%d)", rname, off, siz, 0, len(s.P))
   131  			continue
   132  		}
   133  
   134  		if r.Sym != nil && ((r.Sym.Type == sym.Sxxx && !r.Sym.Attr.VisibilityHidden()) || r.Sym.Type == sym.SXREF) {
   135  			// When putting the runtime but not main into a shared library
   136  			// these symbols are undefined and that's OK.
   137  			if ctxt.BuildMode == BuildModeShared {
   138  				if r.Sym.Name == "main.main" || r.Sym.Name == "main.init" {
   139  					r.Sym.Type = sym.SDYNIMPORT
   140  				} else if strings.HasPrefix(r.Sym.Name, "go.info.") {
   141  					// Skip go.info symbols. They are only needed to communicate
   142  					// DWARF info between the compiler and linker.
   143  					continue
   144  				}
   145  			} else {
   146  				ctxt.ErrorUnresolved(s, r)
   147  				continue
   148  			}
   149  		}
   150  
   151  		if r.Type >= 256 {
   152  			continue
   153  		}
   154  		if r.Siz == 0 { // informational relocation - no work to do
   155  			continue
   156  		}
   157  		if r.Type == objabi.R_DWARFFILEREF {
   158  			// These should have been processed previously during
   159  			// line table writing.
   160  			Errorf(s, "orphan R_DWARFFILEREF reloc to %v", r.Sym.Name)
   161  			continue
   162  		}
   163  
   164  		// We need to be able to reference dynimport symbols when linking against
   165  		// shared libraries, and Solaris and Darwin need it always
   166  		if ctxt.HeadType != objabi.Hsolaris && ctxt.HeadType != objabi.Hdarwin && r.Sym != nil && r.Sym.Type == sym.SDYNIMPORT && !ctxt.DynlinkingGo() && !r.Sym.Attr.SubSymbol() {
   167  			if !(ctxt.Arch.Family == sys.PPC64 && ctxt.LinkMode == LinkExternal && r.Sym.Name == ".TOC.") {
   168  				Errorf(s, "unhandled relocation for %s (type %d (%s) rtype %d (%s))", r.Sym.Name, r.Sym.Type, r.Sym.Type, r.Type, sym.RelocName(ctxt.Arch, r.Type))
   169  			}
   170  		}
   171  		if r.Sym != nil && r.Sym.Type != sym.STLSBSS && r.Type != objabi.R_WEAKADDROFF && !r.Sym.Attr.Reachable() {
   172  			Errorf(s, "unreachable sym in relocation: %s", r.Sym.Name)
   173  		}
   174  
   175  		// TODO(mundaym): remove this special case - see issue 14218.
   176  		if ctxt.Arch.Family == sys.S390X {
   177  			switch r.Type {
   178  			case objabi.R_PCRELDBL:
   179  				r.Type = objabi.R_PCREL
   180  				r.Variant = sym.RV_390_DBL
   181  			case objabi.R_CALL:
   182  				r.Variant = sym.RV_390_DBL
   183  			}
   184  		}
   185  
   186  		var o int64
   187  		switch r.Type {
   188  		default:
   189  			switch siz {
   190  			default:
   191  				Errorf(s, "bad reloc size %#x for %s", uint32(siz), r.Sym.Name)
   192  			case 1:
   193  				o = int64(s.P[off])
   194  			case 2:
   195  				o = int64(ctxt.Arch.ByteOrder.Uint16(s.P[off:]))
   196  			case 4:
   197  				o = int64(ctxt.Arch.ByteOrder.Uint32(s.P[off:]))
   198  			case 8:
   199  				o = int64(ctxt.Arch.ByteOrder.Uint64(s.P[off:]))
   200  			}
   201  			if !thearch.Archreloc(ctxt, r, s, &o) {
   202  				Errorf(s, "unknown reloc to %v: %d (%s)", r.Sym.Name, r.Type, sym.RelocName(ctxt.Arch, r.Type))
   203  			}
   204  		case objabi.R_TLS_LE:
   205  			isAndroidX86 := objabi.GOOS == "android" && (ctxt.Arch.InFamily(sys.AMD64, sys.I386))
   206  
   207  			if ctxt.LinkMode == LinkExternal && ctxt.IsELF && !isAndroidX86 {
   208  				r.Done = false
   209  				if r.Sym == nil {
   210  					r.Sym = ctxt.Tlsg
   211  				}
   212  				r.Xsym = r.Sym
   213  				r.Xadd = r.Add
   214  				o = 0
   215  				if ctxt.Arch.Family != sys.AMD64 {
   216  					o = r.Add
   217  				}
   218  				break
   219  			}
   220  
   221  			if ctxt.IsELF && ctxt.Arch.Family == sys.ARM {
   222  				// On ELF ARM, the thread pointer is 8 bytes before
   223  				// the start of the thread-local data block, so add 8
   224  				// to the actual TLS offset (r->sym->value).
   225  				// This 8 seems to be a fundamental constant of
   226  				// ELF on ARM (or maybe Glibc on ARM); it is not
   227  				// related to the fact that our own TLS storage happens
   228  				// to take up 8 bytes.
   229  				o = 8 + r.Sym.Value
   230  			} else if ctxt.IsELF || ctxt.HeadType == objabi.Hplan9 || ctxt.HeadType == objabi.Hdarwin || isAndroidX86 {
   231  				o = int64(ctxt.Tlsoffset) + r.Add
   232  			} else if ctxt.HeadType == objabi.Hwindows {
   233  				o = r.Add
   234  			} else {
   235  				log.Fatalf("unexpected R_TLS_LE relocation for %v", ctxt.HeadType)
   236  			}
   237  		case objabi.R_TLS_IE:
   238  			isAndroidX86 := objabi.GOOS == "android" && (ctxt.Arch.InFamily(sys.AMD64, sys.I386))
   239  
   240  			if ctxt.LinkMode == LinkExternal && ctxt.IsELF && !isAndroidX86 {
   241  				r.Done = false
   242  				if r.Sym == nil {
   243  					r.Sym = ctxt.Tlsg
   244  				}
   245  				r.Xsym = r.Sym
   246  				r.Xadd = r.Add
   247  				o = 0
   248  				if ctxt.Arch.Family != sys.AMD64 {
   249  					o = r.Add
   250  				}
   251  				break
   252  			}
   253  			if ctxt.BuildMode == BuildModePIE && ctxt.IsELF {
   254  				// We are linking the final executable, so we
   255  				// can optimize any TLS IE relocation to LE.
   256  				if thearch.TLSIEtoLE == nil {
   257  					log.Fatalf("internal linking of TLS IE not supported on %v", ctxt.Arch.Family)
   258  				}
   259  				thearch.TLSIEtoLE(s, int(off), int(r.Siz))
   260  				o = int64(ctxt.Tlsoffset)
   261  				// TODO: o += r.Add when ctxt.Arch.Family != sys.AMD64?
   262  				// Why do we treat r.Add differently on AMD64?
   263  				// Is the external linker using Xadd at all?
   264  			} else {
   265  				log.Fatalf("cannot handle R_TLS_IE (sym %s) when linking internally", s.Name)
   266  			}
   267  		case objabi.R_ADDR:
   268  			if ctxt.LinkMode == LinkExternal && r.Sym.Type != sym.SCONST {
   269  				r.Done = false
   270  
   271  				// set up addend for eventual relocation via outer symbol.
   272  				rs := r.Sym
   273  
   274  				r.Xadd = r.Add
   275  				for rs.Outer != nil {
   276  					r.Xadd += Symaddr(rs) - Symaddr(rs.Outer)
   277  					rs = rs.Outer
   278  				}
   279  
   280  				if rs.Type != sym.SHOSTOBJ && rs.Type != sym.SDYNIMPORT && rs.Sect == nil {
   281  					Errorf(s, "missing section for relocation target %s", rs.Name)
   282  				}
   283  				r.Xsym = rs
   284  
   285  				o = r.Xadd
   286  				if ctxt.IsELF {
   287  					if ctxt.Arch.Family == sys.AMD64 {
   288  						o = 0
   289  					}
   290  				} else if ctxt.HeadType == objabi.Hdarwin {
   291  					if rs.Type != sym.SHOSTOBJ {
   292  						o += Symaddr(rs)
   293  					}
   294  				} else if ctxt.HeadType == objabi.Hwindows {
   295  					// nothing to do
   296  				} else {
   297  					Errorf(s, "unhandled pcrel relocation to %s on %v", rs.Name, ctxt.HeadType)
   298  				}
   299  
   300  				break
   301  			}
   302  
   303  			o = Symaddr(r.Sym) + r.Add
   304  
   305  			// On amd64, 4-byte offsets will be sign-extended, so it is impossible to
   306  			// access more than 2GB of static data; fail at link time is better than
   307  			// fail at runtime. See https://golang.org/issue/7980.
   308  			// Instead of special casing only amd64, we treat this as an error on all
   309  			// 64-bit architectures so as to be future-proof.
   310  			if int32(o) < 0 && ctxt.Arch.PtrSize > 4 && siz == 4 {
   311  				Errorf(s, "non-pc-relative relocation address for %s is too big: %#x (%#x + %#x)", r.Sym.Name, uint64(o), Symaddr(r.Sym), r.Add)
   312  				errorexit()
   313  			}
   314  		case objabi.R_DWARFSECREF:
   315  			if r.Sym.Sect == nil {
   316  				Errorf(s, "missing DWARF section for relocation target %s", r.Sym.Name)
   317  			}
   318  
   319  			if ctxt.LinkMode == LinkExternal {
   320  				r.Done = false
   321  
   322  				// On most platforms, the external linker needs to adjust DWARF references
   323  				// as it combines DWARF sections. However, on Darwin, dsymutil does the
   324  				// DWARF linking, and it understands how to follow section offsets.
   325  				// Leaving in the relocation records confuses it (see
   326  				// https://golang.org/issue/22068) so drop them for Darwin.
   327  				if ctxt.HeadType == objabi.Hdarwin {
   328  					r.Done = true
   329  				}
   330  
   331  				// PE code emits IMAGE_REL_I386_SECREL and IMAGE_REL_AMD64_SECREL
   332  				// for R_DWARFSECREF relocations, while R_ADDR is replaced with
   333  				// IMAGE_REL_I386_DIR32, IMAGE_REL_AMD64_ADDR64 and IMAGE_REL_AMD64_ADDR32.
   334  				// Do not replace R_DWARFSECREF with R_ADDR for windows -
   335  				// let PE code emit correct relocations.
   336  				if ctxt.HeadType != objabi.Hwindows {
   337  					r.Type = objabi.R_ADDR
   338  				}
   339  
   340  				r.Xsym = ctxt.Syms.ROLookup(r.Sym.Sect.Name, 0)
   341  				r.Xadd = r.Add + Symaddr(r.Sym) - int64(r.Sym.Sect.Vaddr)
   342  
   343  				o = r.Xadd
   344  				if ctxt.IsELF && ctxt.Arch.Family == sys.AMD64 {
   345  					o = 0
   346  				}
   347  				break
   348  			}
   349  			o = Symaddr(r.Sym) + r.Add - int64(r.Sym.Sect.Vaddr)
   350  		case objabi.R_WEAKADDROFF:
   351  			if !r.Sym.Attr.Reachable() {
   352  				continue
   353  			}
   354  			fallthrough
   355  		case objabi.R_ADDROFF:
   356  			// The method offset tables using this relocation expect the offset to be relative
   357  			// to the start of the first text section, even if there are multiple.
   358  			if r.Sym.Sect.Name == ".text" {
   359  				o = Symaddr(r.Sym) - int64(Segtext.Sections[0].Vaddr) + r.Add
   360  			} else {
   361  				o = Symaddr(r.Sym) - int64(r.Sym.Sect.Vaddr) + r.Add
   362  			}
   363  
   364  		case objabi.R_ADDRCUOFF:
   365  			// debug_range and debug_loc elements use this relocation type to get an
   366  			// offset from the start of the compile unit.
   367  			o = Symaddr(r.Sym) + r.Add - Symaddr(r.Sym.Lib.Textp[0])
   368  
   369  			// r->sym can be null when CALL $(constant) is transformed from absolute PC to relative PC call.
   370  		case objabi.R_GOTPCREL:
   371  			if ctxt.DynlinkingGo() && ctxt.HeadType == objabi.Hdarwin && r.Sym != nil && r.Sym.Type != sym.SCONST {
   372  				r.Done = false
   373  				r.Xadd = r.Add
   374  				r.Xadd -= int64(r.Siz) // relative to address after the relocated chunk
   375  				r.Xsym = r.Sym
   376  
   377  				o = r.Xadd
   378  				o += int64(r.Siz)
   379  				break
   380  			}
   381  			fallthrough
   382  		case objabi.R_CALL, objabi.R_PCREL:
   383  			if ctxt.LinkMode == LinkExternal && r.Sym != nil && r.Sym.Type != sym.SCONST && (r.Sym.Sect != s.Sect || r.Type == objabi.R_GOTPCREL) {
   384  				r.Done = false
   385  
   386  				// set up addend for eventual relocation via outer symbol.
   387  				rs := r.Sym
   388  
   389  				r.Xadd = r.Add
   390  				for rs.Outer != nil {
   391  					r.Xadd += Symaddr(rs) - Symaddr(rs.Outer)
   392  					rs = rs.Outer
   393  				}
   394  
   395  				r.Xadd -= int64(r.Siz) // relative to address after the relocated chunk
   396  				if rs.Type != sym.SHOSTOBJ && rs.Type != sym.SDYNIMPORT && rs.Sect == nil {
   397  					Errorf(s, "missing section for relocation target %s", rs.Name)
   398  				}
   399  				r.Xsym = rs
   400  
   401  				o = r.Xadd
   402  				if ctxt.IsELF {
   403  					if ctxt.Arch.Family == sys.AMD64 {
   404  						o = 0
   405  					}
   406  				} else if ctxt.HeadType == objabi.Hdarwin {
   407  					if r.Type == objabi.R_CALL {
   408  						if ctxt.LinkMode == LinkExternal && rs.Type == sym.SDYNIMPORT {
   409  							switch ctxt.Arch.Family {
   410  							case sys.AMD64:
   411  								// AMD64 dynamic relocations are relative to the end of the relocation.
   412  								o += int64(r.Siz)
   413  							case sys.I386:
   414  								// I386 dynamic relocations are relative to the start of the section.
   415  								o -= int64(r.Off)                         // offset in symbol
   416  								o -= int64(s.Value - int64(s.Sect.Vaddr)) // offset of symbol in section
   417  							}
   418  						} else {
   419  							if rs.Type != sym.SHOSTOBJ {
   420  								o += int64(uint64(Symaddr(rs)) - rs.Sect.Vaddr)
   421  							}
   422  							o -= int64(r.Off) // relative to section offset, not symbol
   423  						}
   424  					} else if ctxt.Arch.Family == sys.ARM {
   425  						// see ../arm/asm.go:/machoreloc1
   426  						o += Symaddr(rs) - s.Value - int64(r.Off)
   427  					} else {
   428  						o += int64(r.Siz)
   429  					}
   430  				} else if ctxt.HeadType == objabi.Hwindows && ctxt.Arch.Family == sys.AMD64 { // only amd64 needs PCREL
   431  					// PE/COFF's PC32 relocation uses the address after the relocated
   432  					// bytes as the base. Compensate by skewing the addend.
   433  					o += int64(r.Siz)
   434  				} else {
   435  					Errorf(s, "unhandled pcrel relocation to %s on %v", rs.Name, ctxt.HeadType)
   436  				}
   437  
   438  				break
   439  			}
   440  
   441  			o = 0
   442  			if r.Sym != nil {
   443  				o += Symaddr(r.Sym)
   444  			}
   445  
   446  			o += r.Add - (s.Value + int64(r.Off) + int64(r.Siz))
   447  		case objabi.R_SIZE:
   448  			o = r.Sym.Size + r.Add
   449  		}
   450  
   451  		if r.Variant != sym.RV_NONE {
   452  			o = thearch.Archrelocvariant(ctxt, r, s, o)
   453  		}
   454  
   455  		if false {
   456  			nam := "<nil>"
   457  			var addr int64
   458  			if r.Sym != nil {
   459  				nam = r.Sym.Name
   460  				addr = Symaddr(r.Sym)
   461  			}
   462  			xnam := "<nil>"
   463  			if r.Xsym != nil {
   464  				xnam = r.Xsym.Name
   465  			}
   466  			fmt.Printf("relocate %s %#x (%#x+%#x, size %d) => %s %#x +%#x (xsym: %s +%#x) [type %d (%s)/%d, %x]\n", s.Name, s.Value+int64(off), s.Value, r.Off, r.Siz, nam, addr, r.Add, xnam, r.Xadd, r.Type, sym.RelocName(ctxt.Arch, r.Type), r.Variant, o)
   467  		}
   468  		switch siz {
   469  		default:
   470  			Errorf(s, "bad reloc size %#x for %s", uint32(siz), r.Sym.Name)
   471  			fallthrough
   472  
   473  			// TODO(rsc): Remove.
   474  		case 1:
   475  			s.P[off] = byte(int8(o))
   476  		case 2:
   477  			if o != int64(int16(o)) {
   478  				Errorf(s, "relocation address for %s is too big: %#x", r.Sym.Name, o)
   479  			}
   480  			i16 := int16(o)
   481  			ctxt.Arch.ByteOrder.PutUint16(s.P[off:], uint16(i16))
   482  		case 4:
   483  			if r.Type == objabi.R_PCREL || r.Type == objabi.R_CALL {
   484  				if o != int64(int32(o)) {
   485  					Errorf(s, "pc-relative relocation address for %s is too big: %#x", r.Sym.Name, o)
   486  				}
   487  			} else {
   488  				if o != int64(int32(o)) && o != int64(uint32(o)) {
   489  					Errorf(s, "non-pc-relative relocation address for %s is too big: %#x", r.Sym.Name, uint64(o))
   490  				}
   491  			}
   492  
   493  			fl := int32(o)
   494  			ctxt.Arch.ByteOrder.PutUint32(s.P[off:], uint32(fl))
   495  		case 8:
   496  			ctxt.Arch.ByteOrder.PutUint64(s.P[off:], uint64(o))
   497  		}
   498  	}
   499  }
   500  
   501  func (ctxt *Link) reloc() {
   502  	if ctxt.Debugvlog != 0 {
   503  		ctxt.Logf("%5.2f reloc\n", Cputime())
   504  	}
   505  
   506  	for _, s := range ctxt.Textp {
   507  		relocsym(ctxt, s)
   508  	}
   509  	for _, s := range datap {
   510  		relocsym(ctxt, s)
   511  	}
   512  	for _, s := range dwarfp {
   513  		relocsym(ctxt, s)
   514  	}
   515  }
   516  
   517  func windynrelocsym(ctxt *Link, s *sym.Symbol) {
   518  	rel := ctxt.Syms.Lookup(".rel", 0)
   519  	if s == rel {
   520  		return
   521  	}
   522  	for ri := range s.R {
   523  		r := &s.R[ri]
   524  		targ := r.Sym
   525  		if targ == nil {
   526  			continue
   527  		}
   528  		if !targ.Attr.Reachable() {
   529  			if r.Type == objabi.R_WEAKADDROFF {
   530  				continue
   531  			}
   532  			Errorf(s, "dynamic relocation to unreachable symbol %s", targ.Name)
   533  		}
   534  		if r.Sym.Plt == -2 && r.Sym.Got != -2 { // make dynimport JMP table for PE object files.
   535  			targ.Plt = int32(rel.Size)
   536  			r.Sym = rel
   537  			r.Add = int64(targ.Plt)
   538  
   539  			// jmp *addr
   540  			if ctxt.Arch.Family == sys.I386 {
   541  				rel.AddUint8(0xff)
   542  				rel.AddUint8(0x25)
   543  				rel.AddAddr(ctxt.Arch, targ)
   544  				rel.AddUint8(0x90)
   545  				rel.AddUint8(0x90)
   546  			} else {
   547  				rel.AddUint8(0xff)
   548  				rel.AddUint8(0x24)
   549  				rel.AddUint8(0x25)
   550  				rel.AddAddrPlus4(targ, 0)
   551  				rel.AddUint8(0x90)
   552  			}
   553  		} else if r.Sym.Plt >= 0 {
   554  			r.Sym = rel
   555  			r.Add = int64(targ.Plt)
   556  		}
   557  	}
   558  }
   559  
   560  func dynrelocsym(ctxt *Link, s *sym.Symbol) {
   561  	if ctxt.HeadType == objabi.Hwindows {
   562  		if ctxt.LinkMode == LinkInternal {
   563  			windynrelocsym(ctxt, s)
   564  		}
   565  		return
   566  	}
   567  
   568  	for ri := range s.R {
   569  		r := &s.R[ri]
   570  		if ctxt.BuildMode == BuildModePIE && ctxt.LinkMode == LinkInternal {
   571  			// It's expected that some relocations will be done
   572  			// later by relocsym (R_TLS_LE, R_ADDROFF), so
   573  			// don't worry if Adddynrel returns false.
   574  			thearch.Adddynrel(ctxt, s, r)
   575  			continue
   576  		}
   577  		if r.Sym != nil && r.Sym.Type == sym.SDYNIMPORT || r.Type >= 256 {
   578  			if r.Sym != nil && !r.Sym.Attr.Reachable() {
   579  				Errorf(s, "dynamic relocation to unreachable symbol %s", r.Sym.Name)
   580  			}
   581  			if !thearch.Adddynrel(ctxt, s, r) {
   582  				Errorf(s, "unsupported dynamic relocation for symbol %s (type=%d (%s) stype=%d (%s))", r.Sym.Name, r.Type, sym.RelocName(ctxt.Arch, r.Type), r.Sym.Type, r.Sym.Type)
   583  			}
   584  		}
   585  	}
   586  }
   587  
   588  func dynreloc(ctxt *Link, data *[sym.SXREF][]*sym.Symbol) {
   589  	// -d suppresses dynamic loader format, so we may as well not
   590  	// compute these sections or mark their symbols as reachable.
   591  	if *FlagD && ctxt.HeadType != objabi.Hwindows {
   592  		return
   593  	}
   594  	if ctxt.Debugvlog != 0 {
   595  		ctxt.Logf("%5.2f dynreloc\n", Cputime())
   596  	}
   597  
   598  	for _, s := range ctxt.Textp {
   599  		dynrelocsym(ctxt, s)
   600  	}
   601  	for _, syms := range data {
   602  		for _, s := range syms {
   603  			dynrelocsym(ctxt, s)
   604  		}
   605  	}
   606  	if ctxt.IsELF {
   607  		elfdynhash(ctxt)
   608  	}
   609  }
   610  
   611  func Codeblk(ctxt *Link, addr int64, size int64) {
   612  	CodeblkPad(ctxt, addr, size, zeros[:])
   613  }
   614  func CodeblkPad(ctxt *Link, addr int64, size int64, pad []byte) {
   615  	if *flagA {
   616  		ctxt.Logf("codeblk [%#x,%#x) at offset %#x\n", addr, addr+size, ctxt.Out.Offset())
   617  	}
   618  
   619  	blk(ctxt, ctxt.Textp, addr, size, pad)
   620  
   621  	/* again for printing */
   622  	if !*flagA {
   623  		return
   624  	}
   625  
   626  	syms := ctxt.Textp
   627  	for i, s := range syms {
   628  		if !s.Attr.Reachable() {
   629  			continue
   630  		}
   631  		if s.Value >= addr {
   632  			syms = syms[i:]
   633  			break
   634  		}
   635  	}
   636  
   637  	eaddr := addr + size
   638  	for _, s := range syms {
   639  		if !s.Attr.Reachable() {
   640  			continue
   641  		}
   642  		if s.Value >= eaddr {
   643  			break
   644  		}
   645  
   646  		if addr < s.Value {
   647  			ctxt.Logf("%-20s %.8x|", "_", uint64(addr))
   648  			for ; addr < s.Value; addr++ {
   649  				ctxt.Logf(" %.2x", 0)
   650  			}
   651  			ctxt.Logf("\n")
   652  		}
   653  
   654  		ctxt.Logf("%.6x\t%-20s\n", uint64(addr), s.Name)
   655  		q := s.P
   656  
   657  		for len(q) >= 16 {
   658  			ctxt.Logf("%.6x\t% x\n", uint64(addr), q[:16])
   659  			addr += 16
   660  			q = q[16:]
   661  		}
   662  
   663  		if len(q) > 0 {
   664  			ctxt.Logf("%.6x\t% x\n", uint64(addr), q)
   665  			addr += int64(len(q))
   666  		}
   667  	}
   668  
   669  	if addr < eaddr {
   670  		ctxt.Logf("%-20s %.8x|", "_", uint64(addr))
   671  		for ; addr < eaddr; addr++ {
   672  			ctxt.Logf(" %.2x", 0)
   673  		}
   674  	}
   675  }
   676  
   677  func blk(ctxt *Link, syms []*sym.Symbol, addr, size int64, pad []byte) {
   678  	for i, s := range syms {
   679  		if !s.Attr.SubSymbol() && s.Value >= addr {
   680  			syms = syms[i:]
   681  			break
   682  		}
   683  	}
   684  
   685  	// This doesn't distinguish the memory size from the file
   686  	// size, and it lays out the file based on Symbol.Value, which
   687  	// is the virtual address. DWARF compression changes file sizes,
   688  	// so dwarfcompress will fix this up later if necessary.
   689  	eaddr := addr + size
   690  	for _, s := range syms {
   691  		if s.Attr.SubSymbol() {
   692  			continue
   693  		}
   694  		if s.Value >= eaddr {
   695  			break
   696  		}
   697  		if s.Value < addr {
   698  			Errorf(s, "phase error: addr=%#x but sym=%#x type=%d", addr, s.Value, s.Type)
   699  			errorexit()
   700  		}
   701  		if addr < s.Value {
   702  			ctxt.Out.WriteStringPad("", int(s.Value-addr), pad)
   703  			addr = s.Value
   704  		}
   705  		ctxt.Out.Write(s.P)
   706  		addr += int64(len(s.P))
   707  		if addr < s.Value+s.Size {
   708  			ctxt.Out.WriteStringPad("", int(s.Value+s.Size-addr), pad)
   709  			addr = s.Value + s.Size
   710  		}
   711  		if addr != s.Value+s.Size {
   712  			Errorf(s, "phase error: addr=%#x value+size=%#x", addr, s.Value+s.Size)
   713  			errorexit()
   714  		}
   715  		if s.Value+s.Size >= eaddr {
   716  			break
   717  		}
   718  	}
   719  
   720  	if addr < eaddr {
   721  		ctxt.Out.WriteStringPad("", int(eaddr-addr), pad)
   722  	}
   723  	ctxt.Out.Flush()
   724  }
   725  
   726  func Datblk(ctxt *Link, addr int64, size int64) {
   727  	if *flagA {
   728  		ctxt.Logf("datblk [%#x,%#x) at offset %#x\n", addr, addr+size, ctxt.Out.Offset())
   729  	}
   730  
   731  	blk(ctxt, datap, addr, size, zeros[:])
   732  
   733  	/* again for printing */
   734  	if !*flagA {
   735  		return
   736  	}
   737  
   738  	syms := datap
   739  	for i, sym := range syms {
   740  		if sym.Value >= addr {
   741  			syms = syms[i:]
   742  			break
   743  		}
   744  	}
   745  
   746  	eaddr := addr + size
   747  	for _, sym := range syms {
   748  		if sym.Value >= eaddr {
   749  			break
   750  		}
   751  		if addr < sym.Value {
   752  			ctxt.Logf("\t%.8x| 00 ...\n", uint64(addr))
   753  			addr = sym.Value
   754  		}
   755  
   756  		ctxt.Logf("%s\n\t%.8x|", sym.Name, uint64(addr))
   757  		for i, b := range sym.P {
   758  			if i > 0 && i%16 == 0 {
   759  				ctxt.Logf("\n\t%.8x|", uint64(addr)+uint64(i))
   760  			}
   761  			ctxt.Logf(" %.2x", b)
   762  		}
   763  
   764  		addr += int64(len(sym.P))
   765  		for ; addr < sym.Value+sym.Size; addr++ {
   766  			ctxt.Logf(" %.2x", 0)
   767  		}
   768  		ctxt.Logf("\n")
   769  
   770  		if ctxt.LinkMode != LinkExternal {
   771  			continue
   772  		}
   773  		for _, r := range sym.R {
   774  			rsname := ""
   775  			if r.Sym != nil {
   776  				rsname = r.Sym.Name
   777  			}
   778  			typ := "?"
   779  			switch r.Type {
   780  			case objabi.R_ADDR:
   781  				typ = "addr"
   782  			case objabi.R_PCREL:
   783  				typ = "pcrel"
   784  			case objabi.R_CALL:
   785  				typ = "call"
   786  			}
   787  			ctxt.Logf("\treloc %.8x/%d %s %s+%#x [%#x]\n", uint(sym.Value+int64(r.Off)), r.Siz, typ, rsname, r.Add, r.Sym.Value+r.Add)
   788  		}
   789  	}
   790  
   791  	if addr < eaddr {
   792  		ctxt.Logf("\t%.8x| 00 ...\n", uint(addr))
   793  	}
   794  	ctxt.Logf("\t%.8x|\n", uint(eaddr))
   795  }
   796  
   797  func Dwarfblk(ctxt *Link, addr int64, size int64) {
   798  	if *flagA {
   799  		ctxt.Logf("dwarfblk [%#x,%#x) at offset %#x\n", addr, addr+size, ctxt.Out.Offset())
   800  	}
   801  
   802  	blk(ctxt, dwarfp, addr, size, zeros[:])
   803  }
   804  
   805  var zeros [512]byte
   806  
   807  var (
   808  	strdata  = make(map[string]string)
   809  	strnames []string
   810  )
   811  
   812  func addstrdata1(ctxt *Link, arg string) {
   813  	eq := strings.Index(arg, "=")
   814  	dot := strings.LastIndex(arg[:eq+1], ".")
   815  	if eq < 0 || dot < 0 {
   816  		Exitf("-X flag requires argument of the form importpath.name=value")
   817  	}
   818  	pkg := arg[:dot]
   819  	if ctxt.BuildMode == BuildModePlugin && pkg == "main" {
   820  		pkg = *flagPluginPath
   821  	}
   822  	pkg = objabi.PathToPrefix(pkg)
   823  	name := pkg + arg[dot:eq]
   824  	value := arg[eq+1:]
   825  	if _, ok := strdata[name]; !ok {
   826  		strnames = append(strnames, name)
   827  	}
   828  	strdata[name] = value
   829  }
   830  
   831  // addstrdata sets the initial value of the string variable name to value.
   832  func addstrdata(ctxt *Link, name, value string) {
   833  	s := ctxt.Syms.ROLookup(name, 0)
   834  	if s == nil || s.Gotype == nil {
   835  		// Not defined in the loaded packages.
   836  		return
   837  	}
   838  	if s.Gotype.Name != "type.string" {
   839  		Errorf(s, "cannot set with -X: not a var of type string (%s)", s.Gotype.Name)
   840  		return
   841  	}
   842  	if s.Type == sym.SBSS {
   843  		s.Type = sym.SDATA
   844  	}
   845  
   846  	p := fmt.Sprintf("%s.str", s.Name)
   847  	sp := ctxt.Syms.Lookup(p, 0)
   848  
   849  	Addstring(sp, value)
   850  	sp.Type = sym.SRODATA
   851  
   852  	s.Size = 0
   853  	s.P = s.P[:0]
   854  	s.R = s.R[:0]
   855  	reachable := s.Attr.Reachable()
   856  	s.AddAddr(ctxt.Arch, sp)
   857  	s.AddUint(ctxt.Arch, uint64(len(value)))
   858  
   859  	// addstring, addaddr, etc., mark the symbols as reachable.
   860  	// In this case that is not necessarily true, so stick to what
   861  	// we know before entering this function.
   862  	s.Attr.Set(sym.AttrReachable, reachable)
   863  
   864  	sp.Attr.Set(sym.AttrReachable, reachable)
   865  }
   866  
   867  func (ctxt *Link) dostrdata() {
   868  	for _, name := range strnames {
   869  		addstrdata(ctxt, name, strdata[name])
   870  	}
   871  }
   872  
   873  func Addstring(s *sym.Symbol, str string) int64 {
   874  	if s.Type == 0 {
   875  		s.Type = sym.SNOPTRDATA
   876  	}
   877  	s.Attr |= sym.AttrReachable
   878  	r := s.Size
   879  	if s.Name == ".shstrtab" {
   880  		elfsetstring(s, str, int(r))
   881  	}
   882  	s.P = append(s.P, str...)
   883  	s.P = append(s.P, 0)
   884  	s.Size = int64(len(s.P))
   885  	return r
   886  }
   887  
   888  // addgostring adds str, as a Go string value, to s. symname is the name of the
   889  // symbol used to define the string data and must be unique per linked object.
   890  func addgostring(ctxt *Link, s *sym.Symbol, symname, str string) {
   891  	sdata := ctxt.Syms.Lookup(symname, 0)
   892  	if sdata.Type != sym.Sxxx {
   893  		Errorf(s, "duplicate symname in addgostring: %s", symname)
   894  	}
   895  	sdata.Attr |= sym.AttrReachable
   896  	sdata.Attr |= sym.AttrLocal
   897  	sdata.Type = sym.SRODATA
   898  	sdata.Size = int64(len(str))
   899  	sdata.P = []byte(str)
   900  	s.AddAddr(ctxt.Arch, sdata)
   901  	s.AddUint(ctxt.Arch, uint64(len(str)))
   902  }
   903  
   904  func addinitarrdata(ctxt *Link, s *sym.Symbol) {
   905  	p := s.Name + ".ptr"
   906  	sp := ctxt.Syms.Lookup(p, 0)
   907  	sp.Type = sym.SINITARR
   908  	sp.Size = 0
   909  	sp.Attr |= sym.AttrDuplicateOK
   910  	sp.AddAddr(ctxt.Arch, s)
   911  }
   912  
   913  func dosymtype(ctxt *Link) {
   914  	switch ctxt.BuildMode {
   915  	case BuildModeCArchive, BuildModeCShared:
   916  		for _, s := range ctxt.Syms.Allsym {
   917  			// Create a new entry in the .init_array section that points to the
   918  			// library initializer function.
   919  			if s.Name == *flagEntrySymbol {
   920  				addinitarrdata(ctxt, s)
   921  			}
   922  		}
   923  	}
   924  }
   925  
   926  // symalign returns the required alignment for the given symbol s.
   927  func symalign(s *sym.Symbol) int32 {
   928  	min := int32(thearch.Minalign)
   929  	if s.Align >= min {
   930  		return s.Align
   931  	} else if s.Align != 0 {
   932  		return min
   933  	}
   934  	if strings.HasPrefix(s.Name, "go.string.") || strings.HasPrefix(s.Name, "type..namedata.") {
   935  		// String data is just bytes.
   936  		// If we align it, we waste a lot of space to padding.
   937  		return min
   938  	}
   939  	align := int32(thearch.Maxalign)
   940  	for int64(align) > s.Size && align > min {
   941  		align >>= 1
   942  	}
   943  	return align
   944  }
   945  
   946  func aligndatsize(datsize int64, s *sym.Symbol) int64 {
   947  	return Rnd(datsize, int64(symalign(s)))
   948  }
   949  
   950  const debugGCProg = false
   951  
   952  type GCProg struct {
   953  	ctxt *Link
   954  	sym  *sym.Symbol
   955  	w    gcprog.Writer
   956  }
   957  
   958  func (p *GCProg) Init(ctxt *Link, name string) {
   959  	p.ctxt = ctxt
   960  	p.sym = ctxt.Syms.Lookup(name, 0)
   961  	p.w.Init(p.writeByte(ctxt))
   962  	if debugGCProg {
   963  		fmt.Fprintf(os.Stderr, "ld: start GCProg %s\n", name)
   964  		p.w.Debug(os.Stderr)
   965  	}
   966  }
   967  
   968  func (p *GCProg) writeByte(ctxt *Link) func(x byte) {
   969  	return func(x byte) {
   970  		p.sym.AddUint8(x)
   971  	}
   972  }
   973  
   974  func (p *GCProg) End(size int64) {
   975  	p.w.ZeroUntil(size / int64(p.ctxt.Arch.PtrSize))
   976  	p.w.End()
   977  	if debugGCProg {
   978  		fmt.Fprintf(os.Stderr, "ld: end GCProg\n")
   979  	}
   980  }
   981  
   982  func (p *GCProg) AddSym(s *sym.Symbol) {
   983  	typ := s.Gotype
   984  	// Things without pointers should be in sym.SNOPTRDATA or sym.SNOPTRBSS;
   985  	// everything we see should have pointers and should therefore have a type.
   986  	if typ == nil {
   987  		switch s.Name {
   988  		case "runtime.data", "runtime.edata", "runtime.bss", "runtime.ebss":
   989  			// Ignore special symbols that are sometimes laid out
   990  			// as real symbols. See comment about dyld on darwin in
   991  			// the address function.
   992  			return
   993  		}
   994  		Errorf(s, "missing Go type information for global symbol: size %d", s.Size)
   995  		return
   996  	}
   997  
   998  	ptrsize := int64(p.ctxt.Arch.PtrSize)
   999  	nptr := decodetypePtrdata(p.ctxt.Arch, typ) / ptrsize
  1000  
  1001  	if debugGCProg {
  1002  		fmt.Fprintf(os.Stderr, "gcprog sym: %s at %d (ptr=%d+%d)\n", s.Name, s.Value, s.Value/ptrsize, nptr)
  1003  	}
  1004  
  1005  	if decodetypeUsegcprog(p.ctxt.Arch, typ) == 0 {
  1006  		// Copy pointers from mask into program.
  1007  		mask := decodetypeGcmask(p.ctxt, typ)
  1008  		for i := int64(0); i < nptr; i++ {
  1009  			if (mask[i/8]>>uint(i%8))&1 != 0 {
  1010  				p.w.Ptr(s.Value/ptrsize + i)
  1011  			}
  1012  		}
  1013  		return
  1014  	}
  1015  
  1016  	// Copy program.
  1017  	prog := decodetypeGcprog(p.ctxt, typ)
  1018  	p.w.ZeroUntil(s.Value / ptrsize)
  1019  	p.w.Append(prog[4:], nptr)
  1020  }
  1021  
  1022  // dataSortKey is used to sort a slice of data symbol *sym.Symbol pointers.
  1023  // The sort keys are kept inline to improve cache behavior while sorting.
  1024  type dataSortKey struct {
  1025  	size int64
  1026  	name string
  1027  	sym  *sym.Symbol
  1028  }
  1029  
  1030  type bySizeAndName []dataSortKey
  1031  
  1032  func (d bySizeAndName) Len() int      { return len(d) }
  1033  func (d bySizeAndName) Swap(i, j int) { d[i], d[j] = d[j], d[i] }
  1034  func (d bySizeAndName) Less(i, j int) bool {
  1035  	s1, s2 := d[i], d[j]
  1036  	if s1.size != s2.size {
  1037  		return s1.size < s2.size
  1038  	}
  1039  	return s1.name < s2.name
  1040  }
  1041  
  1042  // cutoff is the maximum data section size permitted by the linker
  1043  // (see issue #9862).
  1044  const cutoff = 2e9 // 2 GB (or so; looks better in errors than 2^31)
  1045  
  1046  func checkdatsize(ctxt *Link, datsize int64, symn sym.SymKind) {
  1047  	if datsize > cutoff {
  1048  		Errorf(nil, "too much data in section %v (over %v bytes)", symn, cutoff)
  1049  	}
  1050  }
  1051  
  1052  // datap is a collection of reachable data symbols in address order.
  1053  // Generated by dodata.
  1054  var datap []*sym.Symbol
  1055  
  1056  func (ctxt *Link) dodata() {
  1057  	if ctxt.Debugvlog != 0 {
  1058  		ctxt.Logf("%5.2f dodata\n", Cputime())
  1059  	}
  1060  
  1061  	if ctxt.DynlinkingGo() && ctxt.HeadType == objabi.Hdarwin {
  1062  		// The values in moduledata are filled out by relocations
  1063  		// pointing to the addresses of these special symbols.
  1064  		// Typically these symbols have no size and are not laid
  1065  		// out with their matching section.
  1066  		//
  1067  		// However on darwin, dyld will find the special symbol
  1068  		// in the first loaded module, even though it is local.
  1069  		//
  1070  		// (An hypothesis, formed without looking in the dyld sources:
  1071  		// these special symbols have no size, so their address
  1072  		// matches a real symbol. The dynamic linker assumes we
  1073  		// want the normal symbol with the same address and finds
  1074  		// it in the other module.)
  1075  		//
  1076  		// To work around this we lay out the symbls whose
  1077  		// addresses are vital for multi-module programs to work
  1078  		// as normal symbols, and give them a little size.
  1079  		bss := ctxt.Syms.Lookup("runtime.bss", 0)
  1080  		bss.Size = 8
  1081  		bss.Attr.Set(sym.AttrSpecial, false)
  1082  
  1083  		ctxt.Syms.Lookup("runtime.ebss", 0).Attr.Set(sym.AttrSpecial, false)
  1084  
  1085  		data := ctxt.Syms.Lookup("runtime.data", 0)
  1086  		data.Size = 8
  1087  		data.Attr.Set(sym.AttrSpecial, false)
  1088  
  1089  		ctxt.Syms.Lookup("runtime.edata", 0).Attr.Set(sym.AttrSpecial, false)
  1090  
  1091  		types := ctxt.Syms.Lookup("runtime.types", 0)
  1092  		types.Type = sym.STYPE
  1093  		types.Size = 8
  1094  		types.Attr.Set(sym.AttrSpecial, false)
  1095  
  1096  		etypes := ctxt.Syms.Lookup("runtime.etypes", 0)
  1097  		etypes.Type = sym.SFUNCTAB
  1098  		etypes.Attr.Set(sym.AttrSpecial, false)
  1099  	}
  1100  
  1101  	// Collect data symbols by type into data.
  1102  	var data [sym.SXREF][]*sym.Symbol
  1103  	for _, s := range ctxt.Syms.Allsym {
  1104  		if !s.Attr.Reachable() || s.Attr.Special() || s.Attr.SubSymbol() {
  1105  			continue
  1106  		}
  1107  		if s.Type <= sym.STEXT || s.Type >= sym.SXREF {
  1108  			continue
  1109  		}
  1110  		data[s.Type] = append(data[s.Type], s)
  1111  	}
  1112  
  1113  	// Now that we have the data symbols, but before we start
  1114  	// to assign addresses, record all the necessary
  1115  	// dynamic relocations. These will grow the relocation
  1116  	// symbol, which is itself data.
  1117  	//
  1118  	// On darwin, we need the symbol table numbers for dynreloc.
  1119  	if ctxt.HeadType == objabi.Hdarwin {
  1120  		machosymorder(ctxt)
  1121  	}
  1122  	dynreloc(ctxt, &data)
  1123  
  1124  	if ctxt.UseRelro() {
  1125  		// "read only" data with relocations needs to go in its own section
  1126  		// when building a shared library. We do this by boosting objects of
  1127  		// type SXXX with relocations to type SXXXRELRO.
  1128  		for _, symnro := range sym.ReadOnly {
  1129  			symnrelro := sym.RelROMap[symnro]
  1130  
  1131  			ro := []*sym.Symbol{}
  1132  			relro := data[symnrelro]
  1133  
  1134  			for _, s := range data[symnro] {
  1135  				isRelro := len(s.R) > 0
  1136  				switch s.Type {
  1137  				case sym.STYPE, sym.STYPERELRO, sym.SGOFUNCRELRO:
  1138  					// Symbols are not sorted yet, so it is possible
  1139  					// that an Outer symbol has been changed to a
  1140  					// relro Type before it reaches here.
  1141  					isRelro = true
  1142  				}
  1143  				if isRelro {
  1144  					s.Type = symnrelro
  1145  					if s.Outer != nil {
  1146  						s.Outer.Type = s.Type
  1147  					}
  1148  					relro = append(relro, s)
  1149  				} else {
  1150  					ro = append(ro, s)
  1151  				}
  1152  			}
  1153  
  1154  			// Check that we haven't made two symbols with the same .Outer into
  1155  			// different types (because references two symbols with non-nil Outer
  1156  			// become references to the outer symbol + offset it's vital that the
  1157  			// symbol and the outer end up in the same section).
  1158  			for _, s := range relro {
  1159  				if s.Outer != nil && s.Outer.Type != s.Type {
  1160  					Errorf(s, "inconsistent types for symbol and its Outer %s (%v != %v)",
  1161  						s.Outer.Name, s.Type, s.Outer.Type)
  1162  				}
  1163  			}
  1164  
  1165  			data[symnro] = ro
  1166  			data[symnrelro] = relro
  1167  		}
  1168  	}
  1169  
  1170  	// Sort symbols.
  1171  	var dataMaxAlign [sym.SXREF]int32
  1172  	var wg sync.WaitGroup
  1173  	for symn := range data {
  1174  		symn := sym.SymKind(symn)
  1175  		wg.Add(1)
  1176  		go func() {
  1177  			data[symn], dataMaxAlign[symn] = dodataSect(ctxt, symn, data[symn])
  1178  			wg.Done()
  1179  		}()
  1180  	}
  1181  	wg.Wait()
  1182  
  1183  	// Allocate sections.
  1184  	// Data is processed before segtext, because we need
  1185  	// to see all symbols in the .data and .bss sections in order
  1186  	// to generate garbage collection information.
  1187  	datsize := int64(0)
  1188  
  1189  	// Writable data sections that do not need any specialized handling.
  1190  	writable := []sym.SymKind{
  1191  		sym.SELFSECT,
  1192  		sym.SMACHO,
  1193  		sym.SMACHOGOT,
  1194  		sym.SWINDOWS,
  1195  	}
  1196  	for _, symn := range writable {
  1197  		for _, s := range data[symn] {
  1198  			sect := addsection(ctxt.Arch, &Segdata, s.Name, 06)
  1199  			sect.Align = symalign(s)
  1200  			datsize = Rnd(datsize, int64(sect.Align))
  1201  			sect.Vaddr = uint64(datsize)
  1202  			s.Sect = sect
  1203  			s.Type = sym.SDATA
  1204  			s.Value = int64(uint64(datsize) - sect.Vaddr)
  1205  			datsize += s.Size
  1206  			sect.Length = uint64(datsize) - sect.Vaddr
  1207  		}
  1208  		checkdatsize(ctxt, datsize, symn)
  1209  	}
  1210  
  1211  	// .got (and .toc on ppc64)
  1212  	if len(data[sym.SELFGOT]) > 0 {
  1213  		sect := addsection(ctxt.Arch, &Segdata, ".got", 06)
  1214  		sect.Align = dataMaxAlign[sym.SELFGOT]
  1215  		datsize = Rnd(datsize, int64(sect.Align))
  1216  		sect.Vaddr = uint64(datsize)
  1217  		for _, s := range data[sym.SELFGOT] {
  1218  			datsize = aligndatsize(datsize, s)
  1219  			s.Sect = sect
  1220  			s.Type = sym.SDATA
  1221  			s.Value = int64(uint64(datsize) - sect.Vaddr)
  1222  
  1223  			// Resolve .TOC. symbol for this object file (ppc64)
  1224  			toc := ctxt.Syms.ROLookup(".TOC.", int(s.Version))
  1225  			if toc != nil {
  1226  				toc.Sect = sect
  1227  				toc.Outer = s
  1228  				toc.Sub = s.Sub
  1229  				s.Sub = toc
  1230  
  1231  				toc.Value = 0x8000
  1232  			}
  1233  
  1234  			datsize += s.Size
  1235  		}
  1236  		checkdatsize(ctxt, datsize, sym.SELFGOT)
  1237  		sect.Length = uint64(datsize) - sect.Vaddr
  1238  	}
  1239  
  1240  	/* pointer-free data */
  1241  	sect := addsection(ctxt.Arch, &Segdata, ".noptrdata", 06)
  1242  	sect.Align = dataMaxAlign[sym.SNOPTRDATA]
  1243  	datsize = Rnd(datsize, int64(sect.Align))
  1244  	sect.Vaddr = uint64(datsize)
  1245  	ctxt.Syms.Lookup("runtime.noptrdata", 0).Sect = sect
  1246  	ctxt.Syms.Lookup("runtime.enoptrdata", 0).Sect = sect
  1247  	for _, s := range data[sym.SNOPTRDATA] {
  1248  		datsize = aligndatsize(datsize, s)
  1249  		s.Sect = sect
  1250  		s.Type = sym.SDATA
  1251  		s.Value = int64(uint64(datsize) - sect.Vaddr)
  1252  		datsize += s.Size
  1253  	}
  1254  	checkdatsize(ctxt, datsize, sym.SNOPTRDATA)
  1255  	sect.Length = uint64(datsize) - sect.Vaddr
  1256  
  1257  	hasinitarr := ctxt.linkShared
  1258  
  1259  	/* shared library initializer */
  1260  	switch ctxt.BuildMode {
  1261  	case BuildModeCArchive, BuildModeCShared, BuildModeShared, BuildModePlugin:
  1262  		hasinitarr = true
  1263  	}
  1264  	if hasinitarr {
  1265  		sect := addsection(ctxt.Arch, &Segdata, ".init_array", 06)
  1266  		sect.Align = dataMaxAlign[sym.SINITARR]
  1267  		datsize = Rnd(datsize, int64(sect.Align))
  1268  		sect.Vaddr = uint64(datsize)
  1269  		for _, s := range data[sym.SINITARR] {
  1270  			datsize = aligndatsize(datsize, s)
  1271  			s.Sect = sect
  1272  			s.Value = int64(uint64(datsize) - sect.Vaddr)
  1273  			datsize += s.Size
  1274  		}
  1275  		sect.Length = uint64(datsize) - sect.Vaddr
  1276  		checkdatsize(ctxt, datsize, sym.SINITARR)
  1277  	}
  1278  
  1279  	/* data */
  1280  	sect = addsection(ctxt.Arch, &Segdata, ".data", 06)
  1281  	sect.Align = dataMaxAlign[sym.SDATA]
  1282  	datsize = Rnd(datsize, int64(sect.Align))
  1283  	sect.Vaddr = uint64(datsize)
  1284  	ctxt.Syms.Lookup("runtime.data", 0).Sect = sect
  1285  	ctxt.Syms.Lookup("runtime.edata", 0).Sect = sect
  1286  	var gc GCProg
  1287  	gc.Init(ctxt, "runtime.gcdata")
  1288  	for _, s := range data[sym.SDATA] {
  1289  		s.Sect = sect
  1290  		s.Type = sym.SDATA
  1291  		datsize = aligndatsize(datsize, s)
  1292  		s.Value = int64(uint64(datsize) - sect.Vaddr)
  1293  		gc.AddSym(s)
  1294  		datsize += s.Size
  1295  	}
  1296  	checkdatsize(ctxt, datsize, sym.SDATA)
  1297  	sect.Length = uint64(datsize) - sect.Vaddr
  1298  	gc.End(int64(sect.Length))
  1299  
  1300  	/* bss */
  1301  	sect = addsection(ctxt.Arch, &Segdata, ".bss", 06)
  1302  	sect.Align = dataMaxAlign[sym.SBSS]
  1303  	datsize = Rnd(datsize, int64(sect.Align))
  1304  	sect.Vaddr = uint64(datsize)
  1305  	ctxt.Syms.Lookup("runtime.bss", 0).Sect = sect
  1306  	ctxt.Syms.Lookup("runtime.ebss", 0).Sect = sect
  1307  	gc = GCProg{}
  1308  	gc.Init(ctxt, "runtime.gcbss")
  1309  	for _, s := range data[sym.SBSS] {
  1310  		s.Sect = sect
  1311  		datsize = aligndatsize(datsize, s)
  1312  		s.Value = int64(uint64(datsize) - sect.Vaddr)
  1313  		gc.AddSym(s)
  1314  		datsize += s.Size
  1315  	}
  1316  	checkdatsize(ctxt, datsize, sym.SBSS)
  1317  	sect.Length = uint64(datsize) - sect.Vaddr
  1318  	gc.End(int64(sect.Length))
  1319  
  1320  	/* pointer-free bss */
  1321  	sect = addsection(ctxt.Arch, &Segdata, ".noptrbss", 06)
  1322  	sect.Align = dataMaxAlign[sym.SNOPTRBSS]
  1323  	datsize = Rnd(datsize, int64(sect.Align))
  1324  	sect.Vaddr = uint64(datsize)
  1325  	ctxt.Syms.Lookup("runtime.noptrbss", 0).Sect = sect
  1326  	ctxt.Syms.Lookup("runtime.enoptrbss", 0).Sect = sect
  1327  	for _, s := range data[sym.SNOPTRBSS] {
  1328  		datsize = aligndatsize(datsize, s)
  1329  		s.Sect = sect
  1330  		s.Value = int64(uint64(datsize) - sect.Vaddr)
  1331  		datsize += s.Size
  1332  	}
  1333  
  1334  	sect.Length = uint64(datsize) - sect.Vaddr
  1335  	ctxt.Syms.Lookup("runtime.end", 0).Sect = sect
  1336  	checkdatsize(ctxt, datsize, sym.SNOPTRBSS)
  1337  
  1338  	if len(data[sym.STLSBSS]) > 0 {
  1339  		var sect *sym.Section
  1340  		if ctxt.IsELF && (ctxt.LinkMode == LinkExternal || !*FlagD) {
  1341  			sect = addsection(ctxt.Arch, &Segdata, ".tbss", 06)
  1342  			sect.Align = int32(ctxt.Arch.PtrSize)
  1343  			sect.Vaddr = 0
  1344  		}
  1345  		datsize = 0
  1346  
  1347  		for _, s := range data[sym.STLSBSS] {
  1348  			datsize = aligndatsize(datsize, s)
  1349  			s.Sect = sect
  1350  			s.Value = datsize
  1351  			datsize += s.Size
  1352  		}
  1353  		checkdatsize(ctxt, datsize, sym.STLSBSS)
  1354  
  1355  		if sect != nil {
  1356  			sect.Length = uint64(datsize)
  1357  		}
  1358  	}
  1359  
  1360  	/*
  1361  	 * We finished data, begin read-only data.
  1362  	 * Not all systems support a separate read-only non-executable data section.
  1363  	 * ELF and Windows PE systems do.
  1364  	 * OS X and Plan 9 do not.
  1365  	 * And if we're using external linking mode, the point is moot,
  1366  	 * since it's not our decision; that code expects the sections in
  1367  	 * segtext.
  1368  	 */
  1369  	var segro *sym.Segment
  1370  	if ctxt.IsELF && ctxt.LinkMode == LinkInternal {
  1371  		segro = &Segrodata
  1372  	} else if ctxt.HeadType == objabi.Hwindows {
  1373  		segro = &Segrodata
  1374  	} else {
  1375  		segro = &Segtext
  1376  	}
  1377  
  1378  	datsize = 0
  1379  
  1380  	/* read-only executable ELF, Mach-O sections */
  1381  	if len(data[sym.STEXT]) != 0 {
  1382  		Errorf(nil, "dodata found an sym.STEXT symbol: %s", data[sym.STEXT][0].Name)
  1383  	}
  1384  	for _, s := range data[sym.SELFRXSECT] {
  1385  		sect := addsection(ctxt.Arch, &Segtext, s.Name, 04)
  1386  		sect.Align = symalign(s)
  1387  		datsize = Rnd(datsize, int64(sect.Align))
  1388  		sect.Vaddr = uint64(datsize)
  1389  		s.Sect = sect
  1390  		s.Type = sym.SRODATA
  1391  		s.Value = int64(uint64(datsize) - sect.Vaddr)
  1392  		datsize += s.Size
  1393  		sect.Length = uint64(datsize) - sect.Vaddr
  1394  		checkdatsize(ctxt, datsize, sym.SELFRXSECT)
  1395  	}
  1396  
  1397  	/* read-only data */
  1398  	sect = addsection(ctxt.Arch, segro, ".rodata", 04)
  1399  
  1400  	sect.Vaddr = 0
  1401  	ctxt.Syms.Lookup("runtime.rodata", 0).Sect = sect
  1402  	ctxt.Syms.Lookup("runtime.erodata", 0).Sect = sect
  1403  	if !ctxt.UseRelro() {
  1404  		ctxt.Syms.Lookup("runtime.types", 0).Sect = sect
  1405  		ctxt.Syms.Lookup("runtime.etypes", 0).Sect = sect
  1406  	}
  1407  	for _, symn := range sym.ReadOnly {
  1408  		align := dataMaxAlign[symn]
  1409  		if sect.Align < align {
  1410  			sect.Align = align
  1411  		}
  1412  	}
  1413  	datsize = Rnd(datsize, int64(sect.Align))
  1414  	for _, symn := range sym.ReadOnly {
  1415  		for _, s := range data[symn] {
  1416  			datsize = aligndatsize(datsize, s)
  1417  			s.Sect = sect
  1418  			s.Type = sym.SRODATA
  1419  			s.Value = int64(uint64(datsize) - sect.Vaddr)
  1420  			datsize += s.Size
  1421  		}
  1422  		checkdatsize(ctxt, datsize, symn)
  1423  	}
  1424  	sect.Length = uint64(datsize) - sect.Vaddr
  1425  
  1426  	/* read-only ELF, Mach-O sections */
  1427  	for _, s := range data[sym.SELFROSECT] {
  1428  		sect = addsection(ctxt.Arch, segro, s.Name, 04)
  1429  		sect.Align = symalign(s)
  1430  		datsize = Rnd(datsize, int64(sect.Align))
  1431  		sect.Vaddr = uint64(datsize)
  1432  		s.Sect = sect
  1433  		s.Type = sym.SRODATA
  1434  		s.Value = int64(uint64(datsize) - sect.Vaddr)
  1435  		datsize += s.Size
  1436  		sect.Length = uint64(datsize) - sect.Vaddr
  1437  	}
  1438  	checkdatsize(ctxt, datsize, sym.SELFROSECT)
  1439  
  1440  	for _, s := range data[sym.SMACHOPLT] {
  1441  		sect = addsection(ctxt.Arch, segro, s.Name, 04)
  1442  		sect.Align = symalign(s)
  1443  		datsize = Rnd(datsize, int64(sect.Align))
  1444  		sect.Vaddr = uint64(datsize)
  1445  		s.Sect = sect
  1446  		s.Type = sym.SRODATA
  1447  		s.Value = int64(uint64(datsize) - sect.Vaddr)
  1448  		datsize += s.Size
  1449  		sect.Length = uint64(datsize) - sect.Vaddr
  1450  	}
  1451  	checkdatsize(ctxt, datsize, sym.SMACHOPLT)
  1452  
  1453  	// There is some data that are conceptually read-only but are written to by
  1454  	// relocations. On GNU systems, we can arrange for the dynamic linker to
  1455  	// mprotect sections after relocations are applied by giving them write
  1456  	// permissions in the object file and calling them ".data.rel.ro.FOO". We
  1457  	// divide the .rodata section between actual .rodata and .data.rel.ro.rodata,
  1458  	// but for the other sections that this applies to, we just write a read-only
  1459  	// .FOO section or a read-write .data.rel.ro.FOO section depending on the
  1460  	// situation.
  1461  	// TODO(mwhudson): It would make sense to do this more widely, but it makes
  1462  	// the system linker segfault on darwin.
  1463  	addrelrosection := func(suffix string) *sym.Section {
  1464  		return addsection(ctxt.Arch, segro, suffix, 04)
  1465  	}
  1466  
  1467  	if ctxt.UseRelro() {
  1468  		addrelrosection = func(suffix string) *sym.Section {
  1469  			seg := &Segrelrodata
  1470  			if ctxt.LinkMode == LinkExternal {
  1471  				// Using a separate segment with an external
  1472  				// linker results in some programs moving
  1473  				// their data sections unexpectedly, which
  1474  				// corrupts the moduledata. So we use the
  1475  				// rodata segment and let the external linker
  1476  				// sort out a rel.ro segment.
  1477  				seg = &Segrodata
  1478  			}
  1479  			return addsection(ctxt.Arch, seg, ".data.rel.ro"+suffix, 06)
  1480  		}
  1481  		/* data only written by relocations */
  1482  		sect = addrelrosection("")
  1483  
  1484  		sect.Vaddr = 0
  1485  		ctxt.Syms.Lookup("runtime.types", 0).Sect = sect
  1486  		ctxt.Syms.Lookup("runtime.etypes", 0).Sect = sect
  1487  		for _, symnro := range sym.ReadOnly {
  1488  			symn := sym.RelROMap[symnro]
  1489  			align := dataMaxAlign[symn]
  1490  			if sect.Align < align {
  1491  				sect.Align = align
  1492  			}
  1493  		}
  1494  		datsize = Rnd(datsize, int64(sect.Align))
  1495  		for _, symnro := range sym.ReadOnly {
  1496  			symn := sym.RelROMap[symnro]
  1497  			for _, s := range data[symn] {
  1498  				datsize = aligndatsize(datsize, s)
  1499  				if s.Outer != nil && s.Outer.Sect != nil && s.Outer.Sect != sect {
  1500  					Errorf(s, "s.Outer (%s) in different section from s, %s != %s", s.Outer.Name, s.Outer.Sect.Name, sect.Name)
  1501  				}
  1502  				s.Sect = sect
  1503  				s.Type = sym.SRODATA
  1504  				s.Value = int64(uint64(datsize) - sect.Vaddr)
  1505  				datsize += s.Size
  1506  			}
  1507  			checkdatsize(ctxt, datsize, symn)
  1508  		}
  1509  
  1510  		sect.Length = uint64(datsize) - sect.Vaddr
  1511  	}
  1512  
  1513  	/* typelink */
  1514  	sect = addrelrosection(".typelink")
  1515  	sect.Align = dataMaxAlign[sym.STYPELINK]
  1516  	datsize = Rnd(datsize, int64(sect.Align))
  1517  	sect.Vaddr = uint64(datsize)
  1518  	typelink := ctxt.Syms.Lookup("runtime.typelink", 0)
  1519  	typelink.Sect = sect
  1520  	typelink.Type = sym.SRODATA
  1521  	datsize += typelink.Size
  1522  	checkdatsize(ctxt, datsize, sym.STYPELINK)
  1523  	sect.Length = uint64(datsize) - sect.Vaddr
  1524  
  1525  	/* itablink */
  1526  	sect = addrelrosection(".itablink")
  1527  	sect.Align = dataMaxAlign[sym.SITABLINK]
  1528  	datsize = Rnd(datsize, int64(sect.Align))
  1529  	sect.Vaddr = uint64(datsize)
  1530  	ctxt.Syms.Lookup("runtime.itablink", 0).Sect = sect
  1531  	ctxt.Syms.Lookup("runtime.eitablink", 0).Sect = sect
  1532  	for _, s := range data[sym.SITABLINK] {
  1533  		datsize = aligndatsize(datsize, s)
  1534  		s.Sect = sect
  1535  		s.Type = sym.SRODATA
  1536  		s.Value = int64(uint64(datsize) - sect.Vaddr)
  1537  		datsize += s.Size
  1538  	}
  1539  	checkdatsize(ctxt, datsize, sym.SITABLINK)
  1540  	sect.Length = uint64(datsize) - sect.Vaddr
  1541  
  1542  	/* gosymtab */
  1543  	sect = addrelrosection(".gosymtab")
  1544  	sect.Align = dataMaxAlign[sym.SSYMTAB]
  1545  	datsize = Rnd(datsize, int64(sect.Align))
  1546  	sect.Vaddr = uint64(datsize)
  1547  	ctxt.Syms.Lookup("runtime.symtab", 0).Sect = sect
  1548  	ctxt.Syms.Lookup("runtime.esymtab", 0).Sect = sect
  1549  	for _, s := range data[sym.SSYMTAB] {
  1550  		datsize = aligndatsize(datsize, s)
  1551  		s.Sect = sect
  1552  		s.Type = sym.SRODATA
  1553  		s.Value = int64(uint64(datsize) - sect.Vaddr)
  1554  		datsize += s.Size
  1555  	}
  1556  	checkdatsize(ctxt, datsize, sym.SSYMTAB)
  1557  	sect.Length = uint64(datsize) - sect.Vaddr
  1558  
  1559  	/* gopclntab */
  1560  	sect = addrelrosection(".gopclntab")
  1561  	sect.Align = dataMaxAlign[sym.SPCLNTAB]
  1562  	datsize = Rnd(datsize, int64(sect.Align))
  1563  	sect.Vaddr = uint64(datsize)
  1564  	ctxt.Syms.Lookup("runtime.pclntab", 0).Sect = sect
  1565  	ctxt.Syms.Lookup("runtime.epclntab", 0).Sect = sect
  1566  	for _, s := range data[sym.SPCLNTAB] {
  1567  		datsize = aligndatsize(datsize, s)
  1568  		s.Sect = sect
  1569  		s.Type = sym.SRODATA
  1570  		s.Value = int64(uint64(datsize) - sect.Vaddr)
  1571  		datsize += s.Size
  1572  	}
  1573  	checkdatsize(ctxt, datsize, sym.SRODATA)
  1574  	sect.Length = uint64(datsize) - sect.Vaddr
  1575  
  1576  	// 6g uses 4-byte relocation offsets, so the entire segment must fit in 32 bits.
  1577  	if datsize != int64(uint32(datsize)) {
  1578  		Errorf(nil, "read-only data segment too large: %d", datsize)
  1579  	}
  1580  
  1581  	for symn := sym.SELFRXSECT; symn < sym.SXREF; symn++ {
  1582  		datap = append(datap, data[symn]...)
  1583  	}
  1584  
  1585  	dwarfgeneratedebugsyms(ctxt)
  1586  
  1587  	var i int
  1588  	for ; i < len(dwarfp); i++ {
  1589  		s := dwarfp[i]
  1590  		if s.Type != sym.SDWARFSECT {
  1591  			break
  1592  		}
  1593  
  1594  		sect = addsection(ctxt.Arch, &Segdwarf, s.Name, 04)
  1595  		sect.Align = 1
  1596  		datsize = Rnd(datsize, int64(sect.Align))
  1597  		sect.Vaddr = uint64(datsize)
  1598  		s.Sect = sect
  1599  		s.Type = sym.SRODATA
  1600  		s.Value = int64(uint64(datsize) - sect.Vaddr)
  1601  		datsize += s.Size
  1602  		sect.Length = uint64(datsize) - sect.Vaddr
  1603  	}
  1604  	checkdatsize(ctxt, datsize, sym.SDWARFSECT)
  1605  
  1606  	for i < len(dwarfp) {
  1607  		curType := dwarfp[i].Type
  1608  		var sect *sym.Section
  1609  		switch curType {
  1610  		case sym.SDWARFINFO:
  1611  			sect = addsection(ctxt.Arch, &Segdwarf, ".debug_info", 04)
  1612  		case sym.SDWARFRANGE:
  1613  			sect = addsection(ctxt.Arch, &Segdwarf, ".debug_ranges", 04)
  1614  		case sym.SDWARFLOC:
  1615  			sect = addsection(ctxt.Arch, &Segdwarf, ".debug_loc", 04)
  1616  		default:
  1617  			Errorf(dwarfp[i], "unknown DWARF section %v", curType)
  1618  		}
  1619  
  1620  		sect.Align = 1
  1621  		datsize = Rnd(datsize, int64(sect.Align))
  1622  		sect.Vaddr = uint64(datsize)
  1623  		for ; i < len(dwarfp); i++ {
  1624  			s := dwarfp[i]
  1625  			if s.Type != curType {
  1626  				break
  1627  			}
  1628  			s.Sect = sect
  1629  			s.Type = sym.SRODATA
  1630  			s.Value = int64(uint64(datsize) - sect.Vaddr)
  1631  			s.Attr |= sym.AttrLocal
  1632  			datsize += s.Size
  1633  		}
  1634  		sect.Length = uint64(datsize) - sect.Vaddr
  1635  		checkdatsize(ctxt, datsize, curType)
  1636  	}
  1637  
  1638  	/* number the sections */
  1639  	n := int32(1)
  1640  
  1641  	for _, sect := range Segtext.Sections {
  1642  		sect.Extnum = int16(n)
  1643  		n++
  1644  	}
  1645  	for _, sect := range Segrodata.Sections {
  1646  		sect.Extnum = int16(n)
  1647  		n++
  1648  	}
  1649  	for _, sect := range Segrelrodata.Sections {
  1650  		sect.Extnum = int16(n)
  1651  		n++
  1652  	}
  1653  	for _, sect := range Segdata.Sections {
  1654  		sect.Extnum = int16(n)
  1655  		n++
  1656  	}
  1657  	for _, sect := range Segdwarf.Sections {
  1658  		sect.Extnum = int16(n)
  1659  		n++
  1660  	}
  1661  }
  1662  
  1663  func dodataSect(ctxt *Link, symn sym.SymKind, syms []*sym.Symbol) (result []*sym.Symbol, maxAlign int32) {
  1664  	if ctxt.HeadType == objabi.Hdarwin {
  1665  		// Some symbols may no longer belong in syms
  1666  		// due to movement in machosymorder.
  1667  		newSyms := make([]*sym.Symbol, 0, len(syms))
  1668  		for _, s := range syms {
  1669  			if s.Type == symn {
  1670  				newSyms = append(newSyms, s)
  1671  			}
  1672  		}
  1673  		syms = newSyms
  1674  	}
  1675  
  1676  	var head, tail *sym.Symbol
  1677  	symsSort := make([]dataSortKey, 0, len(syms))
  1678  	for _, s := range syms {
  1679  		if s.Attr.OnList() {
  1680  			log.Fatalf("symbol %s listed multiple times", s.Name)
  1681  		}
  1682  		s.Attr |= sym.AttrOnList
  1683  		switch {
  1684  		case s.Size < int64(len(s.P)):
  1685  			Errorf(s, "initialize bounds (%d < %d)", s.Size, len(s.P))
  1686  		case s.Size < 0:
  1687  			Errorf(s, "negative size (%d bytes)", s.Size)
  1688  		case s.Size > cutoff:
  1689  			Errorf(s, "symbol too large (%d bytes)", s.Size)
  1690  		}
  1691  
  1692  		// If the usually-special section-marker symbols are being laid
  1693  		// out as regular symbols, put them either at the beginning or
  1694  		// end of their section.
  1695  		if ctxt.DynlinkingGo() && ctxt.HeadType == objabi.Hdarwin {
  1696  			switch s.Name {
  1697  			case "runtime.text", "runtime.bss", "runtime.data", "runtime.types":
  1698  				head = s
  1699  				continue
  1700  			case "runtime.etext", "runtime.ebss", "runtime.edata", "runtime.etypes":
  1701  				tail = s
  1702  				continue
  1703  			}
  1704  		}
  1705  
  1706  		key := dataSortKey{
  1707  			size: s.Size,
  1708  			name: s.Name,
  1709  			sym:  s,
  1710  		}
  1711  
  1712  		switch s.Type {
  1713  		case sym.SELFGOT:
  1714  			// For ppc64, we want to interleave the .got and .toc sections
  1715  			// from input files. Both are type sym.SELFGOT, so in that case
  1716  			// we skip size comparison and fall through to the name
  1717  			// comparison (conveniently, .got sorts before .toc).
  1718  			key.size = 0
  1719  		}
  1720  
  1721  		symsSort = append(symsSort, key)
  1722  	}
  1723  
  1724  	sort.Sort(bySizeAndName(symsSort))
  1725  
  1726  	off := 0
  1727  	if head != nil {
  1728  		syms[0] = head
  1729  		off++
  1730  	}
  1731  	for i, symSort := range symsSort {
  1732  		syms[i+off] = symSort.sym
  1733  		align := symalign(symSort.sym)
  1734  		if maxAlign < align {
  1735  			maxAlign = align
  1736  		}
  1737  	}
  1738  	if tail != nil {
  1739  		syms[len(syms)-1] = tail
  1740  	}
  1741  
  1742  	if ctxt.IsELF && symn == sym.SELFROSECT {
  1743  		// Make .rela and .rela.plt contiguous, the ELF ABI requires this
  1744  		// and Solaris actually cares.
  1745  		reli, plti := -1, -1
  1746  		for i, s := range syms {
  1747  			switch s.Name {
  1748  			case ".rel.plt", ".rela.plt":
  1749  				plti = i
  1750  			case ".rel", ".rela":
  1751  				reli = i
  1752  			}
  1753  		}
  1754  		if reli >= 0 && plti >= 0 && plti != reli+1 {
  1755  			var first, second int
  1756  			if plti > reli {
  1757  				first, second = reli, plti
  1758  			} else {
  1759  				first, second = plti, reli
  1760  			}
  1761  			rel, plt := syms[reli], syms[plti]
  1762  			copy(syms[first+2:], syms[first+1:second])
  1763  			syms[first+0] = rel
  1764  			syms[first+1] = plt
  1765  
  1766  			// Make sure alignment doesn't introduce a gap.
  1767  			// Setting the alignment explicitly prevents
  1768  			// symalign from basing it on the size and
  1769  			// getting it wrong.
  1770  			rel.Align = int32(ctxt.Arch.RegSize)
  1771  			plt.Align = int32(ctxt.Arch.RegSize)
  1772  		}
  1773  	}
  1774  
  1775  	return syms, maxAlign
  1776  }
  1777  
  1778  // Add buildid to beginning of text segment, on non-ELF systems.
  1779  // Non-ELF binary formats are not always flexible enough to
  1780  // give us a place to put the Go build ID. On those systems, we put it
  1781  // at the very beginning of the text segment.
  1782  // This ``header'' is read by cmd/go.
  1783  func (ctxt *Link) textbuildid() {
  1784  	if ctxt.IsELF || ctxt.BuildMode == BuildModePlugin || *flagBuildid == "" {
  1785  		return
  1786  	}
  1787  
  1788  	s := ctxt.Syms.Lookup("go.buildid", 0)
  1789  	s.Attr |= sym.AttrReachable
  1790  	// The \xff is invalid UTF-8, meant to make it less likely
  1791  	// to find one of these accidentally.
  1792  	data := "\xff Go build ID: " + strconv.Quote(*flagBuildid) + "\n \xff"
  1793  	s.Type = sym.STEXT
  1794  	s.P = []byte(data)
  1795  	s.Size = int64(len(s.P))
  1796  
  1797  	ctxt.Textp = append(ctxt.Textp, nil)
  1798  	copy(ctxt.Textp[1:], ctxt.Textp)
  1799  	ctxt.Textp[0] = s
  1800  }
  1801  
  1802  // assign addresses to text
  1803  func (ctxt *Link) textaddress() {
  1804  	addsection(ctxt.Arch, &Segtext, ".text", 05)
  1805  
  1806  	// Assign PCs in text segment.
  1807  	// Could parallelize, by assigning to text
  1808  	// and then letting threads copy down, but probably not worth it.
  1809  	sect := Segtext.Sections[0]
  1810  
  1811  	sect.Align = int32(Funcalign)
  1812  
  1813  	text := ctxt.Syms.Lookup("runtime.text", 0)
  1814  	text.Sect = sect
  1815  
  1816  	if ctxt.DynlinkingGo() && ctxt.HeadType == objabi.Hdarwin {
  1817  		etext := ctxt.Syms.Lookup("runtime.etext", 0)
  1818  		etext.Sect = sect
  1819  
  1820  		ctxt.Textp = append(ctxt.Textp, etext, nil)
  1821  		copy(ctxt.Textp[1:], ctxt.Textp)
  1822  		ctxt.Textp[0] = text
  1823  	}
  1824  
  1825  	va := uint64(*FlagTextAddr)
  1826  	n := 1
  1827  	sect.Vaddr = va
  1828  	ntramps := 0
  1829  	for _, s := range ctxt.Textp {
  1830  		sect, n, va = assignAddress(ctxt, sect, n, s, va, false)
  1831  
  1832  		trampoline(ctxt, s) // resolve jumps, may add trampolines if jump too far
  1833  
  1834  		// lay down trampolines after each function
  1835  		for ; ntramps < len(ctxt.tramps); ntramps++ {
  1836  			tramp := ctxt.tramps[ntramps]
  1837  			sect, n, va = assignAddress(ctxt, sect, n, tramp, va, true)
  1838  		}
  1839  	}
  1840  
  1841  	sect.Length = va - sect.Vaddr
  1842  	ctxt.Syms.Lookup("runtime.etext", 0).Sect = sect
  1843  
  1844  	// merge tramps into Textp, keeping Textp in address order
  1845  	if ntramps != 0 {
  1846  		newtextp := make([]*sym.Symbol, 0, len(ctxt.Textp)+ntramps)
  1847  		i := 0
  1848  		for _, s := range ctxt.Textp {
  1849  			for ; i < ntramps && ctxt.tramps[i].Value < s.Value; i++ {
  1850  				newtextp = append(newtextp, ctxt.tramps[i])
  1851  			}
  1852  			newtextp = append(newtextp, s)
  1853  		}
  1854  		newtextp = append(newtextp, ctxt.tramps[i:ntramps]...)
  1855  
  1856  		ctxt.Textp = newtextp
  1857  	}
  1858  }
  1859  
  1860  // assigns address for a text symbol, returns (possibly new) section, its number, and the address
  1861  // Note: once we have trampoline insertion support for external linking, this function
  1862  // will not need to create new text sections, and so no need to return sect and n.
  1863  func assignAddress(ctxt *Link, sect *sym.Section, n int, s *sym.Symbol, va uint64, isTramp bool) (*sym.Section, int, uint64) {
  1864  	if thearch.AssignAddress != nil {
  1865  		return thearch.AssignAddress(ctxt, sect, n, s, va, isTramp)
  1866  	}
  1867  
  1868  	s.Sect = sect
  1869  	if s.Attr.SubSymbol() {
  1870  		return sect, n, va
  1871  	}
  1872  	if s.Align != 0 {
  1873  		va = uint64(Rnd(int64(va), int64(s.Align)))
  1874  	} else {
  1875  		va = uint64(Rnd(int64(va), int64(Funcalign)))
  1876  	}
  1877  	s.Value = 0
  1878  	for sub := s; sub != nil; sub = sub.Sub {
  1879  		sub.Value += int64(va)
  1880  	}
  1881  
  1882  	funcsize := uint64(MINFUNC) // spacing required for findfunctab
  1883  	if s.Size > MINFUNC {
  1884  		funcsize = uint64(s.Size)
  1885  	}
  1886  
  1887  	// On ppc64x a text section should not be larger than 2^26 bytes due to the size of
  1888  	// call target offset field in the bl instruction.  Splitting into smaller text
  1889  	// sections smaller than this limit allows the GNU linker to modify the long calls
  1890  	// appropriately.  The limit allows for the space needed for tables inserted by the linker.
  1891  
  1892  	// If this function doesn't fit in the current text section, then create a new one.
  1893  
  1894  	// Only break at outermost syms.
  1895  
  1896  	if ctxt.Arch.InFamily(sys.PPC64) && s.Outer == nil && ctxt.IsELF && ctxt.LinkMode == LinkExternal && va-sect.Vaddr+funcsize+maxSizeTrampolinesPPC64(s, isTramp) > 0x1c00000 {
  1897  		// Set the length for the previous text section
  1898  		sect.Length = va - sect.Vaddr
  1899  
  1900  		// Create new section, set the starting Vaddr
  1901  		sect = addsection(ctxt.Arch, &Segtext, ".text", 05)
  1902  		sect.Vaddr = va
  1903  		s.Sect = sect
  1904  
  1905  		// Create a symbol for the start of the secondary text sections
  1906  		ctxt.Syms.Lookup(fmt.Sprintf("runtime.text.%d", n), 0).Sect = sect
  1907  		n++
  1908  	}
  1909  	va += funcsize
  1910  
  1911  	return sect, n, va
  1912  }
  1913  
  1914  // address assigns virtual addresses to all segments and sections and
  1915  // returns all segments in file order.
  1916  func (ctxt *Link) address() []*sym.Segment {
  1917  	var order []*sym.Segment // Layout order
  1918  
  1919  	va := uint64(*FlagTextAddr)
  1920  	order = append(order, &Segtext)
  1921  	Segtext.Rwx = 05
  1922  	Segtext.Vaddr = va
  1923  	for _, s := range Segtext.Sections {
  1924  		va = uint64(Rnd(int64(va), int64(s.Align)))
  1925  		s.Vaddr = va
  1926  		va += s.Length
  1927  	}
  1928  
  1929  	Segtext.Length = va - uint64(*FlagTextAddr)
  1930  	if ctxt.HeadType == objabi.Hnacl {
  1931  		va += 32 // room for the "halt sled"
  1932  	}
  1933  
  1934  	if len(Segrodata.Sections) > 0 {
  1935  		// align to page boundary so as not to mix
  1936  		// rodata and executable text.
  1937  		//
  1938  		// Note: gold or GNU ld will reduce the size of the executable
  1939  		// file by arranging for the relro segment to end at a page
  1940  		// boundary, and overlap the end of the text segment with the
  1941  		// start of the relro segment in the file.  The PT_LOAD segments
  1942  		// will be such that the last page of the text segment will be
  1943  		// mapped twice, once r-x and once starting out rw- and, after
  1944  		// relocation processing, changed to r--.
  1945  		//
  1946  		// Ideally the last page of the text segment would not be
  1947  		// writable even for this short period.
  1948  		va = uint64(Rnd(int64(va), int64(*FlagRound)))
  1949  
  1950  		order = append(order, &Segrodata)
  1951  		Segrodata.Rwx = 04
  1952  		Segrodata.Vaddr = va
  1953  		for _, s := range Segrodata.Sections {
  1954  			va = uint64(Rnd(int64(va), int64(s.Align)))
  1955  			s.Vaddr = va
  1956  			va += s.Length
  1957  		}
  1958  
  1959  		Segrodata.Length = va - Segrodata.Vaddr
  1960  	}
  1961  	if len(Segrelrodata.Sections) > 0 {
  1962  		// align to page boundary so as not to mix
  1963  		// rodata, rel-ro data, and executable text.
  1964  		va = uint64(Rnd(int64(va), int64(*FlagRound)))
  1965  
  1966  		order = append(order, &Segrelrodata)
  1967  		Segrelrodata.Rwx = 06
  1968  		Segrelrodata.Vaddr = va
  1969  		for _, s := range Segrelrodata.Sections {
  1970  			va = uint64(Rnd(int64(va), int64(s.Align)))
  1971  			s.Vaddr = va
  1972  			va += s.Length
  1973  		}
  1974  
  1975  		Segrelrodata.Length = va - Segrelrodata.Vaddr
  1976  	}
  1977  
  1978  	va = uint64(Rnd(int64(va), int64(*FlagRound)))
  1979  	order = append(order, &Segdata)
  1980  	Segdata.Rwx = 06
  1981  	Segdata.Vaddr = va
  1982  	var data *sym.Section
  1983  	var noptr *sym.Section
  1984  	var bss *sym.Section
  1985  	var noptrbss *sym.Section
  1986  	for i, s := range Segdata.Sections {
  1987  		if ctxt.IsELF && s.Name == ".tbss" {
  1988  			continue
  1989  		}
  1990  		vlen := int64(s.Length)
  1991  		if i+1 < len(Segdata.Sections) && !(ctxt.IsELF && Segdata.Sections[i+1].Name == ".tbss") {
  1992  			vlen = int64(Segdata.Sections[i+1].Vaddr - s.Vaddr)
  1993  		}
  1994  		s.Vaddr = va
  1995  		va += uint64(vlen)
  1996  		Segdata.Length = va - Segdata.Vaddr
  1997  		if s.Name == ".data" {
  1998  			data = s
  1999  		}
  2000  		if s.Name == ".noptrdata" {
  2001  			noptr = s
  2002  		}
  2003  		if s.Name == ".bss" {
  2004  			bss = s
  2005  		}
  2006  		if s.Name == ".noptrbss" {
  2007  			noptrbss = s
  2008  		}
  2009  	}
  2010  
  2011  	// Assign Segdata's Filelen omitting the BSS. We do this here
  2012  	// simply because right now we know where the BSS starts.
  2013  	Segdata.Filelen = bss.Vaddr - Segdata.Vaddr
  2014  
  2015  	va = uint64(Rnd(int64(va), int64(*FlagRound)))
  2016  	order = append(order, &Segdwarf)
  2017  	Segdwarf.Rwx = 06
  2018  	Segdwarf.Vaddr = va
  2019  	for i, s := range Segdwarf.Sections {
  2020  		vlen := int64(s.Length)
  2021  		if i+1 < len(Segdwarf.Sections) {
  2022  			vlen = int64(Segdwarf.Sections[i+1].Vaddr - s.Vaddr)
  2023  		}
  2024  		s.Vaddr = va
  2025  		va += uint64(vlen)
  2026  		if ctxt.HeadType == objabi.Hwindows {
  2027  			va = uint64(Rnd(int64(va), PEFILEALIGN))
  2028  		}
  2029  		Segdwarf.Length = va - Segdwarf.Vaddr
  2030  	}
  2031  
  2032  	var (
  2033  		text     = Segtext.Sections[0]
  2034  		rodata   = ctxt.Syms.Lookup("runtime.rodata", 0).Sect
  2035  		itablink = ctxt.Syms.Lookup("runtime.itablink", 0).Sect
  2036  		symtab   = ctxt.Syms.Lookup("runtime.symtab", 0).Sect
  2037  		pclntab  = ctxt.Syms.Lookup("runtime.pclntab", 0).Sect
  2038  		types    = ctxt.Syms.Lookup("runtime.types", 0).Sect
  2039  	)
  2040  	lasttext := text
  2041  	// Could be multiple .text sections
  2042  	for _, sect := range Segtext.Sections {
  2043  		if sect.Name == ".text" {
  2044  			lasttext = sect
  2045  		}
  2046  	}
  2047  
  2048  	for _, s := range datap {
  2049  		if s.Sect != nil {
  2050  			s.Value += int64(s.Sect.Vaddr)
  2051  		}
  2052  		for sub := s.Sub; sub != nil; sub = sub.Sub {
  2053  			sub.Value += s.Value
  2054  		}
  2055  	}
  2056  
  2057  	for _, s := range dwarfp {
  2058  		if s.Sect != nil {
  2059  			s.Value += int64(s.Sect.Vaddr)
  2060  		}
  2061  		for sub := s.Sub; sub != nil; sub = sub.Sub {
  2062  			sub.Value += s.Value
  2063  		}
  2064  	}
  2065  
  2066  	if ctxt.BuildMode == BuildModeShared {
  2067  		s := ctxt.Syms.Lookup("go.link.abihashbytes", 0)
  2068  		sectSym := ctxt.Syms.Lookup(".note.go.abihash", 0)
  2069  		s.Sect = sectSym.Sect
  2070  		s.Value = int64(sectSym.Sect.Vaddr + 16)
  2071  	}
  2072  
  2073  	ctxt.xdefine("runtime.text", sym.STEXT, int64(text.Vaddr))
  2074  	ctxt.xdefine("runtime.etext", sym.STEXT, int64(lasttext.Vaddr+lasttext.Length))
  2075  
  2076  	// If there are multiple text sections, create runtime.text.n for
  2077  	// their section Vaddr, using n for index
  2078  	n := 1
  2079  	for _, sect := range Segtext.Sections[1:] {
  2080  		if sect.Name != ".text" {
  2081  			break
  2082  		}
  2083  		symname := fmt.Sprintf("runtime.text.%d", n)
  2084  		ctxt.xdefine(symname, sym.STEXT, int64(sect.Vaddr))
  2085  		n++
  2086  	}
  2087  
  2088  	ctxt.xdefine("runtime.rodata", sym.SRODATA, int64(rodata.Vaddr))
  2089  	ctxt.xdefine("runtime.erodata", sym.SRODATA, int64(rodata.Vaddr+rodata.Length))
  2090  	ctxt.xdefine("runtime.types", sym.SRODATA, int64(types.Vaddr))
  2091  	ctxt.xdefine("runtime.etypes", sym.SRODATA, int64(types.Vaddr+types.Length))
  2092  	ctxt.xdefine("runtime.itablink", sym.SRODATA, int64(itablink.Vaddr))
  2093  	ctxt.xdefine("runtime.eitablink", sym.SRODATA, int64(itablink.Vaddr+itablink.Length))
  2094  
  2095  	s := ctxt.Syms.Lookup("runtime.gcdata", 0)
  2096  	s.Attr |= sym.AttrLocal
  2097  	ctxt.xdefine("runtime.egcdata", sym.SRODATA, Symaddr(s)+s.Size)
  2098  	ctxt.Syms.Lookup("runtime.egcdata", 0).Sect = s.Sect
  2099  
  2100  	s = ctxt.Syms.Lookup("runtime.gcbss", 0)
  2101  	s.Attr |= sym.AttrLocal
  2102  	ctxt.xdefine("runtime.egcbss", sym.SRODATA, Symaddr(s)+s.Size)
  2103  	ctxt.Syms.Lookup("runtime.egcbss", 0).Sect = s.Sect
  2104  
  2105  	ctxt.xdefine("runtime.symtab", sym.SRODATA, int64(symtab.Vaddr))
  2106  	ctxt.xdefine("runtime.esymtab", sym.SRODATA, int64(symtab.Vaddr+symtab.Length))
  2107  	ctxt.xdefine("runtime.pclntab", sym.SRODATA, int64(pclntab.Vaddr))
  2108  	ctxt.xdefine("runtime.epclntab", sym.SRODATA, int64(pclntab.Vaddr+pclntab.Length))
  2109  	ctxt.xdefine("runtime.noptrdata", sym.SNOPTRDATA, int64(noptr.Vaddr))
  2110  	ctxt.xdefine("runtime.enoptrdata", sym.SNOPTRDATA, int64(noptr.Vaddr+noptr.Length))
  2111  	ctxt.xdefine("runtime.bss", sym.SBSS, int64(bss.Vaddr))
  2112  	ctxt.xdefine("runtime.ebss", sym.SBSS, int64(bss.Vaddr+bss.Length))
  2113  	ctxt.xdefine("runtime.data", sym.SDATA, int64(data.Vaddr))
  2114  	ctxt.xdefine("runtime.edata", sym.SDATA, int64(data.Vaddr+data.Length))
  2115  	ctxt.xdefine("runtime.noptrbss", sym.SNOPTRBSS, int64(noptrbss.Vaddr))
  2116  	ctxt.xdefine("runtime.enoptrbss", sym.SNOPTRBSS, int64(noptrbss.Vaddr+noptrbss.Length))
  2117  	ctxt.xdefine("runtime.end", sym.SBSS, int64(Segdata.Vaddr+Segdata.Length))
  2118  
  2119  	return order
  2120  }
  2121  
  2122  // layout assigns file offsets and lengths to the segments in order.
  2123  func (ctxt *Link) layout(order []*sym.Segment) {
  2124  	var prev *sym.Segment
  2125  	for _, seg := range order {
  2126  		if prev == nil {
  2127  			seg.Fileoff = uint64(HEADR)
  2128  		} else {
  2129  			switch ctxt.HeadType {
  2130  			default:
  2131  				// Assuming the previous segment was
  2132  				// aligned, the following rounding
  2133  				// should ensure that this segment's
  2134  				// VA ≡ Fileoff mod FlagRound.
  2135  				seg.Fileoff = uint64(Rnd(int64(prev.Fileoff+prev.Filelen), int64(*FlagRound)))
  2136  				if seg.Vaddr%uint64(*FlagRound) != seg.Fileoff%uint64(*FlagRound) {
  2137  					Exitf("bad segment rounding (Vaddr=%#x Fileoff=%#x FlagRound=%#x)", seg.Vaddr, seg.Fileoff, *FlagRound)
  2138  				}
  2139  			case objabi.Hwindows:
  2140  				seg.Fileoff = prev.Fileoff + uint64(Rnd(int64(prev.Filelen), PEFILEALIGN))
  2141  			case objabi.Hplan9:
  2142  				seg.Fileoff = prev.Fileoff + prev.Filelen
  2143  			}
  2144  		}
  2145  		if seg != &Segdata {
  2146  			// Link.address already set Segdata.Filelen to
  2147  			// account for BSS.
  2148  			seg.Filelen = seg.Length
  2149  		}
  2150  		prev = seg
  2151  	}
  2152  
  2153  }
  2154  
  2155  // add a trampoline with symbol s (to be laid down after the current function)
  2156  func (ctxt *Link) AddTramp(s *sym.Symbol) {
  2157  	s.Type = sym.STEXT
  2158  	s.Attr |= sym.AttrReachable
  2159  	s.Attr |= sym.AttrOnList
  2160  	ctxt.tramps = append(ctxt.tramps, s)
  2161  	if *FlagDebugTramp > 0 && ctxt.Debugvlog > 0 {
  2162  		ctxt.Logf("trampoline %s inserted\n", s)
  2163  	}
  2164  }
  2165  
  2166  // compressSyms compresses syms and returns the contents of the
  2167  // compressed section. If the section would get larger, it returns nil.
  2168  func compressSyms(ctxt *Link, syms []*sym.Symbol) []byte {
  2169  	var total int64
  2170  	for _, sym := range syms {
  2171  		total += sym.Size
  2172  	}
  2173  
  2174  	var buf bytes.Buffer
  2175  	buf.Write([]byte("ZLIB"))
  2176  	var sizeBytes [8]byte
  2177  	binary.BigEndian.PutUint64(sizeBytes[:], uint64(total))
  2178  	buf.Write(sizeBytes[:])
  2179  
  2180  	// Using zlib.BestSpeed achieves very nearly the same
  2181  	// compression levels of zlib.DefaultCompression, but takes
  2182  	// substantially less time. This is important because DWARF
  2183  	// compression can be a significant fraction of link time.
  2184  	z, err := zlib.NewWriterLevel(&buf, zlib.BestSpeed)
  2185  	if err != nil {
  2186  		log.Fatalf("NewWriterLevel failed: %s", err)
  2187  	}
  2188  	for _, sym := range syms {
  2189  		if _, err := z.Write(sym.P); err != nil {
  2190  			log.Fatalf("compression failed: %s", err)
  2191  		}
  2192  		for i := sym.Size - int64(len(sym.P)); i > 0; {
  2193  			b := zeros[:]
  2194  			if i < int64(len(b)) {
  2195  				b = b[:i]
  2196  			}
  2197  			n, err := z.Write(b)
  2198  			if err != nil {
  2199  				log.Fatalf("compression failed: %s", err)
  2200  			}
  2201  			i -= int64(n)
  2202  		}
  2203  	}
  2204  	if err := z.Close(); err != nil {
  2205  		log.Fatalf("compression failed: %s", err)
  2206  	}
  2207  	if int64(buf.Len()) >= total {
  2208  		// Compression didn't save any space.
  2209  		return nil
  2210  	}
  2211  	return buf.Bytes()
  2212  }
  2213  

View as plain text