1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30 package work
31
32 import (
33 "bytes"
34 "debug/elf"
35 "debug/macho"
36 "debug/pe"
37 "debug/plan9obj"
38 "encoding/binary"
39 "fmt"
40 "internal/lazyregexp"
41 "internal/xcoff"
42 "io"
43 "os"
44 "path/filepath"
45 "regexp"
46 "slices"
47 "strconv"
48 "strings"
49 "unicode"
50 "unicode/utf8"
51
52 "cmd/go/internal/base"
53 "cmd/go/internal/cfg"
54 "cmd/go/internal/load"
55 "cmd/go/internal/str"
56 )
57
58 var re = lazyregexp.New
59
60 var validCompilerFlags = []*lazyregexp.Regexp{
61 re(`-D([A-Za-z_][A-Za-z0-9_]*)(=[^@\-]*)?`),
62 re(`-U([A-Za-z_][A-Za-z0-9_]*)`),
63 re(`-F([^@\-].*)`),
64 re(`-I([^@\-].*)`),
65 re(`-O`),
66 re(`-O([^@\-].*)`),
67 re(`-W`),
68 re(`-W([^@,]+)`),
69 re(`-Wa,-mbig-obj`),
70 re(`-Wp,-D([A-Za-z_][A-Za-z0-9_]*)(=[^@,\-]*)?`),
71 re(`-Wp,-U([A-Za-z_][A-Za-z0-9_]*)`),
72 re(`-ansi`),
73 re(`-f(no-)?asynchronous-unwind-tables`),
74 re(`-f(no-)?blocks`),
75 re(`-f(no-)builtin-[a-zA-Z0-9_]*`),
76 re(`-f(no-)?common`),
77 re(`-f(no-)?constant-cfstrings`),
78 re(`-fdebug-prefix-map=([^@]+)=([^@]+)`),
79 re(`-fdiagnostics-show-note-include-stack`),
80 re(`-fexcess-precision=([A-Za-z0-9_]+)`),
81 re(`-ffile-prefix-map=([^@]+)=([^@]+)`),
82 re(`-fno-canonical-system-headers`),
83 re(`-f(no-)?eliminate-unused-debug-types`),
84 re(`-f(no-)?exceptions`),
85 re(`-f(no-)?fast-math`),
86 re(`-f(no-)?inline-functions`),
87 re(`-finput-charset=([^@\-].*)`),
88 re(`-f(no-)?fat-lto-objects`),
89 re(`-f(no-)?keep-inline-dllexport`),
90 re(`-f(no-)?lto`),
91 re(`-fmacro-backtrace-limit=(.+)`),
92 re(`-fmessage-length=(.+)`),
93 re(`-f(no-)?modules`),
94 re(`-f(no-)?objc-arc`),
95 re(`-f(no-)?objc-nonfragile-abi`),
96 re(`-f(no-)?objc-legacy-dispatch`),
97 re(`-f(no-)?omit-frame-pointer`),
98 re(`-f(no-)?openmp(-simd)?`),
99 re(`-f(no-)?permissive`),
100 re(`-f(no-)?(pic|PIC|pie|PIE)`),
101 re(`-f(no-)?plt`),
102 re(`-f(no-)?rtti`),
103 re(`-f(no-)?split-stack`),
104 re(`-f(no-)?stack-(.+)`),
105 re(`-f(no-)?strict-aliasing`),
106 re(`-f(un)signed-char`),
107 re(`-f(no-)?use-linker-plugin`),
108 re(`-f(no-)?visibility-inlines-hidden`),
109 re(`-fsanitize=([^@\-].*)`),
110 re(`-fsanitize-undefined-strip-path-components=(-)?[0-9]+`),
111 re(`-ftemplate-depth-(.+)`),
112 re(`-ftls-model=(global-dynamic|local-dynamic|initial-exec|local-exec)`),
113 re(`-fvisibility=(.+)`),
114 re(`-g([^@\-].*)?`),
115 re(`-m32`),
116 re(`-m64`),
117 re(`-m(abi|arch|cpu|fpu|simd|tls-dialect|tune)=([^@\-].*)`),
118 re(`-m(no-)?v?aes`),
119 re(`-marm`),
120 re(`-mcmodel=[0-9a-z-]+`),
121 re(`-mfloat-abi=([^@\-].*)`),
122 re(`-m(soft|single|double)-float`),
123 re(`-mfpmath=[0-9a-z,+]*`),
124 re(`-m(no-)?avx[0-9a-z.]*`),
125 re(`-m(no-)?ms-bitfields`),
126 re(`-m(no-)?stack-(.+)`),
127 re(`-mmacosx-(.+)`),
128 re(`-m(no-)?relax`),
129 re(`-m(no-)?strict-align`),
130 re(`-m(no-)?(lsx|lasx|frecipe|div32|lam-bh|lamcas|ld-seq-sa)`),
131 re(`-mios-simulator-version-min=(.+)`),
132 re(`-miphoneos-version-min=(.+)`),
133 re(`-mlarge-data-threshold=[0-9]+`),
134 re(`-mtvos-simulator-version-min=(.+)`),
135 re(`-mtvos-version-min=(.+)`),
136 re(`-mwatchos-simulator-version-min=(.+)`),
137 re(`-mwatchos-version-min=(.+)`),
138 re(`-mnop-fun-dllimport`),
139 re(`-m(no-)?sse[0-9.]*`),
140 re(`-m(no-)?ssse3`),
141 re(`-mthumb(-interwork)?`),
142 re(`-mthreads`),
143 re(`-mwindows`),
144 re(`-no-canonical-prefixes`),
145 re(`--param=ssp-buffer-size=[0-9]*`),
146 re(`-pedantic(-errors)?`),
147 re(`-pipe`),
148 re(`-pthread`),
149 re(`--static`),
150 re(`-?-std=([^@\-].*)`),
151 re(`-?-stdlib=([^@\-].*)`),
152 re(`-w`),
153 re(`-x(c|c-header|cpp-output|c\+\+|c\+\+-header|c\+\+-cpp-output|objective-c|objective-c-header|objective-c-cpp-output|objective-c\+\+|objective-c\+\+-header|objective-c\+\+-cpp-output|assembler|assembler-with-cpp)`),
154 re(`-v`),
155 }
156
157 var validCompilerXLang = re(`^(c|c-header|cpp-output|c\+\+|c\+\+-header|c\+\+-cpp-output|objective-c|objective-c-header|objective-c-cpp-output|objective-c\+\+|objective-c\+\+-header|objective-c\+\+-cpp-output|assembler|assembler-with-cpp)$`)
158
159 var validCompilerFlagsWithNextArg = []string{
160 "-arch",
161 "-D",
162 "-U",
163 "-I",
164 "-F",
165 "-framework",
166 "-include",
167 "-isysroot",
168 "-isystem",
169 "-x",
170 }
171
172 var invalidCompilerFlags = []*lazyregexp.Regexp{
173
174
175
176
177 re(`-gen-.*`),
178 re(`-gnat.*`),
179 }
180
181 var invalidLinkerFlags = []*lazyregexp.Regexp{
182
183
184 re(`-lto_library`),
185 re(`-lazy_library`),
186 re(`-lazy_framework`),
187 re(`-load_hidden`),
188
189 re(`-library(-path)?(=.*)?`),
190 re(`-gen-.*`),
191 re(`-gnat.*`),
192
193
194
195 re(`-Wl,--warn-backrefs-exclude`),
196 }
197
198 var validLinkerFlags = []*lazyregexp.Regexp{
199 re(`-F([^@\-].*)`),
200 re(`-l([^@\-:=/\\][^:=/\\]*)`),
201 re(`-L([^@\-].*)`),
202 re(`-O`),
203 re(`-O([^@\-].*)`),
204 re(`-f(no-)?(pic|PIC|pie|PIE)`),
205 re(`-f(no-)?openmp(-simd)?`),
206 re(`-fsanitize=([^@\-].*)`),
207 re(`-flat_namespace`),
208 re(`-g([^@\-].*)?`),
209 re(`-headerpad_max_install_names`),
210 re(`-m(abi|arch|cpu|fpu|simd|tls-dialect|tune)=([^@\-].*)`),
211 re(`-mcmodel=[0-9a-z-]+`),
212 re(`-mfloat-abi=([^@\-].*)`),
213 re(`-m(soft|single|double)-float`),
214 re(`-m(no-)?relax`),
215 re(`-m(no-)?strict-align`),
216 re(`-m(no-)?(lsx|lasx|frecipe|div32|lam-bh|lamcas|ld-seq-sa)`),
217 re(`-mmacosx-(.+)`),
218 re(`-mios-simulator-version-min=(.+)`),
219 re(`-miphoneos-version-min=(.+)`),
220 re(`-mthreads`),
221 re(`-mwindows`),
222 re(`-(pic|PIC|pie|PIE)`),
223 re(`-pthread`),
224 re(`-rdynamic`),
225 re(`-shared`),
226 re(`-?-static([-a-z0-9+]*)`),
227 re(`-?-stdlib=([^@\-].*)`),
228 re(`-v`),
229
230
231
232
233
234
235 re(`-Wl,--(no-)?allow-multiple-definition`),
236 re(`-Wl,--(no-)?allow-shlib-undefined`),
237 re(`-Wl,--(no-)?as-needed`),
238 re(`-Wl,-Bdynamic`),
239 re(`-Wl,-berok`),
240 re(`-Wl,-Bstatic`),
241 re(`-Wl,-Bsymbolic-functions`),
242 re(`-Wl,-O[0-9]+`),
243 re(`-Wl,-d[ny]`),
244 re(`-Wl,--disable-new-dtags`),
245 re(`-Wl,-e[=,][a-zA-Z0-9]+`),
246 re(`-Wl,--enable-new-dtags`),
247 re(`-Wl,--end-group`),
248 re(`-Wl,--(no-)?export-dynamic`),
249 re(`-Wl,-E`),
250 re(`-Wl,-framework,[^,@\-][^,]*`),
251 re(`-Wl,--hash-style=(sysv|gnu|both)`),
252 re(`-Wl,-headerpad_max_install_names`),
253 re(`-Wl,--no-undefined`),
254 re(`-Wl,--pop-state`),
255 re(`-Wl,--push-state`),
256 re(`-Wl,-R[,=]?([^@\-,=][^,@]*$)`),
257 re(`-Wl,--just-symbols[=,]([^,@\-][^,@]*)`),
258 re(`-Wl,-rpath(-link)?[=,]([^,@\-][^,]*)`),
259 re(`-Wl,-s`),
260 re(`-Wl,-search_paths_first`),
261 re(`-Wl,-sectcreate,([^,@\-][^,]*),([^,@\-][^,]*),([^,@\-][^,]*)`),
262 re(`-Wl,--start-group`),
263 re(`-Wl,-?-static`),
264 re(`-Wl,-?-subsystem,(native|windows|console|posix|xbox)`),
265 re(`-Wl,-syslibroot[=,]([^,@\-][^,]*)`),
266 re(`-Wl,-undefined[=,]([^,@\-][^,]*)`),
267 re(`-Wl,-?-unresolved-symbols=[^,]+`),
268 re(`-Wl,--(no-)?warn-([^,]+)`),
269 re(`-Wl,-?-wrap[=,][^,@\-][^,]*`),
270 re(`-Wl(,-z,(relro|now|(no)?execstack))+`),
271
272 re(`[a-zA-Z0-9_/].*\.(a|o|obj|dll|dylib|lib|so|tbd)`),
273 re(`\./.*\.(a|o|obj|dll|dylib|lib|so|tbd)`),
274 }
275
276 var validLinkerFlagsWithNextArg = []string{
277 "-arch",
278 "-F",
279 "-l",
280 "-L",
281 "-framework",
282 "-isysroot",
283 "-Wl,-framework",
284 "-Wl,-rpath",
285 "-Wl,-R",
286 "-Wl,--just-symbols",
287 "-Wl,-undefined",
288 }
289
290
291
292
293 var recombinedLinkerFlagsWithNextArg = []string{
294 "-l",
295 }
296
297 var validPkgConfigFlags = []*lazyregexp.Regexp{
298 re(`--atleast-pkgconfig-version=\d+\.\d+\.\d+`),
299 re(`--atleast-version=\d+\.\d+\.\d+`),
300 re(`--cflags-only-I`),
301 re(`--cflags`),
302 re(`--define-prefix`),
303 re(`--define-variable=[A-Za-z_][A-Za-z0-9_]*=[^@\-=$][^$]*`),
304 re(`--digraph`),
305 re(`--dont-define-prefix`),
306 re(`--dont-relocate-paths`),
307 re(`--dump-personality`),
308 re(`--env-only`),
309 re(`--errors-to-stdout`),
310 re(`--exact-version=\d+\.\d+\.\d+`),
311 re(`--exists`),
312 re(`--fragment-filter=[A-Za-z_][a-zA-Z0-9_]*`),
313 re(`--ignore-conflicts`),
314 re(`--internal-cflags`),
315 re(`--keep-system-cflags`),
316 re(`--keep-system-libs`),
317 re(`--libs-only-l`),
318 re(`--libs-only-L`),
319 re(`--libs`),
320 re(`--list-all`),
321 re(`--list-package-names`),
322 re(`--max-version=\d+\.\d+\.\d+`),
323 re(`--maximum-traverse-depth=[0-9]+`),
324 re(`--modversion`),
325 re(`--msvc-syntax`),
326 re(`--no-cache`),
327 re(`--no-provides`),
328 re(`--no-uninstalled`),
329 re(`--path`),
330 re(`--prefix-variable=[A-Za-z_][a-zA-Z0-9_]*`),
331 re(`--print-errors`),
332 re(`--print-provides`),
333 re(`--print-requires-private`),
334 re(`--print-requires`),
335 re(`--print-variables`),
336 re(`--pure`),
337 re(`--shared`),
338 re(`--short-errors`),
339 re(`--silence-errors`),
340 re(`--simulate`),
341 re(`--static`),
342 re(`--uninstalled`),
343 re(`--validate`),
344 re(`--variable=[A-Za-z_][a-zA-Z0-9_]*`),
345 }
346
347
348
349
350
351 func hasGCCSpecFlags(list []string) bool {
352 var allow *regexp.Regexp
353 if env := cfg.Getenv("CGO_LDFLAGS_ALLOW"); env != "" {
354 allow, _ = regexp.Compile(env)
355 }
356 return hasGCCSpecFlagsAllow(list, allow)
357 }
358
359 func hasGCCSpecFlagsAllow(list []string, allow *regexp.Regexp) bool {
360 hasSanitize := false
361 hasStatic := false
362 for _, arg := range list {
363 if matchAllow(allow, arg) {
364 continue
365 }
366 if arg == "-fopenmp" || arg == "-fopenacc" {
367 return true
368 }
369 if strings.HasPrefix(arg, "-fsanitize=") {
370 hasSanitize = true
371 }
372 if arg == "-static" || arg == "--static" || strings.HasPrefix(arg, "-static-") || strings.HasPrefix(arg, "--static-") {
373 hasStatic = true
374 }
375 }
376 return hasSanitize && hasStatic
377 }
378
379 func matchAllow(allow *regexp.Regexp, s string) bool {
380 return allow != nil && allow.FindString(s) == s
381 }
382
383 func checkCompilerFlags(name, source string, list []string) error {
384 checkOverrides := true
385 return checkFlags(name, source, list, invalidCompilerFlags, validCompilerFlags, nil, validCompilerFlagsWithNextArg, checkOverrides)
386 }
387
388 func checkLinkerFlags(name, source string, list []string) error {
389 checkOverrides := true
390 if err := checkFlags(name, source, list, invalidLinkerFlags, validLinkerFlags, recombinedLinkerFlagsWithNextArg, validLinkerFlagsWithNextArg, checkOverrides); err != nil {
391 return err
392 }
393 var allow *regexp.Regexp
394 if env := cfg.Getenv("CGO_" + name + "_ALLOW"); env != "" {
395 r, err := regexp.Compile(env)
396 if err != nil {
397 return fmt.Errorf("parsing $CGO_%s_ALLOW: %v", name, err)
398 }
399 allow = r
400 }
401 if hasGCCSpecFlagsAllow(list, allow) {
402 if err := scanLinkerSearchDir(source, ".", false, allow); err != nil {
403 return err
404 }
405 }
406 for i := 0; i < len(list); i++ {
407 arg := list[i]
408 switch {
409 case strings.HasPrefix(arg, "-L"):
410 raw := arg
411 dir := arg[2:]
412 if dir == "" && i+1 < len(list) {
413 i++
414 dir = list[i]
415 raw = arg + " " + dir
416 }
417 if dir != "" && !matchAllow(allow, raw) && !matchAllow(allow, "-L"+dir) && !matchAllow(allow, dir) {
418 if err := checkLinkerLibDir(source, dir, allow); err != nil {
419 return err
420 }
421 }
422
423
424
425 case arg == "-isysroot" && i+1 < len(list):
426 i++
427 raw := arg + " " + list[i]
428 if !matchAllow(allow, raw) && !matchAllow(allow, arg+list[i]) && !matchAllow(allow, list[i]) {
429 if err := checkLinkerSysroot(source, raw, list[i], allow); err != nil {
430 return err
431 }
432 }
433 case arg == "-framework" && i+1 < len(list):
434 i++
435 raw := arg + " " + list[i]
436 if !matchAllow(allow, raw) && !matchAllow(allow, arg+list[i]) && !matchAllow(allow, list[i]) {
437 if err := checkLinkerNonPathNonFile(source, raw, list[i]); err != nil {
438 return err
439 }
440 }
441 case strings.HasPrefix(arg, "-Wl,"):
442 raw := arg
443 warg := arg
444 if slices.Contains(validLinkerFlagsWithNextArg, arg) && i+1 < len(list) {
445 i++
446 raw = arg + " " + list[i]
447 warg = arg + "," + strings.TrimPrefix(list[i], "-Wl,")
448 }
449 if !matchAllow(allow, raw) && !matchAllow(allow, warg) {
450 if err := checkLinkerWlFlag(source, raw, warg, allow); err != nil {
451 return err
452 }
453 }
454 case reDirectLinkerInput.MatchString(arg) && isLocalLinkerPath(arg):
455 if !matchAllow(allow, arg) && !matchAllow(allow, filepath.Base(arg)) {
456 if err := checkLinkerInputFile(source, arg); err != nil {
457 return err
458 }
459 }
460 }
461 }
462 return nil
463 }
464
465
466
467
468 func checkLinkerSysroot(source, flag, dir string, allow *regexp.Regexp) error {
469 if fi, err := os.Stat(dir); err == nil && !fi.IsDir() {
470 return fmt.Errorf("invalid flag in %s: %s (not a directory)", source, flag)
471 }
472 return scanLinkerSearchDir(source, dir, false, allow)
473 }
474
475
476
477
478
479
480
481
482
483
484 func checkLinkerNonPathNonFile(source, raw, val string) error {
485 if strings.ContainsAny(val, `/\`) {
486 return fmt.Errorf("invalid flag in %s: %s (see https://go.dev/s/invalidflag)", source, raw)
487 }
488 if fi, err := os.Stat(val); err == nil && !fi.IsDir() {
489 return fmt.Errorf("invalid flag in %s: %s (see https://go.dev/s/invalidflag)", source, raw)
490 }
491 return nil
492 }
493
494 func checkLinkerObjOrDir(source, raw, val string, allow *regexp.Regexp) error {
495 if !isLocalLinkerPath(val) || matchAllow(allow, val) || matchAllow(allow, filepath.Base(val)) {
496 return nil
497 }
498 if fi, err := os.Stat(val); err == nil && !fi.IsDir() {
499 if err := checkLinkerInputFile(source, val); err != nil {
500 return fmt.Errorf("invalid flag in %s: %s (%v)", source, raw, err)
501 }
502 }
503 return nil
504 }
505
506 func checkLinkerWlFlag(source, raw, arg string, allow *regexp.Regexp) error {
507 wargs := []string{arg}
508 if strings.HasPrefix(arg, "-Wl,--push-state,") {
509 for _, sub := range strings.Split(arg, ",")[2:] {
510 wargs = append(wargs, "-Wl,"+sub)
511 }
512 }
513 for _, warg := range wargs {
514 if matchAllow(allow, warg) {
515 continue
516 }
517 switch {
518 case strings.HasPrefix(warg, "-Wl,-syslibroot,"), strings.HasPrefix(warg, "-Wl,-syslibroot="):
519 dir := warg[len("-Wl,-syslibroot,"):]
520 if !matchAllow(allow, dir) {
521 if err := checkLinkerSysroot(source, raw, dir, allow); err != nil {
522 return err
523 }
524 }
525 case strings.HasPrefix(warg, "-Wl,-framework,"):
526 if err := checkLinkerNonPathNonFile(source, raw, warg[len("-Wl,-framework,"):]); err != nil {
527 return err
528 }
529 case strings.HasPrefix(warg, "-Wl,-undefined,"), strings.HasPrefix(warg, "-Wl,-undefined="):
530 if err := checkLinkerNonPathNonFile(source, raw, warg[len("-Wl,-undefined,"):]); err != nil {
531 return err
532 }
533 case strings.HasPrefix(warg, "-Wl,--just-symbols,"), strings.HasPrefix(warg, "-Wl,--just-symbols="):
534 if err := checkLinkerObjOrDir(source, raw, warg[len("-Wl,--just-symbols,"):], allow); err != nil {
535 return err
536 }
537 case strings.HasPrefix(warg, "-Wl,-R"):
538 val := warg[len("-Wl,-R"):]
539 if after, ok := strings.CutPrefix(val, ","); ok {
540 val = after
541 } else if after, ok := strings.CutPrefix(val, "="); ok {
542 val = after
543 }
544 if err := checkLinkerObjOrDir(source, raw, val, allow); err != nil {
545 return err
546 }
547 case strings.HasPrefix(warg, "-Wl,-subsystem,"):
548
549
550
551 if cfg.Goos != "windows" {
552 if err := checkLinkerNonPathNonFile(source, raw, warg[len("-Wl,-subsystem,"):]); err != nil {
553 return err
554 }
555 }
556 case strings.HasPrefix(warg, "-Wl,-sectcreate,"):
557
558
559
560
561
562
563 parts := strings.SplitN(warg[len("-Wl,-sectcreate,"):], ",", 3)
564 if len(parts) == 3 {
565 if err := checkLinkerNonPathNonFile(source, raw, parts[0]); err != nil {
566 return err
567 }
568 if err := checkLinkerNonPathNonFile(source, raw, parts[1]); err != nil {
569 return err
570 }
571 if cfg.Goos != "darwin" && cfg.Goos != "ios" {
572 if fi, err := os.Stat(parts[2]); err == nil && !fi.IsDir() {
573 return fmt.Errorf("invalid flag in %s: %s (see https://go.dev/s/invalidflag)", source, raw)
574 }
575 }
576 }
577 }
578 }
579 return nil
580 }
581
582 func trimLinkerSysrootPrefix(dir string) string {
583 if strings.HasPrefix(dir, "=") {
584 return dir[1:]
585 }
586 if strings.HasPrefix(dir, "$SYSROOT") {
587 return dir[len("$SYSROOT"):]
588 }
589 return dir
590 }
591
592 var (
593 reDirectLinkerInput = re(`^(\./|[a-zA-Z0-9_/]).*\.(a|o|obj|dll|dylib|lib|so|tbd)$`)
594 reLinkerLibFile = re(`(\.(a|o|obj|dll|dylib|lib|so|tbd)$|\.so\.)`)
595 )
596
597
598
599
600
601 func isLocalLinkerPath(path string) bool {
602 if !filepath.IsAbs(path) {
603 return true
604 }
605 clean := filepath.Clean(path)
606 for _, root := range []string{base.Cwd(), cfg.GOMODCACHE, os.TempDir()} {
607 if root == "" {
608 continue
609 }
610 if str.HasFilePathPrefix(clean, filepath.Clean(root)) {
611 return true
612 }
613 if realRoot, err := filepath.EvalSymlinks(root); err == nil {
614 if realClean, err := filepath.EvalSymlinks(clean); err == nil && str.HasFilePathPrefix(realClean, realRoot) {
615 return true
616 }
617 }
618 }
619 return false
620 }
621
622 func checkLinkerSpecDir(source, dir string) error {
623 var allow *regexp.Regexp
624 if env := cfg.Getenv("CGO_LDFLAGS_ALLOW"); env != "" {
625 allow, _ = regexp.Compile(env)
626 }
627 return scanLinkerSearchDir(source, dir, false, allow)
628 }
629
630 func checkLinkerLibDir(source, dir string, allow *regexp.Regexp) error {
631 return scanLinkerSearchDir(source, dir, true, allow)
632 }
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649 func scanLinkerSearchDir(source, rawDir string, checkLibs bool, allow *regexp.Regexp) error {
650 dir := trimLinkerSysrootPrefix(rawDir)
651 if dir == "" || !isLocalLinkerPath(dir) {
652 return nil
653 }
654 visited := make(map[string]bool)
655 var checkTree func(root string) error
656 checkTree = func(root string) error {
657 if abs, err := filepath.Abs(root); err == nil {
658 root = abs
659 } else {
660 root = filepath.Clean(root)
661 }
662 if !isLocalLinkerPath(root) {
663 return nil
664 }
665 if resolved, err := filepath.EvalSymlinks(root); err == nil {
666 root = resolved
667 }
668 if visited[root] || !isLocalLinkerPath(root) {
669 return nil
670 }
671 visited[root] = true
672 if fi, err := os.Stat(root); err != nil || !fi.IsDir() {
673 return nil
674 }
675 return filepath.WalkDir(root, func(path string, d os.DirEntry, err error) error {
676 if err != nil {
677 return nil
678 }
679 if d.IsDir() {
680 if path != root && !isLocalLinkerPath(path) {
681 return filepath.SkipDir
682 }
683 return nil
684 }
685 if d.Type()&os.ModeSymlink != 0 {
686 if fi, err := os.Stat(path); err == nil && fi.IsDir() {
687 return checkTree(path)
688 }
689 }
690 lower := strings.ToLower(d.Name())
691 if lower == "specs" || strings.HasSuffix(lower, ".spec") {
692 if !matchAllow(allow, path) && !matchAllow(allow, d.Name()) {
693 return fmt.Errorf("disallowed GCC spec file in %s: %s", source, path)
694 }
695 }
696 if checkLibs && reLinkerLibFile.MatchString(lower) {
697 if !matchAllow(allow, path) && !matchAllow(allow, d.Name()) {
698 if err := checkLinkerInputFile(source, path); err != nil {
699 return err
700 }
701 }
702 }
703 return nil
704 })
705 }
706 if err := checkTree(dir); err != nil {
707 return err
708 }
709 if !checkLibs {
710 return nil
711 }
712
713
714
715
716 absDir := filepath.Clean(dir)
717 if abs, err := filepath.Abs(dir); err == nil {
718 absDir = abs
719 }
720 bases := []string{absDir}
721 if resolved, err := filepath.EvalSymlinks(absDir); err == nil {
722 if abs, err := filepath.Abs(resolved); err == nil {
723 resolved = abs
724 }
725 if resolved != absDir {
726 bases = append(bases, resolved)
727 }
728 }
729 for _, base := range bases {
730
731
732
733 if parent := filepath.Dir(base); parent == base || filepath.Dir(parent) == parent {
734 continue
735 }
736 for _, sub := range []string{"lib", "lib32", "lib64", "libx32"} {
737 if err := checkTree(filepath.Join(base, "..", sub)); err != nil {
738 return err
739 }
740 }
741 }
742 return nil
743 }
744
745
746
747
748
749 func checkLinkerInputFile(source, path string) error {
750 f, err := os.Open(path)
751 if err != nil {
752 if os.IsNotExist(err) {
753 return nil
754 }
755 return err
756 }
757 defer f.Close()
758
759 fi, err := f.Stat()
760 if err != nil {
761 return err
762 }
763
764 if strings.HasSuffix(strings.ToLower(path), ".tbd") && source != ".syso" {
765 var hdr [256]byte
766 n, _ := f.Read(hdr[:])
767 s := strings.TrimSpace(string(hdr[:n]))
768 if !strings.HasPrefix(s, "---") && !strings.HasPrefix(s, "{") {
769 return fmt.Errorf("invalid .tbd file in %s: %s", source, path)
770 }
771 return nil
772 }
773
774 return checkLinkerObjectRegion(source, path, io.NewSectionReader(f, 0, fi.Size()), 0)
775 }
776
777
778
779
780
781
782
783
784 func isDisallowedLTOSection(name string) bool {
785 return strings.HasPrefix(name, ".gnu.lto_") ||
786 strings.HasPrefix(name, ".gnu.debuglto_") ||
787 strings.HasPrefix(name, ".llvm.lto")
788 }
789
790 func isCOFFMachine(mach uint16) bool {
791 switch mach {
792 case pe.IMAGE_FILE_MACHINE_I386,
793 pe.IMAGE_FILE_MACHINE_AMD64,
794 pe.IMAGE_FILE_MACHINE_ARM,
795 pe.IMAGE_FILE_MACHINE_ARMNT,
796 pe.IMAGE_FILE_MACHINE_ARM64,
797 pe.IMAGE_FILE_MACHINE_LOONGARCH32,
798 pe.IMAGE_FILE_MACHINE_LOONGARCH64,
799 pe.IMAGE_FILE_MACHINE_RISCV32,
800 pe.IMAGE_FILE_MACHINE_RISCV64,
801 pe.IMAGE_FILE_MACHINE_RISCV128:
802 return true
803 }
804 return false
805 }
806
807
808
809 type coffReaderAt struct {
810 r *io.SectionReader
811 }
812
813 func (c coffReaderAt) ReadAt(p []byte, off int64) (int, error) {
814 if off == 0 && len(p) == 96 && c.r.Size() >= 20 && c.r.Size() < 96 {
815 clear(p)
816 if _, err := c.r.ReadAt(p[:c.r.Size()], 0); err != nil {
817 return 0, err
818 }
819 return len(p), nil
820 }
821 return c.r.ReadAt(p, off)
822 }
823
824 func checkLinkerArchive(source, path string, r *io.SectionReader, depth int) error {
825 if source == ".syso" {
826 return fmt.Errorf("archive not allowed as .syso in %s: %s", source, path)
827 }
828 off := int64(8)
829 memberIdx := 0
830 slashCount := 0
831 sawLongNames := false
832 var arhdr [60]byte
833 for off+60 <= r.Size() {
834 if _, err := r.ReadAt(arhdr[:], off); err != nil {
835 return fmt.Errorf("malformed archive in %s: %s", source, path)
836 }
837 if arhdr[58] != '`' || arhdr[59] != '\n' {
838 return fmt.Errorf("malformed archive header in %s: %s", source, path)
839 }
840 name := strings.TrimSpace(string(arhdr[0:16]))
841 sizeStr := strings.TrimSpace(string(arhdr[48:58]))
842 sz, err := strconv.ParseInt(sizeStr, 10, 64)
843 if err != nil || sz < 0 || off+60+sz > r.Size() {
844 return fmt.Errorf("malformed archive member size in %s: %s", source, path)
845 }
846 off += 60
847 switch {
848 case name == "__.SYMDEF" || name == "__.SYMDEF SORTED":
849 if memberIdx != 0 {
850 return fmt.Errorf("unexpected archive symbol table member %q in %s: %s", name, source, path)
851 }
852 case name == "/":
853 if memberIdx != slashCount || slashCount >= 2 || sawLongNames {
854 return fmt.Errorf("unexpected archive symbol table member %q in %s: %s", name, source, path)
855 }
856 if slashCount == 0 {
857 if err := checkArchiveFirstLinkerMember(source, path, r, off, sz); err != nil {
858 return err
859 }
860 } else {
861 if err := checkPESecondLinkerMember(source, path, r, off, sz); err != nil {
862 return err
863 }
864 }
865 slashCount++
866 case name == "//":
867 if memberIdx != slashCount || sawLongNames {
868 return fmt.Errorf("unexpected archive string table member in %s: %s", source, path)
869 }
870 sawLongNames = true
871
872
873 if sz >= 4 {
874 if err := checkLinkerObjectRegion(source, path, io.NewSectionReader(r, off, sz), depth+1); err == nil {
875 return fmt.Errorf("binary object disguised as archive string table in %s: %s", source, path)
876 } else if strings.Contains(err.Error(), "disallowed") {
877 return err
878 }
879 }
880 case strings.HasPrefix(name, "#1/"):
881 nameLen, err := strconv.ParseInt(name[3:], 10, 64)
882 if err != nil || nameLen <= 0 || nameLen > 4096 || nameLen > sz {
883 return fmt.Errorf("malformed BSD archive member in %s: %s", source, path)
884 }
885 nameBytes := make([]byte, nameLen)
886 if _, err := io.ReadFull(io.NewSectionReader(r, off, nameLen), nameBytes); err != nil {
887 return fmt.Errorf("malformed BSD archive member name in %s: %s", source, path)
888 }
889 realName := strings.TrimRight(string(nameBytes), "\x00")
890 isSymdef := memberIdx == 0 && (realName == "__.SYMDEF" || realName == "__.SYMDEF SORTED")
891 if !isSymdef {
892 if sz <= nameLen {
893 return fmt.Errorf("empty BSD archive member in %s: %s", source, path)
894 }
895 if err := checkLinkerObjectRegion(source, path, io.NewSectionReader(r, off+nameLen, sz-nameLen), depth+1); err != nil {
896 return err
897 }
898 }
899 default:
900 if sz <= 0 {
901 return fmt.Errorf("empty archive member in %s: %s", source, path)
902 }
903 if err := checkLinkerObjectRegion(source, path, io.NewSectionReader(r, off, sz), depth+1); err != nil {
904 return err
905 }
906 }
907 off += sz
908 if off&1 != 0 {
909 off++
910 }
911 memberIdx++
912 }
913 if off != r.Size() {
914 return fmt.Errorf("truncated or trailing data in archive in %s: %s", source, path)
915 }
916 return nil
917 }
918
919
920
921
922
923
924
925
926 func checkArchiveFirstLinkerMember(source, path string, r *io.SectionReader, off, sz int64) error {
927 if sz == 0 {
928 return nil
929 }
930 if sz < 4 {
931 return fmt.Errorf("malformed archive symbol table in %s: %s", source, path)
932 }
933 var shdr [4]byte
934 if _, err := r.ReadAt(shdr[:], off); err != nil {
935 return fmt.Errorf("malformed archive symbol table in %s: %s", source, path)
936 }
937 if shdr == [4]byte{0, 0, 0xff, 0xff} {
938 return fmt.Errorf("binary object disguised as archive symbol table in %s: %s", source, path)
939 }
940 numSyms := int64(binary.BigEndian.Uint32(shdr[:]))
941 if 4+4*numSyms > sz {
942 return fmt.Errorf("malformed archive symbol table in %s: %s", source, path)
943 }
944 return nil
945 }
946
947
948
949
950
951 func checkPESecondLinkerMember(source, path string, r *io.SectionReader, off, sz int64) error {
952 if sz < 8 {
953 return fmt.Errorf("malformed PE archive second linker member in %s: %s", source, path)
954 }
955 var mhdr [8]byte
956 if _, err := r.ReadAt(mhdr[:], off); err != nil {
957 return fmt.Errorf("malformed PE archive second linker member in %s: %s", source, path)
958 }
959 numMembers := int64(binary.LittleEndian.Uint32(mhdr[0:4]))
960 if numMembers > r.Size()/60 || 4+4*numMembers+4 > sz {
961 return fmt.Errorf("malformed PE archive second linker member in %s: %s", source, path)
962 }
963 var symCountBuf [4]byte
964 if _, err := r.ReadAt(symCountBuf[:], off+4+4*numMembers); err != nil {
965 return fmt.Errorf("malformed PE archive second linker member in %s: %s", source, path)
966 }
967 numSyms := int64(binary.LittleEndian.Uint32(symCountBuf[:]))
968 if 4+4*numMembers+4+2*numSyms > sz {
969 return fmt.Errorf("malformed PE archive second linker member in %s: %s", source, path)
970 }
971 return nil
972 }
973
974
975
976
977 func checkPEImportObject(source, path string, r *io.SectionReader) error {
978 if r.Size() < 20 {
979 return fmt.Errorf("invalid PE import object header in %s: %s", source, path)
980 }
981 var hdr [20]byte
982 if _, err := r.ReadAt(hdr[:], 0); err != nil {
983 return fmt.Errorf("invalid PE import object header in %s: %s", source, path)
984 }
985 mach := binary.LittleEndian.Uint16(hdr[6:8])
986 if !isCOFFMachine(mach) {
987 return fmt.Errorf("invalid PE import object machine %#x in %s: %s", mach, source, path)
988 }
989 sizeOfData := binary.LittleEndian.Uint32(hdr[12:16])
990 if sizeOfData < 4 || sizeOfData > 1<<20 || 20+int64(sizeOfData) != r.Size() {
991 return fmt.Errorf("invalid PE import object size in %s: %s", source, path)
992 }
993 flags := binary.LittleEndian.Uint16(hdr[18:20])
994 typ := flags & 0x3
995 nameType := (flags >> 2) & 0x7
996 if typ > 2 || nameType > 3 || flags>>5 != 0 {
997 return fmt.Errorf("invalid PE import object type flags %#x in %s: %s", flags, source, path)
998 }
999 data := make([]byte, sizeOfData)
1000 if _, err := io.ReadFull(io.NewSectionReader(r, 20, int64(sizeOfData)), data); err != nil {
1001 return fmt.Errorf("cannot read PE import object data in %s: %s: %v", source, path, err)
1002 }
1003 sep := bytes.IndexByte(data, 0)
1004 if sep <= 0 || sep >= len(data)-2 || data[len(data)-1] != 0 || bytes.IndexByte(data[sep+1:len(data)-1], 0) >= 0 {
1005 return fmt.Errorf("invalid PE import object strings in %s: %s", source, path)
1006 }
1007 return nil
1008 }
1009
1010 func checkLinkerBigArchive(source, path string, r *io.SectionReader, depth int) error {
1011 if source == ".syso" {
1012 return fmt.Errorf("archive not allowed as .syso in %s: %s", source, path)
1013 }
1014 if r.Size() < 128 {
1015 return fmt.Errorf("malformed AIX big archive header in %s: %s", source, path)
1016 }
1017 var fhdr [128]byte
1018 if _, err := r.ReadAt(fhdr[:], 0); err != nil {
1019 return fmt.Errorf("malformed AIX big archive header in %s: %s", source, path)
1020 }
1021 parseDec := func(b []byte) (int64, error) {
1022 return strconv.ParseInt(strings.TrimSpace(string(b)), 10, 64)
1023 }
1024 off, err := parseDec(fhdr[68:88])
1025 if err != nil || off < 0 || (off > 0 && off < 128) || off > r.Size() {
1026 return fmt.Errorf("malformed AIX big archive first member offset in %s: %s", source, path)
1027 }
1028 if off == 0 {
1029 return nil
1030 }
1031 lastoff, err := parseDec(fhdr[88:108])
1032 if err != nil || lastoff < off || lastoff > r.Size() {
1033 return fmt.Errorf("malformed AIX big archive last member offset in %s: %s", source, path)
1034 }
1035 var mhdr [112]byte
1036 for {
1037 if off+112 > r.Size() {
1038 return fmt.Errorf("malformed AIX big archive member header in %s: %s", source, path)
1039 }
1040 if _, err := r.ReadAt(mhdr[:], off); err != nil {
1041 return fmt.Errorf("malformed AIX big archive member header in %s: %s", source, path)
1042 }
1043 sz, err := parseDec(mhdr[0:20])
1044 if err != nil || sz < 0 {
1045 return fmt.Errorf("malformed AIX big archive member size in %s: %s", source, path)
1046 }
1047 namlen, err := parseDec(mhdr[108:112])
1048 if err != nil || namlen <= 0 || namlen > 4096 {
1049 return fmt.Errorf("malformed AIX big archive member name length in %s: %s", source, path)
1050 }
1051 fileoff := off + 112 + namlen
1052 if fileoff&1 != 0 {
1053 fileoff++
1054 }
1055 var fmag [2]byte
1056 if fileoff+2 > r.Size() || sz > r.Size()-(fileoff+2) {
1057 return fmt.Errorf("malformed AIX big archive member bounds in %s: %s", source, path)
1058 }
1059 if _, err := r.ReadAt(fmag[:], fileoff); err != nil || fmag[0] != '`' || fmag[1] != '\n' {
1060 return fmt.Errorf("malformed AIX big archive member magic in %s: %s", source, path)
1061 }
1062 fileoff += 2
1063 if namlen > 0 {
1064 if sz == 0 {
1065 return fmt.Errorf("empty AIX big archive member in %s: %s", source, path)
1066 }
1067 if err := checkLinkerObjectRegion(source, path, io.NewSectionReader(r, fileoff, sz), depth+1); err != nil {
1068 return err
1069 }
1070 }
1071 if off == lastoff {
1072 break
1073 }
1074 nextoff, err := parseDec(mhdr[20:40])
1075 if err != nil || nextoff < fileoff+sz || nextoff > lastoff {
1076 return fmt.Errorf("malformed AIX big archive next member offset in %s: %s", source, path)
1077 }
1078 off = nextoff
1079 }
1080 return nil
1081 }
1082
1083
1084
1085
1086
1087 func hasCOFFControlBeforeComment(buf []byte) bool {
1088 for i := 0; i < len(buf); i++ {
1089 if i+1 < len(buf) && buf[i] == '/' && buf[i+1] == '*' {
1090 return false
1091 }
1092 if buf[i] < 0x09 || (buf[i] > 0x0d && buf[i] < 0x20) || buf[i] == 0x7f {
1093 return true
1094 }
1095 }
1096 return false
1097 }
1098
1099 func checkLinkerObjectRegion(source, path string, r *io.SectionReader, depth int) error {
1100 if depth > 4 {
1101 return fmt.Errorf("nested archive/fat object too deep in %s: %s", source, path)
1102 }
1103 var hdr [64]byte
1104 n, _ := io.ReadFull(r, hdr[:])
1105 if n < 4 {
1106 return fmt.Errorf("invalid object file in %s: %s", source, path)
1107 }
1108 buf := hdr[:n]
1109
1110 if bytes.HasPrefix(buf, []byte("!<arch>\n")) {
1111 return checkLinkerArchive(source, path, r, depth)
1112 }
1113 if bytes.HasPrefix(buf, []byte("<bigaf>\n")) {
1114 return checkLinkerBigArchive(source, path, r, depth)
1115 }
1116
1117
1118
1119 if source != ".syso" && n >= 6 && binary.LittleEndian.Uint16(buf[0:2]) == 0x0000 && binary.LittleEndian.Uint16(buf[2:4]) == 0xffff && binary.LittleEndian.Uint16(buf[4:6]) == 0 {
1120 return checkPEImportObject(source, path, r)
1121 }
1122
1123
1124
1125
1126
1127
1128 mach := binary.LittleEndian.Uint16(buf[0:2])
1129 isMZ := bytes.HasPrefix(buf, []byte("MZ")) && source != ".syso" && binary.LittleEndian.Uint16(buf[2:4]) < 0x200
1130 isCOFF := !isMZ && n >= 20 && isCOFFMachine(mach) && hasCOFFControlBeforeComment(buf[:20])
1131 if isCOFF || isMZ {
1132 var coffBase int64
1133 if isMZ {
1134 if n < 0x40 {
1135 return fmt.Errorf("invalid PE DOS header in %s: %s", source, path)
1136 }
1137 signoff := int64(binary.LittleEndian.Uint32(buf[0x3c:0x40]))
1138 if signoff < 0 || signoff+4 > r.Size() {
1139 return fmt.Errorf("invalid PE signature offset in %s: %s", source, path)
1140 }
1141 coffBase = signoff + 4
1142 }
1143 var rAt io.ReaderAt = r
1144 if !isMZ {
1145 rAt = coffReaderAt{r}
1146 }
1147 pf, err := pe.NewFile(rAt)
1148 if err != nil {
1149 return fmt.Errorf("invalid PE/COFF object in %s: %s: %v", source, path, err)
1150 }
1151 if !isCOFFMachine(pf.FileHeader.Machine) || (isMZ && pf.OptionalHeader == nil) || len(pf.Sections) == 0 {
1152 return fmt.Errorf("invalid PE/COFF header or missing sections in %s: %s", source, path)
1153 }
1154 hdrEnd := coffBase + 20 + int64(pf.FileHeader.SizeOfOptionalHeader) + int64(pf.FileHeader.NumberOfSections)*40
1155 if hdrEnd > r.Size() {
1156 return fmt.Errorf("truncated PE/COFF section table in %s: %s", source, path)
1157 }
1158 if pf.FileHeader.PointerToSymbolTable != 0 {
1159 symOff := int64(pf.FileHeader.PointerToSymbolTable)
1160 symEnd := symOff + int64(pf.FileHeader.NumberOfSymbols)*18
1161 if symOff < hdrEnd || symEnd > r.Size() {
1162 return fmt.Errorf("invalid PE/COFF symbol table bounds in %s: %s", source, path)
1163 }
1164 }
1165 for _, sec := range pf.Sections {
1166 if sec.Offset != 0 {
1167 secEnd := int64(sec.Offset) + int64(sec.Size)
1168 if secEnd > r.Size() || (sec.Size > 0 && int64(sec.Offset) < hdrEnd) {
1169 return fmt.Errorf("invalid PE/COFF section %q bounds in %s: %s", sec.Name, source, path)
1170 }
1171 }
1172 secName := strings.TrimSpace(sec.Name)
1173 if isDisallowedLTOSection(secName) {
1174 return fmt.Errorf("disallowed LTO section %q in %s: %s", secName, source, path)
1175 }
1176 if secName == ".drectve" {
1177 if sec.Size == 0 || sec.Size > 1<<20 {
1178 return fmt.Errorf("suspicious .drectve section size (%d) in %s: %s", sec.Size, source, path)
1179 }
1180 data, err := sec.Data()
1181 if err != nil {
1182 return fmt.Errorf("cannot read .drectve section in %s: %s: %v", source, path, err)
1183 }
1184 if err := checkDrectveDirectives(source, path, data); err != nil {
1185 return err
1186 }
1187 }
1188 }
1189 return nil
1190 }
1191
1192
1193 magicLE := binary.LittleEndian.Uint32(buf[0:4])
1194 magicBE := binary.BigEndian.Uint32(buf[0:4])
1195 if magicLE == macho.Magic32 || magicLE == macho.Magic64 || magicBE == macho.Magic32 || magicBE == macho.Magic64 {
1196 mf, err := macho.NewFile(r)
1197 if err != nil {
1198 return fmt.Errorf("invalid Mach-O object in %s: %s: %v", source, path, err)
1199 }
1200 for _, l := range mf.Loads {
1201 if raw := l.Raw(); len(raw) >= 4 && mf.ByteOrder.Uint32(raw[:4]) == 0x2d {
1202 if err := checkMachOLinkerOption(source, path, mf.ByteOrder, raw); err != nil {
1203 return err
1204 }
1205 }
1206 if seg, ok := l.(*macho.Segment); ok {
1207 if seg.Name == "__GNU_LTO" {
1208 return fmt.Errorf("disallowed LTO segment %q in %s: %s", seg.Name, source, path)
1209 }
1210 }
1211 }
1212 for _, sec := range mf.Sections {
1213 if sec.Seg == "__GNU_LTO" || isDisallowedLTOSection(sec.Name) {
1214 return fmt.Errorf("disallowed LTO section %s,%s in %s: %s", sec.Seg, sec.Name, source, path)
1215 }
1216 }
1217 return nil
1218 }
1219
1220
1221
1222
1223 if magicBE == macho.MagicFat {
1224 if n < 8 {
1225 return fmt.Errorf("truncated universal Mach-O header in %s: %s", source, path)
1226 }
1227 nfat := int(binary.BigEndian.Uint32(buf[4:8]))
1228 if nfat <= 0 || nfat > 32 {
1229 return fmt.Errorf("invalid universal Mach-O arch count in %s: %s", source, path)
1230 }
1231 sr := io.NewSectionReader(r, 8, int64(nfat)*20)
1232 for i := 0; i < nfat; i++ {
1233 var fa macho.FatArchHeader
1234 if err := binary.Read(sr, binary.BigEndian, &fa); err != nil {
1235 return fmt.Errorf("truncated universal Mach-O arch header in %s: %s", source, path)
1236 }
1237 sliceOff := int64(fa.Offset)
1238 sliceSz := int64(fa.Size)
1239 if sliceOff < 0 || sliceSz <= 0 || sliceOff+sliceSz > r.Size() {
1240 return fmt.Errorf("invalid universal Mach-O slice bounds in %s: %s", source, path)
1241 }
1242 if err := checkLinkerObjectRegion(source, path, io.NewSectionReader(r, sliceOff, sliceSz), depth+1); err != nil {
1243 return err
1244 }
1245 }
1246 return nil
1247 }
1248
1249
1250 if bytes.HasPrefix(buf, []byte(elf.ELFMAG)) {
1251 ef, err := elf.NewFile(r)
1252 if err != nil {
1253 return fmt.Errorf("invalid ELF object in %s: %s: %v", source, path, err)
1254 }
1255 if ef.Type == elf.ET_REL && len(ef.Sections) == 0 {
1256 return fmt.Errorf("ELF relocatable object missing section headers in %s: %s", source, path)
1257 }
1258 for _, sec := range ef.Sections {
1259 if sec.Type == 0x6fff4c01 || sec.Type == 0x6fff4c04 {
1260 return fmt.Errorf("disallowed ELF embedded linker options section in %s: %s", source, path)
1261 }
1262 if sec.Type == 0x6fff4c0c {
1263 return fmt.Errorf("disallowed LLVM LTO section in %s: %s", source, path)
1264 }
1265 if isDisallowedLTOSection(sec.Name) {
1266 return fmt.Errorf("disallowed LTO section %q in %s: %s", sec.Name, source, path)
1267 }
1268 }
1269 return nil
1270 }
1271
1272
1273 magicBE16 := binary.BigEndian.Uint16(buf[0:2])
1274 if magicBE16 == xcoff.U802TOCMAGIC || magicBE16 == xcoff.U64_TOCMAGIC {
1275 if _, err := xcoff.NewFile(r); err != nil {
1276 return fmt.Errorf("invalid XCOFF object in %s: %s: %v", source, path, err)
1277 }
1278 return nil
1279 }
1280
1281
1282 if magicBE == plan9obj.Magic386 || magicBE == plan9obj.MagicAMD64 || magicBE == plan9obj.MagicARM {
1283 if _, err := plan9obj.NewFile(r); err != nil {
1284 return fmt.Errorf("invalid Plan 9 object in %s: %s: %v", source, path, err)
1285 }
1286 return nil
1287 }
1288
1289
1290 if bytes.HasPrefix(buf, []byte("\x00asm\x01\x00\x00\x00")) {
1291 return nil
1292 }
1293 return fmt.Errorf("invalid linker input file in %s: %s (unrecognized binary format)", source, path)
1294 }
1295
1296
1297
1298
1299
1300 func checkMachOLinkerOption(source, path string, bo binary.ByteOrder, raw []byte) error {
1301 if len(raw) < 12 {
1302 return fmt.Errorf("malformed LC_LINKER_OPTION in %s: %s", source, path)
1303 }
1304 count := bo.Uint32(raw[8:12])
1305 if count == 0 || count > 2 {
1306 return fmt.Errorf("disallowed LC_LINKER_OPTION in %s: %s", source, path)
1307 }
1308 rest := raw[12:]
1309 opts := make([]string, 0, count)
1310 for range count {
1311 nul := bytes.IndexByte(rest, 0)
1312 if nul <= 0 {
1313 return fmt.Errorf("disallowed LC_LINKER_OPTION in %s: %s", source, path)
1314 }
1315 opts = append(opts, string(rest[:nul]))
1316 rest = rest[nul+1:]
1317 }
1318 for _, b := range rest {
1319 if b != 0 {
1320 return fmt.Errorf("disallowed LC_LINKER_OPTION in %s: %s", source, path)
1321 }
1322 }
1323 switch len(opts) {
1324 case 1:
1325 arg := opts[0]
1326 if !strings.HasPrefix(arg, "-l") || len(arg) <= 2 || !load.SafeArg(arg[2:]) || strings.ContainsAny(arg[2:], `:=/\`) {
1327 return fmt.Errorf("disallowed LC_LINKER_OPTION %q in %s: %s", arg, source, path)
1328 }
1329 for _, re := range invalidLinkerFlags {
1330 if re.FindString(arg) == arg {
1331 return fmt.Errorf("disallowed LC_LINKER_OPTION %q in %s: %s", arg, source, path)
1332 }
1333 }
1334 return nil
1335 case 2:
1336 if (opts[0] == "-framework" || opts[0] == "-weak_framework") && load.SafeArg(opts[1]) {
1337 if err := checkLinkerNonPathNonFile(source, opts[0]+" "+opts[1], opts[1]); err == nil {
1338 return nil
1339 }
1340 }
1341 return fmt.Errorf("disallowed LC_LINKER_OPTION %q in %s: %s", strings.Join(opts, " "), source, path)
1342 }
1343 return fmt.Errorf("disallowed LC_LINKER_OPTION in %s: %s", source, path)
1344 }
1345
1346
1347
1348
1349
1350 func checkDrectveDirectives(source, path string, data []byte) error {
1351 content := strings.TrimPrefix(string(data), "\xef\xbb\xbf")
1352 content = strings.TrimRight(content, "\x00 \t\r\n")
1353 if content == "" {
1354 return nil
1355 }
1356 tokens := tokenizeDrectve(content)
1357 for _, tok := range tokens {
1358 if !isAllowedDrectve(tok) {
1359 return fmt.Errorf("disallowed .drectve directive %q in %s: %s", tok, source, path)
1360 }
1361 }
1362 return nil
1363 }
1364
1365 const drectveSpace = " \t\r\n\v\f\x00"
1366
1367 func tokenizeDrectve(s string) []string {
1368 var tokens []string
1369 s = strings.TrimLeft(s, drectveSpace)
1370 for len(s) > 0 {
1371 var tok strings.Builder
1372 inQuote := false
1373 i := 0
1374 for i < len(s) {
1375 if s[i] == '"' {
1376 inQuote = !inQuote
1377 i++
1378 continue
1379 }
1380 if !inQuote && strings.IndexByte(drectveSpace, s[i]) >= 0 {
1381 break
1382 }
1383 tok.WriteByte(s[i])
1384 i++
1385 }
1386 if tok.Len() > 0 {
1387 tokens = append(tokens, tok.String())
1388 }
1389 s = strings.TrimLeft(s[i:], drectveSpace)
1390 }
1391 return tokens
1392 }
1393
1394 var reDrectveSafeName = lazyregexp.New(`^[a-zA-Z0-9_.][a-zA-Z0-9_.+\-@$=]*$`)
1395
1396 func isAllowedDrectve(tok string) bool {
1397 if strings.ContainsAny(tok, "\r\n\v\f\x00") {
1398 return false
1399 }
1400 norm := strings.ToUpper(tok)
1401 if strings.HasPrefix(norm, "-") && !strings.HasPrefix(norm, "--") {
1402 norm = "/" + norm[1:]
1403 }
1404
1405 if strings.HasPrefix(norm, "/DEFAULTLIB:") ||
1406 strings.HasPrefix(norm, "/DISALLOWLIB:") ||
1407 strings.HasPrefix(norm, "/EXPORT:") ||
1408 strings.HasPrefix(norm, "/INCLUDE:") ||
1409 strings.HasPrefix(norm, "/ALTERNATENAME:") ||
1410 strings.HasPrefix(norm, "/MERGE:") ||
1411 strings.HasPrefix(norm, "/SECTION:") ||
1412 strings.HasPrefix(norm, "/ALIGNCOMM:") ||
1413 strings.HasPrefix(norm, "/EXCLUDE-SYMBOLS:") ||
1414 strings.HasPrefix(norm, "/FAILIFMISMATCH:") ||
1415 strings.HasPrefix(norm, "/MANIFESTDEPENDENCY:") {
1416 val := tok[strings.IndexByte(tok, ':')+1:]
1417 val = strings.Trim(val, `"`)
1418 if val == "" {
1419 return false
1420 }
1421 if strings.ContainsAny(val, `/\`) && !strings.HasPrefix(norm, "/MANIFESTDEPENDENCY:") {
1422 return false
1423 }
1424 if (strings.HasPrefix(norm, "/DEFAULTLIB:") || strings.HasPrefix(norm, "/DISALLOWLIB:")) && (strings.Contains(val, ":") || strings.HasPrefix(val, "@")) {
1425 return false
1426 }
1427 if strings.Contains(val, "..") {
1428 return false
1429 }
1430 return true
1431 }
1432
1433 if norm == "/NODEFAULTLIB" {
1434 return true
1435 }
1436 if strings.HasPrefix(norm, "/NODEFAULTLIB:") {
1437 val := strings.Trim(tok[strings.IndexByte(tok, ':')+1:], `"`)
1438 return val != "" && !strings.ContainsAny(val, `/\:`) && !strings.HasPrefix(val, "@") && !strings.Contains(val, "..")
1439 }
1440 if norm == "/SAFESEH" || norm == "/SAFESEH:NO" {
1441 return true
1442 }
1443 if norm == "/GUARD:CF" || norm == "/GUARD:NO" || norm == "/GUARD:EHCONT" || norm == "/GUARD:LONGJMP" {
1444 return true
1445 }
1446 if norm == "/DYNAMICBASE" || norm == "/DYNAMICBASE:NO" ||
1447 norm == "/NXCOMPAT" || norm == "/NXCOMPAT:NO" ||
1448 norm == "/CETCOMPAT" || norm == "/CETCOMPAT:NO" ||
1449 norm == "/HIGHENTROPYVA" || norm == "/HIGHENTROPYVA:NO" ||
1450 norm == "/LARGEADDRESSAWARE" || norm == "/LARGEADDRESSAWARE:NO" ||
1451 norm == "/TSAWARE" || norm == "/TSAWARE:NO" ||
1452 norm == "/EXPORT-ALL-SYMBOLS" || norm == "/EXCLUDE-ALL-SYMBOLS" {
1453 return true
1454 }
1455
1456 if strings.HasPrefix(tok, "-l") && len(tok) > 2 {
1457 libName := tok[2:]
1458 return reDrectveSafeName.MatchString(libName) && !strings.Contains(libName, "..")
1459 }
1460 switch tok {
1461 case "--enable-auto-import", "--disable-auto-import",
1462 "--enable-runtime-pseudo-reloc", "--disable-runtime-pseudo-reloc",
1463 "--enable-stdcall-fixup", "--disable-stdcall-fixup",
1464 "--export-all-symbols", "--exclude-all-symbols":
1465 return true
1466 }
1467 return false
1468 }
1469
1470 func checkPkgConfigFlags(name, source string, list []string) error {
1471 checkOverrides := false
1472 return checkFlags(name, source, list, nil, validPkgConfigFlags, nil, nil, checkOverrides)
1473 }
1474
1475 func validPkgConfigName(pkg string) bool {
1476 if !load.SafeArg(pkg) || !utf8.ValidString(pkg) {
1477 return false
1478 }
1479 if strings.ContainsAny(pkg, `/\:`) || strings.Contains(pkg, "..") {
1480 return false
1481 }
1482 fields := strings.FieldsFunc(pkg, func(r rune) bool {
1483 return r == ',' || unicode.IsSpace(r)
1484 })
1485 if len(fields) == 0 {
1486 return false
1487 }
1488 for _, field := range fields {
1489 lower := strings.ToLower(field)
1490 if strings.HasSuffix(lower, ".pc") {
1491 return false
1492 }
1493 for i := range len(lower) {
1494 if strings.IndexByte("<>=!", lower[i]) >= 0 && strings.HasSuffix(lower[:i], ".pc") {
1495 return false
1496 }
1497 }
1498 }
1499 return true
1500 }
1501
1502
1503
1504
1505
1506 func checkCompilerFlagsForInternalLink(name, source string, list []string) error {
1507 checkOverrides := false
1508 if err := checkFlags(name, source, list, invalidCompilerFlags, validCompilerFlags, nil, validCompilerFlagsWithNextArg, checkOverrides); err != nil {
1509 return err
1510 }
1511
1512
1513
1514
1515 for _, fl := range list {
1516 if strings.HasPrefix(fl, "-flto") {
1517 return fmt.Errorf("flag %q triggers external linking", fl)
1518 }
1519 if fl == "-static" || fl == "--static" {
1520 return fmt.Errorf("flag %q triggers external linking", fl)
1521 }
1522 }
1523 return nil
1524 }
1525
1526
1527
1528 func checkLinkerFlagsForInternalLink(name, source string, list []string) error {
1529 checkOverrides := false
1530 if err := checkFlags(name, source, list, invalidLinkerFlags, validLinkerFlags, recombinedLinkerFlagsWithNextArg, validLinkerFlagsWithNextArg, checkOverrides); err != nil {
1531 return err
1532 }
1533
1534
1535 for _, fl := range list {
1536 if fl == "-static" || fl == "--static" ||
1537 fl == "-Wl,-static" || fl == "-Wl,--static" ||
1538 fl == "-Wl,-Bstatic" {
1539 return fmt.Errorf("flag %q triggers external linking", fl)
1540 }
1541 }
1542 return nil
1543 }
1544
1545 func checkFlags(name, source string, list []string, invalid, valid []*lazyregexp.Regexp, recombineNext, validNext []string, checkOverrides bool) error {
1546
1547 var (
1548 allow *regexp.Regexp
1549 disallow *regexp.Regexp
1550 )
1551 if checkOverrides {
1552 if env := cfg.Getenv("CGO_" + name + "_ALLOW"); env != "" {
1553 r, err := regexp.Compile(env)
1554 if err != nil {
1555 return fmt.Errorf("parsing $CGO_%s_ALLOW: %v", name, err)
1556 }
1557 allow = r
1558 }
1559 if env := cfg.Getenv("CGO_" + name + "_DISALLOW"); env != "" {
1560 r, err := regexp.Compile(env)
1561 if err != nil {
1562 return fmt.Errorf("parsing $CGO_%s_DISALLOW: %v", name, err)
1563 }
1564 disallow = r
1565 }
1566 }
1567
1568 Args:
1569 for i := 0; i < len(list); i++ {
1570 arg := list[i]
1571 if matchAllow(disallow, arg) {
1572 goto Bad
1573 }
1574 if slices.Contains(validNext, arg) && i+1 < len(list) {
1575 next := list[i+1]
1576 if matchAllow(disallow, next) || matchAllow(disallow, arg+" "+next) || matchAllow(disallow, arg+next) {
1577 goto Bad
1578 }
1579 if matchAllow(allow, arg+" "+next) || matchAllow(allow, arg+next) {
1580 i++
1581 continue Args
1582 }
1583 } else if matchAllow(allow, arg) {
1584 continue Args
1585 }
1586 for _, re := range invalid {
1587 if re.FindString(arg) == arg {
1588 goto Bad
1589 }
1590 }
1591 for _, re := range valid {
1592 if match := re.FindString(arg); match == arg {
1593 continue Args
1594 } else if strings.HasPrefix(arg, "-Wl,--push-state,") {
1595
1596
1597
1598 args := strings.Split(arg, ",")
1599 for _, a := range args[1:] {
1600 a = "-Wl," + a
1601 var found bool
1602 for _, re := range valid {
1603 if re.FindString(a) == a {
1604 found = true
1605 break
1606 }
1607 }
1608 if !found {
1609 goto Bad
1610 }
1611 for _, re := range invalid {
1612 if re.FindString(a) == a {
1613 goto Bad
1614 }
1615 }
1616 }
1617 continue Args
1618 }
1619 }
1620 if slices.Contains(recombineNext, arg) && i+1 < len(list) {
1621 combined := arg + list[i+1]
1622 if disallow != nil && disallow.FindString(combined) == combined {
1623 goto Bad
1624 }
1625 if allow == nil || allow.FindString(combined) != combined {
1626 for _, re := range invalid {
1627 if re.FindString(combined) == combined {
1628 goto Bad
1629 }
1630 }
1631 }
1632 }
1633 for _, x := range validNext {
1634 if arg == x {
1635 if arg == "-x" {
1636 if i+1 < len(list) && validCompilerXLang.MatchString(list[i+1]) {
1637 i++
1638 continue Args
1639 }
1640 if i+1 < len(list) {
1641 return fmt.Errorf("invalid flag in %s: %s %s (see https://go.dev/s/invalidflag)", source, arg, list[i+1])
1642 }
1643 return fmt.Errorf("invalid flag in %s: %s without argument (see https://go.dev/s/invalidflag)", source, arg)
1644 }
1645 if strings.HasPrefix(arg, "-Wl,") {
1646
1647 if i+1 < len(list) &&
1648 strings.HasPrefix(list[i+1], "-Wl,") &&
1649 load.SafeArg(list[i+1][4:]) &&
1650 !strings.Contains(list[i+1][4:], ",") {
1651 i++
1652 continue Args
1653 }
1654
1655 if arg == "-Wl,-R" && i+1 < len(list) && load.SafeArg(list[i+1]) {
1656 i++
1657 continue Args
1658 }
1659 if i+1 < len(list) {
1660 return fmt.Errorf("invalid flag in %s: %s %s (see https://go.dev/s/invalidflag)", source, arg, list[i+1])
1661 }
1662 return fmt.Errorf("invalid flag in %s: %s without argument (see https://go.dev/s/invalidflag)", source, arg)
1663 }
1664 if arg == "-l" {
1665 if i+1 < len(list) && load.SafeArg(list[i+1]) && !strings.ContainsAny(list[i+1], `:=/\`) {
1666 i++
1667 continue Args
1668 }
1669 if i+1 < len(list) {
1670 return fmt.Errorf("invalid flag in %s: %s %s (see https://go.dev/s/invalidflag)", source, arg, list[i+1])
1671 }
1672 return fmt.Errorf("invalid flag in %s: %s without argument (see https://go.dev/s/invalidflag)", source, arg)
1673 }
1674 if i+1 < len(list) && load.SafeArg(list[i+1]) {
1675 i++
1676 continue Args
1677 }
1678
1679
1680 if i+1 < len(list) && arg == "-I" {
1681 if (strings.HasPrefix(list[i+1], "=") || strings.HasPrefix(list[i+1], "$SYSROOT")) &&
1682 load.SafeArg(list[i+1][1:]) {
1683 i++
1684 continue Args
1685 }
1686 }
1687
1688 if i+1 < len(list) {
1689 return fmt.Errorf("invalid flag in %s: %s %s (see https://go.dev/s/invalidflag)", source, arg, list[i+1])
1690 }
1691 return fmt.Errorf("invalid flag in %s: %s without argument (see https://go.dev/s/invalidflag)", source, arg)
1692 }
1693 }
1694 Bad:
1695 return fmt.Errorf("invalid flag in %s: %s (see https://go.dev/s/invalidflag)", source, arg)
1696 }
1697 return nil
1698 }
1699
View as plain text