]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/dist/buildtool.go
all: REVERSE MERGE dev.boringcrypto (cdcb4b6) into master
[gostls13.git] / src / cmd / dist / buildtool.go
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 // Build toolchain using Go 1.4.
6 //
7 // The general strategy is to copy the source files we need into
8 // a new GOPATH workspace, adjust import paths appropriately,
9 // invoke the Go 1.4 go command to build those sources,
10 // and then copy the binaries back.
11
12 package main
13
14 import (
15         "fmt"
16         "os"
17         "path/filepath"
18         "regexp"
19         "runtime"
20         "strings"
21 )
22
23 // bootstrapDirs is a list of directories holding code that must be
24 // compiled with a Go 1.4 toolchain to produce the bootstrapTargets.
25 // All directories in this list are relative to and must be below $GOROOT/src.
26 //
27 // The list has two kinds of entries: names beginning with cmd/ with
28 // no other slashes, which are commands, and other paths, which are packages
29 // supporting the commands. Packages in the standard library can be listed
30 // if a newer copy needs to be substituted for the Go 1.4 copy when used
31 // by the command packages. Paths ending with /... automatically
32 // include all packages within subdirectories as well.
33 // These will be imported during bootstrap as bootstrap/name, like bootstrap/math/big.
34 var bootstrapDirs = []string{
35         "cmd/asm",
36         "cmd/asm/internal/...",
37         "cmd/cgo",
38         "cmd/compile",
39         "cmd/compile/internal/...",
40         "cmd/internal/archive",
41         "cmd/internal/bio",
42         "cmd/internal/codesign",
43         "cmd/internal/dwarf",
44         "cmd/internal/edit",
45         "cmd/internal/gcprog",
46         "cmd/internal/goobj",
47         "cmd/internal/notsha256",
48         "cmd/internal/obj/...",
49         "cmd/internal/objabi",
50         "cmd/internal/pkgpath",
51         "cmd/internal/quoted",
52         "cmd/internal/src",
53         "cmd/internal/sys",
54         "cmd/link",
55         "cmd/link/internal/...",
56         "compress/flate",
57         "compress/zlib",
58         "container/heap",
59         "debug/dwarf",
60         "debug/elf",
61         "debug/macho",
62         "debug/pe",
63         "go/constant",
64         "internal/buildcfg",
65         "internal/goexperiment",
66         "internal/goversion",
67         "internal/pkgbits",
68         "internal/race",
69         "internal/unsafeheader",
70         "internal/xcoff",
71         "math/big",
72         "math/bits",
73         "sort",
74         "strconv",
75 }
76
77 // File prefixes that are ignored by go/build anyway, and cause
78 // problems with editor generated temporary files (#18931).
79 var ignorePrefixes = []string{
80         ".",
81         "_",
82         "#",
83 }
84
85 // File suffixes that use build tags introduced since Go 1.4.
86 // These must not be copied into the bootstrap build directory.
87 // Also ignore test files.
88 var ignoreSuffixes = []string{
89         "_arm64.s",
90         "_arm64.go",
91         "_loong64.s",
92         "_loong64.go",
93         "_riscv64.s",
94         "_riscv64.go",
95         "_wasm.s",
96         "_wasm.go",
97         "_test.s",
98         "_test.go",
99 }
100
101 var tryDirs = []string{
102         "sdk/go1.17",
103         "go1.17",
104 }
105
106 func bootstrapBuildTools() {
107         goroot_bootstrap := os.Getenv("GOROOT_BOOTSTRAP")
108         if goroot_bootstrap == "" {
109                 home := os.Getenv("HOME")
110                 goroot_bootstrap = pathf("%s/go1.4", home)
111                 for _, d := range tryDirs {
112                         if p := pathf("%s/%s", home, d); isdir(p) {
113                                 goroot_bootstrap = p
114                         }
115                 }
116         }
117         xprintf("Building Go toolchain1 using %s.\n", goroot_bootstrap)
118
119         mkbuildcfg(pathf("%s/src/internal/buildcfg/zbootstrap.go", goroot))
120         mkobjabi(pathf("%s/src/cmd/internal/objabi/zbootstrap.go", goroot))
121
122         // Use $GOROOT/pkg/bootstrap as the bootstrap workspace root.
123         // We use a subdirectory of $GOROOT/pkg because that's the
124         // space within $GOROOT where we store all generated objects.
125         // We could use a temporary directory outside $GOROOT instead,
126         // but it is easier to debug on failure if the files are in a known location.
127         workspace := pathf("%s/pkg/bootstrap", goroot)
128         xremoveall(workspace)
129         xatexit(func() { xremoveall(workspace) })
130         base := pathf("%s/src/bootstrap", workspace)
131         xmkdirall(base)
132
133         // Copy source code into $GOROOT/pkg/bootstrap and rewrite import paths.
134         writefile("module bootstrap\n", pathf("%s/%s", base, "go.mod"), 0)
135         for _, dir := range bootstrapDirs {
136                 recurse := strings.HasSuffix(dir, "/...")
137                 dir = strings.TrimSuffix(dir, "/...")
138                 filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
139                         if err != nil {
140                                 fatalf("walking bootstrap dirs failed: %v: %v", path, err)
141                         }
142
143                         name := filepath.Base(path)
144                         src := pathf("%s/src/%s", goroot, path)
145                         dst := pathf("%s/%s", base, path)
146
147                         if info.IsDir() {
148                                 if !recurse && path != dir || name == "testdata" {
149                                         return filepath.SkipDir
150                                 }
151
152                                 xmkdirall(dst)
153                                 if path == "cmd/cgo" {
154                                         // Write to src because we need the file both for bootstrap
155                                         // and for later in the main build.
156                                         mkzdefaultcc("", pathf("%s/zdefaultcc.go", src))
157                                         mkzdefaultcc("", pathf("%s/zdefaultcc.go", dst))
158                                 }
159                                 return nil
160                         }
161
162                         for _, pre := range ignorePrefixes {
163                                 if strings.HasPrefix(name, pre) {
164                                         return nil
165                                 }
166                         }
167                         for _, suf := range ignoreSuffixes {
168                                 if strings.HasSuffix(name, suf) {
169                                         return nil
170                                 }
171                         }
172
173                         text := bootstrapRewriteFile(src)
174                         writefile(text, dst, 0)
175                         return nil
176                 })
177         }
178
179         // Set up environment for invoking Go 1.4 go command.
180         // GOROOT points at Go 1.4 GOROOT,
181         // GOPATH points at our bootstrap workspace,
182         // GOBIN is empty, so that binaries are installed to GOPATH/bin,
183         // and GOOS, GOHOSTOS, GOARCH, and GOHOSTOS are empty,
184         // so that Go 1.4 builds whatever kind of binary it knows how to build.
185         // Restore GOROOT, GOPATH, and GOBIN when done.
186         // Don't bother with GOOS, GOHOSTOS, GOARCH, and GOHOSTARCH,
187         // because setup will take care of those when bootstrapBuildTools returns.
188
189         defer os.Setenv("GOROOT", os.Getenv("GOROOT"))
190         os.Setenv("GOROOT", goroot_bootstrap)
191
192         defer os.Setenv("GOPATH", os.Getenv("GOPATH"))
193         os.Setenv("GOPATH", workspace)
194
195         defer os.Setenv("GOBIN", os.Getenv("GOBIN"))
196         os.Setenv("GOBIN", "")
197
198         os.Setenv("GOOS", "")
199         os.Setenv("GOHOSTOS", "")
200         os.Setenv("GOARCH", "")
201         os.Setenv("GOHOSTARCH", "")
202
203         // Run Go 1.4 to build binaries. Use -gcflags=-l to disable inlining to
204         // workaround bugs in Go 1.4's compiler. See discussion thread:
205         // https://groups.google.com/d/msg/golang-dev/Ss7mCKsvk8w/Gsq7VYI0AwAJ
206         // Use the math_big_pure_go build tag to disable the assembly in math/big
207         // which may contain unsupported instructions.
208         // Note that if we are using Go 1.10 or later as bootstrap, the -gcflags=-l
209         // only applies to the final cmd/go binary, but that's OK: if this is Go 1.10
210         // or later we don't need to disable inlining to work around bugs in the Go 1.4 compiler.
211         cmd := []string{
212                 pathf("%s/bin/go", goroot_bootstrap),
213                 "install",
214                 "-gcflags=-l",
215                 "-tags=math_big_pure_go compiler_bootstrap",
216         }
217         if vflag > 0 {
218                 cmd = append(cmd, "-v")
219         }
220         if tool := os.Getenv("GOBOOTSTRAP_TOOLEXEC"); tool != "" {
221                 cmd = append(cmd, "-toolexec="+tool)
222         }
223         cmd = append(cmd, "bootstrap/cmd/...")
224         run(base, ShowOutput|CheckExit, cmd...)
225
226         // Copy binaries into tool binary directory.
227         for _, name := range bootstrapDirs {
228                 if !strings.HasPrefix(name, "cmd/") {
229                         continue
230                 }
231                 name = name[len("cmd/"):]
232                 if !strings.Contains(name, "/") {
233                         copyfile(pathf("%s/%s%s", tooldir, name, exe), pathf("%s/bin/%s%s", workspace, name, exe), writeExec)
234                 }
235         }
236
237         if vflag > 0 {
238                 xprintf("\n")
239         }
240 }
241
242 var ssaRewriteFileSubstring = filepath.FromSlash("src/cmd/compile/internal/ssa/rewrite")
243
244 // isUnneededSSARewriteFile reports whether srcFile is a
245 // src/cmd/compile/internal/ssa/rewriteARCHNAME.go file for an
246 // architecture that isn't for the current runtime.GOARCH.
247 //
248 // When unneeded is true archCaps is the rewrite base filename without
249 // the "rewrite" prefix or ".go" suffix: AMD64, 386, ARM, ARM64, etc.
250 func isUnneededSSARewriteFile(srcFile string) (archCaps string, unneeded bool) {
251         if !strings.Contains(srcFile, ssaRewriteFileSubstring) {
252                 return "", false
253         }
254         fileArch := strings.TrimSuffix(strings.TrimPrefix(filepath.Base(srcFile), "rewrite"), ".go")
255         if fileArch == "" {
256                 return "", false
257         }
258         b := fileArch[0]
259         if b == '_' || ('a' <= b && b <= 'z') {
260                 return "", false
261         }
262         archCaps = fileArch
263         fileArch = strings.ToLower(fileArch)
264         fileArch = strings.TrimSuffix(fileArch, "splitload")
265         if fileArch == os.Getenv("GOHOSTARCH") {
266                 return "", false
267         }
268         if fileArch == strings.TrimSuffix(runtime.GOARCH, "le") {
269                 return "", false
270         }
271         if fileArch == strings.TrimSuffix(os.Getenv("GOARCH"), "le") {
272                 return "", false
273         }
274         return archCaps, true
275 }
276
277 func bootstrapRewriteFile(srcFile string) string {
278         // During bootstrap, generate dummy rewrite files for
279         // irrelevant architectures. We only need to build a bootstrap
280         // binary that works for the current runtime.GOARCH.
281         // This saves 6+ seconds of bootstrap.
282         if archCaps, ok := isUnneededSSARewriteFile(srcFile); ok {
283                 return fmt.Sprintf(`// Code generated by go tool dist; DO NOT EDIT.
284
285 package ssa
286
287 func rewriteValue%s(v *Value) bool { panic("unused during bootstrap") }
288 func rewriteBlock%s(b *Block) bool { panic("unused during bootstrap") }
289 `, archCaps, archCaps)
290         }
291
292         return bootstrapFixImports(srcFile)
293 }
294
295 func bootstrapFixImports(srcFile string) string {
296         text := readfile(srcFile)
297         if !strings.Contains(srcFile, "/cmd/") && !strings.Contains(srcFile, `\cmd\`) {
298                 text = regexp.MustCompile(`\bany\b`).ReplaceAllString(text, "interface{}")
299         }
300         lines := strings.SplitAfter(text, "\n")
301         inBlock := false
302         for i, line := range lines {
303                 if strings.HasPrefix(line, "import (") {
304                         inBlock = true
305                         continue
306                 }
307                 if inBlock && strings.HasPrefix(line, ")") {
308                         inBlock = false
309                         continue
310                 }
311                 if strings.HasPrefix(line, `import "`) || strings.HasPrefix(line, `import . "`) ||
312                         inBlock && (strings.HasPrefix(line, "\t\"") || strings.HasPrefix(line, "\t. \"") || strings.HasPrefix(line, "\texec \"")) {
313                         line = strings.Replace(line, `"cmd/`, `"bootstrap/cmd/`, -1)
314                         for _, dir := range bootstrapDirs {
315                                 if strings.HasPrefix(dir, "cmd/") {
316                                         continue
317                                 }
318                                 line = strings.Replace(line, `"`+dir+`"`, `"bootstrap/`+dir+`"`, -1)
319                         }
320                         lines[i] = line
321                 }
322         }
323
324         lines[0] = "// Code generated by go tool dist; DO NOT EDIT.\n// This is a bootstrap copy of " + srcFile + "\n\n//line " + srcFile + ":1\n" + lines[0]
325
326         return strings.Join(lines, "")
327 }