github.com/dannin/go@v0.0.0-20161031215817-d35dfd405eaa/src/cmd/dist/util.go (about)

     1  // Copyright 2012 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 main
     6  
     7  import (
     8  	"bytes"
     9  	"fmt"
    10  	"io"
    11  	"io/ioutil"
    12  	"os"
    13  	"os/exec"
    14  	"path/filepath"
    15  	"runtime"
    16  	"sort"
    17  	"strconv"
    18  	"strings"
    19  	"sync"
    20  	"time"
    21  )
    22  
    23  // pathf is fmt.Sprintf for generating paths
    24  // (on windows it turns / into \ after the printf).
    25  func pathf(format string, args ...interface{}) string {
    26  	return filepath.Clean(fmt.Sprintf(format, args...))
    27  }
    28  
    29  // filter returns a slice containing the elements x from list for which f(x) == true.
    30  func filter(list []string, f func(string) bool) []string {
    31  	var out []string
    32  	for _, x := range list {
    33  		if f(x) {
    34  			out = append(out, x)
    35  		}
    36  	}
    37  	return out
    38  }
    39  
    40  // uniq returns a sorted slice containing the unique elements of list.
    41  func uniq(list []string) []string {
    42  	out := make([]string, len(list))
    43  	copy(out, list)
    44  	sort.Strings(out)
    45  	keep := out[:0]
    46  	for _, x := range out {
    47  		if len(keep) == 0 || keep[len(keep)-1] != x {
    48  			keep = append(keep, x)
    49  		}
    50  	}
    51  	return keep
    52  }
    53  
    54  // splitlines returns a slice with the result of splitting
    55  // the input p after each \n.
    56  func splitlines(p string) []string {
    57  	return strings.SplitAfter(p, "\n")
    58  }
    59  
    60  // splitfields replaces the vector v with the result of splitting
    61  // the input p into non-empty fields containing no spaces.
    62  func splitfields(p string) []string {
    63  	return strings.Fields(p)
    64  }
    65  
    66  const (
    67  	CheckExit = 1 << iota
    68  	ShowOutput
    69  	Background
    70  )
    71  
    72  var outputLock sync.Mutex
    73  
    74  // run runs the command line cmd in dir.
    75  // If mode has ShowOutput set and Background unset, run passes cmd's output to
    76  // stdout/stderr directly. Otherwise, run returns cmd's output as a string.
    77  // If mode has CheckExit set and the command fails, run calls fatal.
    78  // If mode has Background set, this command is being run as a
    79  // Background job. Only bgrun should use the Background mode,
    80  // not other callers.
    81  func run(dir string, mode int, cmd ...string) string {
    82  	if vflag > 1 {
    83  		errprintf("run: %s\n", strings.Join(cmd, " "))
    84  	}
    85  
    86  	xcmd := exec.Command(cmd[0], cmd[1:]...)
    87  	xcmd.Dir = dir
    88  	var data []byte
    89  	var err error
    90  
    91  	// If we want to show command output and this is not
    92  	// a background command, assume it's the only thing
    93  	// running, so we can just let it write directly stdout/stderr
    94  	// as it runs without fear of mixing the output with some
    95  	// other command's output. Not buffering lets the output
    96  	// appear as it is printed instead of once the command exits.
    97  	// This is most important for the invocation of 'go1.4 build -v bootstrap/...'.
    98  	if mode&(Background|ShowOutput) == ShowOutput {
    99  		xcmd.Stdout = os.Stdout
   100  		xcmd.Stderr = os.Stderr
   101  		err = xcmd.Run()
   102  	} else {
   103  		data, err = xcmd.CombinedOutput()
   104  	}
   105  	if err != nil && mode&CheckExit != 0 {
   106  		outputLock.Lock()
   107  		if len(data) > 0 {
   108  			xprintf("%s\n", data)
   109  		}
   110  		outputLock.Unlock()
   111  		if mode&Background != 0 {
   112  			// Prevent fatal from waiting on our own goroutine's
   113  			// bghelper to exit:
   114  			bghelpers.Done()
   115  		}
   116  		fatal("FAILED: %v: %v", strings.Join(cmd, " "), err)
   117  	}
   118  	if mode&ShowOutput != 0 {
   119  		outputLock.Lock()
   120  		os.Stdout.Write(data)
   121  		outputLock.Unlock()
   122  	}
   123  	if vflag > 2 {
   124  		errprintf("run: %s DONE\n", strings.Join(cmd, " "))
   125  	}
   126  	return string(data)
   127  }
   128  
   129  var maxbg = 4 /* maximum number of jobs to run at once */
   130  
   131  var (
   132  	bgwork = make(chan func(), 1e5)
   133  
   134  	bghelpers sync.WaitGroup
   135  
   136  	dieOnce sync.Once // guards close of dying
   137  	dying   = make(chan struct{})
   138  )
   139  
   140  func bginit() {
   141  	bghelpers.Add(maxbg)
   142  	for i := 0; i < maxbg; i++ {
   143  		go bghelper()
   144  	}
   145  }
   146  
   147  func bghelper() {
   148  	defer bghelpers.Done()
   149  	for {
   150  		select {
   151  		case <-dying:
   152  			return
   153  		case w := <-bgwork:
   154  			// Dying takes precedence over doing more work.
   155  			select {
   156  			case <-dying:
   157  				return
   158  			default:
   159  				w()
   160  			}
   161  		}
   162  	}
   163  }
   164  
   165  // bgrun is like run but runs the command in the background.
   166  // CheckExit|ShowOutput mode is implied (since output cannot be returned).
   167  // bgrun adds 1 to wg immediately, and calls Done when the work completes.
   168  func bgrun(wg *sync.WaitGroup, dir string, cmd ...string) {
   169  	wg.Add(1)
   170  	bgwork <- func() {
   171  		defer wg.Done()
   172  		run(dir, CheckExit|ShowOutput|Background, cmd...)
   173  	}
   174  }
   175  
   176  // bgwait waits for pending bgruns to finish.
   177  // bgwait must be called from only a single goroutine at a time.
   178  func bgwait(wg *sync.WaitGroup) {
   179  	done := make(chan struct{})
   180  	go func() {
   181  		wg.Wait()
   182  		close(done)
   183  	}()
   184  	select {
   185  	case <-done:
   186  	case <-dying:
   187  	}
   188  }
   189  
   190  // xgetwd returns the current directory.
   191  func xgetwd() string {
   192  	wd, err := os.Getwd()
   193  	if err != nil {
   194  		fatal("%s", err)
   195  	}
   196  	return wd
   197  }
   198  
   199  // xrealwd returns the 'real' name for the given path.
   200  // real is defined as what xgetwd returns in that directory.
   201  func xrealwd(path string) string {
   202  	old := xgetwd()
   203  	if err := os.Chdir(path); err != nil {
   204  		fatal("chdir %s: %v", path, err)
   205  	}
   206  	real := xgetwd()
   207  	if err := os.Chdir(old); err != nil {
   208  		fatal("chdir %s: %v", old, err)
   209  	}
   210  	return real
   211  }
   212  
   213  // isdir reports whether p names an existing directory.
   214  func isdir(p string) bool {
   215  	fi, err := os.Stat(p)
   216  	return err == nil && fi.IsDir()
   217  }
   218  
   219  // isfile reports whether p names an existing file.
   220  func isfile(p string) bool {
   221  	fi, err := os.Stat(p)
   222  	return err == nil && fi.Mode().IsRegular()
   223  }
   224  
   225  // mtime returns the modification time of the file p.
   226  func mtime(p string) time.Time {
   227  	fi, err := os.Stat(p)
   228  	if err != nil {
   229  		return time.Time{}
   230  	}
   231  	return fi.ModTime()
   232  }
   233  
   234  // isabs reports whether p is an absolute path.
   235  func isabs(p string) bool {
   236  	return filepath.IsAbs(p)
   237  }
   238  
   239  // readfile returns the content of the named file.
   240  func readfile(file string) string {
   241  	data, err := ioutil.ReadFile(file)
   242  	if err != nil {
   243  		fatal("%v", err)
   244  	}
   245  	return string(data)
   246  }
   247  
   248  const (
   249  	writeExec = 1 << iota
   250  	writeSkipSame
   251  )
   252  
   253  // writefile writes b to the named file, creating it if needed.
   254  // if exec is non-zero, marks the file as executable.
   255  // If the file already exists and has the expected content,
   256  // it is not rewritten, to avoid changing the time stamp.
   257  func writefile(b, file string, flag int) {
   258  	new := []byte(b)
   259  	if flag&writeSkipSame != 0 {
   260  		old, err := ioutil.ReadFile(file)
   261  		if err == nil && bytes.Equal(old, new) {
   262  			return
   263  		}
   264  	}
   265  	mode := os.FileMode(0666)
   266  	if flag&writeExec != 0 {
   267  		mode = 0777
   268  	}
   269  	err := ioutil.WriteFile(file, new, mode)
   270  	if err != nil {
   271  		fatal("%v", err)
   272  	}
   273  }
   274  
   275  // xmkdir creates the directory p.
   276  func xmkdir(p string) {
   277  	err := os.Mkdir(p, 0777)
   278  	if err != nil {
   279  		fatal("%v", err)
   280  	}
   281  }
   282  
   283  // xmkdirall creates the directory p and its parents, as needed.
   284  func xmkdirall(p string) {
   285  	err := os.MkdirAll(p, 0777)
   286  	if err != nil {
   287  		fatal("%v", err)
   288  	}
   289  }
   290  
   291  // xremove removes the file p.
   292  func xremove(p string) {
   293  	if vflag > 2 {
   294  		errprintf("rm %s\n", p)
   295  	}
   296  	os.Remove(p)
   297  }
   298  
   299  // xremoveall removes the file or directory tree rooted at p.
   300  func xremoveall(p string) {
   301  	if vflag > 2 {
   302  		errprintf("rm -r %s\n", p)
   303  	}
   304  	os.RemoveAll(p)
   305  }
   306  
   307  // xreaddir replaces dst with a list of the names of the files and subdirectories in dir.
   308  // The names are relative to dir; they are not full paths.
   309  func xreaddir(dir string) []string {
   310  	f, err := os.Open(dir)
   311  	if err != nil {
   312  		fatal("%v", err)
   313  	}
   314  	defer f.Close()
   315  	names, err := f.Readdirnames(-1)
   316  	if err != nil {
   317  		fatal("reading %s: %v", dir, err)
   318  	}
   319  	return names
   320  }
   321  
   322  // xreaddir replaces dst with a list of the names of the files in dir.
   323  // The names are relative to dir; they are not full paths.
   324  func xreaddirfiles(dir string) []string {
   325  	f, err := os.Open(dir)
   326  	if err != nil {
   327  		fatal("%v", err)
   328  	}
   329  	defer f.Close()
   330  	infos, err := f.Readdir(-1)
   331  	if err != nil {
   332  		fatal("reading %s: %v", dir, err)
   333  	}
   334  	var names []string
   335  	for _, fi := range infos {
   336  		if !fi.IsDir() {
   337  			names = append(names, fi.Name())
   338  		}
   339  	}
   340  	return names
   341  }
   342  
   343  // xworkdir creates a new temporary directory to hold object files
   344  // and returns the name of that directory.
   345  func xworkdir() string {
   346  	name, err := ioutil.TempDir("", "go-tool-dist-")
   347  	if err != nil {
   348  		fatal("%v", err)
   349  	}
   350  	return name
   351  }
   352  
   353  // fatal prints an error message to standard error and exits.
   354  func fatal(format string, args ...interface{}) {
   355  	fmt.Fprintf(os.Stderr, "go tool dist: %s\n", fmt.Sprintf(format, args...))
   356  
   357  	dieOnce.Do(func() { close(dying) })
   358  
   359  	// Wait for background goroutines to finish,
   360  	// so that exit handler that removes the work directory
   361  	// is not fighting with active writes or open files.
   362  	bghelpers.Wait()
   363  
   364  	xexit(2)
   365  }
   366  
   367  var atexits []func()
   368  
   369  // xexit exits the process with return code n.
   370  func xexit(n int) {
   371  	for i := len(atexits) - 1; i >= 0; i-- {
   372  		atexits[i]()
   373  	}
   374  	os.Exit(n)
   375  }
   376  
   377  // xatexit schedules the exit-handler f to be run when the program exits.
   378  func xatexit(f func()) {
   379  	atexits = append(atexits, f)
   380  }
   381  
   382  // xprintf prints a message to standard output.
   383  func xprintf(format string, args ...interface{}) {
   384  	fmt.Printf(format, args...)
   385  }
   386  
   387  // errprintf prints a message to standard output.
   388  func errprintf(format string, args ...interface{}) {
   389  	fmt.Fprintf(os.Stderr, format, args...)
   390  }
   391  
   392  // main takes care of OS-specific startup and dispatches to xmain.
   393  func main() {
   394  	os.Setenv("TERM", "dumb") // disable escape codes in clang errors
   395  
   396  	slash = string(filepath.Separator)
   397  
   398  	gohostos = runtime.GOOS
   399  	switch gohostos {
   400  	case "darwin":
   401  		// Even on 64-bit platform, darwin uname -m prints i386.
   402  		// We don't support any of the OS X versions that run on 32-bit-only hardware anymore.
   403  		gohostarch = "amd64"
   404  	case "freebsd":
   405  		// Since FreeBSD 10 gcc is no longer part of the base system.
   406  		defaultclang = true
   407  	case "solaris":
   408  		// Even on 64-bit platform, solaris uname -m prints i86pc.
   409  		out := run("", CheckExit, "isainfo", "-n")
   410  		if strings.Contains(out, "amd64") {
   411  			gohostarch = "amd64"
   412  		}
   413  		if strings.Contains(out, "i386") {
   414  			gohostarch = "386"
   415  		}
   416  	case "plan9":
   417  		gohostarch = os.Getenv("objtype")
   418  		if gohostarch == "" {
   419  			fatal("$objtype is unset")
   420  		}
   421  	case "windows":
   422  		exe = ".exe"
   423  	}
   424  
   425  	sysinit()
   426  
   427  	if gohostarch == "" {
   428  		// Default Unix system.
   429  		out := run("", CheckExit, "uname", "-m")
   430  		switch {
   431  		case strings.Contains(out, "x86_64"), strings.Contains(out, "amd64"):
   432  			gohostarch = "amd64"
   433  		case strings.Contains(out, "86"):
   434  			gohostarch = "386"
   435  		case strings.Contains(out, "arm"):
   436  			gohostarch = "arm"
   437  		case strings.Contains(out, "aarch64"):
   438  			gohostarch = "arm64"
   439  		case strings.Contains(out, "ppc64le"):
   440  			gohostarch = "ppc64le"
   441  		case strings.Contains(out, "ppc64"):
   442  			gohostarch = "ppc64"
   443  		case strings.Contains(out, "mips64"):
   444  			gohostarch = "mips64"
   445  			if elfIsLittleEndian(os.Args[0]) {
   446  				gohostarch = "mips64le"
   447  			}
   448  		case strings.Contains(out, "s390x"):
   449  			gohostarch = "s390x"
   450  		case gohostos == "darwin":
   451  			if strings.Contains(run("", CheckExit, "uname", "-v"), "RELEASE_ARM_") {
   452  				gohostarch = "arm"
   453  			}
   454  		default:
   455  			fatal("unknown architecture: %s", out)
   456  		}
   457  	}
   458  
   459  	if gohostarch == "arm" || gohostarch == "mips64" || gohostarch == "mips64le" {
   460  		maxbg = min(maxbg, runtime.NumCPU())
   461  	}
   462  	bginit()
   463  
   464  	// The OS X 10.6 linker does not support external linking mode.
   465  	// See golang.org/issue/5130.
   466  	//
   467  	// OS X 10.6 does not work with clang either, but OS X 10.9 requires it.
   468  	// It seems to work with OS X 10.8, so we default to clang for 10.8 and later.
   469  	// See golang.org/issue/5822.
   470  	//
   471  	// Roughly, OS X 10.N shows up as uname release (N+4),
   472  	// so OS X 10.6 is uname version 10 and OS X 10.8 is uname version 12.
   473  	if gohostos == "darwin" {
   474  		rel := run("", CheckExit, "uname", "-r")
   475  		if i := strings.Index(rel, "."); i >= 0 {
   476  			rel = rel[:i]
   477  		}
   478  		osx, _ := strconv.Atoi(rel)
   479  		if osx <= 6+4 {
   480  			goextlinkenabled = "0"
   481  		}
   482  		if osx >= 8+4 {
   483  			defaultclang = true
   484  		}
   485  	}
   486  
   487  	if len(os.Args) > 1 && os.Args[1] == "-check-goarm" {
   488  		useVFPv1() // might fail with SIGILL
   489  		println("VFPv1 OK.")
   490  		useVFPv3() // might fail with SIGILL
   491  		println("VFPv3 OK.")
   492  		os.Exit(0)
   493  	}
   494  
   495  	xinit()
   496  	xmain()
   497  	xexit(0)
   498  }
   499  
   500  // xsamefile reports whether f1 and f2 are the same file (or dir)
   501  func xsamefile(f1, f2 string) bool {
   502  	fi1, err1 := os.Stat(f1)
   503  	fi2, err2 := os.Stat(f2)
   504  	if err1 != nil || err2 != nil {
   505  		return f1 == f2
   506  	}
   507  	return os.SameFile(fi1, fi2)
   508  }
   509  
   510  func xgetgoarm() string {
   511  	if goos == "nacl" {
   512  		// NaCl guarantees VFPv3 and is always cross-compiled.
   513  		return "7"
   514  	}
   515  	if goos == "darwin" {
   516  		// Assume all darwin/arm devices are have VFPv3. This
   517  		// port is also mostly cross-compiled, so it makes little
   518  		// sense to auto-detect the setting.
   519  		return "7"
   520  	}
   521  	if gohostarch != "arm" || goos != gohostos {
   522  		// Conservative default for cross-compilation.
   523  		return "5"
   524  	}
   525  	if goos == "freebsd" || goos == "openbsd" {
   526  		// FreeBSD has broken VFP support.
   527  		// OpenBSD currently only supports softfloat.
   528  		return "5"
   529  	}
   530  
   531  	// Try to exec ourselves in a mode to detect VFP support.
   532  	// Seeing how far it gets determines which instructions failed.
   533  	// The test is OS-agnostic.
   534  	out := run("", 0, os.Args[0], "-check-goarm")
   535  	v1ok := strings.Contains(out, "VFPv1 OK.")
   536  	v3ok := strings.Contains(out, "VFPv3 OK.")
   537  
   538  	if v1ok && v3ok {
   539  		return "7"
   540  	}
   541  	if v1ok {
   542  		return "6"
   543  	}
   544  	return "5"
   545  }
   546  
   547  func min(a, b int) int {
   548  	if a < b {
   549  		return a
   550  	}
   551  	return b
   552  }
   553  
   554  // elfIsLittleEndian detects if the ELF file is little endian.
   555  func elfIsLittleEndian(fn string) bool {
   556  	// read the ELF file header to determine the endianness without using the
   557  	// debug/elf package.
   558  	file, err := os.Open(fn)
   559  	if err != nil {
   560  		fatal("failed to open file to determine endianness: %v", err)
   561  	}
   562  	defer file.Close()
   563  	var hdr [16]byte
   564  	if _, err := io.ReadFull(file, hdr[:]); err != nil {
   565  		fatal("failed to read ELF header to determine endianness: %v", err)
   566  	}
   567  	// hdr[5] is EI_DATA byte, 1 is ELFDATA2LSB and 2 is ELFDATA2MSB
   568  	switch hdr[5] {
   569  	default:
   570  		fatal("unknown ELF endianness of %s: EI_DATA = %d", fn, hdr[5])
   571  	case 1:
   572  		return true
   573  	case 2:
   574  		return false
   575  	}
   576  	panic("unreachable")
   577  }