diff --git a/src/cmd/cgo/internal/testerrors/errors_test.go b/src/cmd/cgo/internal/testerrors/errors_test.go index 486530e186..870d05b491 100644 --- a/src/cmd/cgo/internal/testerrors/errors_test.go +++ b/src/cmd/cgo/internal/testerrors/errors_test.go @@ -111,6 +111,7 @@ func TestReportsTypeErrors(t *testing.T) { for _, file := range []string{ "err1.go", "err2.go", + "err5.go", "issue11097a.go", "issue11097b.go", "issue18452.go", diff --git a/src/cmd/cgo/internal/testerrors/testdata/err5.go b/src/cmd/cgo/internal/testerrors/testdata/err5.go new file mode 100644 index 0000000000..779d745ba7 --- /dev/null +++ b/src/cmd/cgo/internal/testerrors/testdata/err5.go @@ -0,0 +1,10 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +//line /tmp/_cgo_.go:1 +//go:cgo_dynamic_linker "/elf/interp" // ERROR HERE: only allowed in cgo-generated code + +func main() {} diff --git a/src/cmd/compile/internal/noder/noder.go b/src/cmd/compile/internal/noder/noder.go index 25a6ba7c88..94071581fe 100644 --- a/src/cmd/compile/internal/noder/noder.go +++ b/src/cmd/compile/internal/noder/noder.go @@ -333,8 +333,14 @@ func (p *noder) pragma(pos syntax.Pos, blankLine bool, text string, old syntax.P // contain cgo directives, and for security reasons // (primarily misuse of linker flags), other files are not. // See golang.org/issue/23672. +// Note that cmd/go ignores files whose names start with underscore, +// so the only _cgo_ files we will see from cmd/go are generated by cgo. +// It's easy to bypass this check by calling the compiler directly; +// we only protect against uses by cmd/go. func isCgoGeneratedFile(pos syntax.Pos) bool { - return strings.HasPrefix(filepath.Base(trimFilename(pos.Base())), "_cgo_") + // We need the absolute file, independent of //line directives, + // so we call pos.Base().Pos(). + return strings.HasPrefix(filepath.Base(trimFilename(pos.Base().Pos().Base())), "_cgo_") } // safeArg reports whether arg is a "safe" command-line argument,