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