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