1
2
3
4
5 package build
6
7 import (
8 "bytes"
9 "errors"
10 "fmt"
11 "go/ast"
12 "go/build/constraint"
13 "go/doc"
14 "go/token"
15 "internal/buildcfg"
16 "internal/godebug"
17 "internal/goroot"
18 "internal/goversion"
19 "internal/platform"
20 "internal/syslist"
21 "io"
22 "io/fs"
23 "os"
24 "os/exec"
25 pathpkg "path"
26 "path/filepath"
27 "runtime"
28 "slices"
29 "strconv"
30 "strings"
31 "unicode"
32 "unicode/utf8"
33 _ "unsafe"
34 )
35
36
37 type CgoMode uint8
38
39 const (
40 CgoDisabled CgoMode = iota
41 CgoBindings
42 CgoEnabled
43 )
44
45
46 type Context struct {
47 GOARCH string
48 GOOS string
49 GOROOT string
50 GOPATH string
51
52
53
54
55
56
57
58 Dir string
59
60 CgoEnabled CgoMode
61 UseAllFiles bool
62 Compiler string
63
64
65
66
67
68
69
70
71
72
73
74 BuildTags []string
75 ToolTags []string
76 ReleaseTags []string
77
78
79
80
81
82
83
84 InstallSuffix string
85
86
87
88
89
90
91
92
93
94 JoinPath func(elem ...string) string
95
96
97
98 SplitPathList func(list string) []string
99
100
101
102 IsAbsPath func(path string) bool
103
104
105
106 IsDir func(path string) bool
107
108
109
110
111
112
113
114
115 HasSubdir func(root, dir string) (rel string, ok bool)
116
117
118
119
120 ReadDir func(dir string) ([]fs.FileInfo, error)
121
122
123
124 OpenFile func(path string) (io.ReadCloser, error)
125 }
126
127
128 func (ctxt *Context) joinPath(elem ...string) string {
129 if f := ctxt.JoinPath; f != nil {
130 return f(elem...)
131 }
132 return filepath.Join(elem...)
133 }
134
135
136 func (ctxt *Context) splitPathList(s string) []string {
137 if f := ctxt.SplitPathList; f != nil {
138 return f(s)
139 }
140 return filepath.SplitList(s)
141 }
142
143
144 func (ctxt *Context) isAbsPath(path string) bool {
145 if f := ctxt.IsAbsPath; f != nil {
146 return f(path)
147 }
148 return filepath.IsAbs(path)
149 }
150
151
152 func (ctxt *Context) isDir(path string) bool {
153 if f := ctxt.IsDir; f != nil {
154 return f(path)
155 }
156 fi, err := os.Stat(path)
157 return err == nil && fi.IsDir()
158 }
159
160
161
162 func (ctxt *Context) hasSubdir(root, dir string) (rel string, ok bool) {
163 if f := ctxt.HasSubdir; f != nil {
164 return f(root, dir)
165 }
166
167
168 if rel, ok = hasSubdir(root, dir); ok {
169 return
170 }
171
172
173
174
175 rootSym, _ := filepath.EvalSymlinks(root)
176 dirSym, _ := filepath.EvalSymlinks(dir)
177
178 if rel, ok = hasSubdir(rootSym, dir); ok {
179 return
180 }
181 if rel, ok = hasSubdir(root, dirSym); ok {
182 return
183 }
184 return hasSubdir(rootSym, dirSym)
185 }
186
187
188 func hasSubdir(root, dir string) (rel string, ok bool) {
189 const sep = string(filepath.Separator)
190 root = filepath.Clean(root)
191 if !strings.HasSuffix(root, sep) {
192 root += sep
193 }
194 dir = filepath.Clean(dir)
195 after, found := strings.CutPrefix(dir, root)
196 if !found {
197 return "", false
198 }
199 return filepath.ToSlash(after), true
200 }
201
202
203 func (ctxt *Context) readDir(path string) ([]fs.DirEntry, error) {
204
205 if f := ctxt.ReadDir; f != nil {
206 fis, err := f(path)
207 if err != nil {
208 return nil, err
209 }
210 des := make([]fs.DirEntry, len(fis))
211 for i, fi := range fis {
212 des[i] = fs.FileInfoToDirEntry(fi)
213 }
214 return des, nil
215 }
216 return os.ReadDir(path)
217 }
218
219
220 func (ctxt *Context) openFile(path string) (io.ReadCloser, error) {
221 if fn := ctxt.OpenFile; fn != nil {
222 return fn(path)
223 }
224
225 f, err := os.Open(path)
226 if err != nil {
227 return nil, err
228 }
229 return f, nil
230 }
231
232
233
234
235 func (ctxt *Context) isFile(path string) bool {
236 f, err := ctxt.openFile(path)
237 if err != nil {
238 return false
239 }
240 f.Close()
241 return true
242 }
243
244
245 func (ctxt *Context) gopath() []string {
246 var all []string
247 for _, p := range ctxt.splitPathList(ctxt.GOPATH) {
248 if p == "" || p == ctxt.GOROOT {
249
250
251
252
253 continue
254 }
255 if strings.HasPrefix(p, "~") {
256
257
258
259
260
261
262
263
264
265
266
267
268 continue
269 }
270 all = append(all, p)
271 }
272 return all
273 }
274
275
276
277
278 func (ctxt *Context) SrcDirs() []string {
279 var all []string
280 if ctxt.GOROOT != "" && ctxt.Compiler != "gccgo" {
281 dir := ctxt.joinPath(ctxt.GOROOT, "src")
282 if ctxt.isDir(dir) {
283 all = append(all, dir)
284 }
285 }
286 for _, p := range ctxt.gopath() {
287 dir := ctxt.joinPath(p, "src")
288 if ctxt.isDir(dir) {
289 all = append(all, dir)
290 }
291 }
292 return all
293 }
294
295
296
297
298 var Default Context = defaultContext()
299
300
301 func defaultGOPATH() string {
302 env := "HOME"
303 if runtime.GOOS == "windows" {
304 env = "USERPROFILE"
305 } else if runtime.GOOS == "plan9" {
306 env = "home"
307 }
308 if home := os.Getenv(env); home != "" {
309 def := filepath.Join(home, "go")
310 if filepath.Clean(def) == filepath.Clean(runtime.GOROOT()) {
311
312
313 return ""
314 }
315 return def
316 }
317 return ""
318 }
319
320
321
322
323
324
325
326
327
328
329 var defaultToolTags []string
330
331
332
333
334
335
336
337
338
339
340 var defaultReleaseTags []string
341
342 func defaultContext() Context {
343 var c Context
344
345 c.GOARCH = buildcfg.GOARCH
346 c.GOOS = buildcfg.GOOS
347 if goroot := runtime.GOROOT(); goroot != "" {
348 c.GOROOT = filepath.Clean(goroot)
349 }
350 c.GOPATH = envOr("GOPATH", defaultGOPATH())
351 c.Compiler = runtime.Compiler
352 c.ToolTags = append(c.ToolTags, buildcfg.ToolTags...)
353
354 defaultToolTags = append([]string{}, c.ToolTags...)
355
356
357
358
359
360
361
362
363 for i := 1; i <= goversion.Version; i++ {
364 c.ReleaseTags = append(c.ReleaseTags, "go1."+strconv.Itoa(i))
365 }
366
367 defaultReleaseTags = append([]string{}, c.ReleaseTags...)
368
369 env := os.Getenv("CGO_ENABLED")
370 if env == "" {
371 env = buildcfg.DefaultCGO_ENABLED
372 }
373 switch env {
374 case "1":
375 c.CgoEnabled = CgoEnabled
376 case "0":
377 c.CgoEnabled = CgoDisabled
378 case "bindings":
379 c.CgoEnabled = CgoBindings
380 default:
381
382 if runtime.GOARCH == c.GOARCH && runtime.GOOS == c.GOOS {
383 if platform.CgoSupported(c.GOOS, c.GOARCH) {
384 c.CgoEnabled = CgoEnabled
385 }
386 break
387 }
388 c.CgoEnabled = CgoDisabled
389 }
390
391 return c
392 }
393
394 func envOr(name, def string) string {
395 s := os.Getenv(name)
396 if s == "" {
397 return def
398 }
399 return s
400 }
401
402
403 type ImportMode uint
404
405 const (
406
407
408
409 FindOnly ImportMode = 1 << iota
410
411
412
413
414
415
416
417
418
419
420 AllowBinary
421
422
423
424
425
426 ImportComment
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446 IgnoreVendor
447 )
448
449
450 type Package struct {
451 Dir string
452 Name string
453 ImportComment string
454 Doc string
455 ImportPath string
456 Root string
457 SrcRoot string
458 PkgRoot string
459 PkgTargetRoot string
460 BinDir string
461 Goroot bool
462 PkgObj string
463 AllTags []string
464 ConflictDir string
465 BinaryOnly bool
466
467
468 GoFiles []string
469 CgoFiles []string
470 IgnoredGoFiles []string
471 InvalidGoFiles []string
472 IgnoredOtherFiles []string
473 CFiles []string
474 CXXFiles []string
475 MFiles []string
476 HFiles []string
477 FFiles []string
478 SFiles []string
479 SwigFiles []string
480 SwigCXXFiles []string
481 SysoFiles []string
482
483
484 CgoCFLAGS []string
485 CgoCPPFLAGS []string
486 CgoCXXFLAGS []string
487 CgoFFLAGS []string
488 CgoLDFLAGS []string
489 CgoPkgConfig []string
490 CgoBindings bool
491
492
493 TestGoFiles []string
494 XTestGoFiles []string
495
496
497 Directives []Directive
498 TestDirectives []Directive
499 XTestDirectives []Directive
500
501
502 Imports []string
503 ImportPos map[string][]token.Position
504 TestImports []string
505 TestImportPos map[string][]token.Position
506 XTestImports []string
507 XTestImportPos map[string][]token.Position
508
509
510
511
512
513
514 EmbedPatterns []string
515 EmbedPatternPos map[string][]token.Position
516 TestEmbedPatterns []string
517 TestEmbedPatternPos map[string][]token.Position
518 XTestEmbedPatterns []string
519 XTestEmbedPatternPos map[string][]token.Position
520 }
521
522
523 type Directive struct {
524 Text string
525 Pos token.Position
526 }
527
528
529
530
531 func (p *Package) IsCommand() bool {
532 return p.Name == "main"
533 }
534
535
536
537 func (ctxt *Context) ImportDir(dir string, mode ImportMode) (*Package, error) {
538 return ctxt.Import(".", dir, mode)
539 }
540
541
542
543
544 type NoGoError struct {
545 Dir string
546 }
547
548 func (e *NoGoError) Error() string {
549 return "no buildable Go source files in " + e.Dir
550 }
551
552
553
554 type MultiplePackageError struct {
555 Dir string
556 Packages []string
557 Files []string
558 }
559
560 func (e *MultiplePackageError) Error() string {
561
562 return fmt.Sprintf("found packages %s (%s) and %s (%s) in %s", e.Packages[0], e.Files[0], e.Packages[1], e.Files[1], e.Dir)
563 }
564
565 func nameExt(name string) string {
566 i := strings.LastIndex(name, ".")
567 if i < 0 {
568 return ""
569 }
570 return name[i:]
571 }
572
573 var installgoroot = godebug.New("installgoroot")
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590 func (ctxt *Context) Import(path string, srcDir string, mode ImportMode) (*Package, error) {
591 p := &Package{
592 ImportPath: path,
593 }
594 if path == "" {
595 return p, fmt.Errorf("import %q: invalid import path", path)
596 }
597
598 var pkgtargetroot string
599 var pkga string
600 var pkgerr error
601 suffix := ""
602 if ctxt.InstallSuffix != "" {
603 suffix = "_" + ctxt.InstallSuffix
604 }
605 switch ctxt.Compiler {
606 case "gccgo":
607 pkgtargetroot = "pkg/gccgo_" + ctxt.GOOS + "_" + ctxt.GOARCH + suffix
608 case "gc":
609 pkgtargetroot = "pkg/" + ctxt.GOOS + "_" + ctxt.GOARCH + suffix
610 default:
611
612 pkgerr = fmt.Errorf("import %q: unknown compiler %q", path, ctxt.Compiler)
613 }
614 setPkga := func() {
615 switch ctxt.Compiler {
616 case "gccgo":
617 dir, elem := pathpkg.Split(p.ImportPath)
618 pkga = pkgtargetroot + "/" + dir + "lib" + elem + ".a"
619 case "gc":
620 pkga = pkgtargetroot + "/" + p.ImportPath + ".a"
621 }
622 }
623 setPkga()
624
625 binaryOnly := false
626 if IsLocalImport(path) {
627 pkga = ""
628 if srcDir == "" {
629 return p, fmt.Errorf("import %q: import relative to unknown directory", path)
630 }
631 if !ctxt.isAbsPath(path) {
632 p.Dir = ctxt.joinPath(srcDir, path)
633 }
634
635
636
637 inTestdata := func(sub string) bool {
638 return strings.Contains(sub, "/testdata/") || strings.HasSuffix(sub, "/testdata") || strings.HasPrefix(sub, "testdata/") || sub == "testdata"
639 }
640 if ctxt.GOROOT != "" {
641 root := ctxt.joinPath(ctxt.GOROOT, "src")
642 if sub, ok := ctxt.hasSubdir(root, p.Dir); ok && !inTestdata(sub) {
643 p.Goroot = true
644 p.ImportPath = sub
645 p.Root = ctxt.GOROOT
646 setPkga()
647 goto Found
648 }
649 }
650 all := ctxt.gopath()
651 for i, root := range all {
652 rootsrc := ctxt.joinPath(root, "src")
653 if sub, ok := ctxt.hasSubdir(rootsrc, p.Dir); ok && !inTestdata(sub) {
654
655
656
657 if ctxt.GOROOT != "" && ctxt.Compiler != "gccgo" {
658 if dir := ctxt.joinPath(ctxt.GOROOT, "src", sub); ctxt.isDir(dir) {
659 p.ConflictDir = dir
660 goto Found
661 }
662 }
663 for _, earlyRoot := range all[:i] {
664 if dir := ctxt.joinPath(earlyRoot, "src", sub); ctxt.isDir(dir) {
665 p.ConflictDir = dir
666 goto Found
667 }
668 }
669
670
671
672 p.ImportPath = sub
673 p.Root = root
674 setPkga()
675 goto Found
676 }
677 }
678
679
680 } else {
681 if strings.HasPrefix(path, "/") {
682 return p, fmt.Errorf("import %q: cannot import absolute path", path)
683 }
684
685 if err := ctxt.importGo(p, path, srcDir, mode); err == nil {
686 goto Found
687 } else if err != errNoModules {
688 return p, err
689 }
690
691 gopath := ctxt.gopath()
692
693
694 var tried struct {
695 vendor []string
696 goroot string
697 gopath []string
698 }
699
700
701 if mode&IgnoreVendor == 0 && srcDir != "" {
702 searchVendor := func(root string, isGoroot bool) bool {
703 sub, ok := ctxt.hasSubdir(root, srcDir)
704 if !ok || !strings.HasPrefix(sub, "src/") || strings.Contains(sub, "/testdata/") {
705 return false
706 }
707 for {
708 vendor := ctxt.joinPath(root, sub, "vendor")
709 if ctxt.isDir(vendor) {
710 dir := ctxt.joinPath(vendor, path)
711 if ctxt.isDir(dir) && hasGoFiles(ctxt, dir) {
712 p.Dir = dir
713 p.ImportPath = strings.TrimPrefix(pathpkg.Join(sub, "vendor", path), "src/")
714 p.Goroot = isGoroot
715 p.Root = root
716 setPkga()
717 return true
718 }
719 tried.vendor = append(tried.vendor, dir)
720 }
721 i := strings.LastIndex(sub, "/")
722 if i < 0 {
723 break
724 }
725 sub = sub[:i]
726 }
727 return false
728 }
729 if ctxt.Compiler != "gccgo" && ctxt.GOROOT != "" && searchVendor(ctxt.GOROOT, true) {
730 goto Found
731 }
732 for _, root := range gopath {
733 if searchVendor(root, false) {
734 goto Found
735 }
736 }
737 }
738
739
740 if ctxt.GOROOT != "" {
741
742
743
744
745 gorootFirst := srcDir == "" || !strings.HasPrefix(path, "vendor/")
746 if !gorootFirst {
747 _, gorootFirst = ctxt.hasSubdir(ctxt.GOROOT, srcDir)
748 }
749 if gorootFirst {
750 dir := ctxt.joinPath(ctxt.GOROOT, "src", path)
751 if ctxt.Compiler != "gccgo" {
752 isDir := ctxt.isDir(dir)
753 binaryOnly = !isDir && mode&AllowBinary != 0 && pkga != "" && ctxt.isFile(ctxt.joinPath(ctxt.GOROOT, pkga))
754 if isDir || binaryOnly {
755 p.Dir = dir
756 p.Goroot = true
757 p.Root = ctxt.GOROOT
758 goto Found
759 }
760 }
761 tried.goroot = dir
762 }
763 if ctxt.Compiler == "gccgo" && goroot.IsStandardPackage(os.ReadDir, ctxt.GOROOT, ctxt.Compiler, path) {
764
765
766
767 p.Dir = ctxt.joinPath(ctxt.GOROOT, "src", path)
768 p.Goroot = true
769 p.Root = ctxt.GOROOT
770 goto Found
771 }
772 }
773 for _, root := range gopath {
774 dir := ctxt.joinPath(root, "src", path)
775 isDir := ctxt.isDir(dir)
776 binaryOnly = !isDir && mode&AllowBinary != 0 && pkga != "" && ctxt.isFile(ctxt.joinPath(root, pkga))
777 if isDir || binaryOnly {
778 p.Dir = dir
779 p.Root = root
780 goto Found
781 }
782 tried.gopath = append(tried.gopath, dir)
783 }
784
785
786
787
788 if ctxt.GOROOT != "" && tried.goroot == "" {
789 dir := ctxt.joinPath(ctxt.GOROOT, "src", path)
790 if ctxt.Compiler != "gccgo" {
791 isDir := ctxt.isDir(dir)
792 binaryOnly = !isDir && mode&AllowBinary != 0 && pkga != "" && ctxt.isFile(ctxt.joinPath(ctxt.GOROOT, pkga))
793 if isDir || binaryOnly {
794 p.Dir = dir
795 p.Goroot = true
796 p.Root = ctxt.GOROOT
797 goto Found
798 }
799 }
800 tried.goroot = dir
801 }
802
803
804 var paths []string
805 format := "\t%s (vendor tree)"
806 for _, dir := range tried.vendor {
807 paths = append(paths, fmt.Sprintf(format, dir))
808 format = "\t%s"
809 }
810 if tried.goroot != "" {
811 paths = append(paths, fmt.Sprintf("\t%s (from $GOROOT)", tried.goroot))
812 } else {
813 paths = append(paths, "\t($GOROOT not set)")
814 }
815 format = "\t%s (from $GOPATH)"
816 for _, dir := range tried.gopath {
817 paths = append(paths, fmt.Sprintf(format, dir))
818 format = "\t%s"
819 }
820 if len(tried.gopath) == 0 {
821 paths = append(paths, "\t($GOPATH not set. For more details see: 'go help gopath')")
822 }
823 return p, fmt.Errorf("cannot find package %q in any of:\n%s", path, strings.Join(paths, "\n"))
824 }
825
826 Found:
827 if p.Root != "" {
828 p.SrcRoot = ctxt.joinPath(p.Root, "src")
829 p.PkgRoot = ctxt.joinPath(p.Root, "pkg")
830 p.BinDir = ctxt.joinPath(p.Root, "bin")
831 if pkga != "" {
832
833
834 p.PkgTargetRoot = ctxt.joinPath(p.Root, pkgtargetroot)
835
836
837 if !p.Goroot || (installgoroot.Value() == "all" && p.ImportPath != "unsafe" && p.ImportPath != "builtin") {
838 if p.Goroot {
839 installgoroot.IncNonDefault()
840 }
841 p.PkgObj = ctxt.joinPath(p.Root, pkga)
842 }
843 }
844 }
845
846
847
848
849
850
851 if IsLocalImport(path) && !ctxt.isDir(p.Dir) {
852 if ctxt.Compiler == "gccgo" && p.Goroot {
853
854 return p, nil
855 }
856
857
858 return p, fmt.Errorf("cannot find package %q in:\n\t%s", p.ImportPath, p.Dir)
859 }
860
861 if mode&FindOnly != 0 {
862 return p, pkgerr
863 }
864 if binaryOnly && (mode&AllowBinary) != 0 {
865 return p, pkgerr
866 }
867
868 if ctxt.Compiler == "gccgo" && p.Goroot {
869
870 return p, nil
871 }
872
873 dirs, err := ctxt.readDir(p.Dir)
874 if err != nil {
875 return p, err
876 }
877
878 var badGoError error
879 badGoFiles := make(map[string]bool)
880 badGoFile := func(name string, err error) {
881 if badGoError == nil {
882 badGoError = err
883 }
884 if !badGoFiles[name] {
885 p.InvalidGoFiles = append(p.InvalidGoFiles, name)
886 badGoFiles[name] = true
887 }
888 }
889
890 var Sfiles []string
891 var firstFile, firstCommentFile string
892 embedPos := make(map[string][]token.Position)
893 testEmbedPos := make(map[string][]token.Position)
894 xTestEmbedPos := make(map[string][]token.Position)
895 importPos := make(map[string][]token.Position)
896 testImportPos := make(map[string][]token.Position)
897 xTestImportPos := make(map[string][]token.Position)
898 allTags := make(map[string]bool)
899 fset := token.NewFileSet()
900
901
902
903 type importCFile struct {
904 name string
905 info *fileInfo
906 }
907 var hasImportC []importCFile
908
909 for _, d := range dirs {
910 if d.IsDir() {
911 continue
912 }
913 if d.Type() == fs.ModeSymlink {
914 if ctxt.isDir(ctxt.joinPath(p.Dir, d.Name())) {
915
916 continue
917 }
918 }
919
920 name := d.Name()
921 ext := nameExt(name)
922
923 info, err := ctxt.matchFile(p.Dir, name, allTags, &p.BinaryOnly, fset)
924 if err != nil && strings.HasSuffix(name, ".go") {
925 badGoFile(name, err)
926 continue
927 }
928 if info == nil {
929 if strings.HasPrefix(name, "_") || strings.HasPrefix(name, ".") {
930
931 } else if ext == ".go" {
932 p.IgnoredGoFiles = append(p.IgnoredGoFiles, name)
933 } else if fileListForExt(p, ext) != nil {
934 p.IgnoredOtherFiles = append(p.IgnoredOtherFiles, name)
935 }
936 continue
937 }
938
939
940 switch ext {
941 case ".go":
942
943 case ".S", ".sx":
944
945 Sfiles = append(Sfiles, name)
946 continue
947 default:
948 if list := fileListForExt(p, ext); list != nil {
949 *list = append(*list, name)
950 }
951 continue
952 }
953
954 data, filename := info.header, info.name
955
956 if info.parseErr != nil {
957 badGoFile(name, info.parseErr)
958
959
960 }
961
962 var pkg string
963 if info.parsed != nil {
964 pkg = info.parsed.Name.Name
965 if pkg == "documentation" {
966 p.IgnoredGoFiles = append(p.IgnoredGoFiles, name)
967 continue
968 }
969 }
970
971 isTest := strings.HasSuffix(name, "_test.go")
972 isXTest := false
973 if isTest && strings.HasSuffix(pkg, "_test") && p.Name != pkg {
974 isXTest = true
975 pkg = pkg[:len(pkg)-len("_test")]
976 }
977
978 if p.Name == "" {
979 p.Name = pkg
980 firstFile = name
981 } else if pkg != p.Name {
982
983
984
985 badGoFile(name, &MultiplePackageError{
986 Dir: p.Dir,
987 Packages: []string{p.Name, pkg},
988 Files: []string{firstFile, name},
989 })
990 }
991
992 if info.parsed != nil && info.parsed.Doc != nil && p.Doc == "" && !isTest && !isXTest {
993 p.Doc = doc.Synopsis(info.parsed.Doc.Text())
994 }
995
996 if mode&ImportComment != 0 {
997 qcom, line := findImportComment(data)
998 if line != 0 {
999 com, err := strconv.Unquote(qcom)
1000 if err != nil {
1001 badGoFile(name, fmt.Errorf("%s:%d: cannot parse import comment", filename, line))
1002 } else if p.ImportComment == "" {
1003 p.ImportComment = com
1004 firstCommentFile = name
1005 } else if p.ImportComment != com {
1006 badGoFile(name, fmt.Errorf("found import comments %q (%s) and %q (%s) in %s", p.ImportComment, firstCommentFile, com, name, p.Dir))
1007 }
1008 }
1009 }
1010
1011
1012 isCgo := false
1013 for _, imp := range info.imports {
1014 if imp.path == "C" {
1015 if isTest {
1016 badGoFile(name, fmt.Errorf("use of cgo in test %s not supported", filename))
1017 continue
1018 }
1019 isCgo = true
1020 if imp.doc != nil {
1021 if err := ctxt.saveCgo(filename, p, imp.doc); err != nil {
1022 badGoFile(name, err)
1023 }
1024 }
1025 }
1026 }
1027
1028 var fileList *[]string
1029 var importMap, embedMap map[string][]token.Position
1030 var directives *[]Directive
1031 switch {
1032 case isCgo:
1033 allTags["cgo"] = true
1034 if info.cgoBindings {
1035 allTags["cgobindings"] = true
1036 }
1037 switch ctxt.CgoEnabled {
1038 case CgoEnabled:
1039 fileList = &p.CgoFiles
1040 importMap = importPos
1041 embedMap = embedPos
1042 directives = &p.Directives
1043 if info.cgoBindings {
1044 p.CgoBindings = true
1045 }
1046 case CgoBindings:
1047 if info.cgoBindings {
1048 p.CgoBindings = true
1049 }
1050 hasImportC = append(hasImportC, importCFile{name: name, info: info})
1051 continue
1052 default:
1053
1054 fileList = &p.IgnoredGoFiles
1055 }
1056 case isXTest:
1057 fileList = &p.XTestGoFiles
1058 importMap = xTestImportPos
1059 embedMap = xTestEmbedPos
1060 directives = &p.XTestDirectives
1061 case isTest:
1062 fileList = &p.TestGoFiles
1063 importMap = testImportPos
1064 embedMap = testEmbedPos
1065 directives = &p.TestDirectives
1066 default:
1067 fileList = &p.GoFiles
1068 importMap = importPos
1069 embedMap = embedPos
1070 directives = &p.Directives
1071 }
1072 *fileList = append(*fileList, name)
1073 if importMap != nil {
1074 for _, imp := range info.imports {
1075 importMap[imp.path] = append(importMap[imp.path], fset.Position(imp.pos))
1076 }
1077 }
1078 if embedMap != nil {
1079 for _, emb := range info.embeds {
1080 embedMap[emb.pattern] = append(embedMap[emb.pattern], emb.pos)
1081 }
1082 }
1083 if directives != nil {
1084 *directives = append(*directives, info.directives...)
1085 }
1086 }
1087
1088 if len(hasImportC) > 0 {
1089 for _, cf := range hasImportC {
1090 if p.CgoBindings {
1091 p.CgoFiles = append(p.CgoFiles, cf.name)
1092 for _, imp := range cf.info.imports {
1093 importPos[imp.path] = append(importPos[imp.path], fset.Position(imp.pos))
1094 }
1095 for _, emb := range cf.info.embeds {
1096 embedPos[emb.pattern] = append(embedPos[emb.pattern], emb.pos)
1097 }
1098 p.Directives = append(p.Directives, cf.info.directives...)
1099 } else {
1100 p.IgnoredGoFiles = append(p.IgnoredGoFiles, cf.name)
1101 }
1102 }
1103 if !p.CgoBindings {
1104 slices.Sort(p.IgnoredGoFiles)
1105 }
1106 }
1107
1108 for tag := range allTags {
1109 p.AllTags = append(p.AllTags, tag)
1110 }
1111 slices.Sort(p.AllTags)
1112
1113 p.EmbedPatterns, p.EmbedPatternPos = cleanDecls(embedPos)
1114 p.TestEmbedPatterns, p.TestEmbedPatternPos = cleanDecls(testEmbedPos)
1115 p.XTestEmbedPatterns, p.XTestEmbedPatternPos = cleanDecls(xTestEmbedPos)
1116
1117 p.Imports, p.ImportPos = cleanDecls(importPos)
1118 p.TestImports, p.TestImportPos = cleanDecls(testImportPos)
1119 p.XTestImports, p.XTestImportPos = cleanDecls(xTestImportPos)
1120
1121
1122
1123
1124 if len(p.CgoFiles) > 0 {
1125 p.SFiles = append(p.SFiles, Sfiles...)
1126 slices.Sort(p.SFiles)
1127 } else {
1128 p.IgnoredOtherFiles = append(p.IgnoredOtherFiles, Sfiles...)
1129 slices.Sort(p.IgnoredOtherFiles)
1130 }
1131
1132 if badGoError != nil {
1133 return p, badGoError
1134 }
1135 if len(p.GoFiles)+len(p.CgoFiles)+len(p.TestGoFiles)+len(p.XTestGoFiles) == 0 {
1136 return p, &NoGoError{p.Dir}
1137 }
1138 return p, pkgerr
1139 }
1140
1141 func fileListForExt(p *Package, ext string) *[]string {
1142 switch ext {
1143 case ".c":
1144 return &p.CFiles
1145 case ".cc", ".cpp", ".cxx":
1146 return &p.CXXFiles
1147 case ".m":
1148 return &p.MFiles
1149 case ".h", ".hh", ".hpp", ".hxx":
1150 return &p.HFiles
1151 case ".f", ".F", ".for", ".f90":
1152 return &p.FFiles
1153 case ".s", ".S", ".sx":
1154 return &p.SFiles
1155 case ".swig":
1156 return &p.SwigFiles
1157 case ".swigcxx":
1158 return &p.SwigCXXFiles
1159 case ".syso":
1160 return &p.SysoFiles
1161 }
1162 return nil
1163 }
1164
1165 func uniq(list []string) []string {
1166 if list == nil {
1167 return nil
1168 }
1169 out := make([]string, len(list))
1170 copy(out, list)
1171 slices.Sort(out)
1172 uniq := out[:0]
1173 for _, x := range out {
1174 if len(uniq) == 0 || uniq[len(uniq)-1] != x {
1175 uniq = append(uniq, x)
1176 }
1177 }
1178 return uniq
1179 }
1180
1181 var errNoModules = errors.New("not using modules")
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193 func (ctxt *Context) importGo(p *Package, path, srcDir string, mode ImportMode) error {
1194
1195
1196
1197 if mode&AllowBinary != 0 || mode&IgnoreVendor != 0 ||
1198 ctxt.JoinPath != nil || ctxt.SplitPathList != nil || ctxt.IsAbsPath != nil || ctxt.IsDir != nil || ctxt.HasSubdir != nil || ctxt.ReadDir != nil || ctxt.OpenFile != nil || !slices.Equal(ctxt.ToolTags, defaultToolTags) || !slices.Equal(ctxt.ReleaseTags, defaultReleaseTags) || ctxt.UseAllFiles {
1199 return errNoModules
1200 }
1201
1202
1203
1204
1205 if ctxt.GOROOT == "" {
1206 return errNoModules
1207 }
1208
1209
1210
1211
1212
1213 go111Module := os.Getenv("GO111MODULE")
1214 switch go111Module {
1215 case "off":
1216 return errNoModules
1217 default:
1218
1219 }
1220
1221 if srcDir != "" {
1222 var absSrcDir string
1223 if filepath.IsAbs(srcDir) {
1224 absSrcDir = srcDir
1225 } else if ctxt.Dir != "" {
1226 return fmt.Errorf("go/build: Dir is non-empty, so relative srcDir is not allowed: %v", srcDir)
1227 } else {
1228
1229
1230 var err error
1231 absSrcDir, err = filepath.Abs(srcDir)
1232 if err != nil {
1233 return errNoModules
1234 }
1235 }
1236
1237
1238
1239
1240 if _, ok := ctxt.hasSubdir(filepath.Join(ctxt.GOROOT, "src"), absSrcDir); ok {
1241 return errNoModules
1242 }
1243 }
1244
1245
1246 if dir := ctxt.joinPath(ctxt.GOROOT, "src", path); ctxt.isDir(dir) {
1247 return errNoModules
1248 }
1249
1250
1251
1252 if go111Module == "auto" {
1253 var (
1254 parent string
1255 err error
1256 )
1257 if ctxt.Dir == "" {
1258 parent, err = os.Getwd()
1259 if err != nil {
1260
1261 return errNoModules
1262 }
1263 } else {
1264 parent, err = filepath.Abs(ctxt.Dir)
1265 if err != nil {
1266
1267
1268 return err
1269 }
1270 }
1271 for {
1272 if f, err := ctxt.openFile(ctxt.joinPath(parent, "go.mod")); err == nil {
1273 buf := make([]byte, 100)
1274 _, err := f.Read(buf)
1275 f.Close()
1276 if err == nil || err == io.EOF {
1277
1278 break
1279 }
1280 }
1281 d := filepath.Dir(parent)
1282 if len(d) >= len(parent) {
1283 return errNoModules
1284 }
1285 parent = d
1286 }
1287 }
1288
1289 goCmd := filepath.Join(ctxt.GOROOT, "bin", "go")
1290 cmd := exec.Command(goCmd, "list", "-e", "-compiler="+ctxt.Compiler, "-tags="+strings.Join(ctxt.BuildTags, ","), "-installsuffix="+ctxt.InstallSuffix, "-f={{.Dir}}\n{{.ImportPath}}\n{{.Root}}\n{{.Goroot}}\n{{if .Error}}{{.Error}}{{end}}\n", "--", path)
1291
1292 if ctxt.Dir != "" {
1293 cmd.Dir = ctxt.Dir
1294 }
1295
1296 var stdout, stderr strings.Builder
1297 cmd.Stdout = &stdout
1298 cmd.Stderr = &stderr
1299
1300 cgo := "0"
1301 switch ctxt.CgoEnabled {
1302 case CgoEnabled:
1303 cgo = "1"
1304 case CgoBindings:
1305 cgo = "bindings"
1306 }
1307 cmd.Env = append(cmd.Environ(),
1308 "GOOS="+ctxt.GOOS,
1309 "GOARCH="+ctxt.GOARCH,
1310 "GOROOT="+ctxt.GOROOT,
1311 "GOPATH="+ctxt.GOPATH,
1312 "CGO_ENABLED="+cgo,
1313 )
1314
1315 if err := cmd.Run(); err != nil {
1316 return fmt.Errorf("go/build: go list %s: %v\n%s\n", path, err, stderr.String())
1317 }
1318
1319 f := strings.SplitN(stdout.String(), "\n", 5)
1320 if len(f) != 5 {
1321 return fmt.Errorf("go/build: importGo %s: unexpected output:\n%s\n", path, stdout.String())
1322 }
1323 dir := f[0]
1324 errStr := strings.TrimSpace(f[4])
1325 if errStr != "" && dir == "" {
1326
1327
1328 return errors.New(errStr)
1329 }
1330
1331
1332
1333
1334 p.Dir = dir
1335 p.ImportPath = f[1]
1336 p.Root = f[2]
1337 p.Goroot = f[3] == "true"
1338 return nil
1339 }
1340
1341
1342
1343
1344
1345 func hasGoFiles(ctxt *Context, dir string) bool {
1346 ents, _ := ctxt.readDir(dir)
1347 for _, ent := range ents {
1348 if !ent.IsDir() && strings.HasSuffix(ent.Name(), ".go") {
1349 return true
1350 }
1351 }
1352 return false
1353 }
1354
1355 func findImportComment(data []byte) (s string, line int) {
1356
1357 word, data := parseWord(data)
1358 if string(word) != "package" {
1359 return "", 0
1360 }
1361
1362
1363 _, data = parseWord(data)
1364
1365
1366
1367 for len(data) > 0 && (data[0] == ' ' || data[0] == '\t' || data[0] == '\r') {
1368 data = data[1:]
1369 }
1370
1371 var comment []byte
1372 switch {
1373 case bytes.HasPrefix(data, slashSlash):
1374 comment, _, _ = bytes.Cut(data[2:], newline)
1375 case bytes.HasPrefix(data, slashStar):
1376 var ok bool
1377 comment, _, ok = bytes.Cut(data[2:], starSlash)
1378 if !ok {
1379
1380 return "", 0
1381 }
1382 if bytes.Contains(comment, newline) {
1383 return "", 0
1384 }
1385 }
1386 comment = bytes.TrimSpace(comment)
1387
1388
1389 word, arg := parseWord(comment)
1390 if string(word) != "import" {
1391 return "", 0
1392 }
1393
1394 line = 1 + bytes.Count(data[:cap(data)-cap(arg)], newline)
1395 return strings.TrimSpace(string(arg)), line
1396 }
1397
1398 var (
1399 slashSlash = []byte("//")
1400 slashStar = []byte("/*")
1401 starSlash = []byte("*/")
1402 newline = []byte("\n")
1403 )
1404
1405
1406 func skipSpaceOrComment(data []byte) []byte {
1407 for len(data) > 0 {
1408 switch data[0] {
1409 case ' ', '\t', '\r', '\n':
1410 data = data[1:]
1411 continue
1412 case '/':
1413 if bytes.HasPrefix(data, slashSlash) {
1414 i := bytes.Index(data, newline)
1415 if i < 0 {
1416 return nil
1417 }
1418 data = data[i+1:]
1419 continue
1420 }
1421 if bytes.HasPrefix(data, slashStar) {
1422 data = data[2:]
1423 i := bytes.Index(data, starSlash)
1424 if i < 0 {
1425 return nil
1426 }
1427 data = data[i+2:]
1428 continue
1429 }
1430 }
1431 break
1432 }
1433 return data
1434 }
1435
1436
1437
1438
1439 func parseWord(data []byte) (word, rest []byte) {
1440 data = skipSpaceOrComment(data)
1441
1442
1443 rest = data
1444 for {
1445 r, size := utf8.DecodeRune(rest)
1446 if unicode.IsLetter(r) || '0' <= r && r <= '9' || r == '_' {
1447 rest = rest[size:]
1448 continue
1449 }
1450 break
1451 }
1452
1453 word = data[:len(data)-len(rest)]
1454 if len(word) == 0 {
1455 return nil, nil
1456 }
1457
1458 return word, rest
1459 }
1460
1461
1462
1463
1464
1465
1466
1467 func (ctxt *Context) MatchFile(dir, name string) (match bool, err error) {
1468 info, err := ctxt.matchFile(dir, name, nil, nil, nil)
1469 return info != nil, err
1470 }
1471
1472 var dummyPkg Package
1473
1474
1475 type fileInfo struct {
1476 name string
1477 header []byte
1478 fset *token.FileSet
1479 parsed *ast.File
1480 parseErr error
1481 imports []fileImport
1482 embeds []fileEmbed
1483 directives []Directive
1484 cgoBindings bool
1485 }
1486
1487 type fileImport struct {
1488 path string
1489 pos token.Pos
1490 doc *ast.CommentGroup
1491 }
1492
1493 type fileEmbed struct {
1494 pattern string
1495 pos token.Position
1496 }
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510 func (ctxt *Context) matchFile(dir, name string, allTags map[string]bool, binaryOnly *bool, fset *token.FileSet) (*fileInfo, error) {
1511 if strings.HasPrefix(name, "_") ||
1512 strings.HasPrefix(name, ".") {
1513 return nil, nil
1514 }
1515
1516 i := strings.LastIndex(name, ".")
1517 if i < 0 {
1518 i = len(name)
1519 }
1520 ext := name[i:]
1521
1522 if ext != ".go" && fileListForExt(&dummyPkg, ext) == nil {
1523
1524 return nil, nil
1525 }
1526
1527 if !ctxt.goodOSArchFile(name, allTags) && !ctxt.UseAllFiles {
1528 return nil, nil
1529 }
1530
1531 info := &fileInfo{name: ctxt.joinPath(dir, name), fset: fset}
1532 if ext == ".syso" {
1533
1534 return info, nil
1535 }
1536
1537 f, err := ctxt.openFile(info.name)
1538 if err != nil {
1539 return nil, err
1540 }
1541
1542 if strings.HasSuffix(name, ".go") {
1543 err = readGoInfo(f, info)
1544 if strings.HasSuffix(name, "_test.go") {
1545 binaryOnly = nil
1546 }
1547 } else {
1548 binaryOnly = nil
1549 info.header, err = readComments(f)
1550 }
1551 f.Close()
1552 if err != nil {
1553 return info, fmt.Errorf("read %s: %v", info.name, err)
1554 }
1555
1556
1557 ok, sawBinaryOnly, err := ctxt.shouldBuild(info.header, allTags)
1558 if err != nil {
1559 return nil, fmt.Errorf("%s: %v", name, err)
1560 }
1561 if !ok && !ctxt.UseAllFiles {
1562 return nil, nil
1563 }
1564
1565 if binaryOnly != nil && sawBinaryOnly {
1566 *binaryOnly = true
1567 }
1568
1569 return info, nil
1570 }
1571
1572 func cleanDecls(m map[string][]token.Position) ([]string, map[string][]token.Position) {
1573 all := make([]string, 0, len(m))
1574 for path := range m {
1575 all = append(all, path)
1576 }
1577 slices.Sort(all)
1578 return all, m
1579 }
1580
1581
1582 func Import(path, srcDir string, mode ImportMode) (*Package, error) {
1583 return Default.Import(path, srcDir, mode)
1584 }
1585
1586
1587 func ImportDir(dir string, mode ImportMode) (*Package, error) {
1588 return Default.ImportDir(dir, mode)
1589 }
1590
1591 var (
1592 plusBuild = []byte("+build")
1593
1594 goBuildComment = []byte("//go:build")
1595
1596 errMultipleGoBuild = errors.New("multiple //go:build comments")
1597 )
1598
1599 func isGoBuildComment(line []byte) bool {
1600 if !bytes.HasPrefix(line, goBuildComment) {
1601 return false
1602 }
1603 line = bytes.TrimSpace(line)
1604 rest := line[len(goBuildComment):]
1605 return len(rest) == 0 || len(bytes.TrimSpace(rest)) < len(rest)
1606 }
1607
1608
1609
1610
1611 var binaryOnlyComment = []byte("//go:binary-only-package")
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630 func (ctxt *Context) shouldBuild(content []byte, allTags map[string]bool) (shouldBuild, binaryOnly bool, err error) {
1631
1632
1633
1634 content, goBuild, sawBinaryOnly, err := parseFileHeader(content)
1635 if err != nil {
1636 return false, false, err
1637 }
1638
1639
1640
1641 switch {
1642 case goBuild != nil:
1643 x, err := constraint.Parse(string(goBuild))
1644 if err != nil {
1645 return false, false, fmt.Errorf("parsing //go:build line: %v", err)
1646 }
1647 shouldBuild = ctxt.eval(x, allTags)
1648
1649 default:
1650 shouldBuild = true
1651 p := content
1652 for len(p) > 0 {
1653 line := p
1654 if i := bytes.IndexByte(line, '\n'); i >= 0 {
1655 line, p = line[:i], p[i+1:]
1656 } else {
1657 p = p[len(p):]
1658 }
1659 line = bytes.TrimSpace(line)
1660 if !bytes.HasPrefix(line, slashSlash) || !bytes.Contains(line, plusBuild) {
1661 continue
1662 }
1663 text := string(line)
1664 if !constraint.IsPlusBuild(text) {
1665 continue
1666 }
1667 if x, err := constraint.Parse(text); err == nil {
1668 if !ctxt.eval(x, allTags) {
1669 shouldBuild = false
1670 }
1671 }
1672 }
1673 }
1674
1675 return shouldBuild, sawBinaryOnly, nil
1676 }
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687 func parseFileHeader(content []byte) (trimmed, goBuild []byte, sawBinaryOnly bool, err error) {
1688 end := 0
1689 p := content
1690 ended := false
1691 inSlashStar := false
1692
1693 Lines:
1694 for len(p) > 0 {
1695 line := p
1696 if i := bytes.IndexByte(line, '\n'); i >= 0 {
1697 line, p = line[:i], p[i+1:]
1698 } else {
1699 p = p[len(p):]
1700 }
1701 line = bytes.TrimSpace(line)
1702 if len(line) == 0 && !ended {
1703
1704
1705
1706
1707
1708
1709
1710
1711 end = len(content) - len(p)
1712 continue Lines
1713 }
1714 if !bytes.HasPrefix(line, slashSlash) {
1715 ended = true
1716 }
1717
1718 if !inSlashStar && isGoBuildComment(line) {
1719 if goBuild != nil {
1720 return nil, nil, false, errMultipleGoBuild
1721 }
1722 goBuild = line
1723 }
1724 if !inSlashStar && bytes.Equal(line, binaryOnlyComment) {
1725 sawBinaryOnly = true
1726 }
1727
1728 Comments:
1729 for len(line) > 0 {
1730 if inSlashStar {
1731 if i := bytes.Index(line, starSlash); i >= 0 {
1732 inSlashStar = false
1733 line = bytes.TrimSpace(line[i+len(starSlash):])
1734 continue Comments
1735 }
1736 continue Lines
1737 }
1738 if bytes.HasPrefix(line, slashSlash) {
1739 continue Lines
1740 }
1741 if bytes.HasPrefix(line, slashStar) {
1742 inSlashStar = true
1743 line = bytes.TrimSpace(line[len(slashStar):])
1744 continue Comments
1745 }
1746
1747 break Lines
1748 }
1749 }
1750
1751 return content[:end], goBuild, sawBinaryOnly, nil
1752 }
1753
1754
1755
1756
1757 func (ctxt *Context) saveCgo(filename string, di *Package, cg *ast.CommentGroup) error {
1758 text := cg.Text()
1759 for line := range strings.SplitSeq(text, "\n") {
1760 orig := line
1761
1762
1763
1764
1765 line = strings.TrimSpace(line)
1766 if len(line) < 5 || line[:4] != "#cgo" || (line[4] != ' ' && line[4] != '\t') {
1767 continue
1768 }
1769
1770
1771 if fields := strings.Fields(line); len(fields) == 3 && (fields[1] == "nocallback" || fields[1] == "noescape") {
1772 continue
1773 }
1774
1775
1776 line, argstr, ok := strings.Cut(strings.TrimSpace(line[4:]), ":")
1777 if !ok {
1778 return fmt.Errorf("%s: invalid #cgo line: %s", filename, orig)
1779 }
1780
1781
1782 f := strings.Fields(line)
1783 if len(f) < 1 {
1784 return fmt.Errorf("%s: invalid #cgo line: %s", filename, orig)
1785 }
1786
1787 cond, verb := f[:len(f)-1], f[len(f)-1]
1788 if len(cond) > 0 {
1789 ok := false
1790 for _, c := range cond {
1791 if ctxt.matchAuto(c, nil) {
1792 ok = true
1793 break
1794 }
1795 }
1796 if !ok {
1797 continue
1798 }
1799 }
1800
1801 args, err := splitQuoted(argstr)
1802 if err != nil {
1803 return fmt.Errorf("%s: invalid #cgo line: %s", filename, orig)
1804 }
1805 for i, arg := range args {
1806 if arg, ok = expandSrcDir(arg, di.Dir); !ok {
1807 return fmt.Errorf("%s: malformed #cgo argument: %s", filename, arg)
1808 }
1809 args[i] = arg
1810 }
1811
1812 switch verb {
1813 case "CFLAGS", "CPPFLAGS", "CXXFLAGS", "FFLAGS", "LDFLAGS":
1814
1815 ctxt.makePathsAbsolute(args, di.Dir)
1816 }
1817
1818 switch verb {
1819 case "CFLAGS":
1820 di.CgoCFLAGS = append(di.CgoCFLAGS, args...)
1821 case "CPPFLAGS":
1822 di.CgoCPPFLAGS = append(di.CgoCPPFLAGS, args...)
1823 case "CXXFLAGS":
1824 di.CgoCXXFLAGS = append(di.CgoCXXFLAGS, args...)
1825 case "FFLAGS":
1826 di.CgoFFLAGS = append(di.CgoFFLAGS, args...)
1827 case "LDFLAGS":
1828 di.CgoLDFLAGS = append(di.CgoLDFLAGS, args...)
1829 case "pkg-config":
1830 di.CgoPkgConfig = append(di.CgoPkgConfig, args...)
1831 default:
1832 return fmt.Errorf("%s: invalid #cgo verb: %s", filename, orig)
1833 }
1834 }
1835 return nil
1836 }
1837
1838
1839
1840 func expandSrcDir(str string, srcdir string) (string, bool) {
1841
1842
1843
1844 srcdir = filepath.ToSlash(srcdir)
1845
1846 chunks := strings.Split(str, "${SRCDIR}")
1847 if len(chunks) < 2 {
1848 return str, safeCgoName(str)
1849 }
1850 ok := true
1851 for _, chunk := range chunks {
1852 ok = ok && (chunk == "" || safeCgoName(chunk))
1853 }
1854 ok = ok && (srcdir == "" || safeCgoName(srcdir))
1855 res := strings.Join(chunks, srcdir)
1856 return res, ok && res != ""
1857 }
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870 func (ctxt *Context) makePathsAbsolute(args []string, srcDir string) {
1871 nextPath := false
1872 for i, arg := range args {
1873 if nextPath {
1874 if !filepath.IsAbs(arg) {
1875 args[i] = filepath.Join(srcDir, arg)
1876 }
1877 nextPath = false
1878 } else if strings.HasPrefix(arg, "-I") || strings.HasPrefix(arg, "-L") {
1879 if len(arg) == 2 {
1880 nextPath = true
1881 } else {
1882 if !filepath.IsAbs(arg[2:]) {
1883 args[i] = arg[:2] + filepath.Join(srcDir, arg[2:])
1884 }
1885 }
1886 }
1887 }
1888 }
1889
1890
1891
1892
1893
1894
1895
1896
1897 const safeString = "+-.,/0123456789=ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz:$@%! ~^"
1898
1899 func safeCgoName(s string) bool {
1900 if s == "" {
1901 return false
1902 }
1903 for i := 0; i < len(s); i++ {
1904 if c := s[i]; c < utf8.RuneSelf && strings.IndexByte(safeString, c) < 0 {
1905 return false
1906 }
1907 }
1908 return true
1909 }
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926 func splitQuoted(s string) (r []string, err error) {
1927 var args []string
1928 arg := make([]rune, len(s))
1929 escaped := false
1930 quoted := false
1931 quote := '\x00'
1932 i := 0
1933 for _, rune := range s {
1934 switch {
1935 case escaped:
1936 escaped = false
1937 case rune == '\\':
1938 escaped = true
1939 continue
1940 case quote != '\x00':
1941 if rune == quote {
1942 quote = '\x00'
1943 continue
1944 }
1945 case rune == '"' || rune == '\'':
1946 quoted = true
1947 quote = rune
1948 continue
1949 case unicode.IsSpace(rune):
1950 if quoted || i > 0 {
1951 quoted = false
1952 args = append(args, string(arg[:i]))
1953 i = 0
1954 }
1955 continue
1956 }
1957 arg[i] = rune
1958 i++
1959 }
1960 if quoted || i > 0 {
1961 args = append(args, string(arg[:i]))
1962 }
1963 if quote != 0 {
1964 err = errors.New("unclosed quote")
1965 } else if escaped {
1966 err = errors.New("unfinished escaping")
1967 }
1968 return args, err
1969 }
1970
1971
1972
1973
1974
1975
1976 func (ctxt *Context) matchAuto(text string, allTags map[string]bool) bool {
1977 if strings.ContainsAny(text, "&|()") {
1978 text = "//go:build " + text
1979 } else {
1980 text = "// +build " + text
1981 }
1982 x, err := constraint.Parse(text)
1983 if err != nil {
1984 return false
1985 }
1986 return ctxt.eval(x, allTags)
1987 }
1988
1989 func (ctxt *Context) eval(x constraint.Expr, allTags map[string]bool) bool {
1990 return x.Eval(func(tag string) bool { return ctxt.matchTag(tag, allTags) })
1991 }
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008 func (ctxt *Context) matchTag(name string, allTags map[string]bool) bool {
2009 if allTags != nil {
2010 allTags[name] = true
2011 }
2012
2013
2014 if ctxt.CgoEnabled == CgoEnabled && name == "cgo" {
2015 return true
2016 }
2017 if name == "cgobindings" && (ctxt.CgoEnabled == CgoBindings ||
2018 (ctxt.CgoEnabled == CgoEnabled && slices.Contains(ctxt.ToolTags, "goexperiment.cgobindings"))) {
2019 return true
2020 }
2021 if name == ctxt.GOOS || name == ctxt.GOARCH || name == ctxt.Compiler {
2022 return true
2023 }
2024 if ctxt.GOOS == "android" && name == "linux" {
2025 return true
2026 }
2027 if ctxt.GOOS == "illumos" && name == "solaris" {
2028 return true
2029 }
2030 if ctxt.GOOS == "ios" && name == "darwin" {
2031 return true
2032 }
2033 if name == "unix" && syslist.UnixOS[ctxt.GOOS] {
2034 return true
2035 }
2036 if name == "boringcrypto" {
2037 name = "goexperiment.boringcrypto"
2038 }
2039
2040
2041 return slices.Contains(ctxt.BuildTags, name) || slices.Contains(ctxt.ToolTags, name) ||
2042 slices.Contains(ctxt.ReleaseTags, name)
2043 }
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060 func (ctxt *Context) goodOSArchFile(name string, allTags map[string]bool) bool {
2061 name, _, _ = strings.Cut(name, ".")
2062
2063
2064
2065
2066
2067
2068
2069
2070 i := strings.Index(name, "_")
2071 if i < 0 {
2072 return true
2073 }
2074 name = name[i:]
2075
2076 l := strings.Split(name, "_")
2077 if n := len(l); n > 0 && l[n-1] == "test" {
2078 l = l[:n-1]
2079 }
2080 n := len(l)
2081 if n >= 2 && syslist.KnownOS[l[n-2]] && syslist.KnownArch[l[n-1]] {
2082 if allTags != nil {
2083
2084 allTags[l[n-2]] = true
2085 }
2086 return ctxt.matchTag(l[n-1], allTags) && ctxt.matchTag(l[n-2], allTags)
2087 }
2088 if n >= 1 && (syslist.KnownOS[l[n-1]] || syslist.KnownArch[l[n-1]]) {
2089 return ctxt.matchTag(l[n-1], allTags)
2090 }
2091 return true
2092 }
2093
2094
2095 var ToolDir = getToolDir()
2096
2097
2098
2099 func IsLocalImport(path string) bool {
2100 return path == "." || path == ".." ||
2101 strings.HasPrefix(path, "./") || strings.HasPrefix(path, "../")
2102 }
2103
2104
2105
2106
2107
2108
2109
2110
2111 func ArchChar(goarch string) (string, error) {
2112 return "?", errors.New("architecture letter no longer used")
2113 }
2114
View as plain text