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