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

     1  // Copyright 2009 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package ld
     6  
     7  import (
     8  	"bytes"
     9  	"cmd/internal/codesign"
    10  	"cmd/internal/hash"
    11  	imacho "cmd/internal/macho"
    12  	"cmd/internal/objabi"
    13  	"cmd/internal/sys"
    14  	"cmd/link/internal/loader"
    15  	"cmd/link/internal/sym"
    16  	"debug/macho"
    17  	"encoding/binary"
    18  	"fmt"
    19  	"internal/buildcfg"
    20  	"io"
    21  	"os"
    22  	"slices"
    23  	"sort"
    24  	"strconv"
    25  	"strings"
    26  	"unsafe"
    27  )
    28  
    29  type MachoHdr struct {
    30  	cpu    uint32
    31  	subcpu uint32
    32  }
    33  
    34  type MachoSect struct {
    35  	name    string
    36  	segname string
    37  	addr    uint64
    38  	size    uint64
    39  	off     uint32
    40  	align   uint32
    41  	reloc   uint32
    42  	nreloc  uint32
    43  	flag    uint32
    44  	res1    uint32
    45  	res2    uint32
    46  }
    47  
    48  type MachoSeg struct {
    49  	name       string
    50  	vsize      uint64
    51  	vaddr      uint64
    52  	fileoffset uint64
    53  	filesize   uint64
    54  	prot1      uint32
    55  	prot2      uint32
    56  	nsect      uint32
    57  	msect      uint32
    58  	sect       []MachoSect
    59  	flag       uint32
    60  }
    61  
    62  // MachoPlatformLoad represents a LC_VERSION_MIN_* or
    63  // LC_BUILD_VERSION load command.
    64  type MachoPlatformLoad struct {
    65  	platform MachoPlatform // One of PLATFORM_* constants.
    66  	cmd      MachoLoad
    67  }
    68  
    69  type MachoLoad struct {
    70  	type_ uint32
    71  	data  []uint32
    72  }
    73  
    74  type MachoPlatform int
    75  
    76  /*
    77   * Total amount of space to reserve at the start of the file
    78   * for Header, PHeaders, and SHeaders.
    79   * May waste some.
    80   */
    81  const (
    82  	INITIAL_MACHO_HEADR = 4 * 1024
    83  )
    84  
    85  const (
    86  	MACHO_CPU_AMD64                      = 1<<24 | 7
    87  	MACHO_CPU_386                        = 7
    88  	MACHO_SUBCPU_X86                     = 3
    89  	MACHO_CPU_ARM                        = 12
    90  	MACHO_SUBCPU_ARM                     = 0
    91  	MACHO_SUBCPU_ARMV7                   = 9
    92  	MACHO_CPU_ARM64                      = 1<<24 | 12
    93  	MACHO_SUBCPU_ARM64_ALL               = 0
    94  	MACHO_SUBCPU_ARM64_V8                = 1
    95  	MACHO_SUBCPU_ARM64E                  = 2
    96  	MACHO32SYMSIZE                       = 12
    97  	MACHO64SYMSIZE                       = 16
    98  	MACHO_X86_64_RELOC_UNSIGNED          = 0
    99  	MACHO_X86_64_RELOC_SIGNED            = 1
   100  	MACHO_X86_64_RELOC_BRANCH            = 2
   101  	MACHO_X86_64_RELOC_GOT_LOAD          = 3
   102  	MACHO_X86_64_RELOC_GOT               = 4
   103  	MACHO_X86_64_RELOC_SUBTRACTOR        = 5
   104  	MACHO_X86_64_RELOC_SIGNED_1          = 6
   105  	MACHO_X86_64_RELOC_SIGNED_2          = 7
   106  	MACHO_X86_64_RELOC_SIGNED_4          = 8
   107  	MACHO_ARM_RELOC_VANILLA              = 0
   108  	MACHO_ARM_RELOC_PAIR                 = 1
   109  	MACHO_ARM_RELOC_SECTDIFF             = 2
   110  	MACHO_ARM_RELOC_BR24                 = 5
   111  	MACHO_ARM64_RELOC_UNSIGNED           = 0
   112  	MACHO_ARM64_RELOC_SUBTRACTOR         = 1
   113  	MACHO_ARM64_RELOC_BRANCH26           = 2
   114  	MACHO_ARM64_RELOC_PAGE21             = 3
   115  	MACHO_ARM64_RELOC_PAGEOFF12          = 4
   116  	MACHO_ARM64_RELOC_GOT_LOAD_PAGE21    = 5
   117  	MACHO_ARM64_RELOC_GOT_LOAD_PAGEOFF12 = 6
   118  	MACHO_ARM64_RELOC_POINTER_TO_GOT     = 7
   119  	MACHO_ARM64_RELOC_ADDEND             = 10
   120  	MACHO_GENERIC_RELOC_VANILLA          = 0
   121  	MACHO_FAKE_GOTPCREL                  = 100
   122  )
   123  
   124  const (
   125  	MH_MAGIC    = 0xfeedface
   126  	MH_MAGIC_64 = 0xfeedfacf
   127  
   128  	MH_OBJECT  = 0x1
   129  	MH_EXECUTE = 0x2
   130  	MH_DSYM    = 0xa
   131  
   132  	MH_NOUNDEFS = 0x1
   133  	MH_DYLDLINK = 0x4
   134  	MH_PIE      = 0x200000
   135  )
   136  
   137  const (
   138  	S_REGULAR                  = 0x0
   139  	S_ZEROFILL                 = 0x1
   140  	S_NON_LAZY_SYMBOL_POINTERS = 0x6
   141  	S_SYMBOL_STUBS             = 0x8
   142  	S_MOD_INIT_FUNC_POINTERS   = 0x9
   143  	S_ATTR_PURE_INSTRUCTIONS   = 0x80000000
   144  	S_ATTR_DEBUG               = 0x02000000
   145  	S_ATTR_SOME_INSTRUCTIONS   = 0x00000400
   146  )
   147  
   148  const (
   149  	PLATFORM_MACOS       MachoPlatform = 1
   150  	PLATFORM_IOS         MachoPlatform = 2
   151  	PLATFORM_TVOS        MachoPlatform = 3
   152  	PLATFORM_WATCHOS     MachoPlatform = 4
   153  	PLATFORM_BRIDGEOS    MachoPlatform = 5
   154  	PLATFORM_MACCATALYST MachoPlatform = 6
   155  )
   156  
   157  // rebase table opcode
   158  const (
   159  	REBASE_TYPE_POINTER         = 1
   160  	REBASE_TYPE_TEXT_ABSOLUTE32 = 2
   161  	REBASE_TYPE_TEXT_PCREL32    = 3
   162  
   163  	REBASE_OPCODE_MASK                               = 0xF0
   164  	REBASE_IMMEDIATE_MASK                            = 0x0F
   165  	REBASE_OPCODE_DONE                               = 0x00
   166  	REBASE_OPCODE_SET_TYPE_IMM                       = 0x10
   167  	REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB        = 0x20
   168  	REBASE_OPCODE_ADD_ADDR_ULEB                      = 0x30
   169  	REBASE_OPCODE_ADD_ADDR_IMM_SCALED                = 0x40
   170  	REBASE_OPCODE_DO_REBASE_IMM_TIMES                = 0x50
   171  	REBASE_OPCODE_DO_REBASE_ULEB_TIMES               = 0x60
   172  	REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB            = 0x70
   173  	REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB = 0x80
   174  )
   175  
   176  // bind table opcode
   177  const (
   178  	BIND_TYPE_POINTER         = 1
   179  	BIND_TYPE_TEXT_ABSOLUTE32 = 2
   180  	BIND_TYPE_TEXT_PCREL32    = 3
   181  
   182  	BIND_SPECIAL_DYLIB_SELF            = 0
   183  	BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE = -1
   184  	BIND_SPECIAL_DYLIB_FLAT_LOOKUP     = -2
   185  	BIND_SPECIAL_DYLIB_WEAK_LOOKUP     = -3
   186  
   187  	BIND_SYMBOL_FLAGS_WEAK_IMPORT = 0x1
   188  
   189  	BIND_OPCODE_MASK                                         = 0xF0
   190  	BIND_IMMEDIATE_MASK                                      = 0x0F
   191  	BIND_OPCODE_DONE                                         = 0x00
   192  	BIND_OPCODE_SET_DYLIB_ORDINAL_IMM                        = 0x10
   193  	BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB                       = 0x20
   194  	BIND_OPCODE_SET_DYLIB_SPECIAL_IMM                        = 0x30
   195  	BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM                = 0x40
   196  	BIND_OPCODE_SET_TYPE_IMM                                 = 0x50
   197  	BIND_OPCODE_SET_ADDEND_SLEB                              = 0x60
   198  	BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB                  = 0x70
   199  	BIND_OPCODE_ADD_ADDR_ULEB                                = 0x80
   200  	BIND_OPCODE_DO_BIND                                      = 0x90
   201  	BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB                        = 0xA0
   202  	BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED                  = 0xB0
   203  	BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB             = 0xC0
   204  	BIND_OPCODE_THREADED                                     = 0xD0
   205  	BIND_SUBOPCODE_THREADED_SET_BIND_ORDINAL_TABLE_SIZE_ULEB = 0x00
   206  	BIND_SUBOPCODE_THREADED_APPLY                            = 0x01
   207  )
   208  
   209  const machoHeaderSize64 = 8 * 4 // size of 64-bit Mach-O header
   210  
   211  // Mach-O file writing
   212  // https://developer.apple.com/mac/library/DOCUMENTATION/DeveloperTools/Conceptual/MachORuntime/Reference/reference.html
   213  
   214  var machohdr MachoHdr
   215  
   216  var load []MachoLoad
   217  
   218  var machoPlatform MachoPlatform
   219  
   220  var seg [16]MachoSeg
   221  
   222  var nseg int
   223  
   224  var ndebug int
   225  
   226  var nsect int
   227  
   228  const (
   229  	SymKindLocal = 0 + iota
   230  	SymKindExtdef
   231  	SymKindUndef
   232  	NumSymKind
   233  )
   234  
   235  var nkind [NumSymKind]int
   236  
   237  var sortsym []loader.Sym
   238  
   239  var nsortsym int
   240  
   241  // Amount of space left for adding load commands
   242  // that refer to dynamic libraries. Because these have
   243  // to go in the Mach-O header, we can't just pick a
   244  // "big enough" header size. The initial header is
   245  // one page, the non-dynamic library stuff takes
   246  // up about 1300 bytes; we overestimate that as 2k.
   247  var loadBudget = INITIAL_MACHO_HEADR - 2*1024
   248  
   249  func getMachoHdr() *MachoHdr {
   250  	return &machohdr
   251  }
   252  
   253  // Create a new Mach-O load command. ndata is the number of 32-bit words for
   254  // the data (not including the load command header).
   255  func newMachoLoad(arch *sys.Arch, type_ uint32, ndata uint32) *MachoLoad {
   256  	if ndata&1 != 0 {
   257  		ndata++
   258  	}
   259  
   260  	load = append(load, MachoLoad{})
   261  	l := &load[len(load)-1]
   262  	l.type_ = type_
   263  	l.data = make([]uint32, ndata)
   264  	return l
   265  }
   266  
   267  func newMachoSeg(name string, msect int) *MachoSeg {
   268  	if nseg >= len(seg) {
   269  		Exitf("too many segs")
   270  	}
   271  
   272  	s := &seg[nseg]
   273  	nseg++
   274  	s.name = name
   275  	s.msect = uint32(msect)
   276  	s.sect = make([]MachoSect, msect)
   277  	return s
   278  }
   279  
   280  func newMachoSect(seg *MachoSeg, name string, segname string) *MachoSect {
   281  	if seg.nsect >= seg.msect {
   282  		Exitf("too many sects in segment %s", seg.name)
   283  	}
   284  
   285  	s := &seg.sect[seg.nsect]
   286  	seg.nsect++
   287  	s.name = name
   288  	s.segname = segname
   289  	nsect++
   290  	return s
   291  }
   292  
   293  // Generic linking code.
   294  
   295  var dylib []string
   296  
   297  var linkoff int64
   298  
   299  func machowrite(ctxt *Link, arch *sys.Arch, out *OutBuf, linkmode LinkMode) int {
   300  	o1 := out.Offset()
   301  
   302  	loadsize := 4 * 4 * ndebug
   303  	for i := range load {
   304  		loadsize += 4 * (len(load[i].data) + 2)
   305  	}
   306  	loadsize += 18 * 4 * nseg
   307  	loadsize += 20 * 4 * nsect
   308  
   309  	out.Write32(MH_MAGIC_64)
   310  	out.Write32(machohdr.cpu)
   311  	out.Write32(machohdr.subcpu)
   312  	if out == ctxt.OutDWARF {
   313  		out.Write32(MH_DSYM)
   314  	} else if linkmode == LinkExternal {
   315  		out.Write32(MH_OBJECT) /* file type - mach object */
   316  	} else {
   317  		out.Write32(MH_EXECUTE) /* file type - mach executable */
   318  	}
   319  	out.Write32(uint32(len(load)) + uint32(nseg) + uint32(ndebug))
   320  	out.Write32(uint32(loadsize))
   321  	flags := uint32(0)
   322  	if out != ctxt.OutDWARF {
   323  		if nkind[SymKindUndef] == 0 {
   324  			flags |= MH_NOUNDEFS
   325  		}
   326  		if ctxt.IsPIE() && linkmode == LinkInternal {
   327  			flags |= MH_PIE | MH_DYLDLINK
   328  		}
   329  	}
   330  	out.Write32(flags) /* flags */
   331  	out.Write32(0)     /* reserved */
   332  
   333  	for i := 0; i < nseg; i++ {
   334  		s := &seg[i]
   335  		out.Write32(imacho.LC_SEGMENT_64)
   336  		out.Write32(72 + 80*s.nsect)
   337  		out.WriteStringN(s.name, 16)
   338  		out.Write64(s.vaddr)
   339  		out.Write64(s.vsize)
   340  		out.Write64(s.fileoffset)
   341  		out.Write64(s.filesize)
   342  		out.Write32(s.prot1)
   343  		out.Write32(s.prot2)
   344  		out.Write32(s.nsect)
   345  		out.Write32(s.flag)
   346  
   347  		for j := uint32(0); j < s.nsect; j++ {
   348  			t := &s.sect[j]
   349  			out.WriteStringN(t.name, 16)
   350  			out.WriteStringN(t.segname, 16)
   351  			out.Write64(t.addr)
   352  			out.Write64(t.size)
   353  			out.Write32(t.off)
   354  			out.Write32(t.align)
   355  			out.Write32(t.reloc)
   356  			out.Write32(t.nreloc)
   357  			out.Write32(t.flag)
   358  			out.Write32(t.res1) /* reserved */
   359  			out.Write32(t.res2) /* reserved */
   360  			out.Write32(0)      /* reserved */
   361  		}
   362  	}
   363  
   364  	for i := range load {
   365  		l := &load[i]
   366  		out.Write32(l.type_)
   367  		out.Write32(4 * (uint32(len(l.data)) + 2))
   368  		for j := 0; j < len(l.data); j++ {
   369  			out.Write32(l.data[j])
   370  		}
   371  	}
   372  
   373  	return int(out.Offset() - o1)
   374  }
   375  
   376  type macVersionFlag [3]byte
   377  
   378  func (f *macVersionFlag) String() string {
   379  	return fmt.Sprintf("%d.%d.%d", f[0], f[1], f[2])
   380  }
   381  
   382  func (f *macVersionFlag) Set(s string) error {
   383  	var parsed macVersionFlag
   384  	nums := strings.Split(s, ".")
   385  	if len(nums) > 3 {
   386  		goto Error
   387  	}
   388  	for i, num := range nums {
   389  		n, err := strconv.Atoi(num)
   390  		if err != nil || n < 0 || n > 0xFF {
   391  			goto Error
   392  		}
   393  		parsed[i] = byte(n)
   394  	}
   395  	// success, now modify f
   396  	*f = parsed
   397  	return nil
   398  
   399  Error:
   400  	return fmt.Errorf("invalid version %q", s)
   401  }
   402  
   403  func (f *macVersionFlag) version() uint32 {
   404  	return uint32(f[0])<<16 | uint32(f[1])<<8 | uint32(f[2])
   405  }
   406  
   407  var (
   408  	// On advice from Apple engineers, we keep macOS set to the
   409  	// oldest supported macOS version but keep macSDK to the newest
   410  	// tested OS/SDK version. If these defaults are not good enough,
   411  	// the -macos and -macsdk linker flags can override them.
   412  	// For past problems involving these values, see
   413  	//	go.dev/issue/30488
   414  	//	go.dev/issue/56784
   415  	//	go.dev/issue/77917
   416  	macOS  = macVersionFlag{13, 0, 0}
   417  	macSDK = macVersionFlag{26, 2, 0}
   418  )
   419  
   420  func (ctxt *Link) domacho() {
   421  	// Copy platform load command.
   422  	for _, h := range hostobj {
   423  		load, err := hostobjMachoPlatform(&h)
   424  		if err != nil {
   425  			Exitf("%v", err)
   426  		}
   427  		if load != nil && load.platform != PLATFORM_MACOS {
   428  			ml := newMachoLoad(ctxt.Arch, load.cmd.type_, uint32(len(load.cmd.data)))
   429  			copy(ml.data, load.cmd.data)
   430  			break
   431  		}
   432  	}
   433  	if machoPlatform == 0 {
   434  		machoPlatform = PLATFORM_MACOS
   435  		if buildcfg.GOOS == "ios" {
   436  			machoPlatform = PLATFORM_IOS
   437  		}
   438  		if load == nil && machoPlatform == PLATFORM_MACOS {
   439  			ml := newMachoLoad(ctxt.Arch, imacho.LC_BUILD_VERSION, 4)
   440  			ml.data[0] = uint32(machoPlatform)
   441  			ml.data[1] = macOS.version()
   442  			ml.data[2] = macSDK.version()
   443  			ml.data[3] = 0 // ntools
   444  		}
   445  	}
   446  
   447  	// empirically, string table must begin with " \x00".
   448  	s := ctxt.loader.LookupOrCreateSym(".machosymstr", 0)
   449  	sb := ctxt.loader.MakeSymbolUpdater(s)
   450  
   451  	sb.SetType(sym.SMACHOSYMSTR)
   452  	sb.SetReachable(true)
   453  	sb.AddUint8(' ')
   454  	sb.AddUint8('\x00')
   455  
   456  	s = ctxt.loader.LookupOrCreateSym(".machosymtab", 0)
   457  	sb = ctxt.loader.MakeSymbolUpdater(s)
   458  	sb.SetType(sym.SMACHOSYMTAB)
   459  	sb.SetReachable(true)
   460  
   461  	if ctxt.IsInternal() {
   462  		s = ctxt.loader.LookupOrCreateSym(".plt", 0) // will be __symbol_stub
   463  		sb = ctxt.loader.MakeSymbolUpdater(s)
   464  		sb.SetType(sym.SMACHOPLT)
   465  		sb.SetReachable(true)
   466  
   467  		s = ctxt.loader.LookupOrCreateSym(".got", 0) // will be __got
   468  		sb = ctxt.loader.MakeSymbolUpdater(s)
   469  		if ctxt.UseRelro() {
   470  			sb.SetType(sym.SMACHORELROSECT)
   471  		} else {
   472  			sb.SetType(sym.SMACHOGOT)
   473  		}
   474  		sb.SetReachable(true)
   475  		sb.SetAlign(4)
   476  
   477  		s = ctxt.loader.LookupOrCreateSym(".linkedit.plt", 0) // indirect table for .plt
   478  		sb = ctxt.loader.MakeSymbolUpdater(s)
   479  		sb.SetType(sym.SMACHOINDIRECTPLT)
   480  		sb.SetReachable(true)
   481  
   482  		s = ctxt.loader.LookupOrCreateSym(".linkedit.got", 0) // indirect table for .got
   483  		sb = ctxt.loader.MakeSymbolUpdater(s)
   484  		sb.SetType(sym.SMACHOINDIRECTGOT)
   485  		sb.SetReachable(true)
   486  	}
   487  
   488  	// Add a dummy symbol that will become the __asm marker section.
   489  	if ctxt.IsExternal() {
   490  		s = ctxt.loader.LookupOrCreateSym(".llvmasm", 0)
   491  		sb = ctxt.loader.MakeSymbolUpdater(s)
   492  		sb.SetType(sym.SMACHO)
   493  		sb.SetReachable(true)
   494  		sb.AddUint8(0)
   495  	}
   496  
   497  	// Un-export runtime symbols from plugins. Since the runtime
   498  	// is included in both the main binary and each plugin, these
   499  	// symbols appear in both images. If we leave them exported in
   500  	// the plugin, then the dynamic linker will resolve
   501  	// relocations to these functions in the plugin's functab to
   502  	// point to the main image, causing the runtime to think the
   503  	// plugin's functab is corrupted. By unexporting them, these
   504  	// become static references, which are resolved to the
   505  	// plugin's text.
   506  	//
   507  	// It would be better to omit the runtime from plugins. (Using
   508  	// relative PCs in the functab instead of relocations would
   509  	// also address this.)
   510  	//
   511  	// See issue #18190.
   512  	if ctxt.BuildMode == BuildModePlugin {
   513  		for _, name := range []string{"_cgo_topofstack", "__cgo_topofstack", "_cgo_panic", "crosscall2"} {
   514  			// Most of these are data symbols or C
   515  			// symbols, so they have symbol version 0.
   516  			ver := 0
   517  			// _cgo_panic is a Go function, so it uses ABIInternal.
   518  			if name == "_cgo_panic" {
   519  				ver = abiInternalVer
   520  			}
   521  			s := ctxt.loader.Lookup(name, ver)
   522  			if s != 0 {
   523  				ctxt.loader.SetAttrCgoExportDynamic(s, false)
   524  			}
   525  		}
   526  	}
   527  }
   528  
   529  func machoadddynlib(lib string, linkmode LinkMode) {
   530  	if seenlib[lib] || linkmode == LinkExternal {
   531  		return
   532  	}
   533  	seenlib[lib] = true
   534  
   535  	// Will need to store the library name rounded up
   536  	// and 24 bytes of header metadata. If not enough
   537  	// space, grab another page of initial space at the
   538  	// beginning of the output file.
   539  	loadBudget -= (len(lib)+7)/8*8 + 24
   540  
   541  	if loadBudget < 0 {
   542  		HEADR += 4096
   543  		*FlagTextAddr += 4096
   544  		loadBudget += 4096
   545  	}
   546  
   547  	dylib = append(dylib, lib)
   548  }
   549  
   550  // machoaddrpath reserves space in the Mach-O header for the LC_RPATH load
   551  // command that asmbMacho writes for the cgo rpath entry dir, as
   552  // machoadddynlib does for LC_LOAD_DYLIB.
   553  func machoaddrpath(dir string, linkmode LinkMode) {
   554  	if linkmode == LinkExternal || rpath.set {
   555  		return
   556  	}
   557  	// The load command has an 8-byte header, a 4-byte string offset, and
   558  	// the NUL-terminated string padded to 4 bytes, rounded up to 8 bytes
   559  	// (see newMachoLoad).
   560  	ndata := 1 + (len(dir)+1+3)/4
   561  	loadBudget -= 8 + (ndata+1)/2*8
   562  	for loadBudget < 0 {
   563  		HEADR += 4096
   564  		*FlagTextAddr += 4096
   565  		loadBudget += 4096
   566  	}
   567  }
   568  
   569  func machoshbits(ctxt *Link, mseg *MachoSeg, sect *sym.Section, segname string) {
   570  	buf := "__" + strings.ReplaceAll(sect.Name[1:], ".", "_")
   571  
   572  	msect := newMachoSect(mseg, buf, segname)
   573  
   574  	if sect.Rellen > 0 {
   575  		msect.reloc = uint32(sect.Reloff)
   576  		msect.nreloc = uint32(sect.Rellen / 8)
   577  	}
   578  
   579  	for 1<<msect.align < sect.Align {
   580  		msect.align++
   581  	}
   582  	msect.addr = sect.Vaddr
   583  	msect.size = sect.Length
   584  
   585  	if sect.Vaddr < sect.Seg.Vaddr+sect.Seg.Filelen {
   586  		// data in file
   587  		if sect.Length > sect.Seg.Vaddr+sect.Seg.Filelen-sect.Vaddr {
   588  			Errorf("macho cannot represent section %s crossing data and bss", sect.Name)
   589  		}
   590  		msect.off = uint32(sect.Seg.Fileoff + sect.Vaddr - sect.Seg.Vaddr)
   591  	} else {
   592  		msect.off = 0
   593  		msect.flag |= S_ZEROFILL
   594  	}
   595  
   596  	if sect.Rwx&1 != 0 {
   597  		msect.flag |= S_ATTR_SOME_INSTRUCTIONS
   598  	}
   599  
   600  	if sect.Name == ".text" {
   601  		msect.flag |= S_ATTR_PURE_INSTRUCTIONS
   602  	}
   603  
   604  	if sect.Name == ".plt" {
   605  		msect.name = "__symbol_stub1"
   606  		msect.flag = S_ATTR_PURE_INSTRUCTIONS | S_ATTR_SOME_INSTRUCTIONS | S_SYMBOL_STUBS
   607  		msect.res1 = 0 //nkind[SymKindLocal];
   608  		msect.res2 = 6
   609  	}
   610  
   611  	if sect.Name == ".got" {
   612  		msect.name = "__got"
   613  		msect.flag = S_NON_LAZY_SYMBOL_POINTERS
   614  		msect.res1 = uint32(ctxt.loader.SymSize(ctxt.ArchSyms.LinkEditPLT) / 4) /* offset into indirect symbol table */
   615  	}
   616  
   617  	if sect.Name == ".init_array" {
   618  		msect.name = "__mod_init_func"
   619  		msect.flag = S_MOD_INIT_FUNC_POINTERS
   620  	}
   621  
   622  	// Some platforms such as watchOS and tvOS require binaries with
   623  	// bitcode enabled. The Go toolchain can't output bitcode, so use
   624  	// a marker section in the __LLVM segment, "__asm", to tell the Apple
   625  	// toolchain that the Go text came from assembler and thus has no
   626  	// bitcode. This is not true, but Kotlin/Native, Rust and Flutter
   627  	// are also using this trick.
   628  	if sect.Name == ".llvmasm" {
   629  		msect.name = "__asm"
   630  		msect.segname = "__LLVM"
   631  	}
   632  
   633  	if sect.Name == ".compact_unwind" {
   634  		msect.name = "__compact_unwind"
   635  		msect.segname = "__LD"
   636  		msect.flag = S_ATTR_DEBUG
   637  	}
   638  
   639  	if segname == "__DWARF" {
   640  		msect.flag |= S_ATTR_DEBUG
   641  	}
   642  }
   643  
   644  func asmbMacho(ctxt *Link) {
   645  	machlink := doMachoLink(ctxt)
   646  	if ctxt.IsExternal() {
   647  		symo := int64(Segdwarf.Fileoff + uint64(Rnd(int64(Segdwarf.Filelen), *FlagRound)) + uint64(machlink))
   648  		ctxt.Out.SeekSet(symo)
   649  		machoEmitReloc(ctxt)
   650  	}
   651  	ctxt.Out.SeekSet(0)
   652  
   653  	ldr := ctxt.loader
   654  
   655  	/* apple MACH */
   656  	va := *FlagTextAddr - int64(HEADR)
   657  
   658  	mh := getMachoHdr()
   659  	switch ctxt.Arch.Family {
   660  	default:
   661  		Exitf("unknown macho architecture: %v", ctxt.Arch.Family)
   662  
   663  	case sys.AMD64:
   664  		mh.cpu = MACHO_CPU_AMD64
   665  		mh.subcpu = MACHO_SUBCPU_X86
   666  
   667  	case sys.ARM64:
   668  		mh.cpu = MACHO_CPU_ARM64
   669  		mh.subcpu = MACHO_SUBCPU_ARM64_ALL
   670  	}
   671  
   672  	var ms *MachoSeg
   673  	if ctxt.LinkMode == LinkExternal {
   674  		/* segment for entire file */
   675  		ms = newMachoSeg("", 40)
   676  
   677  		ms.fileoffset = Segtext.Fileoff
   678  		ms.filesize = Segdwarf.Fileoff + Segdwarf.Filelen - Segtext.Fileoff
   679  		ms.vsize = Segdwarf.Vaddr + Segdwarf.Length - Segtext.Vaddr
   680  	}
   681  
   682  	/* segment for zero page */
   683  	if ctxt.LinkMode != LinkExternal {
   684  		ms = newMachoSeg("__PAGEZERO", 0)
   685  		ms.vsize = uint64(va)
   686  	}
   687  
   688  	/* text */
   689  	v := Rnd(int64(uint64(HEADR)+Segtext.Length), *FlagRound)
   690  
   691  	var mstext *MachoSeg
   692  	if ctxt.LinkMode != LinkExternal {
   693  		ms = newMachoSeg("__TEXT", 20)
   694  		ms.vaddr = uint64(va)
   695  		ms.vsize = uint64(v)
   696  		ms.fileoffset = 0
   697  		ms.filesize = uint64(v)
   698  		ms.prot1 = 7
   699  		ms.prot2 = 5
   700  		mstext = ms
   701  	}
   702  
   703  	for _, sect := range Segtext.Sections {
   704  		machoshbits(ctxt, ms, sect, "__TEXT")
   705  	}
   706  
   707  	/* rodata */
   708  	if ctxt.LinkMode != LinkExternal && Segrelrodata.Length > 0 {
   709  		ms = newMachoSeg("__DATA_CONST", 20)
   710  		ms.vaddr = Segrelrodata.Vaddr
   711  		ms.vsize = Segrelrodata.Length
   712  		ms.fileoffset = Segrelrodata.Fileoff
   713  		ms.filesize = Segrelrodata.Filelen
   714  		ms.prot1 = 3
   715  		ms.prot2 = 3
   716  		ms.flag = 0x10 // SG_READ_ONLY
   717  	}
   718  
   719  	for _, sect := range Segrelrodata.Sections {
   720  		machoshbits(ctxt, ms, sect, "__DATA_CONST")
   721  	}
   722  
   723  	/* data */
   724  	if ctxt.LinkMode != LinkExternal {
   725  		ms = newMachoSeg("__DATA", 20)
   726  		ms.vaddr = Segdata.Vaddr
   727  		ms.vsize = Segdata.Length
   728  		ms.fileoffset = Segdata.Fileoff
   729  		ms.filesize = Segdata.Filelen
   730  		ms.prot1 = 3
   731  		ms.prot2 = 3
   732  	}
   733  
   734  	for _, sect := range Segdata.Sections {
   735  		machoshbits(ctxt, ms, sect, "__DATA")
   736  	}
   737  
   738  	/* dwarf */
   739  	if !*FlagW && !(*FlagSplitDWARF && ctxt.IsInternal()) {
   740  		if ctxt.LinkMode != LinkExternal {
   741  			ms = newMachoSeg("__DWARF", 20)
   742  			ms.vaddr = Segdwarf.Vaddr
   743  			ms.vsize = 0
   744  			ms.fileoffset = Segdwarf.Fileoff
   745  			ms.filesize = Segdwarf.Filelen
   746  		}
   747  		for _, sect := range Segdwarf.Sections {
   748  			machoshbits(ctxt, ms, sect, "__DWARF")
   749  		}
   750  	}
   751  
   752  	if ctxt.LinkMode != LinkExternal {
   753  		switch ctxt.Arch.Family {
   754  		default:
   755  			Exitf("unknown macho architecture: %v", ctxt.Arch.Family)
   756  
   757  		case sys.AMD64:
   758  			ml := newMachoLoad(ctxt.Arch, imacho.LC_UNIXTHREAD, 42+2)
   759  			ml.data[0] = 4                           /* thread type */
   760  			ml.data[1] = 42                          /* word count */
   761  			ml.data[2+32] = uint32(Entryvalue(ctxt)) /* start pc */
   762  			ml.data[2+32+1] = uint32(Entryvalue(ctxt) >> 32)
   763  
   764  		case sys.ARM64:
   765  			ml := newMachoLoad(ctxt.Arch, imacho.LC_MAIN, 4)
   766  			ml.data[0] = uint32(uint64(Entryvalue(ctxt)) - (Segtext.Vaddr - uint64(HEADR)))
   767  			ml.data[1] = uint32((uint64(Entryvalue(ctxt)) - (Segtext.Vaddr - uint64(HEADR))) >> 32)
   768  		}
   769  	}
   770  
   771  	var codesigOff int64
   772  	// must match doMachoLink below
   773  	s1 := ldr.SymSize(ldr.Lookup(".machorebase", 0))
   774  	s2 := ldr.SymSize(ldr.Lookup(".machobind", 0))
   775  	s3 := ldr.SymSize(ldr.Lookup(".machosymtab", 0))
   776  	s4 := ldr.SymSize(ctxt.ArchSyms.LinkEditPLT)
   777  	s5 := ldr.SymSize(ctxt.ArchSyms.LinkEditGOT)
   778  	s6 := ldr.SymSize(ldr.Lookup(".machosymstr", 0))
   779  	padding := Rnd(s1+s2+s3+s4+s5+s6, 16) - (s1 + s2 + s3 + s4 + s5 + s6) // 16-byte alignment for code signature, see doMachoLink below
   780  	s7 := ldr.SymSize(ldr.Lookup(".machocodesig", 0))
   781  
   782  	if ctxt.LinkMode != LinkExternal {
   783  		ms := newMachoSeg("__LINKEDIT", 0)
   784  		ms.vaddr = uint64(Rnd(int64(Segdata.Vaddr+Segdata.Length), *FlagRound))
   785  		ms.vsize = uint64(s1 + s2 + s3 + s4 + s5 + s6 + padding + s7)
   786  		ms.fileoffset = uint64(linkoff)
   787  		ms.filesize = ms.vsize
   788  		ms.prot1 = 1
   789  		ms.prot2 = 1
   790  
   791  		codesigOff = linkoff + s1 + s2 + s3 + s4 + s5 + s6 + padding
   792  	}
   793  
   794  	if ctxt.LinkMode != LinkExternal && ctxt.IsPIE() {
   795  		ml := newMachoLoad(ctxt.Arch, imacho.LC_DYLD_INFO_ONLY, 10)
   796  		ml.data[0] = uint32(linkoff)      // rebase off
   797  		ml.data[1] = uint32(s1)           // rebase size
   798  		ml.data[2] = uint32(linkoff + s1) // bind off
   799  		ml.data[3] = uint32(s2)           // bind size
   800  		ml.data[4] = 0                    // weak bind off
   801  		ml.data[5] = 0                    // weak bind size
   802  		ml.data[6] = 0                    // lazy bind off
   803  		ml.data[7] = 0                    // lazy bind size
   804  		ml.data[8] = 0                    // export
   805  		ml.data[9] = 0                    // export size
   806  	}
   807  
   808  	ml := newMachoLoad(ctxt.Arch, imacho.LC_SYMTAB, 4)
   809  	ml.data[0] = uint32(linkoff + s1 + s2)                /* symoff */
   810  	ml.data[1] = uint32(nsortsym)                         /* nsyms */
   811  	ml.data[2] = uint32(linkoff + s1 + s2 + s3 + s4 + s5) /* stroff */
   812  	ml.data[3] = uint32(s6)                               /* strsize */
   813  
   814  	if ctxt.LinkMode != LinkExternal {
   815  		machodysymtab(ctxt, linkoff+s1+s2)
   816  
   817  		ml := newMachoLoad(ctxt.Arch, imacho.LC_LOAD_DYLINKER, 6)
   818  		ml.data[0] = 12 /* offset to string */
   819  		stringtouint32(ml.data[1:], "/usr/lib/dyld")
   820  
   821  		for _, lib := range dylib {
   822  			ml = newMachoLoad(ctxt.Arch, imacho.LC_LOAD_DYLIB, 4+(uint32(len(lib))+1+7)/8*2)
   823  			ml.data[0] = 24 /* offset of string from beginning of load */
   824  			ml.data[1] = 0  /* time stamp */
   825  			ml.data[2] = 0  /* version */
   826  			ml.data[3] = 0  /* compatibility version */
   827  			stringtouint32(ml.data[4:], lib)
   828  		}
   829  
   830  		// The -r flag is documented for ELF only, so only record the
   831  		// cgo rpath entries.
   832  		if !rpath.set {
   833  			for _, dir := range cgoRpaths {
   834  				ml = newMachoLoad(ctxt.Arch, imacho.LC_RPATH, 1+(uint32(len(dir))+1+3)/4)
   835  				ml.data[0] = 12 /* offset of string from beginning of load */
   836  				stringtouint32(ml.data[1:], dir)
   837  			}
   838  		}
   839  	}
   840  
   841  	if ctxt.IsInternal() && *flagHostBuildid != "none" {
   842  		ml := newMachoLoad(ctxt.Arch, imacho.LC_UUID, 4)
   843  		var uuid [16]byte
   844  		if len(buildinfo) >= 16 {
   845  			copy(uuid[:], buildinfo)
   846  		} else {
   847  			// Note: When setting macSDK to 26.2, dyld refuses to run any
   848  			// binary without an LC_UUID, which makes bootstrap fail.
   849  			// To work around that situation, if buildinfo is missing we
   850  			// construct a hash of the binary written so far and use that.
   851  			// Using -B none will bypass this if desired,
   852  			// but the resulting binary may not be runnable.
   853  			copy(uuid[:], uuidFromHash(hash.Sum32(ctxt.Out.Data())))
   854  		}
   855  		ml.data[0] = ctxt.Arch.ByteOrder.Uint32(uuid[0:])
   856  		ml.data[1] = ctxt.Arch.ByteOrder.Uint32(uuid[4:])
   857  		ml.data[2] = ctxt.Arch.ByteOrder.Uint32(uuid[8:])
   858  		ml.data[3] = ctxt.Arch.ByteOrder.Uint32(uuid[12:])
   859  	}
   860  
   861  	if ctxt.IsInternal() && ctxt.NeedCodeSign() {
   862  		ml := newMachoLoad(ctxt.Arch, imacho.LC_CODE_SIGNATURE, 2)
   863  		ml.data[0] = uint32(codesigOff)
   864  		ml.data[1] = uint32(s7)
   865  	}
   866  
   867  	a := machowrite(ctxt, ctxt.Arch, ctxt.Out, ctxt.LinkMode)
   868  	if int32(a) > HEADR {
   869  		Exitf("HEADR too small: %d > %d", a, HEADR)
   870  	}
   871  
   872  	// Now we have written everything. Compute the code signature (which
   873  	// is a hash of the file content, so it must be done at last.)
   874  	if ctxt.IsInternal() && ctxt.NeedCodeSign() {
   875  		cs := ldr.Lookup(".machocodesig", 0)
   876  		data := ctxt.Out.Data()
   877  		if int64(len(data)) != codesigOff {
   878  			panic("wrong size")
   879  		}
   880  		codesign.Sign(ldr.Data(cs), bytes.NewBuffer(data), "a.out", codesigOff, int64(mstext.fileoffset), int64(mstext.filesize), ctxt.IsExe() || ctxt.IsPIE())
   881  		ctxt.Out.SeekSet(codesigOff)
   882  		ctxt.Out.Write(ldr.Data(cs))
   883  	}
   884  
   885  	if *FlagSplitDWARF && ctxt.IsInternal() {
   886  		// Segment order when split DWARF is used, in both virtual address
   887  		// and file layout:
   888  		// - Mapped segments (__PAGEZERO, __TEXT, __DATA, etc.)
   889  		//   - Main binary: contains content in file.
   890  		//   - DWARF file: no content, just header listing virtual address.
   891  		// - __LINKEDIT
   892  		//   - Main binary: symbol table, dyld info, etc.
   893  		//   - DWARF file: start at same virtual address, but shorter,
   894  		//     contains only symbol table.
   895  		// - __DWARF
   896  		//   - DWARF file only.
   897  
   898  		// Write the __LINKEDIT segment (symbol table).
   899  		symtab := ldr.Lookup(".machosymtab", 0)
   900  		symstr := ldr.Lookup(".machosymstr", 0)
   901  		symtabSz := ldr.SymSize(symtab)
   902  		symstrSz := ldr.SymSize(symstr)
   903  		linkeditOff := Rnd(int64(HEADR), *FlagRound)
   904  		ctxt.OutDWARF.SeekSet(linkeditOff)
   905  		ctxt.OutDWARF.Write(ldr.Data(symtab))
   906  		ctxt.OutDWARF.Write(ldr.Data(symstr))
   907  		if Rnd(ctxt.OutDWARF.Offset(), *FlagRound) != int64(Segdwarf.Fileoff) {
   908  			panic("splitdwarf __LINKEDIT size mismatch")
   909  		}
   910  		ctxt.OutDWARF.SeekSet(0)
   911  
   912  		for i := range seg[:nseg] {
   913  			s := &seg[i]
   914  			if s.name == "__LINKEDIT" {
   915  				s.vsize = uint64(symtabSz + symstrSz)
   916  				s.fileoffset = uint64(linkeditOff)
   917  				s.filesize = s.vsize
   918  				continue
   919  			}
   920  			// The split DWARF file does not need the content of the segments
   921  			s.fileoffset = 0
   922  			s.filesize = 0
   923  			for j := range s.nsect {
   924  				s.sect[j].off = 0
   925  			}
   926  		}
   927  
   928  		ms := newMachoSeg("__DWARF", 20)
   929  		ms.vaddr = Segdwarf.Vaddr
   930  		ms.vsize = Segdwarf.Length
   931  		ms.fileoffset = Segdwarf.Fileoff
   932  		ms.filesize = Segdwarf.Filelen
   933  		ms.prot1 = 7
   934  		ms.prot2 = 3
   935  		for _, sect := range Segdwarf.Sections {
   936  			machoshbits(ctxt, ms, sect, "__DWARF")
   937  		}
   938  
   939  		// Keep only LC_BUILD_VERSION, LC_UUID, and LC_SYMTAB, dropping load
   940  		// commands specific to the executable (LC_MAIN, LC_DYLD_INFO_ONLY, etc.).
   941  		load = slices.DeleteFunc(load, func(l MachoLoad) bool {
   942  			return l.type_ != imacho.LC_BUILD_VERSION && l.type_ != imacho.LC_UUID && l.type_ != imacho.LC_SYMTAB
   943  		})
   944  		for i := range load {
   945  			if load[i].type_ == imacho.LC_SYMTAB {
   946  				load[i].data[0] = uint32(linkeditOff)            /* symoff */
   947  				load[i].data[1] = uint32(nsortsym)               /* nsyms */
   948  				load[i].data[2] = uint32(linkeditOff + symtabSz) /* stroff */
   949  				load[i].data[3] = uint32(symstrSz)               /* strsize */
   950  			}
   951  		}
   952  
   953  		a := machowrite(ctxt, ctxt.Arch, ctxt.OutDWARF, ctxt.LinkMode)
   954  		if int32(a) > HEADR {
   955  			Exitf("HEADR too small: %d > %d", a, HEADR)
   956  		}
   957  	}
   958  }
   959  
   960  func symkind(ldr *loader.Loader, s loader.Sym) int {
   961  	if t := ldr.SymType(s); t == sym.SDYNIMPORT || t == sym.SHOSTOBJ || t == sym.SUNDEFEXT {
   962  		return SymKindUndef
   963  	}
   964  	if ldr.AttrCgoExport(s) {
   965  		return SymKindExtdef
   966  	}
   967  	return SymKindLocal
   968  }
   969  
   970  func collectmachosyms(ctxt *Link) {
   971  	ldr := ctxt.loader
   972  
   973  	addsym := func(s loader.Sym) {
   974  		sortsym = append(sortsym, s)
   975  		nkind[symkind(ldr, s)]++
   976  	}
   977  
   978  	// On Mach-O, even with -s, we still need to keep dynamically exported and
   979  	// referenced symbols. We can strip defined local text and data symbols.
   980  	// So *FlagS is applied based on symbol type.
   981  
   982  	// Add special runtime.text and runtime.etext symbols (which are local).
   983  	// We've already included this symbol in Textp on darwin if ctxt.DynlinkingGo().
   984  	// See data.go:/textaddress
   985  	// NOTE: runtime.text.N symbols (if we split text sections) are not added, though,
   986  	// so we handle them here.
   987  	if !*FlagS {
   988  		if !ctxt.DynlinkingGo() {
   989  			s := ldr.Lookup("runtime.text", 0)
   990  			if ldr.SymType(s).IsText() {
   991  				addsym(s)
   992  			}
   993  		}
   994  		for n := range Segtext.Sections[1:] {
   995  			s := ldr.Lookup(fmt.Sprintf("runtime.text.%d", n+1), 0)
   996  			if s != 0 {
   997  				addsym(s)
   998  			} else {
   999  				break
  1000  			}
  1001  		}
  1002  		if !ctxt.DynlinkingGo() {
  1003  			s := ldr.Lookup("runtime.etext", 0)
  1004  			if ldr.SymType(s).IsText() {
  1005  				addsym(s)
  1006  			}
  1007  		}
  1008  	}
  1009  
  1010  	// Add text symbols.
  1011  	for _, s := range ctxt.Textp {
  1012  		if *FlagS && !ldr.AttrCgoExportDynamic(s) {
  1013  			continue
  1014  		}
  1015  		addsym(s)
  1016  	}
  1017  
  1018  	shouldBeInSymbolTable := func(s loader.Sym) bool {
  1019  		if ldr.AttrNotInSymbolTable(s) {
  1020  			return false
  1021  		}
  1022  		name := ldr.SymName(s) // TODO: try not to read the name
  1023  		if name == "" || name[0] == '.' {
  1024  			return false
  1025  		}
  1026  		return true
  1027  	}
  1028  
  1029  	// Add data symbols and external references.
  1030  	for s := loader.Sym(1); s < loader.Sym(ldr.NSym()); s++ {
  1031  		if !ldr.AttrReachable(s) {
  1032  			continue
  1033  		}
  1034  		t := ldr.SymType(s)
  1035  		if t >= sym.SELFRXSECT && t < sym.SFirstUnallocated { // data sections handled in dodata
  1036  			if t == sym.STLSBSS {
  1037  				// TLSBSS is not used on darwin. See data.go:allocateDataSections
  1038  				continue
  1039  			}
  1040  			if !shouldBeInSymbolTable(s) {
  1041  				continue
  1042  			}
  1043  			if *FlagS && !ldr.AttrCgoExportDynamic(s) {
  1044  				continue
  1045  			}
  1046  			addsym(s)
  1047  			continue
  1048  		}
  1049  
  1050  		switch t {
  1051  		case sym.SDYNIMPORT, sym.SHOSTOBJ, sym.SUNDEFEXT:
  1052  			// Keep dynamic symbol references even if *FlagS.
  1053  			addsym(s)
  1054  		}
  1055  
  1056  		// Some 64-bit functions have a "$INODE64" or "$INODE64$UNIX2003" suffix.
  1057  		if t == sym.SDYNIMPORT && ldr.SymDynimplib(s) == "/usr/lib/libSystem.B.dylib" {
  1058  			// But only on macOS.
  1059  			if machoPlatform == PLATFORM_MACOS || machoPlatform == PLATFORM_MACCATALYST {
  1060  				switch n := ldr.SymExtname(s); n {
  1061  				case "fdopendir":
  1062  					switch buildcfg.GOARCH {
  1063  					case "amd64":
  1064  						ldr.SetSymExtname(s, n+"$INODE64")
  1065  					}
  1066  				case "readdir_r", "getfsstat":
  1067  					switch buildcfg.GOARCH {
  1068  					case "amd64":
  1069  						ldr.SetSymExtname(s, n+"$INODE64")
  1070  					}
  1071  				}
  1072  			}
  1073  		}
  1074  	}
  1075  
  1076  	nsortsym = len(sortsym)
  1077  }
  1078  
  1079  func machosymorder(ctxt *Link) {
  1080  	ldr := ctxt.loader
  1081  
  1082  	// On Mac OS X Mountain Lion, we must sort exported symbols
  1083  	// So we sort them here and pre-allocate dynid for them
  1084  	// See https://golang.org/issue/4029
  1085  	for _, s := range ctxt.dynexp {
  1086  		if !ldr.AttrReachable(s) {
  1087  			panic("dynexp symbol is not reachable")
  1088  		}
  1089  	}
  1090  	collectmachosyms(ctxt)
  1091  	sort.Slice(sortsym[:nsortsym], func(i, j int) bool {
  1092  		s1 := sortsym[i]
  1093  		s2 := sortsym[j]
  1094  		k1 := symkind(ldr, s1)
  1095  		k2 := symkind(ldr, s2)
  1096  		if k1 != k2 {
  1097  			return k1 < k2
  1098  		}
  1099  		return ldr.SymExtname(s1) < ldr.SymExtname(s2) // Note: unnamed symbols are not added in collectmachosyms
  1100  	})
  1101  	for i, s := range sortsym {
  1102  		ldr.SetSymDynid(s, int32(i))
  1103  	}
  1104  }
  1105  
  1106  // AddMachoSym adds s to Mach-O symbol table, used in GenSymLate.
  1107  // Currently only used on ARM64 when external linking.
  1108  func AddMachoSym(ctxt *Link, s loader.Sym) {
  1109  	ldr := ctxt.loader
  1110  	ldr.SetSymDynid(s, int32(nsortsym))
  1111  	sortsym = append(sortsym, s)
  1112  	nsortsym++
  1113  	nkind[symkind(ldr, s)]++
  1114  	symtab := ldr.CreateSymForUpdate(".machosymtab", 0)
  1115  	symstr := ldr.CreateSymForUpdate(".machosymstr", 0)
  1116  	machosymtab1(ctxt, symtab, symstr, s)
  1117  }
  1118  
  1119  // machoShouldExport reports whether a symbol needs to be exported.
  1120  //
  1121  // When dynamically linking, all non-local variables and plugin-exported
  1122  // symbols need to be exported.
  1123  func machoShouldExport(ctxt *Link, ldr *loader.Loader, s loader.Sym) bool {
  1124  	if !ctxt.DynlinkingGo() || ldr.AttrLocal(s) || (ldr.IsContentHashed(s) && ldr.SymType(s).IsText()) {
  1125  		return false
  1126  	}
  1127  	if ctxt.BuildMode == BuildModePlugin && strings.HasPrefix(ldr.SymExtname(s), objabi.PathToPrefix(*flagPluginPath)) {
  1128  		return true
  1129  	}
  1130  	name := ldr.SymName(s)
  1131  	if strings.HasPrefix(name, "go:itab.") {
  1132  		return true
  1133  	}
  1134  	if strings.HasPrefix(name, "type:") && !strings.HasPrefix(name, "type:.") {
  1135  		// reduce runtime typemap pressure, but do not
  1136  		// export alg functions (type:.*), as these
  1137  		// appear in pclntable.
  1138  		return true
  1139  	}
  1140  	if strings.HasPrefix(name, "go:link.pkghash") {
  1141  		return true
  1142  	}
  1143  	return ldr.SymType(s) >= sym.SFirstWritable // only writable sections
  1144  }
  1145  
  1146  func machosymtab(ctxt *Link) {
  1147  	ldr := ctxt.loader
  1148  	symtab := ldr.CreateSymForUpdate(".machosymtab", 0)
  1149  	symstr := ldr.CreateSymForUpdate(".machosymstr", 0)
  1150  
  1151  	for _, s := range sortsym[:nsortsym] {
  1152  		machosymtab1(ctxt, symtab, symstr, s)
  1153  	}
  1154  }
  1155  
  1156  func machosymtab1(ctxt *Link, symtab, symstr *loader.SymbolBuilder, s loader.Sym) {
  1157  	ldr := ctxt.loader
  1158  	symtab.AddUint32(ctxt.Arch, uint32(symstr.Size()))
  1159  
  1160  	export := machoShouldExport(ctxt, ldr, s)
  1161  
  1162  	// Prefix symbol names with "_" to match the system toolchain.
  1163  	// (We used to only prefix C symbols, which is all required for the build.
  1164  	// But some tools don't recognize Go symbols as symbols, so we prefix them
  1165  	// as well.)
  1166  	symstr.AddUint8('_')
  1167  
  1168  	// replace "·" as ".", because DTrace cannot handle it.
  1169  	name := strings.ReplaceAll(ldr.SymExtname(s), "·", ".")
  1170  
  1171  	name = mangleABIName(ctxt, ldr, s, name)
  1172  	symstr.Addstring(name)
  1173  
  1174  	if t := ldr.SymType(s); t == sym.SDYNIMPORT || t == sym.SHOSTOBJ || t == sym.SUNDEFEXT {
  1175  		symtab.AddUint8(0x01)                             // type N_EXT, external symbol
  1176  		symtab.AddUint8(0)                                // no section
  1177  		symtab.AddUint16(ctxt.Arch, 0)                    // desc
  1178  		symtab.AddUintXX(ctxt.Arch, 0, ctxt.Arch.PtrSize) // no value
  1179  	} else {
  1180  		if export || ldr.AttrCgoExportDynamic(s) {
  1181  			symtab.AddUint8(0x0f) // N_SECT | N_EXT
  1182  		} else if ldr.AttrCgoExportStatic(s) {
  1183  			// Only export statically, not dynamically. (N_PEXT is like hidden visibility)
  1184  			symtab.AddUint8(0x1f) // N_SECT | N_EXT | N_PEXT
  1185  		} else {
  1186  			symtab.AddUint8(0x0e) // N_SECT
  1187  		}
  1188  		o := s
  1189  		if outer := ldr.OuterSym(o); outer != 0 {
  1190  			o = outer
  1191  		}
  1192  		if ldr.SymSect(o) == nil {
  1193  			ldr.Errorf(s, "missing section for symbol")
  1194  			symtab.AddUint8(0)
  1195  		} else {
  1196  			symtab.AddUint8(uint8(ldr.SymSect(o).Extnum))
  1197  		}
  1198  		symtab.AddUint16(ctxt.Arch, 0) // desc
  1199  		symtab.AddUintXX(ctxt.Arch, uint64(ldr.SymAddr(s)), ctxt.Arch.PtrSize)
  1200  	}
  1201  }
  1202  
  1203  func machodysymtab(ctxt *Link, base int64) {
  1204  	ml := newMachoLoad(ctxt.Arch, imacho.LC_DYSYMTAB, 18)
  1205  
  1206  	n := 0
  1207  	ml.data[0] = uint32(n)                   /* ilocalsym */
  1208  	ml.data[1] = uint32(nkind[SymKindLocal]) /* nlocalsym */
  1209  	n += nkind[SymKindLocal]
  1210  
  1211  	ml.data[2] = uint32(n)                    /* iextdefsym */
  1212  	ml.data[3] = uint32(nkind[SymKindExtdef]) /* nextdefsym */
  1213  	n += nkind[SymKindExtdef]
  1214  
  1215  	ml.data[4] = uint32(n)                   /* iundefsym */
  1216  	ml.data[5] = uint32(nkind[SymKindUndef]) /* nundefsym */
  1217  
  1218  	ml.data[6] = 0  /* tocoffset */
  1219  	ml.data[7] = 0  /* ntoc */
  1220  	ml.data[8] = 0  /* modtaboff */
  1221  	ml.data[9] = 0  /* nmodtab */
  1222  	ml.data[10] = 0 /* extrefsymoff */
  1223  	ml.data[11] = 0 /* nextrefsyms */
  1224  
  1225  	ldr := ctxt.loader
  1226  
  1227  	// must match domacholink below
  1228  	s1 := ldr.SymSize(ldr.Lookup(".machosymtab", 0))
  1229  	s2 := ldr.SymSize(ctxt.ArchSyms.LinkEditPLT)
  1230  	s3 := ldr.SymSize(ctxt.ArchSyms.LinkEditGOT)
  1231  	ml.data[12] = uint32(base + s1)     /* indirectsymoff */
  1232  	ml.data[13] = uint32((s2 + s3) / 4) /* nindirectsyms */
  1233  
  1234  	ml.data[14] = 0 /* extreloff */
  1235  	ml.data[15] = 0 /* nextrel */
  1236  	ml.data[16] = 0 /* locreloff */
  1237  	ml.data[17] = 0 /* nlocrel */
  1238  }
  1239  
  1240  func doMachoLink(ctxt *Link) int64 {
  1241  	machoDyldInfo(ctxt)
  1242  
  1243  	ldr := ctxt.loader
  1244  
  1245  	// write data that will be linkedit section
  1246  	s1 := ldr.Lookup(".machorebase", 0)
  1247  	s2 := ldr.Lookup(".machobind", 0)
  1248  	s3 := ldr.Lookup(".machosymtab", 0)
  1249  	s4 := ctxt.ArchSyms.LinkEditPLT
  1250  	s5 := ctxt.ArchSyms.LinkEditGOT
  1251  	s6 := ldr.Lookup(".machosymstr", 0)
  1252  
  1253  	size := ldr.SymSize(s1) + ldr.SymSize(s2) + ldr.SymSize(s3) + ldr.SymSize(s4) + ldr.SymSize(s5) + ldr.SymSize(s6)
  1254  
  1255  	if size > 0 {
  1256  		linkoff = Rnd(int64(uint64(HEADR)+Segtext.Length), *FlagRound) + Rnd(int64(Segrelrodata.Filelen), *FlagRound) + Rnd(int64(Segdata.Filelen), *FlagRound)
  1257  		if !(*FlagSplitDWARF && ctxt.IsInternal()) {
  1258  			linkoff += Rnd(int64(Segdwarf.Filelen), *FlagRound)
  1259  		}
  1260  		ctxt.Out.SeekSet(linkoff)
  1261  
  1262  		ctxt.Out.Write(ldr.Data(s1))
  1263  		ctxt.Out.Write(ldr.Data(s2))
  1264  		ctxt.Out.Write(ldr.Data(s3))
  1265  		ctxt.Out.Write(ldr.Data(s4))
  1266  		ctxt.Out.Write(ldr.Data(s5))
  1267  		ctxt.Out.Write(ldr.Data(s6))
  1268  
  1269  		// Force the linkedit section to end on a 16-byte
  1270  		// boundary. This allows pure (non-cgo) Go binaries
  1271  		// to be code signed correctly.
  1272  		//
  1273  		// Apple's codesign_allocate (a helper utility for
  1274  		// the codesign utility) can do this fine itself if
  1275  		// it is run on a dynamic Mach-O binary. However,
  1276  		// when it is run on a pure (non-cgo) Go binary, where
  1277  		// the linkedit section is mostly empty, it fails to
  1278  		// account for the extra padding that it itself adds
  1279  		// when adding the LC_CODE_SIGNATURE load command
  1280  		// (which must be aligned on a 16-byte boundary).
  1281  		//
  1282  		// By forcing the linkedit section to end on a 16-byte
  1283  		// boundary, codesign_allocate will not need to apply
  1284  		// any alignment padding itself, working around the
  1285  		// issue.
  1286  		if size%16 != 0 {
  1287  			n := 16 - size%16
  1288  			ctxt.Out.Write(zeros[:n])
  1289  			size += n
  1290  		}
  1291  
  1292  		// Add code signature if necessary. This must be the last.
  1293  		s7 := machoCodeSigSym(ctxt, linkoff+size)
  1294  		size += ldr.SymSize(s7)
  1295  	}
  1296  
  1297  	return Rnd(size, *FlagRound)
  1298  }
  1299  
  1300  func machorelocsect(ctxt *Link, out *OutBuf, sect *sym.Section, syms []loader.Sym) {
  1301  	// If main section has no bits, nothing to relocate.
  1302  	if sect.Vaddr >= sect.Seg.Vaddr+sect.Seg.Filelen {
  1303  		return
  1304  	}
  1305  	ldr := ctxt.loader
  1306  
  1307  	for i, s := range syms {
  1308  		if !ldr.AttrReachable(s) {
  1309  			continue
  1310  		}
  1311  		if uint64(ldr.SymValue(s)) >= sect.Vaddr {
  1312  			syms = syms[i:]
  1313  			break
  1314  		}
  1315  	}
  1316  
  1317  	eaddr := sect.Vaddr + sect.Length
  1318  	for _, s := range syms {
  1319  		if !ldr.AttrReachable(s) {
  1320  			continue
  1321  		}
  1322  		if ldr.SymValue(s) >= int64(eaddr) {
  1323  			break
  1324  		}
  1325  
  1326  		// Compute external relocations on the go, and pass to Machoreloc1
  1327  		// to stream out.
  1328  		relocs := ldr.Relocs(s)
  1329  		for ri := 0; ri < relocs.Count(); ri++ {
  1330  			r := relocs.At(ri)
  1331  			rr, ok := extreloc(ctxt, ldr, s, r)
  1332  			if !ok {
  1333  				continue
  1334  			}
  1335  			if rr.Xsym == 0 {
  1336  				ldr.Errorf(s, "missing xsym in relocation")
  1337  				continue
  1338  			}
  1339  			if !ldr.AttrReachable(rr.Xsym) {
  1340  				ldr.Errorf(s, "unreachable reloc %d (%s) target %v", r.Type(), sym.RelocName(ctxt.Arch, r.Type()), ldr.SymName(rr.Xsym))
  1341  			}
  1342  			if !thearch.Machoreloc1(ctxt.Arch, out, ldr, s, rr, int64(uint64(ldr.SymValue(s)+int64(r.Off()))-sect.Vaddr)) {
  1343  				ldr.Errorf(s, "unsupported obj reloc %d (%s)/%d to %s", r.Type(), sym.RelocName(ctxt.Arch, r.Type()), r.Siz(), ldr.SymName(r.Sym()))
  1344  			}
  1345  		}
  1346  	}
  1347  
  1348  	// sanity check
  1349  	if uint64(out.Offset()) != sect.Reloff+sect.Rellen {
  1350  		panic("machorelocsect: size mismatch")
  1351  	}
  1352  }
  1353  
  1354  func machoEmitReloc(ctxt *Link) {
  1355  	for ctxt.Out.Offset()&7 != 0 {
  1356  		ctxt.Out.Write8(0)
  1357  	}
  1358  
  1359  	sizeExtRelocs(ctxt, thearch.MachorelocSize)
  1360  	relocSect, wg := relocSectFn(ctxt, machorelocsect)
  1361  
  1362  	relocSect(ctxt, Segtext.Sections[0], ctxt.Textp)
  1363  	for _, sect := range Segtext.Sections[1:] {
  1364  		if sect.Name == ".text" {
  1365  			relocSect(ctxt, sect, ctxt.Textp)
  1366  		} else {
  1367  			relocSect(ctxt, sect, ctxt.datap)
  1368  		}
  1369  	}
  1370  	for _, sect := range Segrelrodata.Sections {
  1371  		relocSect(ctxt, sect, ctxt.datap)
  1372  	}
  1373  	for _, sect := range Segdata.Sections {
  1374  		relocSect(ctxt, sect, ctxt.datap)
  1375  	}
  1376  	for i := 0; i < len(Segdwarf.Sections); i++ {
  1377  		sect := Segdwarf.Sections[i]
  1378  		si := dwarfp[i]
  1379  		if si.secSym() != sect.Sym ||
  1380  			ctxt.loader.SymSect(si.secSym()) != sect {
  1381  			panic("inconsistency between dwarfp and Segdwarf")
  1382  		}
  1383  		relocSect(ctxt, sect, si.syms)
  1384  	}
  1385  	wg.Wait()
  1386  }
  1387  
  1388  // hostobjMachoPlatform returns the first platform load command found
  1389  // in the host object, if any.
  1390  func hostobjMachoPlatform(h *Hostobj) (*MachoPlatformLoad, error) {
  1391  	f, err := os.Open(h.file)
  1392  	if err != nil {
  1393  		return nil, fmt.Errorf("%s: failed to open host object: %v\n", h.file, err)
  1394  	}
  1395  	defer f.Close()
  1396  	sr := io.NewSectionReader(f, h.off, h.length)
  1397  	m, err := macho.NewFile(sr)
  1398  	if err != nil {
  1399  		// Not a valid Mach-O file.
  1400  		return nil, nil
  1401  	}
  1402  	return peekMachoPlatform(m)
  1403  }
  1404  
  1405  // peekMachoPlatform returns the first LC_VERSION_MIN_* or LC_BUILD_VERSION
  1406  // load command found in the Mach-O file, if any.
  1407  func peekMachoPlatform(m *macho.File) (*MachoPlatformLoad, error) {
  1408  	for _, cmd := range m.Loads {
  1409  		raw := cmd.Raw()
  1410  		ml := MachoLoad{
  1411  			type_: m.ByteOrder.Uint32(raw),
  1412  		}
  1413  		// Skip the type and command length.
  1414  		data := raw[8:]
  1415  		var p MachoPlatform
  1416  		switch ml.type_ {
  1417  		case imacho.LC_VERSION_MIN_IPHONEOS:
  1418  			p = PLATFORM_IOS
  1419  		case imacho.LC_VERSION_MIN_MACOSX:
  1420  			p = PLATFORM_MACOS
  1421  		case imacho.LC_VERSION_MIN_WATCHOS:
  1422  			p = PLATFORM_WATCHOS
  1423  		case imacho.LC_VERSION_MIN_TVOS:
  1424  			p = PLATFORM_TVOS
  1425  		case imacho.LC_BUILD_VERSION:
  1426  			p = MachoPlatform(m.ByteOrder.Uint32(data))
  1427  		default:
  1428  			continue
  1429  		}
  1430  		ml.data = make([]uint32, len(data)/4)
  1431  		r := bytes.NewReader(data)
  1432  		if err := binary.Read(r, m.ByteOrder, &ml.data); err != nil {
  1433  			return nil, err
  1434  		}
  1435  		return &MachoPlatformLoad{
  1436  			platform: p,
  1437  			cmd:      ml,
  1438  		}, nil
  1439  	}
  1440  	return nil, nil
  1441  }
  1442  
  1443  // A rebase entry tells the dynamic linker the data at sym+off needs to be
  1444  // relocated when the in-memory image moves. (This is somewhat like, say,
  1445  // ELF R_X86_64_RELATIVE).
  1446  // For now, the only kind of entry we support is that the data is an absolute
  1447  // address. That seems all we need.
  1448  // In the binary it uses a compact stateful bytecode encoding. So we record
  1449  // entries as we go and build the table at the end.
  1450  type machoRebaseRecord struct {
  1451  	sym loader.Sym
  1452  	off int64
  1453  }
  1454  
  1455  var machorebase []machoRebaseRecord
  1456  
  1457  func MachoAddRebase(s loader.Sym, off int64) {
  1458  	machorebase = append(machorebase, machoRebaseRecord{s, off})
  1459  }
  1460  
  1461  // A bind entry tells the dynamic linker the data at sym+off should be bound
  1462  // to the address of the target symbol, which is a dynamic import.
  1463  // sym is the symbol containing the pointer (e.g. the GOT or a data symbol),
  1464  // off is the offset within that symbol, and targ is the dynamic import target.
  1465  // For now, the only kind of entry we support is that the data is an absolute
  1466  // address. That seems all we need.
  1467  // In the binary it uses a compact stateful bytecode encoding. So we record
  1468  // entries as we go and build the table at the end.
  1469  type machoBindRecord struct {
  1470  	sym  loader.Sym
  1471  	off  int64
  1472  	targ loader.Sym
  1473  }
  1474  
  1475  var machobind []machoBindRecord
  1476  
  1477  func MachoAddBind(sym loader.Sym, off int64, targ loader.Sym) {
  1478  	machobind = append(machobind, machoBindRecord{sym, off, targ})
  1479  }
  1480  
  1481  // Generate data for the dynamic linker, used in LC_DYLD_INFO_ONLY load command.
  1482  // See mach-o/loader.h, struct dyld_info_command, for the encoding.
  1483  // e.g. https://opensource.apple.com/source/xnu/xnu-6153.81.5/EXTERNAL_HEADERS/mach-o/loader.h
  1484  func machoDyldInfo(ctxt *Link) {
  1485  	ldr := ctxt.loader
  1486  	rebase := ldr.CreateSymForUpdate(".machorebase", 0)
  1487  	bind := ldr.CreateSymForUpdate(".machobind", 0)
  1488  
  1489  	if !(ctxt.IsPIE() && ctxt.IsInternal()) {
  1490  		return
  1491  	}
  1492  
  1493  	segId := func(seg *sym.Segment) uint8 {
  1494  		switch seg {
  1495  		case &Segtext:
  1496  			return 1
  1497  		case &Segrelrodata:
  1498  			return 2
  1499  		case &Segdata:
  1500  			if Segrelrodata.Length > 0 {
  1501  				return 3
  1502  			}
  1503  			return 2
  1504  		}
  1505  		panic("unknown segment")
  1506  	}
  1507  
  1508  	dylibId := func(s loader.Sym) int {
  1509  		slib := ldr.SymDynimplib(s)
  1510  		for i, lib := range dylib {
  1511  			if lib == slib {
  1512  				return i + 1
  1513  			}
  1514  		}
  1515  		return BIND_SPECIAL_DYLIB_FLAT_LOOKUP // don't know where it is from
  1516  	}
  1517  
  1518  	// Rebase table.
  1519  	// TODO: use more compact encoding. The encoding is stateful, and
  1520  	// we can use delta encoding.
  1521  	rebase.AddUint8(REBASE_OPCODE_SET_TYPE_IMM | REBASE_TYPE_POINTER)
  1522  	for _, r := range machorebase {
  1523  		seg := ldr.SymSect(r.sym).Seg
  1524  		off := uint64(ldr.SymValue(r.sym)+r.off) - seg.Vaddr
  1525  		rebase.AddUint8(REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB | segId(seg))
  1526  		rebase.AddUleb(off)
  1527  
  1528  		rebase.AddUint8(REBASE_OPCODE_DO_REBASE_IMM_TIMES | 1)
  1529  	}
  1530  	rebase.AddUint8(REBASE_OPCODE_DONE)
  1531  	sz := Rnd(rebase.Size(), 8)
  1532  	rebase.Grow(sz)
  1533  	rebase.SetSize(sz)
  1534  
  1535  	// Bind table.
  1536  	// TODO: compact encoding, as above.
  1537  	// TODO: lazy binding?
  1538  	bind.AddUint8(BIND_OPCODE_SET_TYPE_IMM | BIND_TYPE_POINTER)
  1539  	for _, r := range machobind {
  1540  		seg := ldr.SymSect(r.sym).Seg
  1541  		off := uint64(ldr.SymValue(r.sym)+r.off) - seg.Vaddr
  1542  		bind.AddUint8(BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB | segId(seg))
  1543  		bind.AddUleb(off)
  1544  
  1545  		d := dylibId(r.targ)
  1546  		if d > 0 && d < 128 {
  1547  			bind.AddUint8(BIND_OPCODE_SET_DYLIB_ORDINAL_IMM | uint8(d)&0xf)
  1548  		} else if d >= 128 {
  1549  			bind.AddUint8(BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB)
  1550  			bind.AddUleb(uint64(d))
  1551  		} else { // d <= 0
  1552  			bind.AddUint8(BIND_OPCODE_SET_DYLIB_SPECIAL_IMM | uint8(d)&0xf)
  1553  		}
  1554  
  1555  		flags := uint8(0)
  1556  		if ldr.SymWeakBinding(r.targ) {
  1557  			flags |= BIND_SYMBOL_FLAGS_WEAK_IMPORT
  1558  		}
  1559  		bind.AddUint8(BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM | flags)
  1560  		// target symbol name as a C string, with _ prefix
  1561  		bind.AddUint8('_')
  1562  		bind.Addstring(ldr.SymExtname(r.targ))
  1563  
  1564  		bind.AddUint8(BIND_OPCODE_DO_BIND)
  1565  	}
  1566  	bind.AddUint8(BIND_OPCODE_DONE)
  1567  	sz = Rnd(bind.Size(), 16) // make it 16-byte aligned, see the comment in doMachoLink
  1568  	bind.Grow(sz)
  1569  	bind.SetSize(sz)
  1570  
  1571  	// TODO: export table.
  1572  	// The symbols names are encoded as a trie. I'm really too lazy to do that
  1573  	// for now.
  1574  	// Without it, the symbols are not dynamically exported, so they cannot be
  1575  	// e.g. dlsym'd. But internal linking is not the default in that case, so
  1576  	// it is fine.
  1577  }
  1578  
  1579  // machoCodeSigSym creates and returns a symbol for code signature.
  1580  // The symbol context is left as zeros, which will be generated at the end
  1581  // (as it depends on the rest of the file).
  1582  func machoCodeSigSym(ctxt *Link, codeSize int64) loader.Sym {
  1583  	ldr := ctxt.loader
  1584  	cs := ldr.CreateSymForUpdate(".machocodesig", 0)
  1585  	if !ctxt.NeedCodeSign() || ctxt.IsExternal() {
  1586  		return cs.Sym()
  1587  	}
  1588  	sz := codesign.Size(codeSize, "a.out")
  1589  	cs.Grow(sz)
  1590  	cs.SetSize(sz)
  1591  	return cs.Sym()
  1592  }
  1593  
  1594  // machoCodeSign code-signs Mach-O file fname with an ad-hoc signature.
  1595  // This is used for updating an external linker generated binary.
  1596  func machoCodeSign(ctxt *Link, fname string) error {
  1597  	f, err := os.OpenFile(fname, os.O_RDWR, 0)
  1598  	if err != nil {
  1599  		return err
  1600  	}
  1601  	defer f.Close()
  1602  
  1603  	mf, err := macho.NewFile(f)
  1604  	if err != nil {
  1605  		return err
  1606  	}
  1607  	if mf.Magic != macho.Magic64 {
  1608  		Exitf("not 64-bit Mach-O file: %s", fname)
  1609  	}
  1610  
  1611  	// Find existing LC_CODE_SIGNATURE and __LINKEDIT segment
  1612  	var sigOff, sigSz, csCmdOff, linkeditOff int64
  1613  	var linkeditSeg, textSeg *macho.Segment
  1614  	loadOff := int64(machoHeaderSize64)
  1615  	get32 := mf.ByteOrder.Uint32
  1616  	for _, l := range mf.Loads {
  1617  		data := l.Raw()
  1618  		cmd, sz := get32(data), get32(data[4:])
  1619  		if cmd == imacho.LC_CODE_SIGNATURE {
  1620  			sigOff = int64(get32(data[8:]))
  1621  			sigSz = int64(get32(data[12:]))
  1622  			csCmdOff = loadOff
  1623  		}
  1624  		if seg, ok := l.(*macho.Segment); ok {
  1625  			switch seg.Name {
  1626  			case "__LINKEDIT":
  1627  				linkeditSeg = seg
  1628  				linkeditOff = loadOff
  1629  			case "__TEXT":
  1630  				textSeg = seg
  1631  			}
  1632  		}
  1633  		loadOff += int64(sz)
  1634  	}
  1635  
  1636  	if sigOff == 0 {
  1637  		// The C linker doesn't generate a signed binary, for some reason.
  1638  		// Skip.
  1639  		return nil
  1640  	}
  1641  
  1642  	fi, err := f.Stat()
  1643  	if err != nil {
  1644  		return err
  1645  	}
  1646  	if sigOff+sigSz != fi.Size() {
  1647  		// We don't expect anything after the signature (this will invalidate
  1648  		// the signature anyway.)
  1649  		return fmt.Errorf("unexpected content after code signature")
  1650  	}
  1651  
  1652  	sz := codesign.Size(sigOff, "a.out")
  1653  	if sz != sigSz {
  1654  		// Update the load command,
  1655  		var tmp [8]byte
  1656  		mf.ByteOrder.PutUint32(tmp[:4], uint32(sz))
  1657  		_, err = f.WriteAt(tmp[:4], csCmdOff+12)
  1658  		if err != nil {
  1659  			return err
  1660  		}
  1661  
  1662  		// Uodate the __LINKEDIT segment.
  1663  		segSz := sigOff + sz - int64(linkeditSeg.Offset)
  1664  		mf.ByteOrder.PutUint64(tmp[:8], uint64(segSz))
  1665  		_, err = f.WriteAt(tmp[:8], linkeditOff+int64(unsafe.Offsetof(macho.Segment64{}.Memsz)))
  1666  		if err != nil {
  1667  			return err
  1668  		}
  1669  		_, err = f.WriteAt(tmp[:8], linkeditOff+int64(unsafe.Offsetof(macho.Segment64{}.Filesz)))
  1670  		if err != nil {
  1671  			return err
  1672  		}
  1673  	}
  1674  
  1675  	cs := make([]byte, sz)
  1676  	codesign.Sign(cs, f, "a.out", sigOff, int64(textSeg.Offset), int64(textSeg.Filesz), ctxt.IsExe() || ctxt.IsPIE())
  1677  	_, err = f.WriteAt(cs, sigOff)
  1678  	if err != nil {
  1679  		return err
  1680  	}
  1681  	err = f.Truncate(sigOff + sz)
  1682  	return err
  1683  }
  1684  

View as plain text