]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/go/internal/load/pkg.go
[dev.boringcrypto] all: merge master into dev.boringcrypto
[gostls13.git] / src / cmd / go / internal / load / pkg.go
1 // Copyright 2011 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 load loads packages.
6 package load
7
8 import (
9         "bytes"
10         "fmt"
11         "go/build"
12         "go/token"
13         "io/ioutil"
14         "os"
15         pathpkg "path"
16         "path/filepath"
17         "sort"
18         "strconv"
19         "strings"
20         "unicode"
21         "unicode/utf8"
22
23         "cmd/go/internal/base"
24         "cmd/go/internal/cfg"
25         "cmd/go/internal/str"
26 )
27
28 var IgnoreImports bool // control whether we ignore imports in packages
29
30 // A Package describes a single package found in a directory.
31 type Package struct {
32         PackagePublic                 // visible in 'go list'
33         Internal      PackageInternal // for use inside go command only
34 }
35
36 type PackagePublic struct {
37         // Note: These fields are part of the go command's public API.
38         // See list.go. It is okay to add fields, but not to change or
39         // remove existing ones. Keep in sync with list.go
40         Dir           string `json:",omitempty"` // directory containing package sources
41         ImportPath    string `json:",omitempty"` // import path of package in dir
42         ImportComment string `json:",omitempty"` // path in import comment on package statement
43         Name          string `json:",omitempty"` // package name
44         Doc           string `json:",omitempty"` // package documentation string
45         Target        string `json:",omitempty"` // installed target for this package (may be executable)
46         Shlib         string `json:",omitempty"` // the shared library that contains this package (only set when -linkshared)
47         Goroot        bool   `json:",omitempty"` // is this package found in the Go root?
48         Standard      bool   `json:",omitempty"` // is this package part of the standard Go library?
49         Root          string `json:",omitempty"` // Go root or Go path dir containing this package
50         ConflictDir   string `json:",omitempty"` // Dir is hidden by this other directory
51         BinaryOnly    bool   `json:",omitempty"` // package cannot be recompiled
52         ForTest       string `json:",omitempty"` // package is only for use in named test
53         DepOnly       bool   `json:",omitempty"` // package is only as a dependency, not explicitly listed
54         Export        string `json:",omitempty"` // file containing export data (set by go list -export)
55
56         // Stale and StaleReason remain here *only* for the list command.
57         // They are only initialized in preparation for list execution.
58         // The regular build determines staleness on the fly during action execution.
59         Stale       bool   `json:",omitempty"` // would 'go install' do anything for this package?
60         StaleReason string `json:",omitempty"` // why is Stale true?
61
62         // Source files
63         // If you add to this list you MUST add to p.AllFiles (below) too.
64         // Otherwise file name security lists will not apply to any new additions.
65         GoFiles        []string `json:",omitempty"` // .go source files (excluding CgoFiles, TestGoFiles, XTestGoFiles)
66         CgoFiles       []string `json:",omitempty"` // .go sources files that import "C"
67         IgnoredGoFiles []string `json:",omitempty"` // .go sources ignored due to build constraints
68         CFiles         []string `json:",omitempty"` // .c source files
69         CXXFiles       []string `json:",omitempty"` // .cc, .cpp and .cxx source files
70         MFiles         []string `json:",omitempty"` // .m source files
71         HFiles         []string `json:",omitempty"` // .h, .hh, .hpp and .hxx source files
72         FFiles         []string `json:",omitempty"` // .f, .F, .for and .f90 Fortran source files
73         SFiles         []string `json:",omitempty"` // .s source files
74         SwigFiles      []string `json:",omitempty"` // .swig files
75         SwigCXXFiles   []string `json:",omitempty"` // .swigcxx files
76         SysoFiles      []string `json:",omitempty"` // .syso system object files added to package
77
78         // Cgo directives
79         CgoCFLAGS    []string `json:",omitempty"` // cgo: flags for C compiler
80         CgoCPPFLAGS  []string `json:",omitempty"` // cgo: flags for C preprocessor
81         CgoCXXFLAGS  []string `json:",omitempty"` // cgo: flags for C++ compiler
82         CgoFFLAGS    []string `json:",omitempty"` // cgo: flags for Fortran compiler
83         CgoLDFLAGS   []string `json:",omitempty"` // cgo: flags for linker
84         CgoPkgConfig []string `json:",omitempty"` // cgo: pkg-config names
85
86         // Dependency information
87         Imports []string `json:",omitempty"` // import paths used by this package
88         Deps    []string `json:",omitempty"` // all (recursively) imported dependencies
89
90         // Error information
91         Incomplete bool            `json:",omitempty"` // was there an error loading this package or dependencies?
92         Error      *PackageError   `json:",omitempty"` // error loading this package (not dependencies)
93         DepsErrors []*PackageError `json:",omitempty"` // errors loading dependencies
94
95         // Test information
96         // If you add to this list you MUST add to p.AllFiles (below) too.
97         // Otherwise file name security lists will not apply to any new additions.
98         TestGoFiles  []string `json:",omitempty"` // _test.go files in package
99         TestImports  []string `json:",omitempty"` // imports from TestGoFiles
100         XTestGoFiles []string `json:",omitempty"` // _test.go files outside package
101         XTestImports []string `json:",omitempty"` // imports from XTestGoFiles
102 }
103
104 // AllFiles returns the names of all the files considered for the package.
105 // This is used for sanity and security checks, so we include all files,
106 // even IgnoredGoFiles, because some subcommands consider them.
107 // The go/build package filtered others out (like foo_wrongGOARCH.s)
108 // and that's OK.
109 func (p *Package) AllFiles() []string {
110         return str.StringList(
111                 p.GoFiles,
112                 p.CgoFiles,
113                 p.IgnoredGoFiles,
114                 p.CFiles,
115                 p.CXXFiles,
116                 p.MFiles,
117                 p.HFiles,
118                 p.FFiles,
119                 p.SFiles,
120                 p.SwigFiles,
121                 p.SwigCXXFiles,
122                 p.SysoFiles,
123                 p.TestGoFiles,
124                 p.XTestGoFiles,
125         )
126 }
127
128 // Desc returns the package "description", for use in b.showOutput.
129 func (p *Package) Desc() string {
130         if p.ForTest != "" {
131                 return p.ImportPath + " [" + p.ForTest + ".test]"
132         }
133         return p.ImportPath
134 }
135
136 type PackageInternal struct {
137         // Unexported fields are not part of the public API.
138         Build        *build.Package
139         Imports      []*Package           // this package's direct imports
140         RawImports   []string             // this package's original imports as they appear in the text of the program
141         ForceLibrary bool                 // this package is a library (even if named "main")
142         CmdlineFiles bool                 // package built from files listed on command line
143         CmdlinePkg   bool                 // package listed on command line
144         Local        bool                 // imported via local path (./ or ../)
145         LocalPrefix  string               // interpret ./ and ../ imports relative to this prefix
146         ExeName      string               // desired name for temporary executable
147         CoverMode    string               // preprocess Go source files with the coverage tool in this mode
148         CoverVars    map[string]*CoverVar // variables created by coverage analysis
149         OmitDebug    bool                 // tell linker not to write debug information
150         GobinSubdir  bool                 // install target would be subdir of GOBIN
151         TestmainGo   *[]byte              // content for _testmain.go
152
153         Asmflags   []string // -asmflags for this package
154         Gcflags    []string // -gcflags for this package
155         Ldflags    []string // -ldflags for this package
156         Gccgoflags []string // -gccgoflags for this package
157 }
158
159 type NoGoError struct {
160         Package *Package
161 }
162
163 func (e *NoGoError) Error() string {
164         // Count files beginning with _ and ., which we will pretend don't exist at all.
165         dummy := 0
166         for _, name := range e.Package.IgnoredGoFiles {
167                 if strings.HasPrefix(name, "_") || strings.HasPrefix(name, ".") {
168                         dummy++
169                 }
170         }
171
172         if len(e.Package.IgnoredGoFiles) > dummy {
173                 // Go files exist, but they were ignored due to build constraints.
174                 return "build constraints exclude all Go files in " + e.Package.Dir
175         }
176         if len(e.Package.TestGoFiles)+len(e.Package.XTestGoFiles) > 0 {
177                 // Test Go files exist, but we're not interested in them.
178                 // The double-negative is unfortunate but we want e.Package.Dir
179                 // to appear at the end of error message.
180                 return "no non-test Go files in " + e.Package.Dir
181         }
182         return "no Go files in " + e.Package.Dir
183 }
184
185 // Resolve returns the resolved version of imports,
186 // which should be p.TestImports or p.XTestImports, NOT p.Imports.
187 // The imports in p.TestImports and p.XTestImports are not recursively
188 // loaded during the initial load of p, so they list the imports found in
189 // the source file, but most processing should be over the vendor-resolved
190 // import paths. We do this resolution lazily both to avoid file system work
191 // and because the eventual real load of the test imports (during 'go test')
192 // can produce better error messages if it starts with the original paths.
193 // The initial load of p loads all the non-test imports and rewrites
194 // the vendored paths, so nothing should ever call p.vendored(p.Imports).
195 func (p *Package) Resolve(imports []string) []string {
196         if len(imports) > 0 && len(p.Imports) > 0 && &imports[0] == &p.Imports[0] {
197                 panic("internal error: p.Resolve(p.Imports) called")
198         }
199         seen := make(map[string]bool)
200         var all []string
201         for _, path := range imports {
202                 path = ResolveImportPath(p, path)
203                 if !seen[path] {
204                         seen[path] = true
205                         all = append(all, path)
206                 }
207         }
208         sort.Strings(all)
209         return all
210 }
211
212 // CoverVar holds the name of the generated coverage variables targeting the named file.
213 type CoverVar struct {
214         File string // local file name
215         Var  string // name of count struct
216 }
217
218 func (p *Package) copyBuild(pp *build.Package) {
219         p.Internal.Build = pp
220
221         if pp.PkgTargetRoot != "" && cfg.BuildPkgdir != "" {
222                 old := pp.PkgTargetRoot
223                 pp.PkgRoot = cfg.BuildPkgdir
224                 pp.PkgTargetRoot = cfg.BuildPkgdir
225                 pp.PkgObj = filepath.Join(cfg.BuildPkgdir, strings.TrimPrefix(pp.PkgObj, old))
226         }
227
228         p.Dir = pp.Dir
229         p.ImportPath = pp.ImportPath
230         p.ImportComment = pp.ImportComment
231         p.Name = pp.Name
232         p.Doc = pp.Doc
233         p.Root = pp.Root
234         p.ConflictDir = pp.ConflictDir
235         p.BinaryOnly = pp.BinaryOnly
236
237         // TODO? Target
238         p.Goroot = pp.Goroot
239         p.Standard = p.Goroot && p.ImportPath != "" && isStandardImportPath(p.ImportPath)
240         p.GoFiles = pp.GoFiles
241         p.CgoFiles = pp.CgoFiles
242         p.IgnoredGoFiles = pp.IgnoredGoFiles
243         p.CFiles = pp.CFiles
244         p.CXXFiles = pp.CXXFiles
245         p.MFiles = pp.MFiles
246         p.HFiles = pp.HFiles
247         p.FFiles = pp.FFiles
248         p.SFiles = pp.SFiles
249         p.SwigFiles = pp.SwigFiles
250         p.SwigCXXFiles = pp.SwigCXXFiles
251         p.SysoFiles = pp.SysoFiles
252         if cfg.BuildMSan {
253                 // There's no way for .syso files to be built both with and without
254                 // support for memory sanitizer. Assume they are built without,
255                 // and drop them.
256                 p.SysoFiles = nil
257         }
258         p.CgoCFLAGS = pp.CgoCFLAGS
259         p.CgoCPPFLAGS = pp.CgoCPPFLAGS
260         p.CgoCXXFLAGS = pp.CgoCXXFLAGS
261         p.CgoFFLAGS = pp.CgoFFLAGS
262         p.CgoLDFLAGS = pp.CgoLDFLAGS
263         p.CgoPkgConfig = pp.CgoPkgConfig
264         // We modify p.Imports in place, so make copy now.
265         p.Imports = make([]string, len(pp.Imports))
266         copy(p.Imports, pp.Imports)
267         p.Internal.RawImports = pp.Imports
268         p.TestGoFiles = pp.TestGoFiles
269         p.TestImports = pp.TestImports
270         p.XTestGoFiles = pp.XTestGoFiles
271         p.XTestImports = pp.XTestImports
272         if IgnoreImports {
273                 p.Imports = nil
274                 p.TestImports = nil
275                 p.XTestImports = nil
276         }
277 }
278
279 // isStandardImportPath reports whether $GOROOT/src/path should be considered
280 // part of the standard distribution. For historical reasons we allow people to add
281 // their own code to $GOROOT instead of using $GOPATH, but we assume that
282 // code will start with a domain name (dot in the first element).
283 func isStandardImportPath(path string) bool {
284         i := strings.Index(path, "/")
285         if i < 0 {
286                 i = len(path)
287         }
288         elem := path[:i]
289         return !strings.Contains(elem, ".")
290 }
291
292 // A PackageError describes an error loading information about a package.
293 type PackageError struct {
294         ImportStack   []string // shortest path from package named on command line to this one
295         Pos           string   // position of error
296         Err           string   // the error itself
297         IsImportCycle bool     `json:"-"` // the error is an import cycle
298         Hard          bool     `json:"-"` // whether the error is soft or hard; soft errors are ignored in some places
299 }
300
301 func (p *PackageError) Error() string {
302         // Import cycles deserve special treatment.
303         if p.IsImportCycle {
304                 return fmt.Sprintf("%s\npackage %s\n", p.Err, strings.Join(p.ImportStack, "\n\timports "))
305         }
306         if p.Pos != "" {
307                 // Omit import stack. The full path to the file where the error
308                 // is the most important thing.
309                 return p.Pos + ": " + p.Err
310         }
311         if len(p.ImportStack) == 0 {
312                 return p.Err
313         }
314         return "package " + strings.Join(p.ImportStack, "\n\timports ") + ": " + p.Err
315 }
316
317 // An ImportStack is a stack of import paths.
318 type ImportStack []string
319
320 func (s *ImportStack) Push(p string) {
321         *s = append(*s, p)
322 }
323
324 func (s *ImportStack) Pop() {
325         *s = (*s)[0 : len(*s)-1]
326 }
327
328 func (s *ImportStack) Copy() []string {
329         return append([]string{}, *s...)
330 }
331
332 // shorterThan reports whether sp is shorter than t.
333 // We use this to record the shortest import sequence
334 // that leads to a particular package.
335 func (sp *ImportStack) shorterThan(t []string) bool {
336         s := *sp
337         if len(s) != len(t) {
338                 return len(s) < len(t)
339         }
340         // If they are the same length, settle ties using string ordering.
341         for i := range s {
342                 if s[i] != t[i] {
343                         return s[i] < t[i]
344                 }
345         }
346         return false // they are equal
347 }
348
349 // packageCache is a lookup cache for loadPackage,
350 // so that if we look up a package multiple times
351 // we return the same pointer each time.
352 var packageCache = map[string]*Package{}
353
354 func ClearPackageCache() {
355         for name := range packageCache {
356                 delete(packageCache, name)
357         }
358 }
359
360 func ClearPackageCachePartial(args []string) {
361         for _, arg := range args {
362                 p := packageCache[arg]
363                 if p != nil {
364                         delete(packageCache, p.Dir)
365                         delete(packageCache, p.ImportPath)
366                 }
367         }
368 }
369
370 // reloadPackage is like loadPackage but makes sure
371 // not to use the package cache.
372 func ReloadPackage(arg string, stk *ImportStack) *Package {
373         p := packageCache[arg]
374         if p != nil {
375                 delete(packageCache, p.Dir)
376                 delete(packageCache, p.ImportPath)
377         }
378         return LoadPackage(arg, stk)
379 }
380
381 // dirToImportPath returns the pseudo-import path we use for a package
382 // outside the Go path. It begins with _/ and then contains the full path
383 // to the directory. If the package lives in c:\home\gopher\my\pkg then
384 // the pseudo-import path is _/c_/home/gopher/my/pkg.
385 // Using a pseudo-import path like this makes the ./ imports no longer
386 // a special case, so that all the code to deal with ordinary imports works
387 // automatically.
388 func dirToImportPath(dir string) string {
389         return pathpkg.Join("_", strings.Map(makeImportValid, filepath.ToSlash(dir)))
390 }
391
392 func makeImportValid(r rune) rune {
393         // Should match Go spec, compilers, and ../../go/parser/parser.go:/isValidImport.
394         const illegalChars = `!"#$%&'()*,:;<=>?[\]^{|}` + "`\uFFFD"
395         if !unicode.IsGraphic(r) || unicode.IsSpace(r) || strings.ContainsRune(illegalChars, r) {
396                 return '_'
397         }
398         return r
399 }
400
401 // Mode flags for loadImport and download (in get.go).
402 const (
403         // ResolveImport means that loadImport should do import path expansion.
404         // That is, ResolveImport means that the import path came from
405         // a source file and has not been expanded yet to account for
406         // vendoring or possible module adjustment.
407         // Every import path should be loaded initially with ResolveImport,
408         // and then the expanded version (for example with the /vendor/ in it)
409         // gets recorded as the canonical import path. At that point, future loads
410         // of that package must not pass ResolveImport, because
411         // disallowVendor will reject direct use of paths containing /vendor/.
412         ResolveImport = 1 << iota
413
414         // ResolveModule is for download (part of "go get") and indicates
415         // that the module adjustment should be done, but not vendor adjustment.
416         ResolveModule
417
418         // GetTestDeps is for download (part of "go get") and indicates
419         // that test dependencies should be fetched too.
420         GetTestDeps
421 )
422
423 // LoadImport scans the directory named by path, which must be an import path,
424 // but possibly a local import path (an absolute file system path or one beginning
425 // with ./ or ../). A local relative path is interpreted relative to srcDir.
426 // It returns a *Package describing the package found in that directory.
427 func LoadImport(path, srcDir string, parent *Package, stk *ImportStack, importPos []token.Position, mode int) *Package {
428         stk.Push(path)
429         defer stk.Pop()
430
431         // Determine canonical identifier for this package.
432         // For a local import the identifier is the pseudo-import path
433         // we create from the full directory to the package.
434         // Otherwise it is the usual import path.
435         // For vendored imports, it is the expanded form.
436         importPath := path
437         origPath := path
438         isLocal := build.IsLocalImport(path)
439         if isLocal {
440                 importPath = dirToImportPath(filepath.Join(srcDir, path))
441         } else if mode&ResolveImport != 0 {
442                 // We do our own path resolution, because we want to
443                 // find out the key to use in packageCache without the
444                 // overhead of repeated calls to buildContext.Import.
445                 // The code is also needed in a few other places anyway.
446                 path = ResolveImportPath(parent, path)
447                 importPath = path
448         } else if mode&ResolveModule != 0 {
449                 path = ModuleImportPath(parent, path)
450                 importPath = path
451         }
452
453         p := packageCache[importPath]
454         if p != nil {
455                 p = reusePackage(p, stk)
456         } else {
457                 p = new(Package)
458                 p.Internal.Local = isLocal
459                 p.ImportPath = importPath
460                 packageCache[importPath] = p
461
462                 // Load package.
463                 // Import always returns bp != nil, even if an error occurs,
464                 // in order to return partial information.
465                 buildMode := build.ImportComment
466                 if mode&ResolveImport == 0 || path != origPath {
467                         // Not vendoring, or we already found the vendored path.
468                         buildMode |= build.IgnoreVendor
469                 }
470                 bp, err := cfg.BuildContext.Import(path, srcDir, buildMode)
471                 bp.ImportPath = importPath
472                 if cfg.GOBIN != "" {
473                         bp.BinDir = cfg.GOBIN
474                 }
475                 if err == nil && !isLocal && bp.ImportComment != "" && bp.ImportComment != path &&
476                         !strings.Contains(path, "/vendor/") && !strings.HasPrefix(path, "vendor/") {
477                         err = fmt.Errorf("code in directory %s expects import %q", bp.Dir, bp.ImportComment)
478                 }
479                 p.load(stk, bp, err)
480                 if p.Error != nil && p.Error.Pos == "" {
481                         p = setErrorPos(p, importPos)
482                 }
483
484                 if origPath != cleanImport(origPath) {
485                         p.Error = &PackageError{
486                                 ImportStack: stk.Copy(),
487                                 Err:         fmt.Sprintf("non-canonical import path: %q should be %q", origPath, pathpkg.Clean(origPath)),
488                         }
489                         p.Incomplete = true
490                 }
491         }
492
493         // Checked on every import because the rules depend on the code doing the importing.
494         if perr := disallowInternal(srcDir, p, stk); perr != p {
495                 return setErrorPos(perr, importPos)
496         }
497         if mode&ResolveImport != 0 {
498                 if perr := disallowVendor(srcDir, origPath, p, stk); perr != p {
499                         return setErrorPos(perr, importPos)
500                 }
501         }
502
503         if p.Name == "main" && parent != nil && parent.Dir != p.Dir {
504                 perr := *p
505                 perr.Error = &PackageError{
506                         ImportStack: stk.Copy(),
507                         Err:         fmt.Sprintf("import %q is a program, not an importable package", path),
508                 }
509                 return setErrorPos(&perr, importPos)
510         }
511
512         if p.Internal.Local && parent != nil && !parent.Internal.Local {
513                 perr := *p
514                 perr.Error = &PackageError{
515                         ImportStack: stk.Copy(),
516                         Err:         fmt.Sprintf("local import %q in non-local package", path),
517                 }
518                 return setErrorPos(&perr, importPos)
519         }
520
521         return p
522 }
523
524 func setErrorPos(p *Package, importPos []token.Position) *Package {
525         if len(importPos) > 0 {
526                 pos := importPos[0]
527                 pos.Filename = base.ShortPath(pos.Filename)
528                 p.Error.Pos = pos.String()
529         }
530         return p
531 }
532
533 func cleanImport(path string) string {
534         orig := path
535         path = pathpkg.Clean(path)
536         if strings.HasPrefix(orig, "./") && path != ".." && !strings.HasPrefix(path, "../") {
537                 path = "./" + path
538         }
539         return path
540 }
541
542 var isDirCache = map[string]bool{}
543
544 func isDir(path string) bool {
545         result, ok := isDirCache[path]
546         if ok {
547                 return result
548         }
549
550         fi, err := os.Stat(path)
551         result = err == nil && fi.IsDir()
552         isDirCache[path] = result
553         return result
554 }
555
556 // ResolveImportPath returns the true meaning of path when it appears in parent.
557 // There are two different resolutions applied.
558 // First, there is Go 1.5 vendoring (golang.org/s/go15vendor).
559 // If vendor expansion doesn't trigger, then the path is also subject to
560 // Go 1.11 vgo legacy conversion (golang.org/issue/25069).
561 func ResolveImportPath(parent *Package, path string) (found string) {
562         found = VendoredImportPath(parent, path)
563         if found != path {
564                 return found
565         }
566         return ModuleImportPath(parent, path)
567 }
568
569 // dirAndRoot returns the source directory and workspace root
570 // for the package p, guaranteeing that root is a path prefix of dir.
571 func dirAndRoot(p *Package) (dir, root string) {
572         dir = filepath.Clean(p.Dir)
573         root = filepath.Join(p.Root, "src")
574         if !str.HasFilePathPrefix(dir, root) || p.ImportPath != "command-line-arguments" && filepath.Join(root, p.ImportPath) != dir {
575                 // Look for symlinks before reporting error.
576                 dir = expandPath(dir)
577                 root = expandPath(root)
578         }
579
580         if !str.HasFilePathPrefix(dir, root) || len(dir) <= len(root) || dir[len(root)] != filepath.Separator || p.ImportPath != "command-line-arguments" && !p.Internal.Local && filepath.Join(root, p.ImportPath) != dir {
581                 base.Fatalf("unexpected directory layout:\n"+
582                         "       import path: %s\n"+
583                         "       root: %s\n"+
584                         "       dir: %s\n"+
585                         "       expand root: %s\n"+
586                         "       expand dir: %s\n"+
587                         "       separator: %s",
588                         p.ImportPath,
589                         filepath.Join(p.Root, "src"),
590                         filepath.Clean(p.Dir),
591                         root,
592                         dir,
593                         string(filepath.Separator))
594         }
595
596         return dir, root
597 }
598
599 // VendoredImportPath returns the vendor-expansion of path when it appears in parent.
600 // If parent is x/y/z, then path might expand to x/y/z/vendor/path, x/y/vendor/path,
601 // x/vendor/path, vendor/path, or else stay path if none of those exist.
602 // VendoredImportPath returns the expanded path or, if no expansion is found, the original.
603 func VendoredImportPath(parent *Package, path string) (found string) {
604         if parent == nil || parent.Root == "" {
605                 return path
606         }
607
608         dir, root := dirAndRoot(parent)
609
610         vpath := "vendor/" + path
611         for i := len(dir); i >= len(root); i-- {
612                 if i < len(dir) && dir[i] != filepath.Separator {
613                         continue
614                 }
615                 // Note: checking for the vendor directory before checking
616                 // for the vendor/path directory helps us hit the
617                 // isDir cache more often. It also helps us prepare a more useful
618                 // list of places we looked, to report when an import is not found.
619                 if !isDir(filepath.Join(dir[:i], "vendor")) {
620                         continue
621                 }
622                 targ := filepath.Join(dir[:i], vpath)
623                 if isDir(targ) && hasGoFiles(targ) {
624                         importPath := parent.ImportPath
625                         if importPath == "command-line-arguments" {
626                                 // If parent.ImportPath is 'command-line-arguments'.
627                                 // set to relative directory to root (also chopped root directory)
628                                 importPath = dir[len(root)+1:]
629                         }
630                         // We started with parent's dir c:\gopath\src\foo\bar\baz\quux\xyzzy.
631                         // We know the import path for parent's dir.
632                         // We chopped off some number of path elements and
633                         // added vendor\path to produce c:\gopath\src\foo\bar\baz\vendor\path.
634                         // Now we want to know the import path for that directory.
635                         // Construct it by chopping the same number of path elements
636                         // (actually the same number of bytes) from parent's import path
637                         // and then append /vendor/path.
638                         chopped := len(dir) - i
639                         if chopped == len(importPath)+1 {
640                                 // We walked up from c:\gopath\src\foo\bar
641                                 // and found c:\gopath\src\vendor\path.
642                                 // We chopped \foo\bar (length 8) but the import path is "foo/bar" (length 7).
643                                 // Use "vendor/path" without any prefix.
644                                 return vpath
645                         }
646                         return importPath[:len(importPath)-chopped] + "/" + vpath
647                 }
648         }
649         return path
650 }
651
652 var (
653         modulePrefix   = []byte("\nmodule ")
654         goModPathCache = make(map[string]string)
655 )
656
657 // goModPath returns the module path in the go.mod in dir, if any.
658 func goModPath(dir string) (path string) {
659         path, ok := goModPathCache[dir]
660         if ok {
661                 return path
662         }
663         defer func() {
664                 goModPathCache[dir] = path
665         }()
666
667         data, err := ioutil.ReadFile(filepath.Join(dir, "go.mod"))
668         if err != nil {
669                 return ""
670         }
671         var i int
672         if bytes.HasPrefix(data, modulePrefix[1:]) {
673                 i = 0
674         } else {
675                 i = bytes.Index(data, modulePrefix)
676                 if i < 0 {
677                         return ""
678                 }
679                 i++
680         }
681         line := data[i:]
682
683         // Cut line at \n, drop trailing \r if present.
684         if j := bytes.IndexByte(line, '\n'); j >= 0 {
685                 line = line[:j]
686         }
687         if line[len(line)-1] == '\r' {
688                 line = line[:len(line)-1]
689         }
690         line = line[len("module "):]
691
692         // If quoted, unquote.
693         path = strings.TrimSpace(string(line))
694         if path != "" && path[0] == '"' {
695                 s, err := strconv.Unquote(path)
696                 if err != nil {
697                         return ""
698                 }
699                 path = s
700         }
701         return path
702 }
703
704 // findVersionElement returns the slice indices of the final version element /vN in path.
705 // If there is no such element, it returns -1, -1.
706 func findVersionElement(path string) (i, j int) {
707         j = len(path)
708         for i = len(path) - 1; i >= 0; i-- {
709                 if path[i] == '/' {
710                         if isVersionElement(path[i:j]) {
711                                 return i, j
712                         }
713                         j = i
714                 }
715         }
716         return -1, -1
717 }
718
719 // isVersionElement reports whether s is a well-formed path version element:
720 // v2, v3, v10, etc, but not v0, v05, v1.
721 func isVersionElement(s string) bool {
722         if len(s) < 3 || s[0] != '/' || s[1] != 'v' || s[2] == '0' || s[2] == '1' && len(s) == 3 {
723                 return false
724         }
725         for i := 2; i < len(s); i++ {
726                 if s[i] < '0' || '9' < s[i] {
727                         return false
728                 }
729         }
730         return true
731 }
732
733 // ModuleImportPath translates import paths found in go modules
734 // back down to paths that can be resolved in ordinary builds.
735 //
736 // Define “new” code as code with a go.mod file in the same directory
737 // or a parent directory. If an import in new code says x/y/v2/z but
738 // x/y/v2/z does not exist and x/y/go.mod says “module x/y/v2”,
739 // then go build will read the import as x/y/z instead.
740 // See golang.org/issue/25069.
741 func ModuleImportPath(parent *Package, path string) (found string) {
742         if parent == nil || parent.Root == "" {
743                 return path
744         }
745
746         // If there are no vN elements in path, leave it alone.
747         // (The code below would do the same, but only after
748         // some other file system accesses that we can avoid
749         // here by returning early.)
750         if i, _ := findVersionElement(path); i < 0 {
751                 return path
752         }
753
754         dir, root := dirAndRoot(parent)
755
756         // Consider dir and parents, up to and including root.
757         for i := len(dir); i >= len(root); i-- {
758                 if i < len(dir) && dir[i] != filepath.Separator {
759                         continue
760                 }
761                 if goModPath(dir[:i]) != "" {
762                         goto HaveGoMod
763                 }
764         }
765         // This code is not in a tree with a go.mod,
766         // so apply no changes to the path.
767         return path
768
769 HaveGoMod:
770         // This import is in a tree with a go.mod.
771         // Allow it to refer to code in GOPATH/src/x/y/z as x/y/v2/z
772         // if GOPATH/src/x/y/go.mod says module "x/y/v2",
773
774         // If x/y/v2/z exists, use it unmodified.
775         if bp, _ := cfg.BuildContext.Import(path, "", build.IgnoreVendor); bp.Dir != "" {
776                 return path
777         }
778
779         // Otherwise look for a go.mod supplying a version element.
780         // Some version-like elements may appear in paths but not
781         // be module versions; we skip over those to look for module
782         // versions. For example the module m/v2 might have a
783         // package m/v2/api/v1/foo.
784         limit := len(path)
785         for limit > 0 {
786                 i, j := findVersionElement(path[:limit])
787                 if i < 0 {
788                         return path
789                 }
790                 if bp, _ := cfg.BuildContext.Import(path[:i], "", build.IgnoreVendor); bp.Dir != "" {
791                         if mpath := goModPath(bp.Dir); mpath != "" {
792                                 // Found a valid go.mod file, so we're stopping the search.
793                                 // If the path is m/v2/p and we found m/go.mod that says
794                                 // "module m/v2", then we return "m/p".
795                                 if mpath == path[:j] {
796                                         return path[:i] + path[j:]
797                                 }
798                                 // Otherwise just return the original path.
799                                 // We didn't find anything worth rewriting,
800                                 // and the go.mod indicates that we should
801                                 // not consider parent directories.
802                                 return path
803                         }
804                 }
805                 limit = i
806         }
807         return path
808 }
809
810 // hasGoFiles reports whether dir contains any files with names ending in .go.
811 // For a vendor check we must exclude directories that contain no .go files.
812 // Otherwise it is not possible to vendor just a/b/c and still import the
813 // non-vendored a/b. See golang.org/issue/13832.
814 func hasGoFiles(dir string) bool {
815         fis, _ := ioutil.ReadDir(dir)
816         for _, fi := range fis {
817                 if !fi.IsDir() && strings.HasSuffix(fi.Name(), ".go") {
818                         return true
819                 }
820         }
821         return false
822 }
823
824 // reusePackage reuses package p to satisfy the import at the top
825 // of the import stack stk. If this use causes an import loop,
826 // reusePackage updates p's error information to record the loop.
827 func reusePackage(p *Package, stk *ImportStack) *Package {
828         // We use p.Internal.Imports==nil to detect a package that
829         // is in the midst of its own loadPackage call
830         // (all the recursion below happens before p.Internal.Imports gets set).
831         if p.Internal.Imports == nil {
832                 if p.Error == nil {
833                         p.Error = &PackageError{
834                                 ImportStack:   stk.Copy(),
835                                 Err:           "import cycle not allowed",
836                                 IsImportCycle: true,
837                         }
838                 }
839                 p.Incomplete = true
840         }
841         // Don't rewrite the import stack in the error if we have an import cycle.
842         // If we do, we'll lose the path that describes the cycle.
843         if p.Error != nil && !p.Error.IsImportCycle && stk.shorterThan(p.Error.ImportStack) {
844                 p.Error.ImportStack = stk.Copy()
845         }
846         return p
847 }
848
849 // disallowInternal checks that srcDir is allowed to import p.
850 // If the import is allowed, disallowInternal returns the original package p.
851 // If not, it returns a new package containing just an appropriate error.
852 func disallowInternal(srcDir string, p *Package, stk *ImportStack) *Package {
853         // golang.org/s/go14internal:
854         // An import of a path containing the element “internal”
855         // is disallowed if the importing code is outside the tree
856         // rooted at the parent of the “internal” directory.
857
858         // There was an error loading the package; stop here.
859         if p.Error != nil {
860                 return p
861         }
862
863         // The generated 'testmain' package is allowed to access testing/internal/...,
864         // as if it were generated into the testing directory tree
865         // (it's actually in a temporary directory outside any Go tree).
866         // This cleans up a former kludge in passing functionality to the testing package.
867         if strings.HasPrefix(p.ImportPath, "testing/internal") && len(*stk) >= 2 && (*stk)[len(*stk)-2] == "testmain" {
868                 return p
869         }
870
871         // We can't check standard packages with gccgo.
872         if cfg.BuildContext.Compiler == "gccgo" && p.Standard {
873                 return p
874         }
875
876         // The stack includes p.ImportPath.
877         // If that's the only thing on the stack, we started
878         // with a name given on the command line, not an
879         // import. Anything listed on the command line is fine.
880         if len(*stk) == 1 {
881                 return p
882         }
883
884         // Check for "internal" element: three cases depending on begin of string and/or end of string.
885         i, ok := findInternal(p.ImportPath)
886         if !ok {
887                 return p
888         }
889
890         // Internal is present.
891         // Map import path back to directory corresponding to parent of internal.
892         if i > 0 {
893                 i-- // rewind over slash in ".../internal"
894         }
895         parent := p.Dir[:i+len(p.Dir)-len(p.ImportPath)]
896         if str.HasFilePathPrefix(filepath.Clean(srcDir), filepath.Clean(parent)) {
897                 return p
898         }
899
900         // Look for symlinks before reporting error.
901         srcDir = expandPath(srcDir)
902         parent = expandPath(parent)
903         if str.HasFilePathPrefix(filepath.Clean(srcDir), filepath.Clean(parent)) {
904                 return p
905         }
906
907         // Internal is present, and srcDir is outside parent's tree. Not allowed.
908         perr := *p
909         perr.Error = &PackageError{
910                 ImportStack: stk.Copy(),
911                 Err:         "use of internal package not allowed",
912         }
913         perr.Incomplete = true
914         return &perr
915 }
916
917 // findInternal looks for the final "internal" path element in the given import path.
918 // If there isn't one, findInternal returns ok=false.
919 // Otherwise, findInternal returns ok=true and the index of the "internal".
920 func findInternal(path string) (index int, ok bool) {
921         // Three cases, depending on internal at start/end of string or not.
922         // The order matters: we must return the index of the final element,
923         // because the final one produces the most restrictive requirement
924         // on the importer.
925         switch {
926         case strings.HasSuffix(path, "/internal"):
927                 return len(path) - len("internal"), true
928         case strings.Contains(path, "/internal/"):
929                 return strings.LastIndex(path, "/internal/") + 1, true
930         case path == "internal", strings.HasPrefix(path, "internal/"):
931                 return 0, true
932         }
933         return 0, false
934 }
935
936 // disallowVendor checks that srcDir is allowed to import p as path.
937 // If the import is allowed, disallowVendor returns the original package p.
938 // If not, it returns a new package containing just an appropriate error.
939 func disallowVendor(srcDir, path string, p *Package, stk *ImportStack) *Package {
940         // The stack includes p.ImportPath.
941         // If that's the only thing on the stack, we started
942         // with a name given on the command line, not an
943         // import. Anything listed on the command line is fine.
944         if len(*stk) == 1 {
945                 return p
946         }
947
948         if perr := disallowVendorVisibility(srcDir, p, stk); perr != p {
949                 return perr
950         }
951
952         // Paths like x/vendor/y must be imported as y, never as x/vendor/y.
953         if i, ok := FindVendor(path); ok {
954                 perr := *p
955                 perr.Error = &PackageError{
956                         ImportStack: stk.Copy(),
957                         Err:         "must be imported as " + path[i+len("vendor/"):],
958                 }
959                 perr.Incomplete = true
960                 return &perr
961         }
962
963         return p
964 }
965
966 // disallowVendorVisibility checks that srcDir is allowed to import p.
967 // The rules are the same as for /internal/ except that a path ending in /vendor
968 // is not subject to the rules, only subdirectories of vendor.
969 // This allows people to have packages and commands named vendor,
970 // for maximal compatibility with existing source trees.
971 func disallowVendorVisibility(srcDir string, p *Package, stk *ImportStack) *Package {
972         // The stack includes p.ImportPath.
973         // If that's the only thing on the stack, we started
974         // with a name given on the command line, not an
975         // import. Anything listed on the command line is fine.
976         if len(*stk) == 1 {
977                 return p
978         }
979
980         // Check for "vendor" element.
981         i, ok := FindVendor(p.ImportPath)
982         if !ok {
983                 return p
984         }
985
986         // Vendor is present.
987         // Map import path back to directory corresponding to parent of vendor.
988         if i > 0 {
989                 i-- // rewind over slash in ".../vendor"
990         }
991         truncateTo := i + len(p.Dir) - len(p.ImportPath)
992         if truncateTo < 0 || len(p.Dir) < truncateTo {
993                 return p
994         }
995         parent := p.Dir[:truncateTo]
996         if str.HasFilePathPrefix(filepath.Clean(srcDir), filepath.Clean(parent)) {
997                 return p
998         }
999
1000         // Look for symlinks before reporting error.
1001         srcDir = expandPath(srcDir)
1002         parent = expandPath(parent)
1003         if str.HasFilePathPrefix(filepath.Clean(srcDir), filepath.Clean(parent)) {
1004                 return p
1005         }
1006
1007         // Vendor is present, and srcDir is outside parent's tree. Not allowed.
1008         perr := *p
1009         perr.Error = &PackageError{
1010                 ImportStack: stk.Copy(),
1011                 Err:         "use of vendored package not allowed",
1012         }
1013         perr.Incomplete = true
1014         return &perr
1015 }
1016
1017 // FindVendor looks for the last non-terminating "vendor" path element in the given import path.
1018 // If there isn't one, FindVendor returns ok=false.
1019 // Otherwise, FindVendor returns ok=true and the index of the "vendor".
1020 //
1021 // Note that terminating "vendor" elements don't count: "x/vendor" is its own package,
1022 // not the vendored copy of an import "" (the empty import path).
1023 // This will allow people to have packages or commands named vendor.
1024 // This may help reduce breakage, or it may just be confusing. We'll see.
1025 func FindVendor(path string) (index int, ok bool) {
1026         // Two cases, depending on internal at start of string or not.
1027         // The order matters: we must return the index of the final element,
1028         // because the final one is where the effective import path starts.
1029         switch {
1030         case strings.Contains(path, "/vendor/"):
1031                 return strings.LastIndex(path, "/vendor/") + 1, true
1032         case strings.HasPrefix(path, "vendor/"):
1033                 return 0, true
1034         }
1035         return 0, false
1036 }
1037
1038 type TargetDir int
1039
1040 const (
1041         ToTool    TargetDir = iota // to GOROOT/pkg/tool (default for cmd/*)
1042         ToBin                      // to bin dir inside package root (default for non-cmd/*)
1043         StalePath                  // an old import path; fail to build
1044 )
1045
1046 // InstallTargetDir reports the target directory for installing the command p.
1047 func InstallTargetDir(p *Package) TargetDir {
1048         if strings.HasPrefix(p.ImportPath, "code.google.com/p/go.tools/cmd/") {
1049                 return StalePath
1050         }
1051         if p.Goroot && strings.HasPrefix(p.ImportPath, "cmd/") && p.Name == "main" {
1052                 switch p.ImportPath {
1053                 case "cmd/go", "cmd/gofmt":
1054                         return ToBin
1055                 }
1056                 return ToTool
1057         }
1058         return ToBin
1059 }
1060
1061 var cgoExclude = map[string]bool{
1062         "runtime/cgo": true,
1063 }
1064
1065 var cgoSyscallExclude = map[string]bool{
1066         "runtime/cgo":  true,
1067         "runtime/race": true,
1068         "runtime/msan": true,
1069 }
1070
1071 var foldPath = make(map[string]string)
1072
1073 // load populates p using information from bp, err, which should
1074 // be the result of calling build.Context.Import.
1075 func (p *Package) load(stk *ImportStack, bp *build.Package, err error) {
1076         p.copyBuild(bp)
1077
1078         // Decide whether p was listed on the command line.
1079         // Given that load is called while processing the command line,
1080         // you might think we could simply pass a flag down into load
1081         // saying whether we are loading something named on the command
1082         // line or something to satisfy an import. But the first load of a
1083         // package named on the command line may be as a dependency
1084         // of an earlier package named on the command line, not when we
1085         // get to that package during command line processing.
1086         // For example "go test fmt reflect" will load reflect as a dependency
1087         // of fmt before it attempts to load as a command-line argument.
1088         // Because loads are cached, the later load will be a no-op,
1089         // so it is important that the first load can fill in CmdlinePkg correctly.
1090         // Hence the call to an explicit matching check here.
1091         p.Internal.CmdlinePkg = isCmdlinePkg(p)
1092
1093         p.Internal.Asmflags = BuildAsmflags.For(p)
1094         p.Internal.Gcflags = BuildGcflags.For(p)
1095         p.Internal.Ldflags = BuildLdflags.For(p)
1096         p.Internal.Gccgoflags = BuildGccgoflags.For(p)
1097
1098         // The localPrefix is the path we interpret ./ imports relative to.
1099         // Synthesized main packages sometimes override this.
1100         if p.Internal.Local {
1101                 p.Internal.LocalPrefix = dirToImportPath(p.Dir)
1102         }
1103
1104         if err != nil {
1105                 if _, ok := err.(*build.NoGoError); ok {
1106                         err = &NoGoError{Package: p}
1107                 }
1108                 p.Incomplete = true
1109                 err = base.ExpandScanner(err)
1110                 p.Error = &PackageError{
1111                         ImportStack: stk.Copy(),
1112                         Err:         err.Error(),
1113                 }
1114                 return
1115         }
1116
1117         useBindir := p.Name == "main"
1118         if !p.Standard {
1119                 switch cfg.BuildBuildmode {
1120                 case "c-archive", "c-shared", "plugin":
1121                         useBindir = false
1122                 }
1123         }
1124
1125         if useBindir {
1126                 // Report an error when the old code.google.com/p/go.tools paths are used.
1127                 if InstallTargetDir(p) == StalePath {
1128                         newPath := strings.Replace(p.ImportPath, "code.google.com/p/go.", "golang.org/x/", 1)
1129                         e := fmt.Sprintf("the %v command has moved; use %v instead.", p.ImportPath, newPath)
1130                         p.Error = &PackageError{Err: e}
1131                         return
1132                 }
1133                 _, elem := filepath.Split(p.Dir)
1134                 full := cfg.BuildContext.GOOS + "_" + cfg.BuildContext.GOARCH + "/" + elem
1135                 if cfg.BuildContext.GOOS != base.ToolGOOS || cfg.BuildContext.GOARCH != base.ToolGOARCH {
1136                         // Install cross-compiled binaries to subdirectories of bin.
1137                         elem = full
1138                 }
1139                 if p.Internal.Build.BinDir != "" {
1140                         // Install to GOBIN or bin of GOPATH entry.
1141                         p.Target = filepath.Join(p.Internal.Build.BinDir, elem)
1142                         if !p.Goroot && strings.Contains(elem, "/") && cfg.GOBIN != "" {
1143                                 // Do not create $GOBIN/goos_goarch/elem.
1144                                 p.Target = ""
1145                                 p.Internal.GobinSubdir = true
1146                         }
1147                 }
1148                 if InstallTargetDir(p) == ToTool {
1149                         // This is for 'go tool'.
1150                         // Override all the usual logic and force it into the tool directory.
1151                         if cfg.BuildToolchainName == "gccgo" {
1152                                 p.Target = filepath.Join(base.ToolDir, elem)
1153                         } else {
1154                                 p.Target = filepath.Join(cfg.GOROOTpkg, "tool", full)
1155                         }
1156                 }
1157                 if p.Target != "" && cfg.BuildContext.GOOS == "windows" {
1158                         p.Target += ".exe"
1159                 }
1160         } else if p.Internal.Local {
1161                 // Local import turned into absolute path.
1162                 // No permanent install target.
1163                 p.Target = ""
1164         } else {
1165                 p.Target = p.Internal.Build.PkgObj
1166                 if cfg.BuildLinkshared {
1167                         shlibnamefile := p.Target[:len(p.Target)-2] + ".shlibname"
1168                         shlib, err := ioutil.ReadFile(shlibnamefile)
1169                         if err != nil && !os.IsNotExist(err) {
1170                                 base.Fatalf("reading shlibname: %v", err)
1171                         }
1172                         if err == nil {
1173                                 libname := strings.TrimSpace(string(shlib))
1174                                 if cfg.BuildContext.Compiler == "gccgo" {
1175                                         p.Shlib = filepath.Join(p.Internal.Build.PkgTargetRoot, "shlibs", libname)
1176                                 } else {
1177                                         p.Shlib = filepath.Join(p.Internal.Build.PkgTargetRoot, libname)
1178                                 }
1179                         }
1180                 }
1181         }
1182
1183         // Build augmented import list to add implicit dependencies.
1184         // Be careful not to add imports twice, just to avoid confusion.
1185         importPaths := p.Imports
1186         addImport := func(path string) {
1187                 for _, p := range importPaths {
1188                         if path == p {
1189                                 return
1190                         }
1191                 }
1192                 importPaths = append(importPaths, path)
1193         }
1194
1195         // Cgo translation adds imports of "runtime/cgo" and "syscall",
1196         // except for certain packages, to avoid circular dependencies.
1197         if p.UsesCgo() && (!p.Standard || !cgoExclude[p.ImportPath]) && cfg.BuildContext.Compiler != "gccgo" {
1198                 addImport("runtime/cgo")
1199         }
1200         if p.UsesCgo() && (!p.Standard || !cgoSyscallExclude[p.ImportPath]) {
1201                 addImport("syscall")
1202         }
1203
1204         // SWIG adds imports of some standard packages.
1205         if p.UsesSwig() {
1206                 if cfg.BuildContext.Compiler != "gccgo" {
1207                         addImport("runtime/cgo")
1208                 }
1209                 addImport("syscall")
1210                 addImport("sync")
1211
1212                 // TODO: The .swig and .swigcxx files can use
1213                 // %go_import directives to import other packages.
1214         }
1215
1216         // The linker loads implicit dependencies.
1217         if p.Name == "main" && !p.Internal.ForceLibrary {
1218                 for _, dep := range LinkerDeps(p) {
1219                         addImport(dep)
1220                 }
1221         }
1222
1223         // Check for case-insensitive collision of input files.
1224         // To avoid problems on case-insensitive files, we reject any package
1225         // where two different input files have equal names under a case-insensitive
1226         // comparison.
1227         inputs := p.AllFiles()
1228         f1, f2 := str.FoldDup(inputs)
1229         if f1 != "" {
1230                 p.Error = &PackageError{
1231                         ImportStack: stk.Copy(),
1232                         Err:         fmt.Sprintf("case-insensitive file name collision: %q and %q", f1, f2),
1233                 }
1234                 return
1235         }
1236
1237         // If first letter of input file is ASCII, it must be alphanumeric.
1238         // This avoids files turning into flags when invoking commands,
1239         // and other problems we haven't thought of yet.
1240         // Also, _cgo_ files must be generated by us, not supplied.
1241         // They are allowed to have //go:cgo_ldflag directives.
1242         // The directory scan ignores files beginning with _,
1243         // so we shouldn't see any _cgo_ files anyway, but just be safe.
1244         for _, file := range inputs {
1245                 if !SafeArg(file) || strings.HasPrefix(file, "_cgo_") {
1246                         p.Error = &PackageError{
1247                                 ImportStack: stk.Copy(),
1248                                 Err:         fmt.Sprintf("invalid input file name %q", file),
1249                         }
1250                         return
1251                 }
1252         }
1253         if name := pathpkg.Base(p.ImportPath); !SafeArg(name) {
1254                 p.Error = &PackageError{
1255                         ImportStack: stk.Copy(),
1256                         Err:         fmt.Sprintf("invalid input directory name %q", name),
1257                 }
1258                 return
1259         }
1260         if !SafeArg(p.ImportPath) {
1261                 p.Error = &PackageError{
1262                         ImportStack: stk.Copy(),
1263                         Err:         fmt.Sprintf("invalid import path %q", p.ImportPath),
1264                 }
1265                 return
1266         }
1267
1268         // Build list of imported packages and full dependency list.
1269         imports := make([]*Package, 0, len(p.Imports))
1270         for i, path := range importPaths {
1271                 if path == "C" {
1272                         continue
1273                 }
1274                 p1 := LoadImport(path, p.Dir, p, stk, p.Internal.Build.ImportPos[path], ResolveImport)
1275                 if p.Standard && p.Error == nil && !p1.Standard && p1.Error == nil {
1276                         p.Error = &PackageError{
1277                                 ImportStack: stk.Copy(),
1278                                 Err:         fmt.Sprintf("non-standard import %q in standard package %q", path, p.ImportPath),
1279                         }
1280                         pos := p.Internal.Build.ImportPos[path]
1281                         if len(pos) > 0 {
1282                                 p.Error.Pos = pos[0].String()
1283                         }
1284                 }
1285
1286                 path = p1.ImportPath
1287                 importPaths[i] = path
1288                 if i < len(p.Imports) {
1289                         p.Imports[i] = path
1290                 }
1291
1292                 imports = append(imports, p1)
1293                 if p1.Incomplete {
1294                         p.Incomplete = true
1295                 }
1296         }
1297         p.Internal.Imports = imports
1298
1299         deps := make(map[string]*Package)
1300         var q []*Package
1301         q = append(q, imports...)
1302         for i := 0; i < len(q); i++ {
1303                 p1 := q[i]
1304                 path := p1.ImportPath
1305                 // The same import path could produce an error or not,
1306                 // depending on what tries to import it.
1307                 // Prefer to record entries with errors, so we can report them.
1308                 p0 := deps[path]
1309                 if p0 == nil || p1.Error != nil && (p0.Error == nil || len(p0.Error.ImportStack) > len(p1.Error.ImportStack)) {
1310                         deps[path] = p1
1311                         for _, p2 := range p1.Internal.Imports {
1312                                 if deps[p2.ImportPath] != p2 {
1313                                         q = append(q, p2)
1314                                 }
1315                         }
1316                 }
1317         }
1318
1319         p.Deps = make([]string, 0, len(deps))
1320         for dep := range deps {
1321                 p.Deps = append(p.Deps, dep)
1322         }
1323         sort.Strings(p.Deps)
1324         for _, dep := range p.Deps {
1325                 p1 := deps[dep]
1326                 if p1 == nil {
1327                         panic("impossible: missing entry in package cache for " + dep + " imported by " + p.ImportPath)
1328                 }
1329                 if p1.Error != nil {
1330                         p.DepsErrors = append(p.DepsErrors, p1.Error)
1331                 }
1332         }
1333
1334         // unsafe is a fake package.
1335         if p.Standard && (p.ImportPath == "unsafe" || cfg.BuildContext.Compiler == "gccgo") {
1336                 p.Target = ""
1337         }
1338
1339         // If cgo is not enabled, ignore cgo supporting sources
1340         // just as we ignore go files containing import "C".
1341         if !cfg.BuildContext.CgoEnabled {
1342                 p.CFiles = nil
1343                 p.CXXFiles = nil
1344                 p.MFiles = nil
1345                 p.SwigFiles = nil
1346                 p.SwigCXXFiles = nil
1347                 // Note that SFiles are okay (they go to the Go assembler)
1348                 // and HFiles are okay (they might be used by the SFiles).
1349                 // Also Sysofiles are okay (they might not contain object
1350                 // code; see issue #16050).
1351         }
1352
1353         setError := func(msg string) {
1354                 p.Error = &PackageError{
1355                         ImportStack: stk.Copy(),
1356                         Err:         msg,
1357                 }
1358         }
1359
1360         // The gc toolchain only permits C source files with cgo or SWIG.
1361         if len(p.CFiles) > 0 && !p.UsesCgo() && !p.UsesSwig() && cfg.BuildContext.Compiler == "gc" {
1362                 setError(fmt.Sprintf("C source files not allowed when not using cgo or SWIG: %s", strings.Join(p.CFiles, " ")))
1363                 return
1364         }
1365
1366         // C++, Objective-C, and Fortran source files are permitted only with cgo or SWIG,
1367         // regardless of toolchain.
1368         if len(p.CXXFiles) > 0 && !p.UsesCgo() && !p.UsesSwig() {
1369                 setError(fmt.Sprintf("C++ source files not allowed when not using cgo or SWIG: %s", strings.Join(p.CXXFiles, " ")))
1370                 return
1371         }
1372         if len(p.MFiles) > 0 && !p.UsesCgo() && !p.UsesSwig() {
1373                 setError(fmt.Sprintf("Objective-C source files not allowed when not using cgo or SWIG: %s", strings.Join(p.MFiles, " ")))
1374                 return
1375         }
1376         if len(p.FFiles) > 0 && !p.UsesCgo() && !p.UsesSwig() {
1377                 setError(fmt.Sprintf("Fortran source files not allowed when not using cgo or SWIG: %s", strings.Join(p.FFiles, " ")))
1378                 return
1379         }
1380
1381         // Check for case-insensitive collisions of import paths.
1382         fold := str.ToFold(p.ImportPath)
1383         if other := foldPath[fold]; other == "" {
1384                 foldPath[fold] = p.ImportPath
1385         } else if other != p.ImportPath {
1386                 setError(fmt.Sprintf("case-insensitive import collision: %q and %q", p.ImportPath, other))
1387                 return
1388         }
1389 }
1390
1391 // SafeArg reports whether arg is a "safe" command-line argument,
1392 // meaning that when it appears in a command-line, it probably
1393 // doesn't have some special meaning other than its own name.
1394 // Obviously args beginning with - are not safe (they look like flags).
1395 // Less obviously, args beginning with @ are not safe (they look like
1396 // GNU binutils flagfile specifiers, sometimes called "response files").
1397 // To be conservative, we reject almost any arg beginning with non-alphanumeric ASCII.
1398 // We accept leading . _ and / as likely in file system paths.
1399 // There is a copy of this function in cmd/compile/internal/gc/noder.go.
1400 func SafeArg(name string) bool {
1401         if name == "" {
1402                 return false
1403         }
1404         c := name[0]
1405         return '0' <= c && c <= '9' || 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z' || c == '.' || c == '_' || c == '/' || c >= utf8.RuneSelf
1406 }
1407
1408 // LinkerDeps returns the list of linker-induced dependencies for main package p.
1409 func LinkerDeps(p *Package) []string {
1410         // Everything links runtime.
1411         deps := []string{"runtime"}
1412
1413         // External linking mode forces an import of runtime/cgo.
1414         if externalLinkingForced(p) && cfg.BuildContext.Compiler != "gccgo" {
1415                 deps = append(deps, "runtime/cgo")
1416         }
1417         // On ARM with GOARM=5, it forces an import of math, for soft floating point.
1418         if cfg.Goarch == "arm" {
1419                 deps = append(deps, "math")
1420         }
1421         // Using the race detector forces an import of runtime/race.
1422         if cfg.BuildRace {
1423                 deps = append(deps, "runtime/race")
1424         }
1425         // Using memory sanitizer forces an import of runtime/msan.
1426         if cfg.BuildMSan {
1427                 deps = append(deps, "runtime/msan")
1428         }
1429
1430         return deps
1431 }
1432
1433 // externalLinkingForced reports whether external linking is being
1434 // forced even for programs that do not use cgo.
1435 func externalLinkingForced(p *Package) bool {
1436         // Some targets must use external linking even inside GOROOT.
1437         switch cfg.BuildContext.GOOS {
1438         case "android":
1439                 return true
1440         case "darwin":
1441                 switch cfg.BuildContext.GOARCH {
1442                 case "arm", "arm64":
1443                         return true
1444                 }
1445         }
1446
1447         if !cfg.BuildContext.CgoEnabled {
1448                 return false
1449         }
1450         // Currently build modes c-shared, pie (on systems that do not
1451         // support PIE with internal linking mode (currently all
1452         // systems: issue #18968)), plugin, and -linkshared force
1453         // external linking mode, as of course does
1454         // -ldflags=-linkmode=external. External linking mode forces
1455         // an import of runtime/cgo.
1456         pieCgo := cfg.BuildBuildmode == "pie"
1457         linkmodeExternal := false
1458         if p != nil {
1459                 ldflags := BuildLdflags.For(p)
1460                 for i, a := range ldflags {
1461                         if a == "-linkmode=external" {
1462                                 linkmodeExternal = true
1463                         }
1464                         if a == "-linkmode" && i+1 < len(ldflags) && ldflags[i+1] == "external" {
1465                                 linkmodeExternal = true
1466                         }
1467                 }
1468         }
1469
1470         return cfg.BuildBuildmode == "c-shared" || cfg.BuildBuildmode == "plugin" || pieCgo || cfg.BuildLinkshared || linkmodeExternal
1471 }
1472
1473 // mkAbs rewrites list, which must be paths relative to p.Dir,
1474 // into a sorted list of absolute paths. It edits list in place but for
1475 // convenience also returns list back to its caller.
1476 func (p *Package) mkAbs(list []string) []string {
1477         for i, f := range list {
1478                 list[i] = filepath.Join(p.Dir, f)
1479         }
1480         sort.Strings(list)
1481         return list
1482 }
1483
1484 // InternalGoFiles returns the list of Go files being built for the package,
1485 // using absolute paths.
1486 func (p *Package) InternalGoFiles() []string {
1487         return p.mkAbs(str.StringList(p.GoFiles, p.CgoFiles, p.TestGoFiles))
1488 }
1489
1490 // InternalXGoFiles returns the list of Go files being built for the XTest package,
1491 // using absolute paths.
1492 func (p *Package) InternalXGoFiles() []string {
1493         return p.mkAbs(p.XTestGoFiles)
1494 }
1495
1496 // InternalGoFiles returns the list of all Go files possibly relevant for the package,
1497 // using absolute paths. "Possibly relevant" means that files are not excluded
1498 // due to build tags, but files with names beginning with . or _ are still excluded.
1499 func (p *Package) InternalAllGoFiles() []string {
1500         var extra []string
1501         for _, f := range p.IgnoredGoFiles {
1502                 if f != "" && f[0] != '.' || f[0] != '_' {
1503                         extra = append(extra, f)
1504                 }
1505         }
1506         return p.mkAbs(str.StringList(extra, p.GoFiles, p.CgoFiles, p.TestGoFiles, p.XTestGoFiles))
1507 }
1508
1509 // usesSwig reports whether the package needs to run SWIG.
1510 func (p *Package) UsesSwig() bool {
1511         return len(p.SwigFiles) > 0 || len(p.SwigCXXFiles) > 0
1512 }
1513
1514 // usesCgo reports whether the package needs to run cgo
1515 func (p *Package) UsesCgo() bool {
1516         return len(p.CgoFiles) > 0
1517 }
1518
1519 // packageList returns the list of packages in the dag rooted at roots
1520 // as visited in a depth-first post-order traversal.
1521 func PackageList(roots []*Package) []*Package {
1522         seen := map[*Package]bool{}
1523         all := []*Package{}
1524         var walk func(*Package)
1525         walk = func(p *Package) {
1526                 if seen[p] {
1527                         return
1528                 }
1529                 seen[p] = true
1530                 for _, p1 := range p.Internal.Imports {
1531                         walk(p1)
1532                 }
1533                 all = append(all, p)
1534         }
1535         for _, root := range roots {
1536                 walk(root)
1537         }
1538         return all
1539 }
1540
1541 var cmdCache = map[string]*Package{}
1542
1543 func ClearCmdCache() {
1544         for name := range cmdCache {
1545                 delete(cmdCache, name)
1546         }
1547 }
1548
1549 // loadPackage is like loadImport but is used for command-line arguments,
1550 // not for paths found in import statements. In addition to ordinary import paths,
1551 // loadPackage accepts pseudo-paths beginning with cmd/ to denote commands
1552 // in the Go command directory, as well as paths to those directories.
1553 func LoadPackage(arg string, stk *ImportStack) *Package {
1554         if build.IsLocalImport(arg) {
1555                 dir := arg
1556                 if !filepath.IsAbs(dir) {
1557                         if abs, err := filepath.Abs(dir); err == nil {
1558                                 // interpret relative to current directory
1559                                 dir = abs
1560                         }
1561                 }
1562                 if sub, ok := hasSubdir(cfg.GOROOTsrc, dir); ok && strings.HasPrefix(sub, "cmd/") && !strings.Contains(sub[4:], "/") {
1563                         arg = sub
1564                 }
1565         }
1566         if strings.HasPrefix(arg, "cmd/") && !strings.Contains(arg[4:], "/") {
1567                 if p := cmdCache[arg]; p != nil {
1568                         return p
1569                 }
1570                 stk.Push(arg)
1571                 defer stk.Pop()
1572
1573                 bp, err := cfg.BuildContext.ImportDir(filepath.Join(cfg.GOROOTsrc, arg), 0)
1574                 bp.ImportPath = arg
1575                 bp.Goroot = true
1576                 bp.BinDir = cfg.GOROOTbin
1577                 if cfg.GOROOTbin != "" {
1578                         bp.BinDir = cfg.GOROOTbin
1579                 }
1580                 bp.Root = cfg.GOROOT
1581                 bp.SrcRoot = cfg.GOROOTsrc
1582                 p := new(Package)
1583                 cmdCache[arg] = p
1584                 p.load(stk, bp, err)
1585                 if p.Error == nil && p.Name != "main" {
1586                         p.Error = &PackageError{
1587                                 ImportStack: stk.Copy(),
1588                                 Err:         fmt.Sprintf("expected package main but found package %s in %s", p.Name, p.Dir),
1589                         }
1590                 }
1591                 return p
1592         }
1593
1594         // Wasn't a command; must be a package.
1595         // If it is a local import path but names a standard package,
1596         // we treat it as if the user specified the standard package.
1597         // This lets you run go test ./ioutil in package io and be
1598         // referring to io/ioutil rather than a hypothetical import of
1599         // "./ioutil".
1600         if build.IsLocalImport(arg) {
1601                 bp, _ := cfg.BuildContext.ImportDir(filepath.Join(base.Cwd, arg), build.FindOnly)
1602                 if bp.ImportPath != "" && bp.ImportPath != "." {
1603                         arg = bp.ImportPath
1604                 }
1605         }
1606
1607         return LoadImport(arg, base.Cwd, nil, stk, nil, 0)
1608 }
1609
1610 // packages returns the packages named by the
1611 // command line arguments 'args'. If a named package
1612 // cannot be loaded at all (for example, if the directory does not exist),
1613 // then packages prints an error and does not include that
1614 // package in the results. However, if errors occur trying
1615 // to load dependencies of a named package, the named
1616 // package is still returned, with p.Incomplete = true
1617 // and details in p.DepsErrors.
1618 func Packages(args []string) []*Package {
1619         var pkgs []*Package
1620         for _, pkg := range PackagesAndErrors(args) {
1621                 if pkg.Error != nil {
1622                         base.Errorf("can't load package: %s", pkg.Error)
1623                         continue
1624                 }
1625                 pkgs = append(pkgs, pkg)
1626         }
1627         return pkgs
1628 }
1629
1630 // packagesAndErrors is like 'packages' but returns a
1631 // *Package for every argument, even the ones that
1632 // cannot be loaded at all.
1633 // The packages that fail to load will have p.Error != nil.
1634 func PackagesAndErrors(args []string) []*Package {
1635         if len(args) > 0 && strings.HasSuffix(args[0], ".go") {
1636                 return []*Package{GoFilesPackage(args)}
1637         }
1638
1639         args = ImportPaths(args)
1640         var (
1641                 pkgs    []*Package
1642                 stk     ImportStack
1643                 seenArg = make(map[string]bool)
1644                 seenPkg = make(map[*Package]bool)
1645         )
1646
1647         for _, arg := range args {
1648                 if seenArg[arg] {
1649                         continue
1650                 }
1651                 seenArg[arg] = true
1652                 pkg := LoadPackage(arg, &stk)
1653                 if seenPkg[pkg] {
1654                         continue
1655                 }
1656                 seenPkg[pkg] = true
1657                 pkgs = append(pkgs, pkg)
1658         }
1659
1660         return pkgs
1661 }
1662
1663 // packagesForBuild is like 'packages' but fails if any of
1664 // the packages or their dependencies have errors
1665 // (cannot be built).
1666 func PackagesForBuild(args []string) []*Package {
1667         pkgs := PackagesAndErrors(args)
1668         printed := map[*PackageError]bool{}
1669         for _, pkg := range pkgs {
1670                 if pkg.Error != nil {
1671                         base.Errorf("can't load package: %s", pkg.Error)
1672                         printed[pkg.Error] = true
1673                 }
1674                 for _, err := range pkg.DepsErrors {
1675                         // Since these are errors in dependencies,
1676                         // the same error might show up multiple times,
1677                         // once in each package that depends on it.
1678                         // Only print each once.
1679                         if !printed[err] {
1680                                 printed[err] = true
1681                                 base.Errorf("%s", err)
1682                         }
1683                 }
1684         }
1685         base.ExitIfErrors()
1686
1687         // Check for duplicate loads of the same package.
1688         // That should be impossible, but if it does happen then
1689         // we end up trying to build the same package twice,
1690         // usually in parallel overwriting the same files,
1691         // which doesn't work very well.
1692         seen := map[string]bool{}
1693         reported := map[string]bool{}
1694         for _, pkg := range PackageList(pkgs) {
1695                 if seen[pkg.ImportPath] && !reported[pkg.ImportPath] {
1696                         reported[pkg.ImportPath] = true
1697                         base.Errorf("internal error: duplicate loads of %s", pkg.ImportPath)
1698                 }
1699                 seen[pkg.ImportPath] = true
1700         }
1701         base.ExitIfErrors()
1702
1703         return pkgs
1704 }
1705
1706 // GoFilesPackage creates a package for building a collection of Go files
1707 // (typically named on the command line). The target is named p.a for
1708 // package p or named after the first Go file for package main.
1709 func GoFilesPackage(gofiles []string) *Package {
1710         // TODO: Remove this restriction.
1711         for _, f := range gofiles {
1712                 if !strings.HasSuffix(f, ".go") {
1713                         base.Fatalf("named files must be .go files")
1714                 }
1715         }
1716
1717         var stk ImportStack
1718         ctxt := cfg.BuildContext
1719         ctxt.UseAllFiles = true
1720
1721         // Synthesize fake "directory" that only shows the named files,
1722         // to make it look like this is a standard package or
1723         // command directory. So that local imports resolve
1724         // consistently, the files must all be in the same directory.
1725         var dirent []os.FileInfo
1726         var dir string
1727         for _, file := range gofiles {
1728                 fi, err := os.Stat(file)
1729                 if err != nil {
1730                         base.Fatalf("%s", err)
1731                 }
1732                 if fi.IsDir() {
1733                         base.Fatalf("%s is a directory, should be a Go file", file)
1734                 }
1735                 dir1, _ := filepath.Split(file)
1736                 if dir1 == "" {
1737                         dir1 = "./"
1738                 }
1739                 if dir == "" {
1740                         dir = dir1
1741                 } else if dir != dir1 {
1742                         base.Fatalf("named files must all be in one directory; have %s and %s", dir, dir1)
1743                 }
1744                 dirent = append(dirent, fi)
1745         }
1746         ctxt.ReadDir = func(string) ([]os.FileInfo, error) { return dirent, nil }
1747
1748         var err error
1749         if dir == "" {
1750                 dir = base.Cwd
1751         }
1752         dir, err = filepath.Abs(dir)
1753         if err != nil {
1754                 base.Fatalf("%s", err)
1755         }
1756
1757         bp, err := ctxt.ImportDir(dir, 0)
1758         pkg := new(Package)
1759         pkg.Internal.Local = true
1760         pkg.Internal.CmdlineFiles = true
1761         stk.Push("main")
1762         pkg.load(&stk, bp, err)
1763         stk.Pop()
1764         pkg.Internal.LocalPrefix = dirToImportPath(dir)
1765         pkg.ImportPath = "command-line-arguments"
1766         pkg.Target = ""
1767
1768         if pkg.Name == "main" {
1769                 _, elem := filepath.Split(gofiles[0])
1770                 exe := elem[:len(elem)-len(".go")] + cfg.ExeSuffix
1771                 if cfg.BuildO == "" {
1772                         cfg.BuildO = exe
1773                 }
1774                 if cfg.GOBIN != "" {
1775                         pkg.Target = filepath.Join(cfg.GOBIN, exe)
1776                 }
1777         }
1778
1779         return pkg
1780 }