github.com/gagliardetto/golang-go@v0.0.0-20201020153340-53909ea70814/cmd/link/internal/ld/util.go (about)

     1  // Copyright 2015 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  	"github.com/gagliardetto/golang-go/cmd/link/internal/sym"
     9  	"encoding/binary"
    10  	"fmt"
    11  	"os"
    12  )
    13  
    14  var atExitFuncs []func()
    15  
    16  func AtExit(f func()) {
    17  	atExitFuncs = append(atExitFuncs, f)
    18  }
    19  
    20  // runAtExitFuncs runs the queued set of AtExit functions.
    21  func runAtExitFuncs() {
    22  	for i := len(atExitFuncs) - 1; i >= 0; i-- {
    23  		atExitFuncs[i]()
    24  	}
    25  	atExitFuncs = nil
    26  }
    27  
    28  // Exit exits with code after executing all atExitFuncs.
    29  func Exit(code int) {
    30  	runAtExitFuncs()
    31  	os.Exit(code)
    32  }
    33  
    34  // Exitf logs an error message then calls Exit(2).
    35  func Exitf(format string, a ...interface{}) {
    36  	fmt.Fprintf(os.Stderr, os.Args[0]+": "+format+"\n", a...)
    37  	nerrors++
    38  	Exit(2)
    39  }
    40  
    41  // Errorf logs an error message.
    42  //
    43  // If more than 20 errors have been printed, exit with an error.
    44  //
    45  // Logging an error means that on exit cmd/link will delete any
    46  // output file and return a non-zero error code.
    47  func Errorf(s *sym.Symbol, format string, args ...interface{}) {
    48  	if s != nil {
    49  		format = s.Name + ": " + format
    50  	}
    51  	format += "\n"
    52  	fmt.Fprintf(os.Stderr, format, args...)
    53  	nerrors++
    54  	if *flagH {
    55  		panic("error")
    56  	}
    57  	if nerrors > 20 {
    58  		Exitf("too many errors")
    59  	}
    60  }
    61  
    62  func artrim(x []byte) string {
    63  	i := 0
    64  	j := len(x)
    65  	for i < len(x) && x[i] == ' ' {
    66  		i++
    67  	}
    68  	for j > i && x[j-1] == ' ' {
    69  		j--
    70  	}
    71  	return string(x[i:j])
    72  }
    73  
    74  func stringtouint32(x []uint32, s string) {
    75  	for i := 0; len(s) > 0; i++ {
    76  		var buf [4]byte
    77  		s = s[copy(buf[:], s):]
    78  		x[i] = binary.LittleEndian.Uint32(buf[:])
    79  	}
    80  }
    81  
    82  // contains reports whether v is in s.
    83  func contains(s []string, v string) bool {
    84  	for _, x := range s {
    85  		if x == v {
    86  			return true
    87  		}
    88  	}
    89  	return false
    90  }
    91  
    92  // implements sort.Interface, for sorting symbols by name.
    93  type byName []*sym.Symbol
    94  
    95  func (s byName) Len() int           { return len(s) }
    96  func (s byName) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
    97  func (s byName) Less(i, j int) bool { return s[i].Name < s[j].Name }