build.go 27.8 KB
Newer Older
Russ Cox's avatar
Russ Cox committed
1 2 3 4
// Copyright 2012 The Go Authors.  All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

5
package main
Russ Cox's avatar
Russ Cox committed
6

7 8 9 10 11
import (
	"bytes"
	"flag"
	"fmt"
	"os"
12
	"os/exec"
13
	"path/filepath"
14
	"sort"
15
	"strings"
16
	"sync"
17 18 19
)

// Initialization for any invocation.
Russ Cox's avatar
Russ Cox committed
20 21

// The usual variables.
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
var (
	goarch           string
	gobin            string
	gohostarch       string
	gohostos         string
	goos             string
	goarm            string
	go386            string
	goroot           string
	goroot_final     string
	goextlinkenabled string
	workdir          string
	tooldir          string
	oldgoos          string
	oldgoarch        string
	slash            string
38
	exe              string
39 40 41 42 43 44 45 46 47 48 49
	defaultcc        string
	defaultcflags    string
	defaultldflags   string
	defaultcxxtarget string
	defaultcctarget  string
	rebuildall       bool
	defaultclang     bool

	sflag bool // build static binaries
	vflag int  // verbosity
)
Russ Cox's avatar
Russ Cox committed
50 51

// The known architectures.
52
var okgoarch = []string{
53
	"386",
Russ Cox's avatar
Russ Cox committed
54
	"amd64",
55
	"amd64p32",
56
	"arm",
57
	"arm64",
Russ Cox's avatar
Russ Cox committed
58 59
	"ppc64",
	"ppc64le",
60
}
Russ Cox's avatar
Russ Cox committed
61 62

// The known operating systems.
63
var okgoos = []string{
Russ Cox's avatar
Russ Cox committed
64
	"darwin",
65
	"dragonfly",
Russ Cox's avatar
Russ Cox committed
66
	"linux",
David Crawshaw's avatar
David Crawshaw committed
67
	"android",
68
	"solaris",
Russ Cox's avatar
Russ Cox committed
69
	"freebsd",
70
	"nacl",
Russ Cox's avatar
Russ Cox committed
71 72 73 74
	"netbsd",
	"openbsd",
	"plan9",
	"windows",
75
}
Russ Cox's avatar
Russ Cox committed
76 77

// find reports the first index of p in l[0:n], or else -1.
78 79 80 81 82 83 84
func find(p string, l []string) int {
	for i, s := range l {
		if p == s {
			return i
		}
	}
	return -1
Russ Cox's avatar
Russ Cox committed
85 86
}

87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
// xinit handles initialization of the various global state, like goroot and goarch.
func xinit() {
	goroot = os.Getenv("GOROOT")
	if slash == "/" && len(goroot) > 1 || slash == `\` && len(goroot) > 3 {
		// if not "/" or "c:\", then strip trailing path separator
		goroot = strings.TrimSuffix(goroot, slash)
	}
	if goroot == "" {
		fatal("$GOROOT must be set")
	}

	goroot_final = os.Getenv("GOROOT_FINAL")
	if goroot_final == "" {
		goroot_final = goroot
	}

	b := os.Getenv("GOBIN")
	if b == "" {
		b = goroot + slash + "bin"
	}
	gobin = b

	b = os.Getenv("GOOS")
	if b == "" {
		b = gohostos
	}
	goos = b
	if find(goos, okgoos) < 0 {
		fatal("unknown $GOOS %s", goos)
	}

	b = os.Getenv("GOARM")
	if b == "" {
		b = xgetgoarm()
	}
	goarm = b

	b = os.Getenv("GO386")
	if b == "" {
		if cansse2() {
			b = "sse2"
		} else {
			b = "387"
		}
	}
	go386 = b

134
	p := pathf("%s/src/all.bash", goroot)
135 136 137 138 139 140 141 142 143 144 145
	if !isfile(p) {
		fatal("$GOROOT is not set correctly or not exported\n"+
			"\tGOROOT=%s\n"+
			"\t%s does not exist", goroot, p)
	}

	b = os.Getenv("GOHOSTARCH")
	if b != "" {
		gohostarch = b
	}

146
	if find(gohostarch, okgoarch) < 0 {
147 148 149 150 151 152 153 154
		fatal("unknown $GOHOSTARCH %s", gohostarch)
	}

	b = os.Getenv("GOARCH")
	if b == "" {
		b = gohostarch
	}
	goarch = b
155
	if find(goarch, okgoarch) < 0 {
156 157 158 159 160 161 162 163 164 165 166 167 168
		fatal("unknown $GOARCH %s", goarch)
	}

	b = os.Getenv("GO_EXTLINK_ENABLED")
	if b != "" {
		if b != "0" && b != "1" {
			fatal("unknown $GO_EXTLINK_ENABLED %s", b)
		}
		goextlinkenabled = b
	}

	b = os.Getenv("CC")
	if b == "" {
169 170 171 172 173
		// Use clang on OS X, because gcc is deprecated there.
		// Xcode for OS X 10.9 Mavericks will ship a fake "gcc" binary that
		// actually runs clang. We prepare different command
		// lines for the two binaries, so it matters what we call it.
		// See golang.org/issue/5822.
174 175 176 177 178
		if defaultclang {
			b = "clang"
		} else {
			b = "gcc"
		}
179
	}
180
	defaultcc = b
181

182
	defaultcflags = os.Getenv("CFLAGS")
183

184
	defaultldflags = os.Getenv("LDFLAGS")
185

186 187 188
	b = os.Getenv("CC_FOR_TARGET")
	if b == "" {
		b = defaultcc
189
	}
190 191 192 193 194 195 196 197 198 199 200
	defaultcctarget = b

	b = os.Getenv("CXX_FOR_TARGET")
	if b == "" {
		b = os.Getenv("CXX")
		if b == "" {
			if defaultclang {
				b = "clang++"
			} else {
				b = "g++"
			}
201
		}
202
	}
203 204 205 206 207 208 209 210 211 212 213
	defaultcxxtarget = b

	// For tools being invoked but also for os.ExpandEnv.
	os.Setenv("GO386", go386)
	os.Setenv("GOARCH", goarch)
	os.Setenv("GOARM", goarm)
	os.Setenv("GOHOSTARCH", gohostarch)
	os.Setenv("GOHOSTOS", gohostos)
	os.Setenv("GOOS", goos)
	os.Setenv("GOROOT", goroot)
	os.Setenv("GOROOT_FINAL", goroot_final)
214

Russ Cox's avatar
Russ Cox committed
215
	// Make the environment more predictable.
216 217
	os.Setenv("LANG", "C")
	os.Setenv("LANGUAGE", "en_US.UTF8")
218

219 220
	workdir = xworkdir()
	xatexit(rmworkdir)
Russ Cox's avatar
Russ Cox committed
221

222
	tooldir = pathf("%s/pkg/tool/%s_%s", goroot, gohostos, gohostarch)
Russ Cox's avatar
Russ Cox committed
223 224 225
}

// rmworkdir deletes the work directory.
226 227 228 229 230
func rmworkdir() {
	if vflag > 1 {
		errprintf("rm -rf %s\n", workdir)
	}
	xremoveall(workdir)
Russ Cox's avatar
Russ Cox committed
231 232
}

233
// Remove trailing spaces.
234 235
func chomp(s string) string {
	return strings.TrimRight(s, " \t\r\n")
236 237
}

238 239 240 241
func branchtag(branch string) (tag string, precise bool) {
	b := run(goroot, CheckExit, "git", "log", "--decorate=full", "--format=format:%d", "master.."+branch)
	tag = branch
	for _, line := range splitlines(b) {
242 243 244
		// Each line is either blank, or looks like
		//	  (tag: refs/tags/go1.4rc2, refs/remotes/origin/release-branch.go1.4, refs/heads/release-branch.go1.4)
		// We need to find an element starting with refs/tags/.
245 246 247 248 249
		i := strings.Index(line, " refs/tags/")
		if i < 0 {
			continue
		}
		i += len(" refs/tags/")
250
		// The tag name ends at a comma or paren (prefer the first).
251 252 253 254 255 256 257 258 259 260 261 262 263 264
		j := strings.Index(line[i:], ",")
		if j < 0 {
			j = strings.Index(line[i:], ")")
		}
		if j < 0 {
			continue // malformed line; ignore it
		}
		tag = line[i : i+j]
		if i == 0 {
			precise = true // tag denotes HEAD
		}
		break
	}
	return
265
}
266 267

// findgoversion determines the Go version to use in the version string.
268
func findgoversion() string {
269
	// The $GOROOT/VERSION file takes priority, for distributions
270
	// without the source repo.
271 272 273
	path := pathf("%s/VERSION", goroot)
	if isfile(path) {
		b := chomp(readfile(path))
274 275 276 277
		// Commands such as "dist version > VERSION" will cause
		// the shell to create an empty VERSION file and set dist's
		// stdout to its fd. dist in turn looks at VERSION and uses
		// its content if available, which is empty at this point.
278 279 280 281
		// Only use the VERSION file if it is non-empty.
		if b != "" {
			return b
		}
282 283 284
	}

	// The $GOROOT/VERSION.cache file is a cache to avoid invoking
285
	// git every time we run this command.  Unlike VERSION, it gets
286
	// deleted by the clean command.
287 288 289
	path = pathf("%s/VERSION.cache", goroot)
	if isfile(path) {
		return chomp(readfile(path))
290 291
	}

292 293 294 295 296
	// Show a nicer error message if this isn't a Git repo.
	if !isGitRepo() {
		fatal("FAILED: not a Git repo; must put a VERSION file in $GOROOT")
	}

297
	// Otherwise, use Git.
298
	// What is the current branch?
299
	branch := chomp(run(goroot, CheckExit, "git", "rev-parse", "--abbrev-ref", "HEAD"))
300 301

	// What are the tags along the current branch?
302 303
	tag := "devel"
	precise := false
304

305 306
	// If we're on a release branch, use the closest matching tag
	// that is on the release branch (and not on the master branch).
307 308 309
	if strings.HasPrefix(branch, "release-branch.") {
		tag, precise = branchtag(branch)
	}
310

311
	if !precise {
312
		// Tag does not point at HEAD; add hash and date to version.
313
		tag += chomp(run(goroot, CheckExit, "git", "log", "-n", "1", "--format=format: +%h %cd", "HEAD"))
314
	}
315 316

	// Cache version.
317
	writefile(tag, path, 0)
318

319
	return tag
320 321
}

322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
// isGitRepo reports whether the working directory is inside a Git repository.
func isGitRepo() bool {
	p := ".git"
	for {
		fi, err := os.Stat(p)
		if os.IsNotExist(err) {
			p = filepath.Join("..", p)
			continue
		}
		if err != nil || !fi.IsDir() {
			return false
		}
		return true
	}
}

Russ Cox's avatar
Russ Cox committed
338 339 340 341 342
/*
 * Initial tree setup.
 */

// The old tools that no longer live in $GOBIN or $GOROOT/bin.
343
var oldtool = []string{
Russ Cox's avatar
Russ Cox committed
344 345 346
	"5a", "5c", "5g", "5l",
	"6a", "6c", "6g", "6l",
	"8a", "8c", "8g", "8l",
347
	"9a", "9c", "9g", "9l",
Russ Cox's avatar
Russ Cox committed
348 349
	"6cov",
	"6nm",
Russ Cox's avatar
Russ Cox committed
350
	"6prof",
Russ Cox's avatar
Russ Cox committed
351 352 353 354 355 356 357 358 359 360 361 362 363
	"cgo",
	"ebnflint",
	"goapi",
	"gofix",
	"goinstall",
	"gomake",
	"gopack",
	"gopprof",
	"gotest",
	"gotype",
	"govet",
	"goyacc",
	"quietgcc",
364
}
Russ Cox's avatar
Russ Cox committed
365

366 367
// Unreleased directories (relative to $GOROOT) that should
// not be in release branches.
368
var unreleased = []string{
Russ Cox's avatar
Russ Cox committed
369
	"src/cmd/newlink",
370
	"src/cmd/objwriter",
371 372
	"src/debug/goobj",
	"src/old",
373
}
374

Russ Cox's avatar
Russ Cox committed
375
// setup sets up the tree for the initial build.
376
func setup() {
Russ Cox's avatar
Russ Cox committed
377
	// Create bin directory.
378 379 380
	if p := pathf("%s/bin", goroot); !isdir(p) {
		xmkdir(p)
	}
Russ Cox's avatar
Russ Cox committed
381 382

	// Create package directory.
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
	if p := pathf("%s/pkg", goroot); !isdir(p) {
		xmkdir(p)
	}

	p := pathf("%s/pkg/%s_%s", goroot, gohostos, gohostarch)
	if rebuildall {
		xremoveall(p)
	}
	xmkdirall(p)

	if goos != gohostos || goarch != gohostarch {
		p := pathf("%s/pkg/%s_%s", goroot, goos, goarch)
		if rebuildall {
			xremoveall(p)
		}
		xmkdirall(p)
Russ Cox's avatar
Russ Cox committed
399
	}
400

401 402
	// Create object directory.
	// We keep it in pkg/ so that all the generated binaries
Russ Cox's avatar
Russ Cox committed
403 404 405
	// are in one tree.  If pkg/obj/libgc.a exists, it is a dreg from
	// before we used subdirectories of obj.  Delete all of obj
	// to clean up.
406 407 408 409 410 411 412 413
	if p := pathf("%s/pkg/obj/libgc.a", goroot); isfile(p) {
		xremoveall(pathf("%s/pkg/obj", goroot))
	}
	p = pathf("%s/pkg/obj/%s_%s", goroot, gohostos, gohostarch)
	if rebuildall {
		xremoveall(p)
	}
	xmkdirall(p)
Russ Cox's avatar
Russ Cox committed
414 415 416

	// Create tool directory.
	// We keep it in pkg/, just like the object directory above.
417 418 419 420
	if rebuildall {
		xremoveall(tooldir)
	}
	xmkdirall(tooldir)
Russ Cox's avatar
Russ Cox committed
421 422

	// Remove tool binaries from before the tool/gohostos_gohostarch
423
	xremoveall(pathf("%s/bin/tool", goroot))
Russ Cox's avatar
Russ Cox committed
424 425

	// Remove old pre-tool binaries.
426 427 428
	for _, old := range oldtool {
		xremove(pathf("%s/bin/%s", goroot, old))
	}
Russ Cox's avatar
Russ Cox committed
429

Russ Cox's avatar
Russ Cox committed
430
	// If $GOBIN is set and has a Go compiler, it must be cleaned.
431
	for _, char := range "56789" {
432 433 434 435 436
		if isfile(pathf("%s%s%c%s", gobin, slash, char, "g")) {
			for _, old := range oldtool {
				xremove(pathf("%s/%s", gobin, old))
			}
			break
Russ Cox's avatar
Russ Cox committed
437 438 439
		}
	}

440
	// For release, make sure excluded things are excluded.
441
	goversion := findgoversion()
442 443 444 445 446 447
	if strings.HasPrefix(goversion, "release.") || (strings.HasPrefix(goversion, "go") && !strings.Contains(goversion, "beta")) {
		for _, dir := range unreleased {
			if p := pathf("%s/%s", goroot, dir); isdir(p) {
				fatal("%s should not exist in release build", p)
			}
		}
448
	}
Russ Cox's avatar
Russ Cox committed
449 450 451
}

/*
452
 * Tool building
Russ Cox's avatar
Russ Cox committed
453 454 455
 */

// deptab lists changes to the default dependencies for a given prefix.
456
// deps ending in /* read the whole directory; deps beginning with -
Russ Cox's avatar
Russ Cox committed
457
// exclude files with that prefix.
458 459 460 461 462
var deptab = []struct {
	prefix string   // prefix of target
	dep    []string // dependency tweaks for targets with that prefix
}{
	{"cmd/go", []string{
463 464
		"zdefaultcc.go",
	}},
465
	{"runtime", []string{
466
		"zversion.go",
Russ Cox's avatar
Russ Cox committed
467
	}},
468
}
Russ Cox's avatar
Russ Cox committed
469 470

// depsuffix records the allowed suffixes for source files.
471
var depsuffix = []string{
Russ Cox's avatar
Russ Cox committed
472 473
	".s",
	".go",
474
}
Russ Cox's avatar
Russ Cox committed
475 476

// gentab records how to generate some trivial files.
477 478 479 480
var gentab = []struct {
	nameprefix string
	gen        func(string, string)
}{
481
	{"zdefaultcc.go", mkzdefaultcc},
482
	{"zversion.go", mkzversion},
483 484 485

	// not generated anymore, but delete the file if we see it
	{"enam.c", nil},
Russ Cox's avatar
Russ Cox committed
486 487 488 489
	{"anames5.c", nil},
	{"anames6.c", nil},
	{"anames8.c", nil},
	{"anames9.c", nil},
490
}
Russ Cox's avatar
Russ Cox committed
491

492 493 494 495
// installed maps from a dir name (as given to install) to a chan
// closed when the dir's package is installed.
var installed = make(map[string]chan struct{})

Russ Cox's avatar
Russ Cox committed
496 497
// install installs the library, package, or binary associated with dir,
// which is relative to $GOROOT/src.
498
func install(dir string) {
499 500 501 502 503 504 505
	if ch, ok := installed[dir]; ok {
		defer close(ch)
	}
	for _, dep := range builddeps[dir] {
		<-installed[dep]
	}

506 507 508 509 510 511 512
	if vflag > 0 {
		if goos != gohostos || goarch != gohostarch {
			errprintf("%s (%s/%s)\n", dir, goos, goarch)
		} else {
			errprintf("%s\n", dir)
		}
	}
513

514 515 516
	workdir := pathf("%s/%s", workdir, dir)
	xmkdirall(workdir)

517 518 519 520 521 522
	var clean []string
	defer func() {
		for _, name := range clean {
			xremove(name)
		}
	}()
523

524
	// path = full path to dir.
525 526
	path := pathf("%s/src/%s", goroot, dir)
	name := filepath.Base(dir)
527

528
	ispkg := !strings.HasPrefix(dir, "cmd/") || strings.HasPrefix(dir, "cmd/internal/") || strings.HasPrefix(dir, "cmd/asm/internal/")
529

Russ Cox's avatar
Russ Cox committed
530
	// Start final link command line.
Scott Lawrence's avatar
Scott Lawrence committed
531
	// Note: code below knows that link.p[targ] is the target.
532 533 534 535 536
	var (
		link      []string
		targ      int
		ispackcmd bool
	)
537
	if ispkg {
Russ Cox's avatar
Russ Cox committed
538
		// Go library (package).
539 540 541 542
		ispackcmd = true
		link = []string{"pack", pathf("%s/pkg/%s_%s/%s.a", goroot, goos, goarch, dir)}
		targ = len(link) - 1
		xmkdirall(filepath.Dir(link[targ]))
543
	} else {
Russ Cox's avatar
Russ Cox committed
544
		// Go command.
545 546 547 548
		elem := name
		if elem == "go" {
			elem = "go_bootstrap"
		}
549
		link = []string{pathf("%s/link", tooldir), "-o", pathf("%s/%s%s", tooldir, elem, exe)}
550
		targ = len(link) - 1
Russ Cox's avatar
Russ Cox committed
551
	}
552
	ttarg := mtime(link[targ])
Russ Cox's avatar
Russ Cox committed
553 554 555 556

	// Gather files that are sources for this target.
	// Everything in that directory, and any target-specific
	// additions.
557
	files := xreaddir(path)
558 559 560 561 562 563

	// Remove files beginning with . or _,
	// which are likely to be editor temporary files.
	// This is the same heuristic build.ScanDir uses.
	// There do exist real C files beginning with _,
	// so limit that check to just Go files.
564 565 566 567 568 569 570 571
	files = filter(files, func(p string) bool {
		return !strings.HasPrefix(p, ".") && (!strings.HasPrefix(p, "_") || !strings.HasSuffix(p, ".go"))
	})

	for _, dt := range deptab {
		if dir == dt.prefix || strings.HasSuffix(dt.prefix, "/") && strings.HasPrefix(dir, dt.prefix) {
			for _, p := range dt.dep {
				p = os.ExpandEnv(p)
572
				files = append(files, p)
Russ Cox's avatar
Russ Cox committed
573 574 575
			}
		}
	}
576
	files = uniq(files)
577

Russ Cox's avatar
Russ Cox committed
578
	// Convert to absolute paths.
579 580 581
	for i, p := range files {
		if !isabs(p) {
			files[i] = pathf("%s/%s", path, p)
Russ Cox's avatar
Russ Cox committed
582 583 584 585
		}
	}

	// Is the target up-to-date?
586 587 588 589 590 591 592 593 594
	var gofiles, missing []string
	stale := rebuildall
	files = filter(files, func(p string) bool {
		for _, suf := range depsuffix {
			if strings.HasSuffix(p, suf) {
				goto ok
			}
		}
		return false
Russ Cox's avatar
Russ Cox committed
595
	ok:
596 597 598
		t := mtime(p)
		if !t.IsZero() && !strings.HasSuffix(p, ".a") && !shouldbuild(p, dir) {
			return false
599
		}
600 601
		if strings.HasSuffix(p, ".go") {
			gofiles = append(gofiles, p)
Russ Cox's avatar
Russ Cox committed
602
		}
603 604 605 606 607 608 609 610
		if t.After(ttarg) {
			stale = true
		}
		if t.IsZero() {
			missing = append(missing, p)
		}
		return true
	})
611

612
	// If there are no files to compile, we're done.
613 614 615
	if len(files) == 0 {
		return
	}
616

617 618 619
	if !stale {
		return
	}
Russ Cox's avatar
Russ Cox committed
620

621
	// For package runtime, copy some files into the work space.
622
	if dir == "runtime" {
623
		xmkdirall(pathf("%s/pkg/include", goroot))
624
		// For use by assembly and C files.
625
		copyfile(pathf("%s/pkg/include/textflag.h", goroot),
626
			pathf("%s/src/runtime/textflag.h", goroot), 0)
627
		copyfile(pathf("%s/pkg/include/funcdata.h", goroot),
628
			pathf("%s/src/runtime/funcdata.h", goroot), 0)
629 630 631
	}

	// Generate any missing files; regenerate existing ones.
632 633 634 635 636 637 638 639 640 641 642
	for _, p := range files {
		elem := filepath.Base(p)
		for _, gt := range gentab {
			if gt.gen == nil {
				continue
			}
			if strings.HasPrefix(elem, gt.nameprefix) {
				if vflag > 1 {
					errprintf("generate %s\n", p)
				}
				gt.gen(path, p)
643
				// Do not add generated file to clean list.
644
				// In runtime, we want to be able to
645 646 647 648 649
				// build the package with the go tool,
				// and it assumes these generated files already
				// exist (it does not know how to build them).
				// The 'clean' command can remove
				// the generated files.
650
				goto built
Russ Cox's avatar
Russ Cox committed
651 652
			}
		}
653
		// Did not rebuild p.
654 655 656 657
		if find(p, missing) >= 0 {
			fatal("missing file %s", p)
		}
	built:
Russ Cox's avatar
Russ Cox committed
658 659
	}

660
	if goos != gohostos || goarch != gohostarch {
Russ Cox's avatar
Russ Cox committed
661
		// We've generated the right files; the go command can do the build.
662 663 664 665
		if vflag > 1 {
			errprintf("skip build for cross-compile %s\n", dir)
		}
		return
Russ Cox's avatar
Russ Cox committed
666
	}
667

668
	var archive string
669 670 671 672 673 674 675 676 677 678 679 680 681 682
	// The next loop will compile individual non-Go files.
	// Hand the Go files to the compiler en masse.
	// For package runtime, this writes go_asm.h, which
	// the assembly files will need.
	pkg := dir
	if strings.HasPrefix(dir, "cmd/") {
		pkg = "main"
	}
	b := pathf("%s/_go_.a", workdir)
	clean = append(clean, b)
	if !ispackcmd {
		link = append(link, b)
	} else {
		archive = b
683
	}
684
	compile := []string{pathf("%s/compile", tooldir), "-pack", "-o", b, "-p", pkg}
685 686 687 688 689
	if dir == "runtime" {
		compile = append(compile, "-+", "-asmhdr", pathf("%s/go_asm.h", workdir))
	}
	compile = append(compile, gofiles...)
	run(path, CheckExit|ShowOutput, compile...)
690

Russ Cox's avatar
Russ Cox committed
691
	// Compile the files.
692
	var wg sync.WaitGroup
693
	for _, p := range files {
694
		if !strings.HasSuffix(p, ".s") {
695 696
			continue
		}
Russ Cox's avatar
Russ Cox committed
697

698
		var compile []string
699 700
		// Assembly file for a Go package.
		compile = []string{
Russ Cox's avatar
Russ Cox committed
701
			pathf("%s/asm", tooldir),
702
			"-I", workdir,
703
			"-I", pathf("%s/pkg/include", goroot),
704 705 706
			"-D", "GOOS_" + goos,
			"-D", "GOARCH_" + goarch,
			"-D", "GOOS_GOARCH_" + goos + "_" + goarch,
707
		}
Russ Cox's avatar
Russ Cox committed
708

709 710
		doclean := true
		b := pathf("%s/%s", workdir, filepath.Base(p))
711

712
		// Change the last character of the output file (which was c or s).
713
		b = b[:len(b)-1] + "o"
714
		compile = append(compile, "-o", b, p)
715
		bgrun(&wg, path, compile...)
Russ Cox's avatar
Russ Cox committed
716

717 718 719 720
		link = append(link, b)
		if doclean {
			clean = append(clean, b)
		}
Russ Cox's avatar
Russ Cox committed
721
	}
722
	bgwait(&wg)
723

724
	if ispackcmd {
725 726 727
		xremove(link[targ])
		dopack(link[targ], archive, link[targ+1:])
		return
Russ Cox's avatar
Russ Cox committed
728 729 730
	}

	// Remove target before writing it.
731 732
	xremove(link[targ])
	run("", CheckExit|ShowOutput, link...)
Russ Cox's avatar
Russ Cox committed
733 734
}

Russ Cox's avatar
Russ Cox committed
735 736
// matchfield reports whether the field (x,y,z) matches this build.
// all the elements in the field must be satisfied.
737 738
func matchfield(f string) bool {
	for _, tag := range strings.Split(f, ",") {
Russ Cox's avatar
Russ Cox committed
739 740
		if !matchtag(tag) {
			return false
741 742 743
		}
	}
	return true
Russ Cox's avatar
Russ Cox committed
744 745
}

Russ Cox's avatar
Russ Cox committed
746 747 748 749 750 751 752 753 754 755 756 757 758 759
// matchtag reports whether the tag (x or !x) matches this build.
func matchtag(tag string) bool {
	if tag == "" {
		return false
	}
	if tag[0] == '!' {
		if len(tag) == 1 || tag[1] == '!' {
			return false
		}
		return !matchtag(tag[1:])
	}
	return tag == goos || tag == goarch || tag == "cmd_go_bootstrap" || tag == "go1.1" || (goos == "android" && tag == "linux")
}

Russ Cox's avatar
Russ Cox committed
760 761 762 763 764 765 766
// shouldbuild reports whether we should build this file.
// It applies the same rules that are used with context tags
// in package go/build, except that the GOOS and GOARCH
// can appear anywhere in the file name, not just after _.
// In particular, they can be the entire file name (like windows.c).
// We also allow the special tag cmd_go_bootstrap.
// See ../go/bootstrap.go and package go/build.
767
func shouldbuild(file, dir string) bool {
Russ Cox's avatar
Russ Cox committed
768
	// Check file name for GOOS or GOARCH.
769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787
	name := filepath.Base(file)
	excluded := func(list []string, ok string) bool {
		for _, x := range list {
			if x == ok {
				continue
			}
			i := strings.Index(name, x)
			if i < 0 {
				continue
			}
			i += len(x)
			if i == len(name) || name[i] == '.' || name[i] == '_' {
				return true
			}
		}
		return false
	}
	if excluded(okgoos, goos) || excluded(okgoarch, goarch) {
		return false
788
	}
789

Russ Cox's avatar
Russ Cox committed
790
	// Omit test files.
791 792 793
	if strings.Contains(name, "_test") {
		return false
	}
794

Russ Cox's avatar
Russ Cox committed
795
	// Check file contents for // +build lines.
796 797 798 799 800 801 802
	for _, p := range splitlines(readfile(file)) {
		p = strings.TrimSpace(p)
		if p == "" {
			continue
		}
		if strings.Contains(p, "package documentation") {
			return false
Russ Cox's avatar
Russ Cox committed
803
		}
804 805
		if strings.Contains(p, "package main") && dir != "cmd/go" && dir != "cmd/cgo" {
			return false
Russ Cox's avatar
Russ Cox committed
806
		}
807 808
		if !strings.HasPrefix(p, "//") {
			break
Russ Cox's avatar
Russ Cox committed
809
		}
810 811 812 813 814 815 816 817
		if !strings.Contains(p, "+build") {
			continue
		}
		fields := splitfields(p)
		if len(fields) < 2 || fields[1] != "+build" {
			continue
		}
		for _, p := range fields[2:] {
Russ Cox's avatar
Russ Cox committed
818
			if matchfield(p) {
819 820 821 822 823
				goto fieldmatch
			}
		}
		return false
	fieldmatch:
Russ Cox's avatar
Russ Cox committed
824 825
	}

826
	return true
Russ Cox's avatar
Russ Cox committed
827 828 829
}

// copy copies the file src to dst, via memory (so only good for small files).
830
func copyfile(dst, src string, flag int) {
831 832 833
	if vflag > 1 {
		errprintf("cp %s %s\n", src, dst)
	}
834
	writefile(readfile(src), dst, flag)
Russ Cox's avatar
Russ Cox committed
835 836
}

837 838 839
// dopack copies the package src to dst,
// appending the files listed in extra.
// The archive format is the traditional Unix ar format.
840 841 842 843
func dopack(dst, src string, extra []string) {
	bdst := bytes.NewBufferString(readfile(src))
	for _, file := range extra {
		b := readfile(file)
844
		// find last path element for archive member name
845 846 847 848
		i := strings.LastIndex(file, "/") + 1
		j := strings.LastIndex(file, `\`) + 1
		if i < j {
			i = j
849
		}
850 851 852 853
		fmt.Fprintf(bdst, "%-16.16s%-12d%-6d%-6d%-8o%-10d`\n", file[i:], 0, 0, 0, 0644, len(b))
		bdst.WriteString(b)
		if len(b)&1 != 0 {
			bdst.WriteByte(0)
854 855
		}
	}
856
	writefile(bdst.String(), dst, 0)
857 858
}

859 860 861 862 863 864 865 866 867 868 869 870 871
// builddeps records the build dependencies for the 'go bootstrap' command.
// It is a map[string][]string and generated by mkdeps.bash into deps.go.

// buildlist is the list of directories being built, sorted by name.
var buildlist = makeBuildlist()

func makeBuildlist() []string {
	var all []string
	for dir := range builddeps {
		all = append(all, dir)
	}
	sort.Strings(all)
	return all
872
}
Russ Cox's avatar
Russ Cox committed
873

874
var runtimegen = []string{
875 876
	"zaexperiment.h",
	"zversion.go",
877 878 879
}

func clean() {
880
	for _, name := range buildlist {
881
		path := pathf("%s/src/%s", goroot, name)
882
		// Remove generated files.
883 884 885 886 887
		for _, elem := range xreaddir(path) {
			for _, gt := range gentab {
				if strings.HasPrefix(elem, gt.nameprefix) {
					xremove(pathf("%s/%s", path, elem))
				}
888 889 890
			}
		}
		// Remove generated binary named for directory.
891 892 893
		if strings.HasPrefix(name, "cmd/") {
			xremove(pathf("%s/%s", path, name[4:]))
		}
894 895
	}

896 897 898 899 900
	// remove runtimegen files.
	path := pathf("%s/src/runtime", goroot)
	for _, elem := range runtimegen {
		xremove(pathf("%s/%s", path, elem))
	}
901

902
	if rebuildall {
Russ Cox's avatar
Russ Cox committed
903
		// Remove object tree.
904
		xremoveall(pathf("%s/pkg/obj/%s_%s", goroot, gohostos, gohostarch))
905

Russ Cox's avatar
Russ Cox committed
906
		// Remove installed packages and tools.
907 908 909
		xremoveall(pathf("%s/pkg/%s_%s", goroot, gohostos, gohostarch))
		xremoveall(pathf("%s/pkg/%s_%s", goroot, goos, goarch))
		xremoveall(tooldir)
Russ Cox's avatar
Russ Cox committed
910 911

		// Remove cached version info.
912
		xremove(pathf("%s/VERSION.cache", goroot))
Russ Cox's avatar
Russ Cox committed
913
	}
914 915 916 917 918 919
}

/*
 * command implementations
 */

920 921 922 923 924 925 926 927 928
func usage() {
	xprintf("usage: go tool dist [command]\n" +
		"Commands are:\n" +
		"\n" +
		"banner         print installation banner\n" +
		"bootstrap      rebuild everything\n" +
		"clean          deletes all built files\n" +
		"env [-p]       print environment (-p: include $PATH)\n" +
		"install [dir]  install individual directory\n" +
929
		"test [-h]      run Go test(s)\n" +
930 931 932 933 934
		"version        print Go version\n" +
		"\n" +
		"All commands take -v flags to emit extra information.\n",
	)
	xexit(2)
935 936 937
}

// The env command prints the default environment.
938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974
func cmdenv() {
	path := flag.Bool("p", false, "emit updated PATH")
	plan9 := flag.Bool("9", false, "emit plan 9 syntax")
	windows := flag.Bool("w", false, "emit windows syntax")
	xflagparse(0)

	format := "%s=\"%s\"\n"
	switch {
	case *plan9:
		format = "%s='%s'\n"
	case *windows:
		format = "set %s=%s\r\n"
	}

	xprintf(format, "CC", defaultcc)
	xprintf(format, "CC_FOR_TARGET", defaultcctarget)
	xprintf(format, "GOROOT", goroot)
	xprintf(format, "GOBIN", gobin)
	xprintf(format, "GOARCH", goarch)
	xprintf(format, "GOOS", goos)
	xprintf(format, "GOHOSTARCH", gohostarch)
	xprintf(format, "GOHOSTOS", gohostos)
	xprintf(format, "GOTOOLDIR", tooldir)
	if goarch == "arm" {
		xprintf(format, "GOARM", goarm)
	}
	if goarch == "386" {
		xprintf(format, "GO386", go386)
	}

	if *path {
		sep := ":"
		if gohostos == "windows" {
			sep = ";"
		}
		xprintf(format, "PATH", fmt.Sprintf("%s%s%s", gobin, sep, os.Getenv("PATH")))
	}
975 976
}

Russ Cox's avatar
Russ Cox committed
977 978
// The bootstrap command runs a build from scratch,
// stopping at having installed the go_bootstrap command.
979 980 981 982 983 984 985 986 987 988 989
func cmdbootstrap() {
	flag.BoolVar(&rebuildall, "a", rebuildall, "rebuild all")
	flag.BoolVar(&sflag, "s", sflag, "build static binaries")
	xflagparse(0)

	if isdir(pathf("%s/src/pkg", goroot)) {
		fatal("\n\n"+
			"The Go package sources have moved to $GOROOT/src.\n"+
			"*** %s still exists. ***\n"+
			"It probably contains stale files that may confuse the build.\n"+
			"Please (check what's there and) remove it and try again.\n"+
990
			"See https://golang.org/s/go14nopkg\n",
991 992
			pathf("%s/src/pkg", goroot))
	}
993

994 995
	if rebuildall {
		clean()
996
	}
997

998
	setup()
999

1000
	checkCC()
1001 1002
	bootstrapBuildTools()

Russ Cox's avatar
Russ Cox committed
1003
	// For the main bootstrap, building for host os/arch.
1004 1005 1006 1007 1008 1009 1010 1011 1012
	oldgoos = goos
	oldgoarch = goarch
	goos = gohostos
	goarch = gohostarch
	os.Setenv("GOHOSTARCH", gohostarch)
	os.Setenv("GOHOSTOS", gohostos)
	os.Setenv("GOARCH", goarch)
	os.Setenv("GOOS", goos)

1013 1014 1015 1016 1017 1018 1019 1020
	// TODO(rsc): Enable when appropriate.
	// This step is only needed if we believe that the Go compiler built from Go 1.4
	// will produce different object files than the Go compiler built from itself.
	// In the absence of bugs, that should not happen.
	// And if there are bugs, they're more likely in the current development tree
	// than in a standard release like Go 1.4, so don't do this rebuild by default.
	if false {
		xprintf("##### Building Go toolchain using itself.\n")
1021 1022
		for _, dir := range buildlist {
			installed[dir] = make(chan struct{})
1023
		}
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
		var wg sync.WaitGroup
		for _, dir := range builddeps["cmd/go"] {
			wg.Add(1)
			dir := dir
			go func() {
				defer wg.Done()
				install(dir)
			}()
		}
		wg.Wait()
1034 1035 1036
		xprintf("\n")
	}

1037
	xprintf("##### Building go_bootstrap for host, %s/%s.\n", gohostos, gohostarch)
1038 1039 1040 1041 1042
	for _, dir := range buildlist {
		installed[dir] = make(chan struct{})
	}
	for _, dir := range buildlist {
		go install(dir)
1043
	}
1044
	<-installed["cmd/go"]
Russ Cox's avatar
Russ Cox committed
1045

1046 1047 1048 1049
	goos = oldgoos
	goarch = oldgoarch
	os.Setenv("GOARCH", goarch)
	os.Setenv("GOOS", goos)
Russ Cox's avatar
Russ Cox committed
1050

1051 1052
	// Build runtime for actual goos/goarch too.
	if goos != gohostos || goarch != gohostarch {
1053
		installed["runtime"] = make(chan struct{})
1054 1055
		install("runtime")
	}
Russ Cox's avatar
Russ Cox committed
1056 1057
}

1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
// Copied from go/build/build.go.
// Cannot use go/build directly because cmd/dist for a new release
// builds against an old release's go/build, which may be out of sync.
var cgoEnabled = map[string]bool{
	"darwin/386":      true,
	"darwin/amd64":    true,
	"darwin/arm":      true,
	"darwin/arm64":    true,
	"dragonfly/amd64": true,
	"freebsd/386":     true,
	"freebsd/amd64":   true,
	"linux/386":       true,
	"linux/amd64":     true,
	"linux/arm":       true,
	"linux/arm64":     true,
	"linux/ppc64le":   true,
	"android/386":     true,
	"android/amd64":   true,
	"android/arm":     true,
	"netbsd/386":      true,
	"netbsd/amd64":    true,
	"netbsd/arm":      true,
	"openbsd/386":     true,
	"openbsd/amd64":   true,
	"solaris/amd64":   true,
	"windows/386":     true,
	"windows/amd64":   true,
}

func needCC() bool {
	switch os.Getenv("CGO_ENABLED") {
	case "1":
		return true
	case "0":
		return false
	}
	return cgoEnabled[gohostos+"/"+gohostarch]
}

func checkCC() {
	if !needCC() {
		return
	}
	if _, err := exec.Command(defaultcc, "--help").Output(); err != nil {
		fatal("cannot invoke C compiler %q: %v\n\n"+
			"Go needs a system C compiler for use with cgo.\n"+
			"To set a C compiler, export CC=the-compiler.\n"+
			"To disable cgo, export CGO_ENABLED=0.\n", defaultcc, err)
	}
}

1109
func defaulttarg() string {
1110 1111 1112 1113
	// xgetwd might return a path with symlinks fully resolved, and if
	// there happens to be symlinks in goroot, then the hasprefix test
	// will never succeed. Instead, we use xrealwd to get a canonical
	// goroot/src before the comparison to avoid this problem.
1114 1115 1116 1117 1118 1119 1120
	pwd := xgetwd()
	src := pathf("%s/src/", goroot)
	real_src := xrealwd(src)
	if !strings.HasPrefix(pwd, real_src) {
		fatal("current directory %s is not under %s", pwd, real_src)
	}
	pwd = pwd[len(real_src):]
1121
	// guard againt xrealwd return the directory without the trailing /
1122
	pwd = strings.TrimPrefix(pwd, "/")
1123

1124
	return pwd
1125 1126
}

Russ Cox's avatar
Russ Cox committed
1127
// Install installs the list of packages named on the command line.
1128 1129 1130
func cmdinstall() {
	flag.BoolVar(&sflag, "s", sflag, "build static binaries")
	xflagparse(-1)
1131

1132 1133 1134
	if flag.NArg() == 0 {
		install(defaulttarg())
	}
1135

1136 1137 1138
	for _, arg := range flag.Args() {
		install(arg)
	}
Russ Cox's avatar
Russ Cox committed
1139
}
1140 1141

// Clean deletes temporary objects.
1142 1143 1144
func cmdclean() {
	xflagparse(0)
	clean()
1145 1146 1147
}

// Banner prints the 'now you've installed Go' banner.
1148 1149
func cmdbanner() {
	xflagparse(0)
1150

1151 1152 1153 1154
	xprintf("\n")
	xprintf("---\n")
	xprintf("Installed Go for %s/%s in %s\n", goos, goarch, goroot)
	xprintf("Installed commands in %s\n", gobin)
1155

1156
	if !xsamefile(goroot_final, goroot) {
1157 1158
		// If the files are to be moved, don't check that gobin
		// is on PATH; assume they know what they are doing.
1159
	} else if gohostos == "plan9" {
1160
		// Check that gobin is bound before /bin.
1161 1162 1163 1164 1165
		pid := strings.Replace(readfile("#c/pid"), " ", "", -1)
		ns := fmt.Sprintf("/proc/%s/ns", pid)
		if !strings.Contains(readfile(ns), fmt.Sprintf("bind -b %s /bin", gobin)) {
			xprintf("*** You need to bind %s before /bin.\n", gobin)
		}
1166 1167
	} else {
		// Check that gobin appears in $PATH.
1168 1169 1170 1171 1172 1173 1174
		pathsep := ":"
		if gohostos == "windows" {
			pathsep = ";"
		}
		if !strings.Contains(pathsep+os.Getenv("PATH")+pathsep, pathsep+gobin+pathsep) {
			xprintf("*** You need to add %s to your PATH.\n", gobin)
		}
1175
	}
1176

1177 1178
	if !xsamefile(goroot_final, goroot) {
		xprintf("\n"+
1179
			"The binaries expect %s to be copied or moved to %s\n",
1180
			goroot, goroot_final)
1181 1182 1183 1184
	}
}

// Version prints the Go version.
1185 1186
func cmdversion() {
	xflagparse(0)
1187
	xprintf("%s\n", findgoversion())
1188
}