Compare commits

..

132 Commits

Author SHA1 Message Date
Gopher Robot
8a4c24f9bb [release-branch.go1.24] go1.24rc2
Change-Id: I37362fe37c47078c17f3f6f610d8ca7664985bd0
Reviewed-on: https://go-review.googlesource.com/c/go/+/643157
Auto-Submit: Gopher Robot <gobot@golang.org>
Reviewed-by: Michael Pratt <mpratt@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Michael Knyszek <mknyszek@google.com>
2025-01-16 12:13:48 -08:00
Filippo Valsorda
3de5aca7d0 [release-branch.go1.24] crypto/x509: avoid panic when parsing partial PKCS#1 private keys
These keys are off-spec, but have historically been accepted by
ParsePKCS1PrivateKey.

Thanks to Philippe Antoine (Catena cyber) for reporting this issue.

Fixes #71216
Fixes CVE-2025-22865

Change-Id: I6a6a46564156fa32e29e8d6acbec3fbac47c7352
Reviewed-on: https://go-internal-review.googlesource.com/c/go/+/1820
Reviewed-by: Tatiana Bradley <tatianabradley@google.com>
Reviewed-by: Damien Neil <dneil@google.com>
Commit-Queue: Roland Shoemaker <bracewell@google.com>
(cherry picked from commit 36c6c8b6957e155770461fd710aea9477ef3bc88)
Reviewed-on: https://go-internal-review.googlesource.com/c/go/+/1841
Reviewed-on: https://go-review.googlesource.com/c/go/+/643102
Auto-Submit: Michael Knyszek <mknyszek@google.com>
Reviewed-by: Michael Pratt <mpratt@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2025-01-16 11:36:09 -08:00
Sam Thanawalla
8336dfde70 [release-branch.go1.24] cmd/go: restore netrc preferences for GOAUTH and fix domain lookup
Store netrc lines into the credential map backward so that earlier lines
take priority over later lines. This matches Go 1.23 netrc lookup which
stopped at the first match it found.
Additionally, this fixes a security issue related to domain parsing
which could have allowed servers to read credentials belonging to other
servers. The fix was to switch from using path.Dir(currentPrefix) to
strings.Cut(currentPrefix, "/")

Thanks to Juho Forsén of Mattermost for reporting this issue.

Fixes #71249
Fixes CVE-2024-45340

Change-Id: I175a00d6d7f4d31c9e4d79b7cf1c2a0ad35b2781
Reviewed-on: https://go-internal-review.googlesource.com/c/go/+/1781
Reviewed-by: Tatiana Bradley <tatianabradley@google.com>
Commit-Queue: Roland Shoemaker <bracewell@google.com>
Reviewed-by: Roland Shoemaker <bracewell@google.com>
Reviewed-by: Damien Neil <dneil@google.com>
(cherry picked from commit 76833d221aa3ccc978b6f41bd24e26babf771375)
Reviewed-on: https://go-internal-review.googlesource.com/c/go/+/1840
Reviewed-on: https://go-review.googlesource.com/c/go/+/643101
Reviewed-by: Michael Pratt <mpratt@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Michael Knyszek <mknyszek@google.com>
2025-01-16 11:36:07 -08:00
Damien Neil
6b60550504 [release-branch.go1.24] net/http: persist header stripping across repeated redirects
When an HTTP redirect changes the host of a request, we drop
sensitive headers such as Authorization from the redirected request.
Fix a bug where a chain of redirects could result in sensitive
headers being sent to the wrong host:

  1. request to a.tld with Authorization header
  2. a.tld redirects to b.tld
  3. request to b.tld with no Authorization header
  4. b.tld redirects to b.tld
  3. request to b.tld with Authorization header restored

Thanks to Kyle Seely for reporting this issue.

For #70530
Fixes #71212
Fixes CVE-2024-45336

Change-Id: Ia58a2e10d33d6b0cc7220935e771450e5c34de72
Reviewed-on: https://go-internal-review.googlesource.com/c/go/+/1641
Reviewed-by: Roland Shoemaker <bracewell@google.com>
Reviewed-by: Tatiana Bradley <tatianabradley@google.com>
Commit-Queue: Roland Shoemaker <bracewell@google.com>
(cherry picked from commit 2889169b87a61f1218a02994feb80fd3d8bfa87c)
Reviewed-on: https://go-internal-review.googlesource.com/c/go/+/1766
Reviewed-on: https://go-review.googlesource.com/c/go/+/643100
Auto-Submit: Michael Knyszek <mknyszek@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Michael Pratt <mpratt@google.com>
2025-01-16 11:36:03 -08:00
Roland Shoemaker
468fad45a2 [release-branch.go1.24] crypto/x509: properly check for IPv6 hosts in URIs
When checking URI constraints, use netip.ParseAddr, which understands
zones, unlike net.ParseIP which chokes on them. This prevents zone IDs
from mistakenly satisfying URI constraints.

Thanks to Juho Forsén of Mattermost for reporting this issue.

For #71156
Fixes #71209
Fixes CVE-2024-45341

Change-Id: Iecac2529f3605382d257996e0fb6d6983547e400
Reviewed-on: https://go-internal-review.googlesource.com/c/go/+/1700
Reviewed-by: Tatiana Bradley <tatianabradley@google.com>
Reviewed-by: Damien Neil <dneil@google.com>
(cherry picked from commit 22ca55d396ba801e6ae9b2bd67a059fcb30562fd)
Reviewed-on: https://go-internal-review.googlesource.com/c/go/+/1800
Commit-Queue: Roland Shoemaker <bracewell@google.com>
Reviewed-by: Roland Shoemaker <bracewell@google.com>
Reviewed-on: https://go-review.googlesource.com/c/go/+/643099
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Michael Knyszek <mknyszek@google.com>
Reviewed-by: Michael Pratt <mpratt@google.com>
2025-01-16 11:08:59 -08:00
Michael Pratt
e06b6fc58d [release-branch.go1.24] all: merge master (e966a27) into release-branch.go1.24
Merge List:

+ 2025-01-08 e966a2773c crypto/internal/fips140/drbg: avoid global lock on rand state

Change-Id: I1ca8f6bf2ba14ff3d5c4183a26cbd51ac20dad0a
2025-01-08 14:01:58 -05:00
Russ Cox
e966a2773c crypto/internal/fips140/drbg: avoid global lock on rand state
Having a global lock on the random state (used only in FIPS-140 mode)
introduces contention in concurrent programs. Use an approximately
per-P random state instead, using sync.Pool to manage per-P state.

This code is important to land for the Go 1.24 release because it is
part of the FIPS-140 module that will be validated and certified,
so it will live for a long time. We otherwise wouldn't be able to
correct this contention for at least a year, perhaps more.

At the same time, the code is only used in the FIPS-140 mode,
so there is no risk to normal programs.

Fixes #71155.

Change-Id: I6b779f15ddfdf232f608f5cda08f75906e58114f
Reviewed-on: https://go-review.googlesource.com/c/go/+/641097
Reviewed-by: Austin Clements <austin@google.com>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Michael Knyszek <mknyszek@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2025-01-08 10:28:31 -08:00
Michael Pratt
b3799ba634 [release-branch.go1.24] all: merge master (9a44df6) into release-branch.go1.24
Merge List:

+ 2025-01-08 9a44df6675 cmd/go/testdata/script: fix TestScript/env_gocacheprog on Windows
+ 2025-01-08 f025d19e7b runtime: hold traceAcquire across casgstatus in injectglist
+ 2025-01-08 1e9835f5b1 internal/sync: fix typo of panic message
+ 2025-01-07 39f2032c17 testing/synctest: add some examples
+ 2025-01-07 b50ccef67a cmd/go/internal/modindex: don't write index entry if file open
+ 2025-01-07 b2aa18b96c cmd/internal/hash: stop using md5, sha1
+ 2025-01-07 d93b549f05 cmd/go/internal/cache: handle cacheprog not responding to close
+ 2025-01-07 d62154db83 weak: don't panic when calling Value on a zero Pointer
+ 2025-01-07 9d0772b23e cmd/compile/internal/syntax: add test case for invalid label use
+ 2025-01-07 1d20bce981 go/types, types2: expand documentation for Info.Types map
+ 2025-01-07 a9bd6239a4 cmd/go/internal/env: add GOCACHEPROG to go env output
+ 2025-01-07 850b276a67 crypto/tls: send illegal_parameter on invalid ECHClientHello.type
+ 2025-01-06 27c5164374 crypto/internal/fips140: zeroise integrity test temporary values
+ 2025-01-06 d8ad4af78b cmd/internal/disasm: correct instruction length handling for riscv64
+ 2025-01-06 a76cc5a4ec crypto/rsa: use λ(N) instead of φ(N)
+ 2025-01-06 3f002abb60 internal/sync: add test from issue 70970
+ 2025-01-06 7a2e88e911 net/http: update NewRequestWithContext wrong link to NewRequest
+ 2025-01-06 c112c0af13 Revert "internal/sync: optimize CompareAndSwap and Swap"
+ 2025-01-03 705b5a569a crypto/ecdsa: drop SEC 1 reference from package doc
+ 2025-01-03 f966695cce context: use "canceled" in docs to refer to timed-out contexts
+ 2025-01-03 5da026354c cmd/go/internal/vcweb: close the .access file
+ 2025-01-03 31cabcf084 crypto/internal/fips140: mark OpenBSD unsupported
+ 2025-01-03 eb0c2b2f96 crypto/internal/fips140: add Supported
+ 2025-01-03 f0a9b6df45 internal/fuzz: remove the exp2 method
+ 2025-01-03 5d626c49ec spec: fix a dead link
+ 2025-01-03 81566aff3a internal/exportdata: add missing return
+ 2025-01-03 e7a8bd5d8b crypto/internal/fips140/check: remove Enabled
+ 2025-01-02 4b652e9f5f cmd/go: fix two typos in helpdoc.go
+ 2025-01-02 0afd7e85e5 cmd/go: document GOCACHEPROG in go help environment
+ 2025-01-02 3c8e5b13df cmd/go/internal/cacheprog: drop redundant Prog prefixes
+ 2025-01-02 20da34c6d2 cmd/go: move GOCACHEPROG protocol types to their own package
+ 2025-01-02 858a0e9dfd crypto/tls: properly return ECH retry configs
+ 2025-01-02 a63aee4955 cmd/go: improve GOCACHEPROG types documentation
+ 2025-01-02 847c357bbb cmd/go: remove references to gopath-get
+ 2025-01-01 d1d9312950 crypto/tls: fix Config.Time in tests using expired certificates
+ 2024-12-31 94f15810e6 cmd/go: document default GOARM value
+ 2024-12-30 856a7bc8e9 builtin: use list instead of indentation for comments in cap, len, and make
+ 2024-12-30 5efb4239c6 spec: document that string conversions don't guarantee result slice capacity
+ 2024-12-30 0d8aa8cce6 spec: describe representation of values
+ 2024-12-30 8857a5a33f crypto/tls: fix misspelling in comment
+ 2024-12-30 3c4102bfd4 encoding/binary: add documentation for endian methods
+ 2024-12-30 b702a26cf8 os: mention fsys modifications during CopyFS
+ 2024-12-30 15f232456a encoding/json: remove suggestion on Unmarshaler with JSON null
+ 2024-12-30 ba1deb1cee cmd/link: document that -s implies -w
+ 2024-12-30 fd5e0d26d9 go/doc: resolve imports before predeclared identifiers in examples
+ 2024-12-30 a785d11ac4 unique: fix typo
+ 2024-12-27 2b794ed86c encoding/json: expand and modernize TestInterfaceSet
+ 2024-12-27 e3cd55e9d2 cmd/go/internal/work: allow @ character in some -Wl, linker flags on darwin
+ 2024-12-27 39794819aa doc/initial: remove fixed-width spacing notice
+ 2024-12-27 7c03fe70b8 cmd/compile: improve compiler directive docs
+ 2024-12-27 d7c3e93c16 iter: improve documentation with iterator example
+ 2024-12-26 cce75da30b crypto/mlkem: swap order of return values of Encapsulate
+ 2024-12-23 772f024c61 weak: fix typo in warning about tiny allocator optimization
+ 2024-12-23 b9955f0ad9 cmd/link, runtime: apply a delta to RODATA->DATA relocations
+ 2024-12-23 eef35e3bd9 internal/goexperiment: run go generate for synctest
+ 2024-12-23 9f6c80a76a cmd/go/internal/work: allow single character values in -Wl, linker flags
+ 2024-12-22 05d8984781 net: document LookupTXT behavior with multiple strings per record
+ 2024-12-21 500675a7c8 cmd/compile: load map length with the right type
+ 2024-12-21 06b191e11f internal/syscall/unix: apply fstatat fix to linux/mips64le
+ 2024-12-21 110ab1aaf4 slices: document two oddities
+ 2024-12-19 669d87a935 runtime/pprof: continued attempt to deflake the VMInfo test.
+ 2024-12-19 45f49139f5 runtime: test trap panic parsing in TestTracebackSystem
+ 2024-12-19 e63eb98e98 net/http: fix nil panic in test
+ 2024-12-19 7b6c94dd03 cmd/go: drop fips140 build ID hacks
+ 2024-12-19 cb72406c36 cmd/go: fix two-step toolchain upgrade through go install, GOTOOLCHAIN
+ 2024-12-18 4f0561f9d3 cmd/dist: skip fips140test in exe mode on Android
+ 2024-12-18 87dbfb9fa7 weak: improve grammar in doc comments
+ 2024-12-18 f4e3ec3dbe crypto/ecdsa: fix condition for fips140=only check
+ 2024-12-18 6aa46eb750 crypto/tls: normalize spelling of "ClientHello" in comments
+ 2024-12-18 10ca5ba4ff crypto/pbkdf2: update RFC reference in package doc
+ 2024-12-18 8ff4cee564 cmd/go,crypto: reject using Go+BoringCrypto and fips140 together
+ 2024-12-18 971448ddf8 testing: support B.Context and F.Context
+ 2024-12-17 95b433eed4 debug/elf: adjust version API per issue discussion
+ 2024-12-17 b2c0168893 crypto/internal/fips140/aes/gcm: use aes.EncryptBlockInternal on ppc64x and s390x
+ 2024-12-17 b9e2ffdcd2 crypto/internal/fips140: add Name and Version
+ 2024-12-17 8790372a8d cmd, go: fix some typos
+ 2024-12-17 b057b8872d bytes, strings: add cross-references in docstrings
+ 2024-12-17 e977b83b32 cmd/go/internal/help: use secure link to swig.org
+ 2024-12-17 4ac8f552e9 syscall, internal/syscall/unix: fix fstatat on linux/mips64
+ 2024-12-17 236a0b4ffb spec: explain function invocation and passing of parameters more precisely
+ 2024-12-17 9f806bb76c go/build: streamline the crypto package graph in TestDependencies
+ 2024-12-17 0cd833d198 go/build: remove nonexistent package from TestDependencies
+ 2024-12-17 31e50af5f3 crypto/rsa: revert minimum GenerateKey size to 32 bits
+ 2024-12-17 b47ce8b0e9 crypto/cipher: block non-AES CTR and CBC in fips140=only mode
+ 2024-12-17 dd7a7ba38f crypto/internal/fips140/aes: mark AES-ECB as not approved
+ 2024-12-17 427a2401af cmd/go/testdata/script: update test_flags for new test output
+ 2024-12-17 75736cc169 fmt, strconv: document that exponent is always two digits
+ 2024-12-16 1218566fe5 cmd/link: update runtime dependency list
+ 2024-12-16 d92c34a387 cmd/go: don't create test actions for incomplete packages
+ 2024-12-16 3bd08b9792 runtime: usleep in TestWeakToStrongMarkTermination
+ 2024-12-15 18b5435fc8 testing: don't measure cleanup time after B.Loop
+ 2024-12-15 c1f2542c8b testing: improve B.Loop test
+ 2024-12-15 6bd56fcaeb testing: improve b.Loop example
+ 2024-12-15 090748d6c7 testing: improve B.Loop docs, use B.Loop in examples
+ 2024-12-13 e39e965e0e cmd/go: drop FailedBuild field if gotestjsonbuildtext=1
+ 2024-12-13 08770a5b94 cmd/link: make dwarf name slice index self-describing
+ 2024-12-13 c4f356dd86 crypto/ecdsa: fix s390x assembly with P-521
+ 2024-12-13 08725f9de2 crypto/internal/cryptotest: skip TestAllocations on s390x
+ 2024-12-13 1cbfe8c482 fmt: add more function and allocation tests
+ 2024-12-13 8391579ece runtime: migrate missing map linkname allowlists
+ 2024-12-12 80a2982a80 spec: align EBNF rules consistently (cosmetic change)
+ 2024-12-12 38e9a671d7 syscall: on freebsd-386 only update written for certain errors
+ 2024-12-12 6f7a4540b1 net: fix example function name for IP.To4
+ 2024-12-12 14e5093ee5 cmd/internal/obj: disallow linknamed access to builtin symbols
+ 2024-12-12 fb764cdad0 cmd/link: block new standard library linknames

Change-Id: Ie423f050db80034c3af6c12bd6007db273c5d281
2025-01-08 13:21:10 -05:00
Michael Matloob
9a44df6675 cmd/go/testdata/script: fix TestScript/env_gocacheprog on Windows
The backslashes on the windows paths will be escaped, so when checking
for them in the regular expression we'd have to have quadruple
backslashes '\\\\'. Since it's difficult to escape $GOCACHEPROG properly
for both json and regexp, just check for a string that ends in
cacheprog$GOEXE. We already check that the proper value is reported in
go env and go env -changed, and the json test case is mostly useful to
verify that GOCACHEPROG shows up in the json output.

For #71059

Change-Id: I52d49de61f2309a139f84c4d232b4cd94546ec8c
Cq-Include-Trybots: luci.golang.try:gotip-windows-amd64-longtest,gotip-linux-amd64-longtest
Reviewed-on: https://go-review.googlesource.com/c/go/+/641375
Reviewed-by: Dmitri Shuralyov <dmitshur@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Sam Thanawalla <samthanawalla@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
2025-01-08 10:11:09 -08:00
Michael Anthony Knyszek
f025d19e7b runtime: hold traceAcquire across casgstatus in injectglist
Currently injectglist emits all the trace events before actually calling
casgstatus on each goroutine. This is a problem, since tracing can
observe an inconsistent state (gstatus does not match tracer's 'emitted
an event' state).

This change fixes the problem by having injectglist do what every other
scheduler function does, and that's wrap each call to casgstatus in
traceAcquire/traceRelease.

Fixes #70883.

Change-Id: I857e96cec01688013597e8efc0c4c3d0b72d3a70
Reviewed-on: https://go-review.googlesource.com/c/go/+/638558
Reviewed-by: Michael Pratt <mpratt@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2025-01-08 09:25:53 -08:00
Koichi Shiraishi
1e9835f5b1 internal/sync: fix typo of panic message
Change-Id: I3e7a8498514da1d278acd566d526fdf6278f7d41
Reviewed-on: https://go-review.googlesource.com/c/go/+/638916
Reviewed-by: Dmitri Shuralyov <dmitshur@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Ian Lance Taylor <iant@google.com>
Auto-Submit: Dmitri Shuralyov <dmitshur@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
2025-01-08 09:02:13 -08:00
Damien Neil
39f2032c17 testing/synctest: add some examples
For #67434

Change-Id: Iebcfc2559a62405fea7e3ceff8cf6c2f50b61def
Reviewed-on: https://go-review.googlesource.com/c/go/+/641176
Reviewed-by: Ian Lance Taylor <iant@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Damien Neil <dneil@google.com>
2025-01-07 20:05:28 -08:00
Michael Matloob
b50ccef67a cmd/go/internal/modindex: don't write index entry if file open
On Windows, we can't open a file that's already been opened. Before this
change, we'd try to write an index entry if mmapping the entry failed.
But that could happen either if the file doesn't exist or if there was a
problem mmapping an already opened file. Pass through information about
whether the file was actually opened so that we don't try to write to an
already opened file.

For #71059

Change-Id: I6adabe1093fed9ec37e7fafb13384c102786cbce
Reviewed-on: https://go-review.googlesource.com/c/go/+/640577
Reviewed-by: Sam Thanawalla <samthanawalla@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2025-01-07 12:50:01 -08:00
Russ Cox
b2aa18b96c cmd/internal/hash: stop using md5, sha1
These break if the tools are run with GODEBUG=fips140=only,
which happens if someone sets that during 'go test' (and a test
binary must be built).

The easiest fix is to make the tools compatible with this GODEBUG
by just using sha256 as the underlying hash always. Just in case,
I made the wrappers select different sections of the hash, but
none of the call sites really care.

This CL is for the Go 1.24 release, but a follow-up during the Go 1.25
dev cycle could change all the usage sites to only use Sum32/New32.

For #70514
Fixes #70878

Change-Id: Id5fea779c83df51d1680dbe561e0949c56e8d1e5
Reviewed-on: https://go-review.googlesource.com/c/go/+/641096
Reviewed-by: Keith Randall <khr@golang.org>
Auto-Submit: Russ Cox <rsc@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Keith Randall <khr@google.com>
2025-01-07 10:59:33 -08:00
Michael Matloob
d93b549f05 cmd/go/internal/cache: handle cacheprog not responding to close
Allow a gocacheprog to not respond to close. The intention of the code
is that after we send the close message we'd ignore errors reading from
the cacheprog's stdout. But before this change if a cacheprog
did not respond to close and we got an EOF reading from the cacheprog's
stdout we'd just ignore all pending requests. The send operation would
then block forever waiting for a response. With this change, we close
all response channels for pending responses if there's an error reading
from the cacheprog's stdout while we're closing. The receives from the
response channels would then proceed (but now have to handle a nil
value). Then the send operation would return and the (*ProgCache).Close
function can proceed.

Fixes #70848

Change-Id: I6631d317ba7aea3f25f714f31cd2aeef0f4d4e3e
Cq-Include-Trybots: luci.golang.try:gotip-linux-amd64-longtest,gotip-windows-amd64-longtest
Reviewed-on: https://go-review.googlesource.com/c/go/+/640516
Reviewed-by: Austin Clements <austin@google.com>
Reviewed-by: Sam Thanawalla <samthanawalla@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2025-01-07 10:21:05 -08:00
Michael Anthony Knyszek
d62154db83 weak: don't panic when calling Value on a zero Pointer
Currently weak.Pointer.Value will panic if the weak.Pointer is
uninitialized (zero value) which goes against it's documentation. Fix
this and add a test. While we're here, also add a test to ensure
weak.Make[T](nil) is equivalent to the zero value of weak.Pointer[T].

Fixes #71153.

Change-Id: I4d9196026360bc42a5bfcb33ce449131ec251dba
Reviewed-on: https://go-review.googlesource.com/c/go/+/641095
Reviewed-by: David Finkel <david.finkel@gmail.com>
Auto-Submit: Michael Knyszek <mknyszek@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Carlos Amedee <carlos@golang.org>
2025-01-07 10:08:42 -08:00
Robert Griesemer
9d0772b23e cmd/compile/internal/syntax: add test case for invalid label use
This case is not properly handled by the type checkers (see issue)
but the compiler uses the parser's label checking so it works as
expected.

For #70974.

Change-Id: I0849376bf7514a9a7730846649c3fe28c91f44ca
Reviewed-on: https://go-review.googlesource.com/c/go/+/640895
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Alan Donovan <adonovan@google.com>
Reviewed-by: Robert Griesemer <gri@google.com>
Auto-Submit: Robert Griesemer <gri@google.com>
2025-01-07 09:56:13 -08:00
Robert Griesemer
1d20bce981 go/types, types2: expand documentation for Info.Types map
Function types for function (and method) declarations do not
appear in Info.Types maps, only Info.Defs maps, because the
function type is implicit in the declaration and not a proper
(function) type expression. This is true even though the AST
represents these types via an (artificial) FuncType node.

Document this explicitly in the API.

No functional code changes.

Fixes #70908.

Change-Id: I2aa897daed04e7ad0fa8b625d9adc7b423c57387
Reviewed-on: https://go-review.googlesource.com/c/go/+/640776
Reviewed-by: Alan Donovan <adonovan@google.com>
Auto-Submit: Robert Griesemer <gri@google.com>
Reviewed-by: Robert Griesemer <gri@google.com>
Reviewed-by: Robert Findley <rfindley@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2025-01-07 09:56:11 -08:00
Michael Matloob
a9bd6239a4 cmd/go/internal/env: add GOCACHEPROG to go env output
For #71059

Change-Id: I4bbdd14d416dc2e6dae3549a84c16dbef9d4e645
Reviewed-on: https://go-review.googlesource.com/c/go/+/640755
Reviewed-by: Sam Thanawalla <samthanawalla@google.com>
Reviewed-by: Austin Clements <austin@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2025-01-07 07:48:33 -08:00
thekuwayama
850b276a67 crypto/tls: send illegal_parameter on invalid ECHClientHello.type
The spec indicates that if a client sends an invalid ECHClientHello.type
in ClientHelloOuter, the server will abort the handshake with a
decode_error alert.

Define errInvalidECHExt for invalid ECHClientHello.type. If parseECHExt
returns an errInvalidECHExt error, Conn now sends an illegal_parameter
alert.

Fixes #71061.

Change-Id: I240241fe8bbe3e77d6ad1af989794647bfa2ff87
GitHub-Last-Rev: 3d6c233ccd
GitHub-Pull-Request: golang/go#71062
Reviewed-on: https://go-review.googlesource.com/c/go/+/639235
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Roland Shoemaker <roland@golang.org>
2025-01-07 06:36:26 -08:00
Filippo Valsorda
27c5164374 crypto/internal/fips140: zeroise integrity test temporary values
There is no point to zeroise anything here because there are no secrets,
but there is a strict FIPS 140-3 test requirement for it.

> TE05.08.02 (Levels 1, 2, 3, and 4): verify that any temporary values
> generated during the integrity test are zeroised upon completion of
> the integrity test

Change-Id: I7b0db075dae9910f8e825a22ca2caa2b4c918980
Reviewed-on: https://go-review.googlesource.com/c/go/+/636556
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Daniel McCarney <daniel@binaryparadox.net>
Reviewed-by: Michael Pratt <mpratt@google.com>
Reviewed-by: Roland Shoemaker <roland@golang.org>
Auto-Submit: Filippo Valsorda <filippo@golang.org>
2025-01-06 23:44:33 -08:00
Joel Sing
d8ad4af78b cmd/internal/disasm: correct instruction length handling for riscv64
disasm_riscv64 currently always returns an instruction length of four,
which is not correct if compressed instructions are in use. Return the
length of the decoded instruction, defaulting to two bytes if the
instruction is unknown.

With this change it is possible to correctly objdump a binary that is
written in C and includes compressed instructions:

$ go tool objdump ./hello
TEXT _start(SB)
  :0                    0x5b0                   ef002002                CALL 8(PC)
  :0                    0x5b4                   aa87                    ADD X10, X0, X15
  :0                    0x5b6                   17250000                AUIPC $2, X10
  :0                    0x5ba                   033525a3                MOV -1486(X10), X10
  :0                    0x5be                   8265                    MOV (X2), X11
  :0                    0x5c0                   3000                    ADDI $8, X2, X12
  ...

Fixes #71102

Change-Id: Ia99eb114a98c6d535de872ce8a526cd5e6203fff
Reviewed-on: https://go-review.googlesource.com/c/go/+/639995
Reviewed-by: Michael Knyszek <mknyszek@google.com>
Reviewed-by: Jorropo <jorropo.pgm@gmail.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Michael Pratt <mpratt@google.com>
2025-01-06 23:43:06 -08:00
Filippo Valsorda
a76cc5a4ec crypto/rsa: use λ(N) instead of φ(N)
This has no practical advantage, and requires extra variable time code,
but is an explicit FIPS 186-5 requirement.

Note that the new behavior is consistent with Go+BoringCrypto, but not
with Go 1.23. The resulting keys are essentially interchangeable, but
it's not impossible for applications to notice (google/go-tpm#383).

gcd_lcm_tests.txt is from BoringSSL.

Change-Id: I6a6a4656fd5e92912c87bedc667456d0e8787023
Reviewed-on: https://go-review.googlesource.com/c/go/+/639936
Reviewed-by: Russ Cox <rsc@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Roland Shoemaker <roland@golang.org>
Auto-Submit: Filippo Valsorda <filippo@golang.org>
2025-01-06 16:16:41 -08:00
Michael Anthony Knyszek
3f002abb60 internal/sync: add test from issue 70970
This test checks a use-case of sync.Map that's expected to be more
common in Go 1.24 and beyond, as a concurrent weak cache.

The test will also fail if CompareAndSwap is not properly atomic with
CompareAndDelete, which is what #70970 is actually about. We should have
more explicit tests checking mutual atomicity of operations, but
for now this is OK, and still useful.

For #70970.

Change-Id: I6db508660691586a8af9ad511c9a96432d333343
Reviewed-on: https://go-review.googlesource.com/c/go/+/640737
Reviewed-by: David Chase <drchase@google.com>
Auto-Submit: Michael Knyszek <mknyszek@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2025-01-06 11:54:59 -08:00
yincong
7a2e88e911 net/http: update NewRequestWithContext wrong link to NewRequest
Fixes #70874

Change-Id: Icbcfc95e6b45521880287dcc3bc8609461a3b401
GitHub-Last-Rev: 05276c56b0
GitHub-Pull-Request: golang/go#70877
Reviewed-on: https://go-review.googlesource.com/c/go/+/637035
Reviewed-by: qiu laidongfeng2 <2645477756@qq.com>
Reviewed-by: Damien Neil <dneil@google.com>
Reviewed-by: David Chase <drchase@google.com>
Auto-Submit: Ian Lance Taylor <iant@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Ian Lance Taylor <iant@google.com>
2025-01-06 11:01:12 -08:00
Michael Knyszek
c112c0af13 Revert "internal/sync: optimize CompareAndSwap and Swap"
This reverts CL 606462.

Reason for revert: Breaks atomicity between operations. See #70970.

Change-Id: I1a899f2784da5a0f9da3193e3267275c23aea661
Reviewed-on: https://go-review.googlesource.com/c/go/+/638615
Auto-Submit: Michael Knyszek <mknyszek@google.com>
Commit-Queue: Michael Knyszek <mknyszek@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: David Chase <drchase@google.com>
2025-01-06 09:57:18 -08:00
Filippo Valsorda
705b5a569a crypto/ecdsa: drop SEC 1 reference from package doc
FIPS 186-4 used to defer to ANSI X9.62-2005, which is not freely
available, so we were referring to SEC 1 instead. Our new reference,
FIPS 186-5, actually specifies the full algorithm, so there is no need
to refer to SEC 1 anymore.

Change-Id: Ief499d0f7778f3221547993e9e8951ae873aacef
Reviewed-on: https://go-review.googlesource.com/c/go/+/640115
Reviewed-by: Daniel McCarney <daniel@binaryparadox.net>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Auto-Submit: Filippo Valsorda <filippo@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Roland Shoemaker <roland@golang.org>
2025-01-03 14:40:11 -08:00
Damien Neil
f966695cce context: use "canceled" in docs to refer to timed-out contexts
In documentation, we've usually but not always referred to a
context with a closed Done channel as "done" rather than
"canceled", to avoid ambiguity between a context canceled
by calling a CancelFunc and one past its deadline.

This actually adds ambiguity, however, since it's common to
see references to a "canceled context" that are intended to
cover contexts past their deadline. If you see "function F
returns if its context is canceled", you can reasonably
assume that F will return if its context passes its
deadline, unless something says otherwise.

Update the context package docs to explicitly state that
a context is canceled when its deadline passes. Drop references
to contexts becoming "done" and just use "canceled" throughout.

Fixes #70945

Change-Id: I99fbd800c6049deaa37015a304f7f9d9a84100e1
Reviewed-on: https://go-review.googlesource.com/c/go/+/640095
Reviewed-by: Ian Lance Taylor <iant@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Damien Neil <dneil@google.com>
2025-01-03 14:30:13 -08:00
Ian Lance Taylor
5da026354c cmd/go/internal/vcweb: close the .access file
For #71112

Change-Id: Ifda4fc8de148c42a2154da54b53d7215b9a6faa0
Reviewed-on: https://go-review.googlesource.com/c/go/+/640175
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Ian Lance Taylor <iant@golang.org>
Auto-Submit: Ian Lance Taylor <iant@google.com>
Reviewed-by: Michael Matloob <matloob@golang.org>
Reviewed-by: Ian Lance Taylor <iant@google.com>
2025-01-03 14:12:15 -08:00
Filippo Valsorda
31cabcf084 crypto/internal/fips140: mark OpenBSD unsupported
Since OpenBSD 7.3, external linking uses -fexecute-only, which breaks
the integrity check. Since we are not validating on OpenBSD anyway,
mark it as unsupported at least for now.

Fixes #70880

Change-Id: I6a6a4656b6c7a97c0962b4158d920f9e6b19678e
Reviewed-on: https://go-review.googlesource.com/c/go/+/639337
Auto-Submit: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Daniel McCarney <daniel@binaryparadox.net>
Reviewed-by: Roland Shoemaker <roland@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Joel Sing <joel@sing.id.au>
Reviewed-by: صادق <sadq04724@gmail.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2025-01-03 10:53:43 -08:00
Filippo Valsorda
eb0c2b2f96 crypto/internal/fips140: add Supported
Move the logic duplicated in multiple places to a central function.

Change-Id: I6a6a4656469c91dd62b0be716ec8367358f4a3e1
Reviewed-on: https://go-review.googlesource.com/c/go/+/639336
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Auto-Submit: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Daniel McCarney <daniel@binaryparadox.net>
Reviewed-by: Roland Shoemaker <roland@golang.org>
2025-01-03 10:12:06 -08:00
Jakub Ciolek
f0a9b6df45 internal/fuzz: remove the exp2 method
It's not being used anywhere, remove it.

Change-Id: I9c3eecacd4e5d44b18243bdec24ad88bc38c82bf
Reviewed-on: https://go-review.googlesource.com/c/go/+/639957
Reviewed-by: Roland Shoemaker <roland@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Roland Shoemaker <roland@golang.org>
2025-01-03 10:10:07 -08:00
yaxum62
5d626c49ec spec: fix a dead link
Change-Id: If99aa8073cc0e7fe36d3775c635eaaab230fcd04
GitHub-Last-Rev: 06dbd990c7
GitHub-Pull-Request: golang/go#71083
Reviewed-on: https://go-review.googlesource.com/c/go/+/638638
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Auto-Submit: Jorropo <jorropo.pgm@gmail.com>
Reviewed-by: Jorropo <jorropo.pgm@gmail.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Ian Lance Taylor <iant@google.com>
2025-01-03 09:23:39 -08:00
Mateusz Poliwczak
81566aff3a internal/exportdata: add missing return
Change-Id: I9703c6a4a2ae4a608d33cf706106c92e9bd2aef7
GitHub-Last-Rev: 3eee41957d
GitHub-Pull-Request: golang/go#71096
Reviewed-on: https://go-review.googlesource.com/c/go/+/637962
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Auto-Submit: Ian Lance Taylor <iant@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Ian Lance Taylor <iant@google.com>
2025-01-03 08:43:47 -08:00
Filippo Valsorda
e7a8bd5d8b crypto/internal/fips140/check: remove Enabled
check.Enabled, internal/fips140.Enabled, and crypto/fips140.Enabled were
redundant. Package check can just use internal/fips140.Enabled.

check.Verified is still there for the tests and belt-and-suspenders
assurance in crypto/fips140.Enabled, although it's implied by Enabled.

For #69536

Change-Id: I83921cc925da841aba4da79a9a5e9ac526a3f2bf
Reviewed-on: https://go-review.googlesource.com/c/go/+/638855
Reviewed-by: Roland Shoemaker <roland@golang.org>
Reviewed-by: Daniel McCarney <daniel@binaryparadox.net>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Filippo Valsorda <filippo@golang.org>
2025-01-03 08:29:24 -08:00
linmaolin
4b652e9f5f cmd/go: fix two typos in helpdoc.go
Change-Id: Ib750438107db6c82020cfb4abbab52435012b7fc
GitHub-Last-Rev: 3fa9b8c7bc
GitHub-Pull-Request: golang/go#71082
Reviewed-on: https://go-review.googlesource.com/c/go/+/639217
Auto-Submit: Ian Lance Taylor <iant@golang.org>
Reviewed-by: Michael Matloob <matloob@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Sam Thanawalla <samthanawalla@google.com>
2025-01-02 16:10:54 -08:00
Austin Clements
0afd7e85e5 cmd/go: document GOCACHEPROG in go help environment
This adds GOCACHEPROG to the list of environment variables in "go help
environment" and points to the cacheprog package documentation for
details of the protocol.

Fixes #71032
Updates #59719

Change-Id: Ib8f5804926a8fa59237661076d129c2852665ac3
Reviewed-on: https://go-review.googlesource.com/c/go/+/638997
Auto-Submit: Austin Clements <austin@google.com>
Reviewed-by: Mauri de Souza Meneguzzo <mauri870@gmail.com>
Reviewed-by: Michael Matloob <matloob@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
2025-01-02 10:36:34 -08:00
Austin Clements
3c8e5b13df cmd/go/internal/cacheprog: drop redundant Prog prefixes
Now that these types are in their own package, drop the unnecessary
Prog prefixes from everything.

Updates #71032
Updates #59719

Change-Id: Id54edf0473754e3b21a71beb72803fb5481206c1
Reviewed-on: https://go-review.googlesource.com/c/go/+/638996
Reviewed-by: Mauri de Souza Meneguzzo <mauri870@gmail.com>
Reviewed-by: Michael Matloob <matloob@golang.org>
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Auto-Submit: Austin Clements <austin@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2025-01-02 10:36:30 -08:00
Austin Clements
20da34c6d2 cmd/go: move GOCACHEPROG protocol types to their own package
This is a step toward making it easy to point to them in
documentation. The other option is that we copy-paste all of these
type definitions wholesale, which seems ridiculous.

Updates #71032
Updates #59719

Change-Id: I7117e03308ae0adc721ed7a57792c33ba68ce827
Reviewed-on: https://go-review.googlesource.com/c/go/+/638995
Auto-Submit: Austin Clements <austin@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Michael Matloob <matloob@golang.org>
2025-01-02 10:36:27 -08:00
Roland Shoemaker
858a0e9dfd crypto/tls: properly return ECH retry configs
When ECH is rejected, properly take retry configs from the encrypted
extensions message. Also fix the bogo shim to properly test for this
behavior.

We should properly map the full BoringSSL -> Go errors so that we don't
run into a similar failure in the future, but this is left for a follow
up CL.

Fixes #70915

Change-Id: Icc1878ff6f87df059e7b83e0a431f50f1fea833c
Reviewed-on: https://go-review.googlesource.com/c/go/+/638583
Reviewed-by: Damien Neil <dneil@google.com>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2025-01-02 09:38:03 -08:00
Austin Clements
a63aee4955 cmd/go: improve GOCACHEPROG types documentation
This is in preparation for adding a "go help" topic for GOCACHEPROG.

Updates #71032
Updates #59719

Change-Id: I9dbbe56fa328dffe89207b5b41a0f37afd51e2b5
Reviewed-on: https://go-review.googlesource.com/c/go/+/638566
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Austin Clements <austin@google.com>
Reviewed-by: Michael Matloob <matloob@golang.org>
2025-01-02 09:17:35 -08:00
Sean Liao
847c357bbb cmd/go: remove references to gopath-get
Fixes #70912

Change-Id: Id87a13f7c9bf972502d14c9674a27f743b849715
Reviewed-on: https://go-review.googlesource.com/c/go/+/639155
Reviewed-by: Sam Thanawalla <samthanawalla@google.com>
Reviewed-by: Michael Matloob <matloob@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Sam Thanawalla <samthanawalla@google.com>
2025-01-02 08:02:15 -08:00
Filippo Valsorda
d1d9312950 crypto/tls: fix Config.Time in tests using expired certificates
Fixes #71077

Change-Id: I6a6a465685f3bd50a5bb35a160f87b59b74fa6af
Reviewed-on: https://go-review.googlesource.com/c/go/+/639655
Auto-Submit: Ian Lance Taylor <iant@google.com>
Reviewed-by: Damien Neil <dneil@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Filippo Valsorda <filippo@golang.org>
Auto-Submit: Damien Neil <dneil@google.com>
Reviewed-by: Joel Sing <joel@sing.id.au>
Reviewed-by: Ian Lance Taylor <iant@google.com>
2025-01-01 21:18:59 -08:00
Ian Lance Taylor
94f15810e6 cmd/go: document default GOARM value
For #24904
For #58884

Change-Id: I0fc61f1a0bc6ebb22bdfd7a7b13ef36c68879384
Reviewed-on: https://go-review.googlesource.com/c/go/+/639276
Reviewed-by: Dmitri Shuralyov <dmitshur@golang.org>
Reviewed-by: Ian Lance Taylor <iant@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Commit-Queue: Ian Lance Taylor <iant@google.com>
Auto-Submit: Ian Lance Taylor <iant@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
2024-12-31 18:00:57 -08:00
Shulhan
856a7bc8e9 builtin: use list instead of indentation for comments in cap, len, and make
Using list make the document more readable in HTML and CLI.

Change-Id: Ib84c84656f32806e8612b1ca13938d93f618e27f
Reviewed-on: https://go-review.googlesource.com/c/go/+/639315
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Ian Lance Taylor <iant@google.com>
Auto-Submit: Ian Lance Taylor <iant@google.com>
2024-12-30 15:59:23 -08:00
Robert Griesemer
5efb4239c6 spec: document that string conversions don't guarantee result slice capacity
Fixes #24163.

Change-Id: If389c4abf3b9b6e4eba6f31c3c12779329456df6
Reviewed-on: https://go-review.googlesource.com/c/go/+/637655
Reviewed-by: Robert Griesemer <gri@google.com>
Reviewed-by: Ian Lance Taylor <iant@google.com>
Auto-Submit: Robert Griesemer <gri@google.com>
TryBot-Bypass: Robert Griesemer <gri@google.com>
2024-12-30 12:51:01 -08:00
Robert Griesemer
0d8aa8cce6 spec: describe representation of values
Add a section on the representation of values:
distinguish between values that are self-contained
and values that contain references while avoiding
the notion of "reference types" which is misleading.

Also, use "predeclared identifier nil" rather than
"predeclared value nil" because it is the identifier
that is predeclared.

Fixes #5083.

Change-Id: I2235673c6404f2c055f195e879f198c7ab246d58
Reviewed-on: https://go-review.googlesource.com/c/go/+/635801
Reviewed-by: Rob Pike <r@golang.org>
Reviewed-by: David Chase <drchase@google.com>
Auto-Submit: Robert Griesemer <gri@google.com>
Reviewed-by: Ian Lance Taylor <iant@google.com>
TryBot-Bypass: Robert Griesemer <gri@google.com>
Reviewed-by: Robert Griesemer <gri@google.com>
2024-12-30 12:50:25 -08:00
thekuwayama
8857a5a33f crypto/tls: fix misspelling in comment
Change-Id: Ie36a19ed6d6922e68f98e43745a417a24f8a7828
GitHub-Last-Rev: 6fb32e3d1d
GitHub-Pull-Request: golang/go#71060
Reviewed-on: https://go-review.googlesource.com/c/go/+/639215
Auto-Submit: Ian Lance Taylor <iant@google.com>
Reviewed-by: Roland Shoemaker <roland@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Ian Lance Taylor <iant@google.com>
2024-12-30 12:38:22 -08:00
willboland
3c4102bfd4 encoding/binary: add documentation for endian methods
While the comments are on an unexported type, gopls correctly
shows them when using the exported vars LittleEndian and BigEndian.

Fixes #68083

Change-Id: I53668c3140ad00f7b58437be74e6df773e2916f1
GitHub-Last-Rev: cef717123c
GitHub-Pull-Request: golang/go#71058
Reviewed-on: https://go-review.googlesource.com/c/go/+/638936
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Ian Lance Taylor <iant@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Ian Lance Taylor <iant@google.com>
Reviewed-by: Jorropo <jorropo.pgm@gmail.com>
2024-12-30 12:32:26 -08:00
Sean Liao
b702a26cf8 os: mention fsys modifications during CopyFS
Fixes #70465

Change-Id: I47055df9ca5b1df21a361b0b8eea4c7d157e6403
Reviewed-on: https://go-review.googlesource.com/c/go/+/639156
Commit-Queue: Ian Lance Taylor <iant@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Ian Lance Taylor <iant@google.com>
Auto-Submit: Ian Lance Taylor <iant@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
2024-12-30 12:23:28 -08:00
Joe Tsai
15f232456a encoding/json: remove suggestion on Unmarshaler with JSON null
It is not true that Unmarshal always treats a JSON null
as being equivalent to a no-op.
For bools, ints, uints, floats, strings, arrays, and structs,
it treats a JSON null as a no-op. However, for []byte, slice,
map, pointer, or interface, it zeros the underlying value.

Remove this suggestion as the actual behavior is inconsistent.

Note that the proposed behavior in v2 Unmarshal is to consistently
zero out the underlying value.

Change-Id: I02cef0bf7919f25cfd0aceb04486d37498761181
Reviewed-on: https://go-review.googlesource.com/c/go/+/638416
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Ian Lance Taylor <iant@google.com>
Run-TryBot: Joseph Tsai <joetsai@digital-static.net>
2024-12-30 12:21:48 -08:00
willboland
ba1deb1cee cmd/link: document that -s implies -w
Existing documentation does not reference implicit behavior.
Updates the documentation to reflect that -s implies -w.

Fixes #71051

Change-Id: I5c139c37f5f78596365e38479be4c865a4d4dd62
GitHub-Last-Rev: a3e462c416
GitHub-Pull-Request: golang/go#71053
Reviewed-on: https://go-review.googlesource.com/c/go/+/638976
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Auto-Submit: Ian Lance Taylor <iant@golang.org>
Reviewed-by: Cherry Mui <cherryyz@google.com>
2024-12-30 12:06:30 -08:00
Sean Liao
fd5e0d26d9 go/doc: resolve imports before predeclared identifiers in examples
Fixes #70611
Fixes #70630

Change-Id: I868e68dbdf50ce34259eeef7b3d7985ede1f4c0b
Reviewed-on: https://go-review.googlesource.com/c/go/+/639175
Reviewed-by: Ian Lance Taylor <iant@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Auto-Submit: Ian Lance Taylor <iant@google.com>
2024-12-30 09:19:22 -08:00
Koichi Shiraishi
a785d11ac4 unique: fix typo
Change-Id: I9f66e3d7aa7b546ebf34d6aa8c7a6558bf35ca82
Reviewed-on: https://go-review.googlesource.com/c/go/+/639055
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Ian Lance Taylor <iant@google.com>
Auto-Submit: Ian Lance Taylor <iant@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
2024-12-30 08:59:20 -08:00
Joe Tsai
2b794ed86c encoding/json: expand and modernize TestInterfaceSet
Add more test cases to cover a wider range of edge cases.
Use a generic addr function to take the address of a value.
Even though redudant, explicitly include a cast to the
top-level Go type so that it is more readable what the
expected input and ouput types are.

Change-Id: I3ef68df6f1beb903ae237cd49f3dcb91e5270fe7
Reviewed-on: https://go-review.googlesource.com/c/go/+/638256
Reviewed-by: Daniel Martí <mvdan@mvdan.cc>
Reviewed-by: Damien Neil <dneil@google.com>
Reviewed-by: Ian Lance Taylor <iant@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2024-12-27 17:23:24 -08:00
Pedro Tôrres
e3cd55e9d2 cmd/go/internal/work: allow @ character in some -Wl, linker flags on darwin
The GNU linker interprets @file as "read command-line options from file".
Thus, we forbid values starting with @ on linker flags. However, this
causes a problem when targeting Darwin. @executable_path, @loader_path, and
@rpath are special values used in Mach-O to change the library search path
and can be used in conjunction with the -install_name and -rpath linker
flags. Since the GNU linker does not support Mach-O, targeting Darwin
implies not using the GNU linker. Therefore, we allow @ in the linker flags
if and only if cfg.Goos == "darwin".

Fixes #40559

Change-Id: I0896758f0835e444ea0d501ea3fd8423cff97a27
GitHub-Last-Rev: 2b81dcd12e
GitHub-Pull-Request: golang/go#70939
Reviewed-on: https://go-review.googlesource.com/c/go/+/638075
Auto-Submit: Ian Lance Taylor <iant@golang.org>
Reviewed-by: Ian Lance Taylor <iant@google.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2024-12-27 12:34:09 -08:00
Austin Clements
39794819aa doc/initial: remove fixed-width spacing notice
Ever since CL 362015 in 2021 it hasn't been necessary to set
"fixed-width phrases with non-fixed-width spaces" because the site CSS
now takes care of this typesetting convention.

Change-Id: Id84f711b65cddf389dc485aa362b23c9c531cbfd
Reviewed-on: https://go-review.googlesource.com/c/go/+/638565
Reviewed-by: Jonathan Amsterdam <jba@google.com>
Auto-Submit: Austin Clements <austin@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2024-12-27 08:54:04 -08:00
Austin Clements
7c03fe70b8 cmd/compile: improve compiler directive docs
This section has gotten long enough that it deserves to be multiple
sections. This also allows us to better structure information shared
by subsets of directives. In particular, this enables a self-contained
section on the wasm directives.

Updates #66984.

Change-Id: I062081d46c6b0aef7887fdaf9efae80f32ad4b21
Reviewed-on: https://go-review.googlesource.com/c/go/+/638881
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Austin Clements <austin@google.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
2024-12-27 08:31:59 -08:00
Harald Albrecht
d7c3e93c16 iter: improve documentation with iterator example
In introducing iterators, package iter gives an example of how to
use an iterator in a range-over-func loop, but currently does not
give an example of what an iterator implementation might look like.

This change adds the example of map.Keys() before the usage example.
Additionally, it references to the Go blog for further examples,
as well as the language spec about for-range loops.

Fixes #70986

Change-Id: I7108d341d314d7de146b4c221700736c943a9f5d
Reviewed-on: https://go-review.googlesource.com/c/go/+/638895
Reviewed-by: Cherry Mui <cherryyz@google.com>
Reviewed-by: Ian Lance Taylor <iant@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Ian Lance Taylor <iant@google.com>
2024-12-27 05:44:33 -08:00
Alec Bakholdin
cce75da30b crypto/mlkem: swap order of return values of Encapsulate
Per FIPS 203 (https://csrc.nist.gov/pubs/fips/203/final), the order of return values should be sharedKey, ciphertext. This commit simply swaps those return values and updates any consumers of the Encapsulate() method to respect the new order.

Fixes #70950

Change-Id: I2a0d605e3baf7fe69510d60d3d35bbac18f883c9
Reviewed-on: https://go-review.googlesource.com/c/go/+/638376
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Austin Clements <austin@google.com>
Auto-Submit: Ian Lance Taylor <iant@golang.org>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Cherry Mui <cherryyz@google.com>
2024-12-26 12:33:05 -08:00
Michael Anthony Knyszek
772f024c61 weak: fix typo in warning about tiny allocator optimization
Fixes #70972.

Change-Id: Ib04c2a3129a1da651a0b4674b372aec73966115a
Reviewed-on: https://go-review.googlesource.com/c/go/+/638377
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Ian Lance Taylor <iant@google.com>
2024-12-23 17:53:33 -08:00
Cherry Mui
b9955f0ad9 cmd/link, runtime: apply a delta to RODATA->DATA relocations
On AIX, an R_ADDR relocation from an RODATA symbol to a DATA
symbol does not work, as the dynamic loader can change the address
of the data section, and it is not possible to apply a dynamic
relocation to RODATA. In order to get the correct address, we
apply the delta between unrelocated and relocated data section
addresses at run time. The linker saves both the unrelocated and
the relocated addresses, so we can compute the delta.

This is possible because RODATA symbols are generated by the
compiler and so we have full control of. On AIX, the only case
is the on-demand GC pointer masks from the type descriptors, for
very large types.

Perhaps there is a better way.

Fixes #70483.

Change-Id: I2664c0a813b38f7b146794cb1e73ccf5e238ca65
Reviewed-on: https://go-review.googlesource.com/c/go/+/638016
Reviewed-by: Keith Randall <khr@golang.org>
Reviewed-by: Keith Randall <khr@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2024-12-23 09:49:40 -08:00
Jorropo
eef35e3bd9 internal/goexperiment: run go generate for synctest
Updates #70954

Change-Id: If5f9c8b8b820b1cc4e41e76b50038c6155b575a8
Reviewed-on: https://go-review.googlesource.com/c/go/+/638355
Reviewed-by: David Chase <drchase@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Michael Pratt <mpratt@google.com>
2024-12-23 07:08:40 -08:00
Pedro Tôrres
9f6c80a76a cmd/go/internal/work: allow single character values in -Wl, linker flags
Allow single character values in -Wl, linker flags by modifying the regular
expressions to use the star operator instead of the plus operator.

Fixes #70924

Change-Id: Ie7940197cc8503440a87c6b29409a13377a20534
GitHub-Last-Rev: 42e8ac87d6
GitHub-Pull-Request: golang/go#70937
Reviewed-on: https://go-review.googlesource.com/c/go/+/638035
Auto-Submit: Ian Lance Taylor <iant@google.com>
Reviewed-by: David Chase <drchase@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Ian Lance Taylor <iant@google.com>
2024-12-23 07:08:22 -08:00
Simon Ser
05d8984781 net: document LookupTXT behavior with multiple strings per record
CL 8966 ("net: allow a dns TXT record to contain more than
one <character-string>") concatenates strings in a TXT record. Document
that behavior, since it's not obvious whether the strings will be
concatenated or accumulated in the returned slice.

Change-Id: I6acb27b296290361a95a6058a056f8e7c2df9a2b
GitHub-Last-Rev: ec0726c7b8
GitHub-Pull-Request: golang/go#65233
Reviewed-on: https://go-review.googlesource.com/c/go/+/557695
Auto-Submit: Ian Lance Taylor <iant@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Damien Neil <dneil@google.com>
Reviewed-by: Ian Lance Taylor <iant@google.com>
2024-12-22 16:27:28 -08:00
Cherry Mui
500675a7c8 cmd/compile: load map length with the right type
len(map) is lowered to loading the first field of the map
structure, which is the length. Currently it is a load of an int.
With the old map, the first field is indeed an int. With Swiss
map, however, it is a uint64. On big-endian 32-bit machine,
loading an (32-bit) int from a uint64 would load just the high
bits, which are (probably) all 0. Change to a load with the proper
type.

Fixes #70248.

Change-Id: I39cf2d1e6658dac5a8de25c858e1580e2a14b894
Reviewed-on: https://go-review.googlesource.com/c/go/+/638375
Run-TryBot: Cherry Mui <cherryyz@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Keith Randall <khr@google.com>
Reviewed-by: Keith Randall <khr@golang.org>
2024-12-21 19:25:03 -08:00
Cherry Mui
06b191e11f internal/syscall/unix: apply fstatat fix to linux/mips64le
Apply CL 633280 to linux/mips64le, as it has the same struct as
mips64.

Updates #70659.

Change-Id: Ibab635e69e44682eb214bf6a00f4cd75816b2d34
Reviewed-on: https://go-review.googlesource.com/c/go/+/637739
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Ian Lance Taylor <iant@google.com>
Run-TryBot: Cherry Mui <cherryyz@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2024-12-21 12:51:34 -08:00
Alan Donovan
110ab1aaf4 slices: document two oddities
Fixes #70935

Change-Id: Idf4a38a05ba595d616b6469a14419ff873bbd354
Reviewed-on: https://go-review.googlesource.com/c/go/+/638095
Reviewed-by: Keith Randall <khr@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Keith Randall <khr@google.com>
Reviewed-by: Ian Lance Taylor <iant@golang.org>
2024-12-21 08:22:08 -08:00
Cosmos Nicolaou
669d87a935 runtime/pprof: continued attempt to deflake the VMInfo test.
This change catches an additional error message to trigger skipping
the test when the underlying system is failing.

Fixes #62352

Change-Id: I5c12b20f3e9023597ff89fc905c0646a80ec4811
Reviewed-on: https://go-review.googlesource.com/c/go/+/637995
Reviewed-by: Cherry Mui <cherryyz@google.com>
Auto-Submit: Michael Pratt <mpratt@google.com>
Reviewed-by: Michael Pratt <mpratt@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2024-12-19 19:19:59 -08:00
Michael Pratt
45f49139f5 runtime: test trap panic parsing in TestTracebackSystem
This mirrors https://go.dev/cl/637755, as x/telemetry is now aware of
sigpanic preceding trap frames.

For #70637.

Change-Id: I13a775f25e89047702d4f2d463ce3210bcf192d9
Reviewed-on: https://go-review.googlesource.com/c/go/+/638015
Reviewed-by: Cherry Mui <cherryyz@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2024-12-19 19:19:50 -08:00
Russ Cox
e63eb98e98 net/http: fix nil panic in test
Observed on a builder in an unrelated CL.
https://logs.chromium.org/logs/golang/buildbucket/cr-buildbucket/8728107031663629713/+/u/step/11/log/2

goroutine 27937 gp=0xc00000f6c0 m=20 mp=0xc000085008 [running]:
panic({0x560ac0?, 0xa1f400?})
	C:/b/s/w/ir/x/w/goroot/src/runtime/panic.go:806 +0x168 fp=0xc00043fac8 sp=0xc00043fa18 pc=0xa5f88
testing.tRunner.func1.2({0x560ac0, 0xa1f400})
	C:/b/s/w/ir/x/w/goroot/src/testing/testing.go:1734 +0x219 fp=0xc00043fb78 sp=0xc00043fac8 pc=0x1537f9
testing.tRunner.func1()
	C:/b/s/w/ir/x/w/goroot/src/testing/testing.go:1737 +0x359 fp=0xc00043fce0 sp=0xc00043fb78 pc=0x153259
panic({0x560ac0?, 0xa1f400?})
	C:/b/s/w/ir/x/w/goroot/src/runtime/panic.go:787 +0x132 fp=0xc00043fd90 sp=0xc00043fce0 pc=0xa5f52
runtime.panicmem(...)
	C:/b/s/w/ir/x/w/goroot/src/runtime/panic.go:262
runtime.sigpanic()
	C:/b/s/w/ir/x/w/goroot/src/runtime/signal_windows.go:401 +0x198 fp=0xc00043fdd8 sp=0xc00043fd90 pc=0x87938
net/http_test.testTransportIdleConnTimeout.func3(...)
	C:/b/s/w/ir/x/w/goroot/src/net/http/transport_test.go:5503
net/http_test.testTransportIdleConnTimeout(0xc000e83340, {0x5ec863, 0x2})
	C:/b/s/w/ir/x/w/goroot/src/net/http/transport_test.go:5522 +0x4c1 fp=0xc00043ff20 sp=0xc00043fdd8 pc=0x47a841
net/http_test.run[...].func1()
	C:/b/s/w/ir/x/w/goroot/src/net/http/clientserver_test.go:93 +0xfe fp=0xc00043ff70 sp=0xc00043ff20 pc=0x49a21e
testing.tRunner(0xc000e83340, 0xc0004687b0)
	C:/b/s/w/ir/x/w/goroot/src/testing/testing.go:1792 +0xcb fp=0xc00043ffc0 sp=0xc00043ff70 pc=0x152e4b
testing.(*T).Run.gowrap1()
	C:/b/s/w/ir/x/w/goroot/src/testing/testing.go:1851 +0x25 fp=0xc00043ffe0 sp=0xc00043ffc0 pc=0x153e65
runtime.goexit({})
	C:/b/s/w/ir/x/w/goroot/src/runtime/asm_amd64.s:1700 +0x1 fp=0xc00043ffe8 sp=0xc00043ffe0 pc=0xadfe1
created by testing.(*T).Run in goroutine 27899
	C:/b/s/w/ir/x/w/goroot/src/testing/testing.go:1851 +0x3f6


Change-Id: I3f8bd7c7863b5031ff43d4837dfe11d26ac75652
Reviewed-on: https://go-review.googlesource.com/c/go/+/637897
Reviewed-by: Damien Neil <dneil@google.com>
Auto-Submit: Russ Cox <rsc@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2024-12-19 10:59:58 -08:00
Russ Cox
7b6c94dd03 cmd/go: drop fips140 build ID hacks
We were trying to keep all binaries stale in fips140 mode
so that every build would write and leave behind a fips.o
in the work directory for use by validating labs.
That breaks various staleness checks, including the one
in cmd/dist during GOFIPS140=latest ./make.bash.

Revert the fips140 hack. Validating labs will still be able
to find the fips.o when building against a clean cache.

Add the default godebug to the link hash though,
so that it is clear that GOFIPS140=latest
and GOFIPS140=off binaries have different hashes.
(The only effect is the default GODEBUG setting.)
They already had different hashes, because the
default GODEBUG ends up in p.Internal.BuildInfo,
and that gets hashed in a "modinfo" line,
but better to be explicit.

Fixes #70873.

Change-Id: I49a38c180208098c2b6720facef48f4e96d44c54
Reviewed-on: https://go-review.googlesource.com/c/go/+/637116
Reviewed-by: Michael Matloob <matloob@golang.org>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Sam Thanawalla <samthanawalla@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2024-12-19 10:36:27 -08:00
Russ Cox
cb72406c36 cmd/go: fix two-step toolchain upgrade through go install, GOTOOLCHAIN
If we do one upgrade because of a go install target's go.mod file,
we still might need a second upgrade to implement the GOTOOLCHAIN
minimum. Instead of allowing a two-step switch (which we were
cutting off anyway), skip the first step and go straight to the
GOTOOLCHAIN min upgrade.

Fixes #69051.

Change-Id: I16f060f473574d8b8f84c55fae2fd0cdabc8aa19
Reviewed-on: https://go-review.googlesource.com/c/go/+/637496
Reviewed-by: Michael Matloob <matloob@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2024-12-19 08:12:29 -08:00
Cherry Mui
4f0561f9d3 cmd/dist: skip fips140test in exe mode on Android
Android does not support non-PIE linking. Skip the test.

Change-Id: I53071538c82f1e1f96eed1a2619f92eacd18d263
Reviewed-on: https://go-review.googlesource.com/c/go/+/637495
Run-TryBot: Cherry Mui <cherryyz@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@golang.org>
TryBot-Result: Gopher Robot <gobot@golang.org>
2024-12-18 20:48:37 -08:00
Michal Bohuslávek
87dbfb9fa7 weak: improve grammar in doc comments
Change-Id: I577b8a6bf2b7d899cc7ff7211c73549c90db9d94
Reviewed-on: https://go-review.googlesource.com/c/go/+/637355
Reviewed-by: Ian Lance Taylor <iant@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Ian Lance Taylor <iant@google.com>
Reviewed-by: Michael Knyszek <mknyszek@google.com>
2024-12-18 20:27:29 -08:00
Mauri de Souza Meneguzzo
f4e3ec3dbe crypto/ecdsa: fix condition for fips140=only check
Fixes #70894

Change-Id: I78c9f2e46006ffc5f1d2886218f8aaaf3f1b59eb
GitHub-Last-Rev: 11f0b452f5
GitHub-Pull-Request: golang/go#70904
Reviewed-on: https://go-review.googlesource.com/c/go/+/637455
Reviewed-by: Filippo Valsorda <filippo@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Carlos Amedee <carlos@golang.org>
Reviewed-by: David Chase <drchase@google.com>
2024-12-18 14:59:07 -08:00
Filippo Valsorda
6aa46eb750 crypto/tls: normalize spelling of "ClientHello" in comments
Change-Id: I2b62fb37ae390c42682354eaa2a9d03159563b6d
Reviewed-on: https://go-review.googlesource.com/c/go/+/637179
Reviewed-by: Daniel McCarney <daniel@binaryparadox.net>
Reviewed-by: Roland Shoemaker <roland@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Filippo Valsorda <filippo@golang.org>
Reviewed-by: David Chase <drchase@google.com>
2024-12-18 08:50:08 -08:00
Filippo Valsorda
10ca5ba4ff crypto/pbkdf2: update RFC reference in package doc
Now that it's published, we don't need to explain how we diverge from
the old one.

Change-Id: If2c22e89dd1b9fc531a363b5fb7b1eb5720eb84e
Reviewed-on: https://go-review.googlesource.com/c/go/+/637215
Auto-Submit: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Daniel McCarney <daniel@binaryparadox.net>
Reviewed-by: David Chase <drchase@google.com>
Reviewed-by: Roland Shoemaker <roland@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2024-12-18 08:49:24 -08:00
Filippo Valsorda
8ff4cee564 cmd/go,crypto: reject using Go+BoringCrypto and fips140 together
The combination is untested and nonsensical. Both are solutions to the
same problem.

For #69536

Change-Id: I95cc3baaf03b64ce08096e304e311a29e9577385
Reviewed-on: https://go-review.googlesource.com/c/go/+/637177
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Russ Cox <rsc@golang.org>
Auto-Submit: Filippo Valsorda <filippo@golang.org>
Reviewed-by: David Chase <drchase@google.com>
2024-12-18 08:49:21 -08:00
Ian Lance Taylor
971448ddf8 testing: support B.Context and F.Context
CL 603959 added T.Context for #36532.

The discussion on the proposal only mentions t.Context.
However, the implementation of CL 603959 also added B.Context and F.Context.
They were added to the API listing, and B.Context was mentioned in
the release notes.

Unfortunately, the new B.Context and F.Context methods always
returned nil, rather than a context.Context value.

This change adds a working implementation of B.Context and F.Context.

For #36532
Fixes #70866

Change-Id: I8a44e6649fb658e4f641ffb7efd08b4374f578ef
Reviewed-on: https://go-review.googlesource.com/c/go/+/637236
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: David Chase <drchase@google.com>
Reviewed-by: Damien Neil <dneil@google.com>
2024-12-18 08:18:04 -08:00
Ian Lance Taylor
95b433eed4 debug/elf: adjust version API per issue discussion
This updates the new version API for the discussion on #63952.

Note that the current tests do not have symbols with hidden versions.
Leaving that for later.

For #63952

Change-Id: I1ad4b1e485429a216ba8e5b68f7f4299d120628f
Reviewed-on: https://go-review.googlesource.com/c/go/+/637235
Reviewed-by: Ian Lance Taylor <iant@google.com>
Auto-Submit: Ian Lance Taylor <iant@google.com>
Reviewed-by: Austin Clements <austin@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Commit-Queue: Ian Lance Taylor <iant@google.com>
2024-12-17 13:28:29 -08:00
Filippo Valsorda
b2c0168893 crypto/internal/fips140/aes/gcm: use aes.EncryptBlockInternal on ppc64x and s390x
Left them out of CL 636775 because I did a search by reference, which
does not span architectures.

Fixes crypto/cipher.TestFIPSServiceIndicator failure on ppc64x and s390x.

For #69536

Change-Id: I34b49705a7099066e8c3871a7a34b394a9298e98
Reviewed-on: https://go-review.googlesource.com/c/go/+/637175
Reviewed-by: David Chase <drchase@google.com>
Reviewed-by: Roland Shoemaker <roland@golang.org>
Auto-Submit: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Daniel McCarney <daniel@binaryparadox.net>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2024-12-17 11:35:53 -08:00
Filippo Valsorda
b9e2ffdcd2 crypto/internal/fips140: add Name and Version
Per ISO/IEC 19790:2012, Section 7.4.3.1.

> A cryptographic module shall [04.12] provide the following services to
> operators.
>
> a) Show module’s versioning information. The cryptographic module
> shall [04.13] output the name or module identifier and the versioning
> information that can be correlated with a validation record (e.g.
> hardware, software and/or firmware versioning information)."

For #69536

Change-Id: I8061f64e4ae60a4666f6abd892cb1301d6bf2452
Reviewed-on: https://go-review.googlesource.com/c/go/+/636558
Auto-Submit: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Daniel McCarney <daniel@binaryparadox.net>
Reviewed-by: Roland Shoemaker <roland@golang.org>
Reviewed-by: David Chase <drchase@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2024-12-17 11:35:50 -08:00
wangshuo
8790372a8d cmd, go: fix some typos
Change-Id: I0fd54ae5294eb4ef30cdef05adb8825f69077b14
GitHub-Last-Rev: ccfa48cbe4
GitHub-Pull-Request: golang/go#70823
Reviewed-on: https://go-review.googlesource.com/c/go/+/635915
Reviewed-by: Ian Lance Taylor <iant@google.com>
Reviewed-by: Robert Griesemer <gri@google.com>
Auto-Submit: Ian Lance Taylor <iant@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2024-12-17 11:19:09 -08:00
Oleksandr Redko
b057b8872d bytes, strings: add cross-references in docstrings
For newly funcs SplitSeq, SplitAfterSeq, FieldsSeq, FieldsFuncSeq.

Updates #61901.

Change-Id: I3c97bfd9c2250de68aaea348c82a05635ee797af
Reviewed-on: https://go-review.googlesource.com/c/go/+/637176
Auto-Submit: Ian Lance Taylor <iant@google.com>
Reviewed-by: Robert Griesemer <gri@google.com>
Reviewed-by: Ian Lance Taylor <iant@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2024-12-17 11:08:32 -08:00
Oleksandr Redko
e977b83b32 cmd/go/internal/help: use secure link to swig.org
Change-Id: Ifd315128ceeddf92bc16647869c3ace77ed1f430
Reviewed-on: https://go-review.googlesource.com/c/go/+/637195
Reviewed-by: Michael Matloob <matloob@golang.org>
Auto-Submit: Ian Lance Taylor <iant@google.com>
Reviewed-by: Ian Lance Taylor <iant@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2024-12-17 10:54:56 -08:00
Damien Neil
4ac8f552e9 syscall, internal/syscall/unix: fix fstatat on linux/mips64
On linux/mips64, the syscall.Stat_t struct does not match the
kernel version of the struct. Functions that operate on a Stat_t
translate between it and the kernel struct.

The fstatat function was not doing this translation.
Make it do so.

Export a syscall.Fstatat on mips64 for usage by
internal/syscall/unix. Perhaps we should just do this on all
architectures, but this is the smaller change for now.

Fixes #70659

Change-Id: I38e36473689be25861953b418c9abc5b270a7bcf
Reviewed-on: https://go-review.googlesource.com/c/go/+/633280
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Ian Lance Taylor <iant@google.com>
2024-12-17 10:04:38 -08:00
Robert Griesemer
236a0b4ffb spec: explain function invocation and passing of parameters more precisely
- Describe that function invocation allocates space for a functions'
  variables.
- Explain parameter passing in terms of assignments.

Change-Id: Ia693d73a570f7d1aa2ac05e6095b4e602e4e9bf2
Reviewed-on: https://go-review.googlesource.com/c/go/+/635800
Reviewed-by: Robert Griesemer <gri@google.com>
Reviewed-by: Ian Lance Taylor <iant@google.com>
TryBot-Bypass: Robert Griesemer <gri@google.com>
Auto-Submit: Robert Griesemer <gri@google.com>
Reviewed-by: Rob Pike <r@golang.org>
2024-12-17 08:37:52 -08:00
Filippo Valsorda
9f806bb76c go/build: streamline the crypto package graph in TestDependencies
Change-Id: I975243b4897d5161b839f142afbd2a46bfa1fab0
Reviewed-on: https://go-review.googlesource.com/c/go/+/636555
Reviewed-by: Daniel McCarney <daniel@binaryparadox.net>
Auto-Submit: Filippo Valsorda <filippo@golang.org>
Reviewed-by: David Chase <drchase@google.com>
TryBot-Bypass: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Roland Shoemaker <roland@golang.org>
2024-12-17 08:07:47 -08:00
qmuntal
0cd833d198 go/build: remove nonexistent package from TestDependencies
crypto/internal/boring/fips140tls is not a package in the Go standard
library, so it should not be listed in TestDependencies.

Change-Id: I6476da397b0204fcbd0a11b27a29112fca4b6023
Reviewed-on: https://go-review.googlesource.com/c/go/+/636415
Reviewed-by: Filippo Valsorda <filippo@golang.org>
Auto-Submit: Quim Muntal <quimmuntal@gmail.com>
Reviewed-by: David Chase <drchase@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
2024-12-17 08:07:44 -08:00
Filippo Valsorda
31e50af5f3 crypto/rsa: revert minimum GenerateKey size to 32 bits
No point in causing breakage even with GODEBUG=rsa1024min=0.

Change-Id: I923254a8c8afaca77be551b19e3555c44ebdbb67
Reviewed-on: https://go-review.googlesource.com/c/go/+/636557
Reviewed-by: Roland Shoemaker <roland@golang.org>
Reviewed-by: David Chase <drchase@google.com>
Auto-Submit: Filippo Valsorda <filippo@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Daniel McCarney <daniel@binaryparadox.net>
2024-12-17 08:05:08 -08:00
Filippo Valsorda
b47ce8b0e9 crypto/cipher: block non-AES CTR and CBC in fips140=only mode
Somehow I had missed these.

For #69536

Change-Id: I5e60b6f052bbfb707742ad15f663517c6c5f68d3
Reviewed-on: https://go-review.googlesource.com/c/go/+/636795
Auto-Submit: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Roland Shoemaker <roland@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: David Chase <drchase@google.com>
2024-12-17 08:02:43 -08:00
Filippo Valsorda
dd7a7ba38f crypto/internal/fips140/aes: mark AES-ECB as not approved
NIST SP 800-131Ar3 ipd, scheduled for publication in 2025Q1, marks
AES-ECB as disallowed for encryption, and legacy use for decryption.

There are apparently no details on how the transition is going to work,
so to avoid surprises we just mark direct use of the Block as
non-approved.

We need to use Encrypt from higher level modes without tripping the
service indicator. Within the aes package, we just use the internal
function. For the gcm package we could do something more clever, but
this deep into the freeze, just make an exported function that we commit
to use nowhere else.

I could not figure out a decent way to block ECB on GODEBUG=fips140=only.

For #69536

Change-Id: I972a4b5da8efd0a0ab68d7dd509bec73aa2d6b68
Reviewed-on: https://go-review.googlesource.com/c/go/+/636775
Reviewed-by: David Chase <drchase@google.com>
Reviewed-by: Roland Shoemaker <roland@golang.org>
Auto-Submit: Filippo Valsorda <filippo@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2024-12-17 08:02:39 -08:00
Michael Matloob
427a2401af cmd/go/testdata/script: update test_flags for new test output
With CL 635856, an error for a package missing go files is now caught at
load time rather than at build time, so it's reported differently.
Update the test to check for the correct output unbreak the builders.

For #70820

Change-Id: I91fcac17961635b9a92782caa58c9a6f057a7e02
Reviewed-on: https://go-review.googlesource.com/c/go/+/637115
Reviewed-by: Sam Thanawalla <samthanawalla@google.com>
Auto-Submit: Michael Matloob <matloob@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2024-12-17 07:54:16 -08:00
Ian Lance Taylor
75736cc169 fmt, strconv: document that exponent is always two digits
Except for %b where it is only one.

Fixes #70862

Change-Id: Ic423a799b73bfa534f4083f6544bb9cd639fef06
Reviewed-on: https://go-review.googlesource.com/c/go/+/636915
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: David Chase <drchase@google.com>
Reviewed-by: Rob Pike <r@golang.org>
Reviewed-by: Ian Lance Taylor <iant@google.com>
Auto-Submit: Ian Lance Taylor <iant@google.com>
2024-12-17 07:54:13 -08:00
Cherry Mui
1218566fe5 cmd/link: update runtime dependency list
There have been a number of internal packages that the runtime
package depends on. Update the list. We should stop using a hard-
coded list.

Change-Id: I6f9338d6690d955b8200f3301addd0e133a1bfe2
Reviewed-on: https://go-review.googlesource.com/c/go/+/636478
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Michael Pratt <mpratt@google.com>
2024-12-16 18:19:39 -08:00
Michael Matloob
d92c34a387 cmd/go: don't create test actions for incomplete packages
If a package is incomplete, don't create the actions for building and
testing it. Instead report the errors for the package's dependencies
and report a setup failed error (similar to what we'd to for a load
error when producing the test packages). This produces similar errors to
what were produced by load.CheckPackageErrors while still produing the
test failure actions per package under test.

(I wasn't sure what to do about the last test case in test_setup_error.
I think it should be treated the same as other load errors?)

Fixes #70820

Change-Id: Ie95e3c158c50ed35a1f27237ef3db40502719993
Reviewed-on: https://go-review.googlesource.com/c/go/+/635856
Reviewed-by: Sam Thanawalla <samthanawalla@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Michael Matloob <matloob@golang.org>
Reviewed-by: Austin Clements <austin@google.com>
2024-12-16 13:43:25 -08:00
Michael Anthony Knyszek
3bd08b9792 runtime: usleep in TestWeakToStrongMarkTermination
There's a subtle bug in this test (big surprise): time.Sleep allocates,
so the time.Sleep(100*time.Millisecond) before unblocking gcMarkDone
might itself end up in gcMarkDone.

Work around this by using usleep here instead.

Fixes #70532.

Change-Id: I4c642ebb12f737cdb0d79ccff64b6059fc3d8b34
Reviewed-on: https://go-review.googlesource.com/c/go/+/636155
Reviewed-by: Cherry Mui <cherryyz@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2024-12-16 08:57:31 -08:00
Austin Clements
18b5435fc8 testing: don't measure cleanup time after B.Loop
B.Loop resets the timer on the first iteration so that setup code
isn't measured, but it currently leaves the timer running after the
last iteration, meaning that cleanup code will still be measured. Fix
this by stopping the timer when B.Loop returns false to indicate the
end of the benchmark.

Updates #61515

Change-Id: I0e0502cb2ce3c24cf872682b88d74e8be2c4529b
Reviewed-on: https://go-review.googlesource.com/c/go/+/635898
Reviewed-by: Junyang Shao <shaojunyang@google.com>
Auto-Submit: Austin Clements <austin@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
2024-12-15 21:41:28 -08:00
Austin Clements
c1f2542c8b testing: improve B.Loop test
This moves the B.Loop test from package testing_test to package
testing, where it can check on more of the internals of the benchmark
state.

Updates #61515.

Change-Id: Ia32d7104526125c5e8a1e35dab7660008afcbf80
Reviewed-on: https://go-review.googlesource.com/c/go/+/635897
Auto-Submit: Austin Clements <austin@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Junyang Shao <shaojunyang@google.com>
2024-12-15 21:41:26 -08:00
Austin Clements
6bd56fcaeb testing: improve b.Loop example
The current b.Loop example doesn't focus on the basic usage of b.Loop.
Replace this with a new example that uses (slightly) more realistic
things to demonstrate the most salient points of b.Loop.

We also move the example into an example file so that we can write a
real Benchmark function and a real function to be benchmarks, which
makes this much closer to what a user would actually write.

Updates #61515.

Change-Id: I4d830b3bfe3eb3cd8cdecef469fea0541baebb43
Reviewed-on: https://go-review.googlesource.com/c/go/+/635896
Auto-Submit: Austin Clements <austin@google.com>
Reviewed-by: Junyang Shao <shaojunyang@google.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2024-12-15 21:41:23 -08:00
Austin Clements
090748d6c7 testing: improve B.Loop docs, use B.Loop in examples
This updates the testing documentation to frame B.Loop as the
canonical way to write benchmarks. We retain documentation on b.N
benchmarks because people will definitely continue to see them (and
write them), but it's demoted to clearly second class.

This also attempts to clarify and refine the B.Loop documentation
itself.

Updates #61515
Fixes #70787

Change-Id: If5123435bfe3a5883a753119ecdf7bbc41afd499
Reviewed-on: https://go-review.googlesource.com/c/go/+/635895
Reviewed-by: Junyang Shao <shaojunyang@google.com>
Reviewed-by: Caleb Spare <cespare@gmail.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Austin Clements <austin@google.com>
2024-12-15 21:41:19 -08:00
Austin Clements
e39e965e0e cmd/go: drop FailedBuild field if gotestjsonbuildtext=1
go test -json has two new effects in Go 1.24: it implies go build
-json, and it adds a FailedBuild field in test events. For
compatibility, CL 629335 added gotestjsonbuildtext=1, which disables
the implicit go build -json, but that CL didn't affect the FailedBuild
field. In principle this shouldn't matter because it's just another
JSON field, but just so we don't have to worry about some intermediate
behavior, this CL makes gotestjsonbuildtext=1 disable the FailedBuild
field as well.

Updates #62067
Updates #70402

Change-Id: I006d1ea0468980ee2564495324e8b4ed082898af
Reviewed-on: https://go-review.googlesource.com/c/go/+/635899
Auto-Submit: Austin Clements <austin@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
2024-12-13 15:07:27 -08:00
Michael Pratt
08770a5b94 cmd/link: make dwarf name slice index self-describing
cmd/compile/internal/dwarfgen.createComplexVar does it this way, which
has the nice property of documenting the expected prefix.

This is primarily for newtype, since defgotype checks for the prefix
immediately prior, but I changed both for consistency.

Change-Id: I49fa7c6166bdcbd19aaf91fe3dc20537080afcfc
Reviewed-on: https://go-review.googlesource.com/c/go/+/635177
Reviewed-by: Michael Knyszek <mknyszek@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Michael Pratt <mpratt@google.com>
2024-12-13 12:32:22 -08:00
Filippo Valsorda
c4f356dd86 crypto/ecdsa: fix s390x assembly with P-521
I had incorrectly assumed that the blocksize was always the same as the
curve field size. This is true of P-256 and P-384, but not P-521.

Fixes #70660
Fixes #70771

Change-Id: Idb6b510fcd3dd42d9b1e6cf42c1bb92e0ce8bd07
Reviewed-on: https://go-review.googlesource.com/c/go/+/636015
Run-TryBot: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Carlos Amedee <carlos@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Filippo Valsorda <filippo@golang.org>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Roland Shoemaker <roland@golang.org>
2024-12-13 11:22:11 -08:00
Filippo Valsorda
08725f9de2 crypto/internal/cryptotest: skip TestAllocations on s390x
TestXAESAllocations fails like #70448, and crypto/rand's fails in FIPS
mode. We can't keep chasing these without even a LUCI builder.

Updates #67307

Change-Id: I5d0edddf470180a321dec55cabfb018db62eb940
Reviewed-on: https://go-review.googlesource.com/c/go/+/636055
Auto-Submit: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Roland Shoemaker <roland@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Carlos Amedee <carlos@golang.org>
2024-12-13 11:20:55 -08:00
thepudds
1cbfe8c482 fmt: add more function and allocation tests
This is part of a series of CLs that aim to reduce how often interface
arguments escape for the print functions in fmt.

Currently, method values are one of two reasons reflect.Value.Interface
always escapes its reflect.Value.

Our later CLs modify behavior around method values, so we add some tests
of function formatting (including method values) to help reduce the
chances of breaking behavior later.

We also add in some allocation tests focused on interface arguments for
the print functions. These currently do not show any improvements
compared to Go 1.21.

These tests were originally in a later CL in our stack (CL 528538),
but we split them out into this CL and moved them earlier in the stack.

Updates #8618

Change-Id: Iec51abc3b7f86a2711e7497fc2fb7a678b9f8f73
Reviewed-on: https://go-review.googlesource.com/c/go/+/529575
Reviewed-by: Carlos Amedee <carlos@golang.org>
Auto-Submit: Ian Lance Taylor <iant@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Ian Lance Taylor <iant@google.com>
2024-12-13 11:20:04 -08:00
Gopher Robot
16afa6a740 [release-branch.go1.24] go1.24rc1
Change-Id: Ia3b0a8ec25312b73879d2561a2b4d1cfc648c295
Reviewed-on: https://go-review.googlesource.com/c/go/+/636036
Reviewed-by: Carlos Amedee <carlos@golang.org>
Auto-Submit: Gopher Robot <gobot@golang.org>
TryBot-Bypass: Carlos Amedee <carlos@golang.org>
Reviewed-by: Michael Knyszek <mknyszek@google.com>
2024-12-13 08:52:10 -08:00
Michael Pratt
8391579ece runtime: migrate missing map linkname allowlists
The swissmap implementation forgot to copy some of the linkname
allowlists from the old implementation. Copy them from map_noswiss.go.
Some were missing linkname entirely; others were linknamed but missing
the hall of shame comment.

For #54766.

Change-Id: Icc715384123e73d868b4cb729ab639abcd6bbfd7
Reviewed-on: https://go-review.googlesource.com/c/go/+/635995
Reviewed-by: Cherry Mui <cherryyz@google.com>
Auto-Submit: Michael Pratt <mpratt@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2024-12-13 07:53:26 -08:00
Robert Griesemer
80a2982a80 spec: align EBNF rules consistently (cosmetic change)
Change-Id: Ib1b14b8880c6de5606f7f425a5fc1c8749d8a4b7
Reviewed-on: https://go-review.googlesource.com/c/go/+/635799
TryBot-Bypass: Robert Griesemer <gri@google.com>
Reviewed-by: Ian Lance Taylor <iant@google.com>
Reviewed-by: Robert Griesemer <gri@google.com>
Auto-Submit: Robert Griesemer <gri@google.com>
2024-12-12 15:39:44 -08:00
Ian Lance Taylor
38e9a671d7 syscall: on freebsd-386 only update written for certain errors
Testing on the freebsd-386 gomote seems to show that sendfile returns
a non-zero number of bytes written even when it returns EINVAL.
This confuses the caller. Change the Go code to only return non-zero
on success or EINTR or EAGAIN, which are the only cases where the
man page says that sendfile updates the number of bytes.

For #70763

Change-Id: Icc04e6286b5b29a2029237711d50fe4973234f0a
Reviewed-on: https://go-review.googlesource.com/c/go/+/635815
Reviewed-by: Ian Lance Taylor <iant@google.com>
Commit-Queue: Ian Lance Taylor <iant@google.com>
Reviewed-by: Damien Neil <dneil@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Ian Lance Taylor <iant@google.com>
2024-12-12 14:43:37 -08:00
Oleksandr Redko
6f7a4540b1 net: fix example function name for IP.To4
Change-Id: Ia9a2c3a9f53792173cd1fb9f8e1a078fe3444945
Reviewed-on: https://go-review.googlesource.com/c/go/+/635136
Auto-Submit: Ian Lance Taylor <iant@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Carlos Amedee <carlos@golang.org>
Reviewed-by: Ian Lance Taylor <iant@google.com>
2024-12-12 13:01:47 -08:00
Cherry Mui
14e5093ee5 cmd/internal/obj: disallow linknamed access to builtin symbols
Currently, a symbol reference is counted as a reference to a
builtin symbol if the name matches a builtin. Usually builtin
references are generated by the compiler. But one could manually
write one with linkname. Since the list of builtin functions are
subject to change from time to time, we don't want users to depend
on their names. So we don't count a linknamed reference as a
builtin reference, and instead, count it as a named reference, so
it is checked by the linker.

Change-Id: Id3543295185c6bbd73a8cff82afb8f9cb4fd6f71
Reviewed-on: https://go-review.googlesource.com/c/go/+/635755
Reviewed-by: Michael Pratt <mpratt@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2024-12-12 12:58:47 -08:00
Cherry Mui
fb764cdad0 cmd/link: block new standard library linknames
In Go 1.24 we added a number of new linknames for standard library
internal uses. Add them to the linker's blocklist to keep them
internal.

Change-Id: Ibb7fa095506c161604e978ae196a7cf248475b2e
Reviewed-on: https://go-review.googlesource.com/c/go/+/635676
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Michael Pratt <mpratt@google.com>
2024-12-12 11:54:53 -08:00
Carlos Amedee
817d7bdc0a [release-branch.go1.24] all: merge master (9118060) into release-branch.go1.24
Merge List:

+ 2024-12-12 9118060040 builtin: document clear is a no-op if its argument's value is nil
+ 2024-12-11 077d51909d internal/poll: in SendFile treat ENOTSUP like EOPNOTSUPP
+ 2024-12-11 fafd4477f3 cmd/cgo: use full prototype for main in C code

Change-Id: I4c4941eff4a1e842920eb9be47d28351af0e4c36
2024-12-12 12:06:37 -05:00
apocelipes
9118060040 builtin: document clear is a no-op if its argument's value is nil
Just like the builtin function delete's comment does.

Change-Id: Id94a3aaa03c7b09594bae2b1af901d9060d9e255
GitHub-Last-Rev: 30cbebca96
GitHub-Pull-Request: golang/go#70801
Reviewed-on: https://go-review.googlesource.com/c/go/+/635535
Reviewed-by: Carlos Amedee <carlos@golang.org>
Reviewed-by: Keith Randall <khr@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Keith Randall <khr@google.com>
Auto-Submit: Keith Randall <khr@golang.org>
2024-12-12 07:43:21 -08:00
Ian Lance Taylor
077d51909d internal/poll: in SendFile treat ENOTSUP like EOPNOTSUPP
Fixes #70763

Change-Id: Ifb79b5b0529f7977df0fe1b59d224b8b31df2c9b
Reviewed-on: https://go-review.googlesource.com/c/go/+/635396
Reviewed-by: Ian Lance Taylor <iant@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Damien Neil <dneil@google.com>
Auto-Submit: Ian Lance Taylor <iant@google.com>
2024-12-11 17:52:03 -08:00
Ian Lance Taylor
fafd4477f3 cmd/cgo: use full prototype for main in C code
Avoids pedantic errors from modern C compilers.

Fixes #70769

Change-Id: Ibe0d9960e998eb0346b97d7bd69eb7de0d0e6c60
Reviewed-on: https://go-review.googlesource.com/c/go/+/635095
Reviewed-by: Robert Griesemer <gri@google.com>
Reviewed-by: Mauri de Souza Meneguzzo <mauri870@gmail.com>
Reviewed-by: Ian Lance Taylor <iant@google.com>
Auto-Submit: Ian Lance Taylor <iant@google.com>
Commit-Queue: Ian Lance Taylor <iant@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2024-12-11 15:57:34 -08:00
Carlos Amedee
14bb1e11b9 [release-branch.go1.24] all: merge master (0ca521f) into release-branch.go1.24
Merge List:

+ 2024-12-11 0ca521f9c1 debug/elf: adjust version API per issue discussion

Change-Id: Ibd6f628528dd366837ad0bbacad624474eee0088
2024-12-11 18:55:28 -05:00
Ian Lance Taylor
0ca521f9c1 debug/elf: adjust version API per issue discussion
This updates the new version API for the discussion on #63952.

This change reveals that in fact none of the tests set the
VERSYM_HIDDEN bit. The code before this CL set the hidden flag
for symbols that appear in DynamicVersionNeed, but that is not
an accurate representation of the ELF. The readelf program
does print undefined symbols that way (with a single '@'),
but that doesn't mean that the hidden flag is set.
Leaving tests with the hidden bit set for later.

For #63952

Change-Id: Ida60831e0c9922dfc10f10c7a64bc76a2b197537
Reviewed-on: https://go-review.googlesource.com/c/go/+/635079
Reviewed-by: Austin Clements <austin@google.com>
Commit-Queue: Ian Lance Taylor <iant@google.com>
Auto-Submit: Ian Lance Taylor <iant@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Ian Lance Taylor <iant@google.com>
2024-12-11 15:40:12 -08:00
Carlos Amedee
2297c34cdf [release-branch.go1.24] all: merge master (c93477b) into release-branch.go1.24
Merge List:

+ 2024-12-11 c93477b5e5 crypto: use provided random Reader in FIPS mode
+ 2024-12-11 3104b6adbb log/slog: make DiscardHandler example package-level
+ 2024-12-11 5424f2e200 cmd/go: add more tests for GOAUTH's user provided authenticator
+ 2024-12-11 d5c1333eb4 net/http: document zero value of Protocols
+ 2024-12-11 a7c4cadce0 cmd/compile: update broken link
+ 2024-12-11 979c1cfbe8 net: avoid unnecessary interface lookup fetching all interface addresses
+ 2024-12-11 e424d78c3d internal/goos: fix bug in gengoos.go
+ 2024-12-11 6c25cf1c5f cmd/internal/objfile: break out dissassemblers to another package
+ 2024-12-11 e0c76d95ab syscall: remove a wrong comment in Clearenv
+ 2024-12-11 a9922d096f reflect: consistently document when value must be settable
+ 2024-12-10 4ce116a884 runtime: avoid panic in expired synctest timer chan read
+ 2024-12-10 e6de1b2deb html/template: escape script tags in JS errors case insensitively
+ 2024-12-10 fce17b0c77 crypto/internal/fips140/ecdsa: fix reseed_counter check for HMAC_DRBG_Generate_algorithm
+ 2024-12-09 d87878c62b runtime: make special offset a uintptr
+ 2024-12-09 6705ac6885 runtime: remove datadog-agent from prof labels hall of shame
+ 2024-12-09 07398d2e57 weak: align weak.Pointer documentation with runtime.AddCleanup
+ 2024-12-09 e3e1d73528 bufio: make the description of Peek's behavior better
+ 2024-12-09 e79b2e1e3a cmd/go: document the build cache as safe for concurrent use
+ 2024-12-08 c8fb6ae617 lib/wasm: provide fs.constants.O_DIRECTORY definition
+ 2024-12-07 8c3e391573 runtime: improve AddCleanup documentation
+ 2024-12-07 04cdaa9984 cmd/go: document c-shared buildmode for building WASI library/reactor
+ 2024-12-06 312f7c1bd3 runtime: add note that Callers never returns an entry PC

Change-Id: I52e035228121de3d8219ab13f195d4293daaaa34
2024-12-11 17:45:39 -05:00
Filippo Valsorda
c93477b5e5 crypto: use provided random Reader in FIPS mode
This removes the difference in behavior between FIPS mode on and off.

Instead of the sentinel type we could have moved the Reader to the
drbg package and checked for equality, but then we would have locked the
crypto/rand.Reader implementation to the one in the FIPS module (which
we might have to support for years).

In internal/ed25519.GenerateKey we remove the random parameter entirely,
since that function is not actually used by crypto/ed25519.GenerateKey,
which instead commits to being deterministic.

Fixes #70772

Change-Id: Ic1c7ca2c1cd59eb9cd090a8b235c0ce218921ac5
Reviewed-on: https://go-review.googlesource.com/c/go/+/635195
Reviewed-by: Roland Shoemaker <roland@golang.org>
Auto-Submit: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Russ Cox <rsc@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2024-12-11 13:26:50 -08:00
Jonathan Amsterdam
3104b6adbb log/slog: make DiscardHandler example package-level
Fixes #70782.

Change-Id: I8e8b763040bd10147eb7d1a30ac0774e28f90911
Reviewed-on: https://go-review.googlesource.com/c/go/+/635217
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Ian Lance Taylor <iant@google.com>
2024-12-11 13:06:33 -08:00
Sam Thanawalla
5424f2e200 cmd/go: add more tests for GOAUTH's user provided authenticator
For #26232
Cq-Include-Trybots: luci.golang.try:gotip-linux-amd64-longtest,gotip-windows-amd64-longtest
Change-Id: I4b6eb63d4c1d71983e1ae764a6a38744a5f01317
Reviewed-on: https://go-review.googlesource.com/c/go/+/635255
Auto-Submit: Sam Thanawalla <samthanawalla@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Michael Matloob <matloob@golang.org>
2024-12-11 12:29:07 -08:00
Damien Neil
d5c1333eb4 net/http: document zero value of Protocols
For #67814

Change-Id: I182e9c7e720493adb9d2384336e757dace818525
Reviewed-on: https://go-review.googlesource.com/c/go/+/635335
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Damien Neil <dneil@google.com>
Reviewed-by: Austin Clements <austin@google.com>
2024-12-11 12:15:29 -08:00
Ian Lance Taylor
a7c4cadce0 cmd/compile: update broken link
Fixes #70778

Change-Id: Ie5ed53aa39446beb0316eb134cc705ea06b37435
Reviewed-on: https://go-review.googlesource.com/c/go/+/635295
Auto-Submit: Ian Lance Taylor <iant@golang.org>
Reviewed-by: Keith Randall <khr@golang.org>
Reviewed-by: Keith Randall <khr@google.com>
Reviewed-by: Ian Lance Taylor <iant@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2024-12-11 10:13:44 -08:00
Antonio Ojea
979c1cfbe8 net: avoid unnecessary interface lookup fetching all interface addresses
InterfaceAddrs returns a list of the system's unicast interface addresses.

In order to do so, the function reuses the existing helpers and
list first all addresses with the netlink call RTM_GETADDR, then
all interfaces with RTM_GETLINK, and later it merge both lists
(each address references an interface).

However, the list of interfaces and addresses are obtained at
different times and there can be inconsistencies and, if an
address references an interface that is not present in the list
of interfaces, the function fails with an error.

Since the function InterfaceAddress is only about the system
addresses, there is no need to list all the interfaces, and we can
obtain the list of addresses directly from the netlink call RTM_GETADDR.
There is no need to correlate this list with the list of interfaces, as
the OS is the source of truth and should be the one providing the
consistency between addresses and interfaces.

Fixes #51934

Change-Id: I3b816e8146b1c07fdfe1bf6af338f001ef75734f
Reviewed-on: https://go-review.googlesource.com/c/go/+/635196
Reviewed-by: Ian Lance Taylor <iant@google.com>
Commit-Queue: Ian Lance Taylor <iant@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Ian Lance Taylor <iant@google.com>
2024-12-11 10:02:08 -08:00
zfdx123
e424d78c3d internal/goos: fix bug in gengoos.go
CL 601357 mistakenly added an extra period.

Change-Id: I54db621663797f094059a4eb86bf5d9626fa59d6
GitHub-Last-Rev: c756e0a824
GitHub-Pull-Request: golang/go#70733
Reviewed-on: https://go-review.googlesource.com/c/go/+/634517
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Ian Lance Taylor <iant@google.com>
Reviewed-by: Michael Pratt <mpratt@google.com>
Reviewed-by: Ian Lance Taylor <iant@google.com>
2024-12-11 09:54:18 -08:00
Cherry Mui
6c25cf1c5f cmd/internal/objfile: break out dissassemblers to another package
Currently, cmd/internal/objfile provides dissassembly routines for
various architectures, which depend on dissassemblers from x/arch.
cmd/internal/objfile is imported in tools that need dissassembly
(objdump, pprof) and tools that don't need dissassembly (nm,
addr2line). Adding/improving disassembly support for more
architectures can cause binary size increase, and for some tools
(nm, addr2line) it is not necessary.

This CL breaks out dissassembly routines to a different package,
which is only imported in tools that need dissassembly. Other
tools can depend on cmd/internal/objfile without the disassembly
code from x/arch.

This reduces binary sizes for those tools. On darwin/arm64,

                                 old         new
cmd/addr2line                  4554418     3648882   -20%
cmd/addr2line (-ldflags=-w)    3464626     2641650   -24%
cmd/nm                         4503874     3616722   -20%
cmd/nm (-ldflags=-w)           3430594     2609490   -24%

For #70699.

Change-Id: Ie45d5d5c5500c5f3882e8b3c4e6eb81f0d815292
Reviewed-on: https://go-review.googlesource.com/c/go/+/634916
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: David Chase <drchase@google.com>
2024-12-11 08:53:20 -08:00
Kir Kolyshkin
e0c76d95ab syscall: remove a wrong comment in Clearenv
The comment being removed was added by commit ff3173849e
(which predates Gerrit and Rietveld, so no CL link), and
at the time it made sense.

Since CL 148370043 (and up to the current implementation of Clearenv)
the env map, which is populated by copyenv, is actually used, so the
comment is no longer valid.

It is also misleading, so it's best to remove it.

Change-Id: I8bd2e8bca6262759538e5bcbd396f0c71cca6a4c
Reviewed-on: https://go-review.googlesource.com/c/go/+/635078
Reviewed-by: Carlos Amedee <carlos@golang.org>
Reviewed-by: Ian Lance Taylor <iant@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Ian Lance Taylor <iant@google.com>
2024-12-11 07:58:51 -08:00
Ian Lance Taylor
a9922d096f reflect: consistently document when value must be settable
Fixes #70760

Change-Id: Ia00723698b7e502fa2c63f8f1dbe1143af22e0a5
Reviewed-on: https://go-review.googlesource.com/c/go/+/634799
Reviewed-by: Ian Lance Taylor <iant@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Keith Randall <khr@google.com>
Commit-Queue: Ian Lance Taylor <iant@google.com>
Reviewed-by: Keith Randall <khr@golang.org>
Auto-Submit: Ian Lance Taylor <iant@golang.org>
Auto-Submit: Ian Lance Taylor <iant@google.com>
2024-12-11 04:00:12 +00:00
Michael Anthony Knyszek
26682773ca [release-branch.go1.24] update codereview.cfg for release-branch.go1.24
Change-Id: I63ffca43a935bc5ff060f19c01152a20182cba03
Reviewed-on: https://go-review.googlesource.com/c/go/+/634317
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Auto-Submit: Michael Knyszek <mknyszek@google.com>
2024-12-06 21:58:36 +00:00
201 changed files with 4190 additions and 1845 deletions

2
VERSION Normal file
View File

@@ -0,0 +1,2 @@
go1.24rc2
time 2025-01-13T18:38:39Z

View File

@@ -106,33 +106,26 @@ pkg debug/elf, const VER_FLG_INFO = 4 #63952
pkg debug/elf, const VER_FLG_INFO DynamicVersionFlag #63952
pkg debug/elf, const VER_FLG_WEAK = 2 #63952
pkg debug/elf, const VER_FLG_WEAK DynamicVersionFlag #63952
pkg debug/elf, const VerFlagGlobal = 2 #63952
pkg debug/elf, const VerFlagGlobal SymbolVersionFlag #63952
pkg debug/elf, const VerFlagHidden = 4 #63952
pkg debug/elf, const VerFlagHidden SymbolVersionFlag #63952
pkg debug/elf, const VerFlagLocal = 1 #63952
pkg debug/elf, const VerFlagLocal SymbolVersionFlag #63952
pkg debug/elf, const VerFlagNone = 0 #63952
pkg debug/elf, const VerFlagNone SymbolVersionFlag #63952
pkg debug/elf, method (*File) DynamicVersionNeeds() ([]DynamicVersionNeed, error) #63952
pkg debug/elf, method (*File) DynamicVersions() ([]DynamicVersion, error) #63952
pkg debug/elf, type DynamicVersion struct #63952
pkg debug/elf, type DynamicVersion struct, Deps []string #63952
pkg debug/elf, type DynamicVersion struct, Flags DynamicVersionFlag #63952
pkg debug/elf, type DynamicVersion struct, Name string #63952
pkg debug/elf, type DynamicVersion struct, Index uint16 #63952
pkg debug/elf, type DynamicVersion struct, Version uint16 #63952
pkg debug/elf, type DynamicVersionDep struct #63952
pkg debug/elf, type DynamicVersionDep struct, Dep string #63952
pkg debug/elf, type DynamicVersionDep struct, Flags DynamicVersionFlag #63952
pkg debug/elf, type DynamicVersionDep struct, Other uint16 #63952
pkg debug/elf, type DynamicVersionDep struct, Index uint16 #63952
pkg debug/elf, type DynamicVersionFlag uint16 #63952
pkg debug/elf, type DynamicVersionNeed struct #63952
pkg debug/elf, type DynamicVersionNeed struct, Name string #63952
pkg debug/elf, type DynamicVersionNeed struct, Needs []DynamicVersionDep #63952
pkg debug/elf, type DynamicVersionNeed struct, Version uint16 #63952
pkg debug/elf, type Symbol struct, VersionFlags SymbolVersionFlag #63952
pkg debug/elf, type Symbol struct, VersionIndex int16 #63952
pkg debug/elf, type SymbolVersionFlag uint8 #63952
pkg debug/elf, type Symbol struct, HasVersion bool #63952
pkg debug/elf, type Symbol struct, VersionIndex VersionIndex #63952
pkg debug/elf, method (VersionIndex) Index() uint16 #63952
pkg debug/elf, method (VersionIndex) IsHidden() bool #63952
pkg debug/elf, type VersionIndex uint16 #63952
pkg encoding, type BinaryAppender interface { AppendBinary } #62384
pkg encoding, type BinaryAppender interface, AppendBinary([]uint8) ([]uint8, error) #62384
pkg encoding, type TextAppender interface { AppendText } #62384

View File

@@ -1 +1,2 @@
branch: master
branch: release-branch.go1.24
parent-branch: master

View File

@@ -1,6 +1,6 @@
<!--{
"Title": "The Go Programming Language Specification",
"Subtitle": "Language version go1.24 (Nov 20, 2024)",
"Subtitle": "Language version go1.24 (Dec 30, 2024)",
"Path": "/ref/spec"
}-->
@@ -798,7 +798,6 @@ If a variable has not yet been assigned a value, its value is the
<a href="#The_zero_value">zero value</a> for its type.
</p>
<h2 id="Types">Types</h2>
<p>
@@ -810,12 +809,12 @@ from existing types.
</p>
<pre class="ebnf">
Type = TypeName [ TypeArgs ] | TypeLit | "(" Type ")" .
TypeName = identifier | QualifiedIdent .
TypeArgs = "[" TypeList [ "," ] "]" .
TypeList = Type { "," Type } .
TypeLit = ArrayType | StructType | PointerType | FunctionType | InterfaceType |
SliceType | MapType | ChannelType .
Type = TypeName [ TypeArgs ] | TypeLit | "(" Type ")" .
TypeName = identifier | QualifiedIdent .
TypeArgs = "[" TypeList [ "," ] "]" .
TypeList = Type { "," Type } .
TypeLit = ArrayType | StructType | PointerType | FunctionType | InterfaceType |
SliceType | MapType | ChannelType .
</pre>
<p>
@@ -1200,7 +1199,7 @@ type (
<p>
A pointer type denotes the set of all pointers to <a href="#Variables">variables</a> of a given
type, called the <i>base type</i> of the pointer.
The value of an uninitialized pointer is <code>nil</code>.
The <a href="#Representation_of_values">value</a> of an uninitialized pointer is <code>nil</code>.
</p>
<pre class="ebnf">
@@ -1216,18 +1215,18 @@ BaseType = Type .
<h3 id="Function_types">Function types</h3>
<p>
A function type denotes the set of all functions with the same parameter
and result types. The value of an uninitialized variable of function type
is <code>nil</code>.
A function type denotes the set of all functions with the same parameter and result types.
The <a href="#Representation_of_values">value</a> of an uninitialized variable of function
type is <code>nil</code>.
</p>
<pre class="ebnf">
FunctionType = "func" Signature .
Signature = Parameters [ Result ] .
Result = Parameters | Type .
Parameters = "(" [ ParameterList [ "," ] ] ")" .
ParameterList = ParameterDecl { "," ParameterDecl } .
ParameterDecl = [ IdentifierList ] [ "..." ] Type .
FunctionType = "func" Signature .
Signature = Parameters [ Result ] .
Result = Parameters | Type .
Parameters = "(" [ ParameterList [ "," ] ] ")" .
ParameterList = ParameterDecl { "," ParameterDecl } .
ParameterDecl = [ IdentifierList ] [ "..." ] Type .
</pre>
<p>
@@ -1267,7 +1266,8 @@ An interface type defines a <i>type set</i>.
A variable of interface type can store a value of any type that is in the type
set of the interface. Such a type is said to
<a href="#Implementing_an_interface">implement the interface</a>.
The value of an uninitialized variable of interface type is <code>nil</code>.
The <a href="#Representation_of_values">value</a> of an uninitialized variable of
interface type is <code>nil</code>.
</p>
<pre class="ebnf">
@@ -1630,12 +1630,12 @@ implements the interface.
A map is an unordered group of elements of one type, called the
element type, indexed by a set of unique <i>keys</i> of another type,
called the key type.
The value of an uninitialized map is <code>nil</code>.
The <a href="#Representation_of_values">value</a> of an uninitialized map is <code>nil</code>.
</p>
<pre class="ebnf">
MapType = "map" "[" KeyType "]" ElementType .
KeyType = Type .
MapType = "map" "[" KeyType "]" ElementType .
KeyType = Type .
</pre>
<p>
@@ -1693,7 +1693,7 @@ to communicate by
<a href="#Send_statements">sending</a> and
<a href="#Receive_operator">receiving</a>
values of a specified element type.
The value of an uninitialized channel is <code>nil</code>.
The <a href="#Representation_of_values">value</a> of an uninitialized channel is <code>nil</code>.
</p>
<pre class="ebnf">
@@ -1772,6 +1772,57 @@ received in the order sent.
<h2 id="Properties_of_types_and_values">Properties of types and values</h2>
<h3 id="Representation_of_values">Representation of values</h3>
<p>
Values of predeclared types (see below for the interfaces <code>any</code>
and <code>error</code>), arrays, and structs are self-contained:
Each such value contains a complete copy of all its data,
and <a href="#Variables">variables</a> of such types store the entire value.
For instance, an array variable provides the storage (the variables)
for all elements of the array.
The respective <a href="#The_zero_value">zero values</a> are specific to the
value's types; they are never <code>nil</code>.
</p>
<p>
Non-nil pointer, function, slice, map, and channel values contain references
to underlying data which may be shared by multiple values:
</p>
<ul>
<li>
A pointer value is a reference to the variable holding
the pointer base type value.
</li>
<li>
A function value contains references to the (possibly
<a href="#Function_literals">anonymous</a>) function
and enclosed variables.
</li>
<li>
A slice value contains the slice length, capacity, and
a reference to its <a href="#Slice_types">underlying array</a>.
</li>
<li>
A map or channel value is a reference to the implementation-specific
data structure of the map or channel.
</li>
</ul>
<p>
An interface value may be self-contained or contain references to underlying data
depending on the interface's <a href="#Variables">dynamic type</a>.
The predeclared identifier <code>nil</code> is the zero value for types whose values
can contain references.
</p>
<p>
When multiple values share underlying data, changing one value may change another.
For instance, changing an element of a <a href="#Slice_types">slice</a> will change
that element in the underlying array for all slices that share the array.
</p>
<h3 id="Underlying_types">Underlying types</h3>
<p>
@@ -2176,7 +2227,7 @@ within matching brace brackets.
</p>
<pre class="ebnf">
Block = "{" StatementList "}" .
Block = "{" StatementList "}" .
StatementList = { Statement ";" } .
</pre>
@@ -2233,8 +2284,8 @@ and like the blank identifier it does not introduce a new binding.
</p>
<pre class="ebnf">
Declaration = ConstDecl | TypeDecl | VarDecl .
TopLevelDecl = Declaration | FunctionDecl | MethodDecl .
Declaration = ConstDecl | TypeDecl | VarDecl .
TopLevelDecl = Declaration | FunctionDecl | MethodDecl .
</pre>
<p>
@@ -2679,9 +2730,9 @@ in square brackets rather than parentheses
</p>
<pre class="ebnf">
TypeParameters = "[" TypeParamList [ "," ] "]" .
TypeParamList = TypeParamDecl { "," TypeParamDecl } .
TypeParamDecl = IdentifierList TypeConstraint .
TypeParameters = "[" TypeParamList [ "," ] "]" .
TypeParamList = TypeParamDecl { "," TypeParamDecl } .
TypeParamDecl = IdentifierList TypeConstraint .
</pre>
<p>
@@ -2819,7 +2870,7 @@ values or variables, or components of other, non-interface types.
<p>
A type argument <code>T</code><i> satisfies</i> a type constraint <code>C</code>
if <code>T</code> is an element of the type set defined by <code>C</code>; i.e.,
if <code>T</code> is an element of the type set defined by <code>C</code>; in other words,
if <code>T</code> <a href="#Implementing_an_interface">implements</a> <code>C</code>.
As an exception, a <a href="#Comparison_operators">strictly comparable</a>
type constraint may also be satisfied by a <a href="#Comparison_operators">comparable</a>
@@ -2869,8 +2920,8 @@ binds corresponding identifiers to them, and gives each a type and an initial va
</p>
<pre class="ebnf">
VarDecl = "var" ( VarSpec | "(" { VarSpec ";" } ")" ) .
VarSpec = IdentifierList ( Type [ "=" ExpressionList ] | "=" ExpressionList ) .
VarDecl = "var" ( VarSpec | "(" { VarSpec ";" } ")" ) .
VarSpec = IdentifierList ( Type [ "=" ExpressionList ] | "=" ExpressionList ) .
</pre>
<pre>
@@ -2899,7 +2950,7 @@ initialization value in the assignment.
If that value is an untyped constant, it is first implicitly
<a href="#Conversions">converted</a> to its <a href="#Constants">default type</a>;
if it is an untyped boolean value, it is first implicitly converted to type <code>bool</code>.
The predeclared value <code>nil</code> cannot be used to initialize a variable
The predeclared identifier <code>nil</code> cannot be used to initialize a variable
with no explicit type.
</p>
@@ -3210,15 +3261,15 @@ Each element may optionally be preceded by a corresponding key.
</p>
<pre class="ebnf">
CompositeLit = LiteralType LiteralValue .
LiteralType = StructType | ArrayType | "[" "..." "]" ElementType |
SliceType | MapType | TypeName [ TypeArgs ] .
LiteralValue = "{" [ ElementList [ "," ] ] "}" .
ElementList = KeyedElement { "," KeyedElement } .
KeyedElement = [ Key ":" ] Element .
Key = FieldName | Expression | LiteralValue .
FieldName = identifier .
Element = Expression | LiteralValue .
CompositeLit = LiteralType LiteralValue .
LiteralType = StructType | ArrayType | "[" "..." "]" ElementType |
SliceType | MapType | TypeName [ TypeArgs ] .
LiteralValue = "{" [ ElementList [ "," ] ] "}" .
ElementList = KeyedElement { "," KeyedElement } .
KeyedElement = [ Key ":" ] Element .
Key = FieldName | Expression | LiteralValue .
FieldName = identifier .
Element = Expression | LiteralValue .
</pre>
<p>
@@ -3450,22 +3501,21 @@ Primary expressions are the operands for unary and binary expressions.
</p>
<pre class="ebnf">
PrimaryExpr =
Operand |
Conversion |
MethodExpr |
PrimaryExpr Selector |
PrimaryExpr Index |
PrimaryExpr Slice |
PrimaryExpr TypeAssertion |
PrimaryExpr Arguments .
PrimaryExpr = Operand |
Conversion |
MethodExpr |
PrimaryExpr Selector |
PrimaryExpr Index |
PrimaryExpr Slice |
PrimaryExpr TypeAssertion |
PrimaryExpr Arguments .
Selector = "." identifier .
Index = "[" Expression [ "," ] "]" .
Slice = "[" [ Expression ] ":" [ Expression ] "]" |
"[" [ Expression ] ":" Expression ":" Expression "]" .
TypeAssertion = "." "(" Type ")" .
Arguments = "(" [ ( ExpressionList | Type [ "," ExpressionList ] ) [ "..." ] [ "," ] ] ")" .
Selector = "." identifier .
Index = "[" Expression [ "," ] "]" .
Slice = "[" [ Expression ] ":" [ Expression ] "]" |
"[" [ Expression ] ":" Expression ":" Expression "]" .
TypeAssertion = "." "(" Type ")" .
Arguments = "(" [ ( ExpressionList | Type [ "," ExpressionList ] ) [ "..." ] [ "," ] ] ")" .
</pre>
@@ -3638,8 +3688,8 @@ argument that is the receiver of the method.
</p>
<pre class="ebnf">
MethodExpr = ReceiverType "." MethodName .
ReceiverType = Type .
MethodExpr = ReceiverType "." MethodName .
ReceiverType = Type .
</pre>
<p>
@@ -4230,8 +4280,7 @@ calls <code>f</code> with arguments <code>a1, a2, … an</code>.
Except for one special case, arguments must be single-valued expressions
<a href="#Assignability">assignable</a> to the parameter types of
<code>F</code> and are evaluated before the function is called.
The type of the expression is the result type
of <code>F</code>.
The type of the expression is the result type of <code>F</code>.
A method invocation is similar but the method itself
is specified as a selector upon a value of the receiver type for
the method.
@@ -4252,9 +4301,14 @@ or used as a function value.
<p>
In a function call, the function value and arguments are evaluated in
<a href="#Order_of_evaluation">the usual order</a>.
After they are evaluated, the parameters of the call are passed by value to the function
After they are evaluated, new storage is allocated for the function's
<a href="#Variables">variables</a>, which includes its parameters
and results.
Then, the arguments of the call are <i>passed</i> to the function,
which means that they are <a href="#Assignment_statements">assigned</a>
to their corresponding function parameters,
and the called function begins execution.
The return parameters of the function are passed by value
The return parameters of the function are passed
back to the caller when the function returns.
</p>
@@ -4268,9 +4322,9 @@ As a special case, if the return values of a function or method
<code>g</code> are equal in number and individually
assignable to the parameters of another function or method
<code>f</code>, then the call <code>f(g(<i>parameters_of_g</i>))</code>
will invoke <code>f</code> after binding the return values of
<code>g</code> to the parameters of <code>f</code> in order. The call
of <code>f</code> must contain no parameters other than the call of <code>g</code>,
will invoke <code>f</code> after passing the return values of
<code>g</code> to the parameters of <code>f</code> in order.
The call of <code>f</code> must contain no parameters other than the call of <code>g</code>,
and <code>g</code> must have at least one return value.
If <code>f</code> has a final <code>...</code> parameter, it is
assigned the return values of <code>g</code> that remain after
@@ -4316,7 +4370,7 @@ If <code>f</code> is <a href="#Function_types">variadic</a> with a final
parameter <code>p</code> of type <code>...T</code>, then within <code>f</code>
the type of <code>p</code> is equivalent to type <code>[]T</code>.
If <code>f</code> is invoked with no actual arguments for <code>p</code>,
the value passed to <code>p</code> is <code>nil</code>.
the value <a href="#Calls">passed</a> to <code>p</code> is <code>nil</code>.
Otherwise, the value passed is a new slice
of type <code>[]T</code> with a new underlying array whose successive elements
are the actual arguments, which all must be <a href="#Assignability">assignable</a>
@@ -5632,6 +5686,8 @@ myString([]myRune{0x1f30e}) // "\U0001f30e" == "🌎"
<li>
Converting a value of a string type to a slice of bytes type
yields a non-nil slice whose successive elements are the bytes of the string.
The <a href="#Length_and_capacity">capacity</a> of the resulting slice is
implementation-specific and may be larger than the slice length.
<pre>
[]byte("hellø") // []byte{'h', 'e', 'l', 'l', '\xc3', '\xb8'}
@@ -5647,6 +5703,8 @@ bytes("hellø") // []byte{'h', 'e', 'l', 'l', '\xc3', '\xb8'}
<li>
Converting a value of a string type to a slice of runes type
yields a slice containing the individual Unicode code points of the string.
The <a href="#Length_and_capacity">capacity</a> of the resulting slice is
implementation-specific and may be larger than the slice length.
<pre>
[]rune(myString("白鵬翔")) // []rune{0x767d, 0x9d6c, 0x7fd4}
@@ -5848,7 +5906,7 @@ Otherwise, when evaluating the <a href="#Operands">operands</a> of an
expression, assignment, or
<a href="#Return_statements">return statement</a>,
all function calls, method calls,
<a href="#Receive operator">receive operations</a>,
<a href="#Receive_operator">receive operations</a>,
and <a href="#Logical_operators">binary logical operations</a>
are evaluated in lexical left-to-right order.
</p>
@@ -5916,11 +5974,10 @@ Statements control execution.
</p>
<pre class="ebnf">
Statement =
Declaration | LabeledStmt | SimpleStmt |
GoStmt | ReturnStmt | BreakStmt | ContinueStmt | GotoStmt |
FallthroughStmt | Block | IfStmt | SwitchStmt | SelectStmt | ForStmt |
DeferStmt .
Statement = Declaration | LabeledStmt | SimpleStmt |
GoStmt | ReturnStmt | BreakStmt | ContinueStmt | GotoStmt |
FallthroughStmt | Block | IfStmt | SwitchStmt | SelectStmt | ForStmt |
DeferStmt .
SimpleStmt = EmptyStmt | ExpressionStmt | SendStmt | IncDecStmt | Assignment | ShortVarDecl .
</pre>
@@ -6132,7 +6189,7 @@ matching number of variables.
<pre class="ebnf">
Assignment = ExpressionList assign_op ExpressionList .
assign_op = [ add_op | mul_op ] "=" .
assign_op = [ add_op | mul_op ] "=" .
</pre>
<p>
@@ -6261,6 +6318,26 @@ to the type of the operand to which it is assigned, with the following special c
</li>
</ol>
<p>
When a value is assigned to a variable, only the data that is stored in the variable
is replaced. If the value contains a <a href="#Representation_of_values">reference</a>,
the assignment copies the reference but does not make a copy of the referenced data
(such as the underlying array of a slice).
</p>
<pre>
var s1 = []int{1, 2, 3}
var s2 = s1 // s2 stores the slice descriptor of s1
s1 = s1[:1] // s1's length is 1 but it still shares its underlying array with s2
s2[0] = 42 // setting s2[0] changes s1[0] as well
fmt.Println(s1, s2) // prints [42] [42 2 3]
var m1 = make(map[string]int)
var m2 = m1 // m2 stores the map descriptor of m1
m1["foo"] = 42 // setting m1["foo"] changes m2["foo"] as well
fmt.Println(m2["foo"]) // prints 42
</pre>
<h3 id="If_statements">If statements</h3>
<p>
@@ -6548,7 +6625,7 @@ The iteration may be controlled by a single condition, a "for" clause, or a "ran
</p>
<pre class="ebnf">
ForStmt = "for" [ Condition | ForClause | RangeClause ] Block .
ForStmt = "for" [ Condition | ForClause | RangeClause ] Block .
Condition = Expression .
</pre>
@@ -6580,8 +6657,8 @@ an increment or decrement statement. The init statement may be a
<pre class="ebnf">
ForClause = [ InitStmt ] ";" [ Condition ] ";" [ PostStmt ] .
InitStmt = SimpleStmt .
PostStmt = SimpleStmt .
InitStmt = SimpleStmt .
PostStmt = SimpleStmt .
</pre>
<pre>
@@ -7909,7 +7986,7 @@ types, variables, and constants.
</p>
<pre class="ebnf">
SourceFile = PackageClause ";" { ImportDecl ";" } { TopLevelDecl ";" } .
SourceFile = PackageClause ";" { ImportDecl ";" } { TopLevelDecl ";" } .
</pre>
<h3 id="Package_clause">Package clause</h3>
@@ -7920,8 +7997,8 @@ to which the file belongs.
</p>
<pre class="ebnf">
PackageClause = "package" PackageName .
PackageName = identifier .
PackageClause = "package" PackageName .
PackageName = identifier .
</pre>
<p>
@@ -7950,9 +8027,9 @@ that specifies the package to be imported.
</p>
<pre class="ebnf">
ImportDecl = "import" ( ImportSpec | "(" { ImportSpec ";" } ")" ) .
ImportSpec = [ "." | PackageName ] ImportPath .
ImportPath = string_lit .
ImportDecl = "import" ( ImportSpec | "(" { ImportSpec ";" } ")" ) .
ImportSpec = [ "." | PackageName ] ImportPath .
ImportPath = string_lit .
</pre>
<p>

View File

@@ -1,9 +1,3 @@
<!--
NOTE: In this document and others in this directory, the convention is to
set fixed-width phrases with non-fixed-width spaces, as in
`hello` `world`.
-->
<style>
main ul li { margin: 0.5em 0; }
</style>

View File

@@ -162,12 +162,12 @@ func delete(m map[Type]Type1, key Type)
// The len built-in function returns the length of v, according to its type:
//
// Array: the number of elements in v.
// Pointer to array: the number of elements in *v (even if v is nil).
// Slice, or map: the number of elements in v; if v is nil, len(v) is zero.
// String: the number of bytes in v.
// Channel: the number of elements queued (unread) in the channel buffer;
// if v is nil, len(v) is zero.
// - Array: the number of elements in v.
// - Pointer to array: the number of elements in *v (even if v is nil).
// - Slice, or map: the number of elements in v; if v is nil, len(v) is zero.
// - String: the number of bytes in v.
// - Channel: the number of elements queued (unread) in the channel buffer;
// if v is nil, len(v) is zero.
//
// For some arguments, such as a string literal or a simple array expression, the
// result can be a constant. See the Go language specification's "Length and
@@ -176,12 +176,12 @@ func len(v Type) int
// The cap built-in function returns the capacity of v, according to its type:
//
// Array: the number of elements in v (same as len(v)).
// Pointer to array: the number of elements in *v (same as len(v)).
// Slice: the maximum length the slice can reach when resliced;
// if v is nil, cap(v) is zero.
// Channel: the channel buffer capacity, in units of elements;
// if v is nil, cap(v) is zero.
// - Array: the number of elements in v (same as len(v)).
// - Pointer to array: the number of elements in *v (same as len(v)).
// - Slice: the maximum length the slice can reach when resliced;
// if v is nil, cap(v) is zero.
// - Channel: the channel buffer capacity, in units of elements;
// if v is nil, cap(v) is zero.
//
// For some arguments, such as a simple array expression, the result can be a
// constant. See the Go language specification's "Length and capacity" section for
@@ -194,18 +194,18 @@ func cap(v Type) int
// argument, not a pointer to it. The specification of the result depends on
// the type:
//
// Slice: The size specifies the length. The capacity of the slice is
// equal to its length. A second integer argument may be provided to
// specify a different capacity; it must be no smaller than the
// length. For example, make([]int, 0, 10) allocates an underlying array
// of size 10 and returns a slice of length 0 and capacity 10 that is
// backed by this underlying array.
// Map: An empty map is allocated with enough space to hold the
// specified number of elements. The size may be omitted, in which case
// a small starting size is allocated.
// Channel: The channel's buffer is initialized with the specified
// buffer capacity. If zero, or the size is omitted, the channel is
// unbuffered.
// - Slice: The size specifies the length. The capacity of the slice is
// equal to its length. A second integer argument may be provided to
// specify a different capacity; it must be no smaller than the
// length. For example, make([]int, 0, 10) allocates an underlying array
// of size 10 and returns a slice of length 0 and capacity 10 that is
// backed by this underlying array.
// - Map: An empty map is allocated with enough space to hold the
// specified number of elements. The size may be omitted, in which case
// a small starting size is allocated.
// - Channel: The channel's buffer is initialized with the specified
// buffer capacity. If zero, or the size is omitted, the channel is
// unbuffered.
func make(t Type, size ...IntegerType) Type
// The max built-in function returns the largest value of a fixed number of
@@ -247,7 +247,7 @@ func imag(c ComplexType) FloatType
// to the zero value of the respective element type. If the argument
// type is a type parameter, the type parameter's type set must
// contain only map or slice types, and clear performs the operation
// implied by the type argument.
// implied by the type argument. If t is nil, clear is a no-op.
func clear[T ~[]Type | ~map[Type]Type1](t T)
// The close built-in function closes a channel, which must be either

View File

@@ -68,7 +68,7 @@ func splitSeq(s, sep []byte, sepSave int) iter.Seq[[]byte] {
}
// SplitSeq returns an iterator over all substrings of s separated by sep.
// The iterator yields the same strings that would be returned by Split(s, sep),
// The iterator yields the same strings that would be returned by [Split](s, sep),
// but without constructing the slice.
// It returns a single-use iterator.
func SplitSeq(s, sep []byte) iter.Seq[[]byte] {
@@ -76,7 +76,7 @@ func SplitSeq(s, sep []byte) iter.Seq[[]byte] {
}
// SplitAfterSeq returns an iterator over substrings of s split after each instance of sep.
// The iterator yields the same strings that would be returned by SplitAfter(s, sep),
// The iterator yields the same strings that would be returned by [SplitAfter](s, sep),
// but without constructing the slice.
// It returns a single-use iterator.
func SplitAfterSeq(s, sep []byte) iter.Seq[[]byte] {
@@ -84,8 +84,8 @@ func SplitAfterSeq(s, sep []byte) iter.Seq[[]byte] {
}
// FieldsSeq returns an iterator over substrings of s split around runs of
// whitespace characters, as defined by unicode.IsSpace.
// The iterator yields the same strings that would be returned by Fields(s),
// whitespace characters, as defined by [unicode.IsSpace].
// The iterator yields the same strings that would be returned by [Fields](s),
// but without constructing the slice.
func FieldsSeq(s []byte) iter.Seq[[]byte] {
return func(yield func([]byte) bool) {
@@ -118,7 +118,7 @@ func FieldsSeq(s []byte) iter.Seq[[]byte] {
// FieldsFuncSeq returns an iterator over substrings of s split around runs of
// Unicode code points satisfying f(c).
// The iterator yields the same strings that would be returned by FieldsFunc(s),
// The iterator yields the same strings that would be returned by [FieldsFunc](s),
// but without constructing the slice.
func FieldsFuncSeq(s []byte, f func(rune) bool) iter.Seq[[]byte] {
return func(yield func([]byte) bool) {

View File

@@ -796,7 +796,7 @@ Instead, the build process generates an object file using dynamic
linkage to the desired libraries. The main function is provided by
_cgo_main.c:
int main() { return 0; }
int main(int argc, char **argv) { return 0; }
void crosscall2(void(*fn)(void*), void *a, int c, uintptr_t ctxt) { }
uintptr_t _cgo_wait_runtime_init_done(void) { return 0; }
void _cgo_release_context(uintptr_t ctxt) { }

View File

@@ -59,7 +59,7 @@ func (p *Package) writeDefs() {
// Write C main file for using gcc to resolve imports.
fmt.Fprintf(fm, "#include <stddef.h>\n") // For size_t below.
fmt.Fprintf(fm, "int main() { return 0; }\n")
fmt.Fprintf(fm, "int main(int argc __attribute__((unused)), char **argv __attribute__((unused))) { return 0; }\n")
if *importRuntimeCgo {
fmt.Fprintf(fm, "void crosscall2(void(*fn)(void*) __attribute__((unused)), void *a __attribute__((unused)), int c __attribute__((unused)), size_t ctxt __attribute__((unused))) { }\n")
fmt.Fprintf(fm, "size_t _cgo_wait_runtime_init_done(void) { return 0; }\n")

View File

@@ -15,7 +15,7 @@ the package and about types used by symbols imported by the package from
other packages. It is therefore not necessary when compiling client C of
package P to read the files of P's dependencies, only the compiled output of P.
Command Line
# Command Line
Usage:
@@ -150,14 +150,21 @@ Flags to debug the compiler itself:
-w
Debug type checking.
Compiler Directives
# Compiler Directives
The compiler accepts directives in the form of comments.
To distinguish them from non-directive comments, directives
require no space between the comment opening and the name of the directive. However, since
they are comments, tools unaware of the directive convention or of a particular
Each directive must be placed its own line, with only leading spaces and tabs
allowed before the comment, and there must be no space between the comment
opening and the name of the directive, to distinguish it from a regular comment.
Tools unaware of the directive convention or of a particular
directive can skip over a directive like any other comment.
Other than the line directive, which is a historical special case;
all other compiler directives are of the form
//go:name, indicating that they are defined by the Go toolchain.
*/
// # Line Directives
//
// Line directives come in several forms:
//
// //line :line
@@ -197,12 +204,9 @@ directive can skip over a directive like any other comment.
// Line directives typically appear in machine-generated code, so that compilers and debuggers
// will report positions in the original input to the generator.
/*
The line directive is a historical special case; all other directives are of the form
//go:name, indicating that they are defined by the Go toolchain.
Each directive must be placed its own line, with only leading spaces and tabs
allowed before the comment.
Each directive applies to the Go code that immediately follows it,
which typically must be a declaration.
# Function Directives
A function directive applies to the Go function that immediately follows it.
//go:noescape
@@ -245,6 +249,8 @@ It specifies that the function must omit its usual stack overflow check.
This is most commonly used by low-level runtime code invoked
at times when it is unsafe for the calling goroutine to be preempted.
# Linkname Directive
//go:linkname localname [importpath.name]
The //go:linkname directive conventionally precedes the var or func
@@ -295,17 +301,34 @@ The declaration of lower.f may also have a linkname directive with a
single argument, f. This is optional, but helps alert the reader that
the function is accessed from outside the package.
# WebAssembly Directives
//go:wasmimport importmodule importname
The //go:wasmimport directive is wasm-only and must be followed by a
function declaration.
function declaration with no body.
It specifies that the function is provided by a wasm module identified
by ``importmodule`` and ``importname``.
by ``importmodule'' and ``importname''. For example,
//go:wasmimport a_module f
func g()
The types of parameters and return values to the Go function are translated to
causes g to refer to the WebAssembly function f from module a_module.
//go:wasmexport exportname
The //go:wasmexport directive is wasm-only and must be followed by a
function definition.
It specifies that the function is exported to the wasm host as ``exportname''.
For example,
//go:wasmexport h
func hWasm() { ... }
make Go function hWasm available outside this WebAssembly module as h.
For both go:wasmimport and go:wasmexport,
the types of parameters and return values to the Go function are translated to
Wasm according to the following table:
Go types Wasm types
@@ -318,24 +341,12 @@ Wasm according to the following table:
pointer i32 (more restrictions below)
string (i32, i32) (only permitted as a parameters, not a result)
Any other parameter types are disallowed by the compiler.
For a pointer type, its element type must be a bool, int8, uint8, int16, uint16,
int32, uint32, int64, uint64, float32, float64, an array whose element type is
a permitted pointer element type, or a struct, which, if non-empty, embeds
structs.HostLayout, and contains only fields whose types are permitted pointer
[structs.HostLayout], and contains only fields whose types are permitted pointer
element types.
Any other parameter types are disallowed by the compiler.
//go:wasmexport exportname
The //go:wasmexport directive is wasm-only and must be followed by a
function definition.
It specifies that the function is exported to the wasm host as ``exportname``.
//go:wasmexport f
func g()
The types of parameters and return values to the Go function are permitted and
translated to Wasm in the same way as //go:wasmimport functions.
*/
package main

View File

@@ -5,7 +5,8 @@
// This program generates Go code that applies rewrite rules to a Value.
// The generated code implements a function of type func (v *Value) bool
// which reports whether if did something.
// Ideas stolen from Swift: http://www.hpl.hp.com/techreports/Compaq-DEC/WRL-2000-2.html
// Ideas stolen from the Swift Java compiler:
// https://bitsavers.org/pdf/dec/tech_reports/WRL-2000-2.pdf
package main

View File

@@ -5452,12 +5452,15 @@ func (s *state) referenceTypeBuiltin(n *ir.UnaryExpr, x *ssa.Value) *ssa.Value {
if n.X.Type().IsChan() && n.Op() == ir.OCAP {
s.Fatalf("cannot inline cap(chan)") // must use runtime.chancap now
}
if n.X.Type().IsMap() && n.Op() == ir.OCAP {
s.Fatalf("cannot inline cap(map)") // cap(map) does not exist
}
// if n == nil {
// return 0
// } else {
// // len
// return *((*int)n)
// // cap
// // len, the actual loadType depends
// return int(*((*loadType)n))
// // cap (chan only, not used for now)
// return *(((*int)n)+1)
// }
lenType := n.Type()
@@ -5485,7 +5488,9 @@ func (s *state) referenceTypeBuiltin(n *ir.UnaryExpr, x *ssa.Value) *ssa.Value {
case ir.OLEN:
if buildcfg.Experiment.SwissMap && n.X.Type().IsMap() {
// length is stored in the first word.
s.vars[n] = s.load(lenType, x)
loadType := reflectdata.SwissMapType().Field(0).Type // uint64
load := s.load(loadType, x)
s.vars[n] = s.conv(nil, load, loadType, lenType) // integer conversion doesn't need Node
} else {
// length is stored in the first word for map/chan
s.vars[n] = s.load(lenType, x)

View File

@@ -0,0 +1,17 @@
// Copyright 2025 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 p
func _() {
M:
L:
for range 0 {
break L
break /* ERROR invalid break label M */ M
}
for range 0 {
break /* ERROR invalid break label L */ L
}
}

View File

@@ -56,7 +56,7 @@ The tests are in:
Tests are .go files annotated with `/* ERROR "msg" */` or `/* ERRORx "msg" */`
comments (or the respective line comment form).
For each such error comment, typechecking the respective file is expected to
report an error at the position of the syntactic token _immediately preceeding_
report an error at the position of the syntactic token _immediately preceding_
the comment.
For `ERROR`, the `"msg"` string must be a substring of the error message
reported by the typechecker;

View File

@@ -208,11 +208,19 @@ type Info struct {
//
// The Types map does not record the type of every identifier,
// only those that appear where an arbitrary expression is
// permitted. For instance, the identifier f in a selector
// expression x.f is found only in the Selections map, the
// identifier z in a variable declaration 'var z int' is found
// only in the Defs map, and identifiers denoting packages in
// qualified identifiers are collected in the Uses map.
// permitted. For instance:
// - an identifier f in a selector expression x.f is found
// only in the Selections map;
// - an identifier z in a variable declaration 'var z int'
// is found only in the Defs map;
// - an identifier p denoting a package in a qualified
// identifier p.X is found only in the Uses map.
//
// Similarly, no type is recorded for the (synthetic) FuncType
// node in a FuncDecl.Type field, since there is no corresponding
// syntactic function type expression in the source in this case
// Instead, the function type is found in the Defs.map entry for
// the corresponding function declaration.
Types map[syntax.Expr]TypeAndValue
// If StoreTypesInSyntax is set, type information identical to

View File

@@ -174,7 +174,7 @@ func (check *Checker) collectRecv(rparam *syntax.Field, scopePos syntax.Pos) (*V
} else {
// If there are type parameters, rbase must denote a generic base type.
// Important: rbase must be resolved before declaring any receiver type
// parameters (wich may have the same name, see below).
// parameters (which may have the same name, see below).
var baseType *Named // nil if not valid
var cause string
if t := check.genericType(rbase, &cause); isValid(t) {

25
src/cmd/dist/test.go vendored
View File

@@ -876,16 +876,18 @@ func (t *tester) registerTests() {
}
if t.extLink() && !t.compileOnly {
t.registerTest("external linking, -buildmode=exe",
&goTest{
variant: "exe_external",
timeout: 60 * time.Second,
buildmode: "exe",
ldflags: "-linkmode=external",
env: []string{"CGO_ENABLED=1"},
pkg: "crypto/internal/fips140test",
runTests: "TestFIPSCheck",
})
if goos != "android" { // Android does not support non-PIE linking
t.registerTest("external linking, -buildmode=exe",
&goTest{
variant: "exe_external",
timeout: 60 * time.Second,
buildmode: "exe",
ldflags: "-linkmode=external",
env: []string{"CGO_ENABLED=1"},
pkg: "crypto/internal/fips140test",
runTests: "TestFIPSCheck",
})
}
if t.externalLinkPIE() && !disablePIE {
t.registerTest("external linking, -buildmode=pie",
&goTest{
@@ -1795,6 +1797,8 @@ func isEnvSet(evar string) bool {
}
func (t *tester) fipsSupported() bool {
// Keep this in sync with [crypto/internal/fips140.Supported].
// Use GOFIPS140 or GOEXPERIMENT=boringcrypto, but not both.
if strings.Contains(goexperiment, "boringcrypto") {
return false
@@ -1808,6 +1812,7 @@ func (t *tester) fipsSupported() bool {
case goarch == "wasm",
goos == "windows" && goarch == "386",
goos == "windows" && goarch == "arm",
goos == "openbsd",
goos == "aix":
return false
}

View File

@@ -739,11 +739,6 @@
//
// For more about specifying packages, see 'go help packages'.
//
// This text describes the behavior of get using modules to manage source
// code and dependencies. If instead the go command is running in GOPATH
// mode, the details of get's flags and effects change, as does 'go help get'.
// See 'go help gopath-get'.
//
// See also: go build, go install, go clean, go mod.
//
// # Compile and install packages and dependencies
@@ -2186,7 +2181,7 @@
// fields of all events to reconstruct the text format output, as it would
// have appeared from go build without the -json flag.
//
// Note that there may also be non-JSON error text on stdnard error, even
// Note that there may also be non-JSON error text on standard error, even
// with the -json flag. Typically, this indicates an early, serious error.
// Consumers should be robust to this.
//
@@ -2250,7 +2245,7 @@
//
// The second is the SWIG program, which is a general tool for
// interfacing between languages. For information on SWIG see
// http://swig.org/. When running go build, any file with a .swig
// https://swig.org/. When running go build, any file with a .swig
// extension will be passed to SWIG. Any file with a .swigcxx extension
// will be passed to SWIG with the -c++ option.
//
@@ -2338,6 +2333,10 @@
// GOCACHE
// The directory where the go command will store cached
// information for reuse in future builds.
// GOCACHEPROG
// A command (with optional space-separated flags) that implements an
// external go command build cache.
// See 'go doc cmd/go/internal/cacheprog'.
// GODEBUG
// Enable various debugging facilities. See https://go.dev/doc/godebug
// for details.
@@ -2448,6 +2447,11 @@
// GOARM
// For GOARCH=arm, the ARM architecture for which to compile.
// Valid values are 5, 6, 7.
// When the Go tools are built on an arm system,
// the default value is set based on what the build system supports.
// When the Go tools are not built on an arm system
// (that is, when building a cross-compiler),
// the default value is 7.
// The value can be followed by an option specifying how to implement floating point instructions.
// Valid options are ,softfloat (default for 5) and ,hardfloat (default for 6 and 7).
// GOARM64
@@ -2612,7 +2616,7 @@
// Example: Data
//
// If the server responds with any 4xx code, the go command will write the
// following to the programs' stdin:
// following to the program's stdin:
// Response = StatusLine { HeaderLine } BlankLine .
// StatusLine = Protocol Space Status '\n' .
// Protocol = /* HTTP protocol */ .
@@ -2969,11 +2973,7 @@
// same meta tag and then git clone https://code.org/r/p/exproj into
// GOPATH/src/example.org.
//
// When using GOPATH, downloaded packages are written to the first directory
// listed in the GOPATH environment variable.
// (See 'go help gopath-get' and 'go help gopath'.)
//
// When using modules, downloaded packages are stored in the module cache.
// Downloaded packages are stored in the module cache.
// See https://golang.org/ref/mod#module-cache.
//
// When using modules, an additional variant of the go-import meta tag is

View File

@@ -12,7 +12,6 @@ import (
"log"
"net/http"
"os"
"path"
"path/filepath"
"slices"
"strings"
@@ -73,7 +72,12 @@ func runGoAuth(client *http.Client, res *http.Response, url string) {
if err != nil {
base.Fatalf("go: could not parse netrc (GOAUTH=%s): %v", cfg.GOAUTH, err)
}
for _, l := range lines {
// Process lines in reverse so that if the same machine is listed
// multiple times, we end up saving the earlier one
// (overwriting later ones). This matches the way the go command
// worked before GOAUTH.
for i := len(lines) - 1; i >= 0; i-- {
l := lines[i]
r := http.Request{Header: make(http.Header)}
r.SetBasicAuth(l.login, l.password)
storeCredential(l.machine, r.Header)
@@ -137,11 +141,13 @@ func runGoAuth(client *http.Client, res *http.Response, url string) {
func loadCredential(req *http.Request, url string) bool {
currentPrefix := strings.TrimPrefix(url, "https://")
// Iteratively try prefixes, moving up the path hierarchy.
for currentPrefix != "/" && currentPrefix != "." && currentPrefix != "" {
for {
headers, ok := credentialCache.Load(currentPrefix)
if !ok {
// Move to the parent directory.
currentPrefix = path.Dir(currentPrefix)
currentPrefix, _, ok = strings.Cut(currentPrefix, "/")
if !ok {
return false
}
continue
}
for key, values := range headers.(http.Header) {
@@ -151,7 +157,6 @@ func loadCredential(req *http.Request, url string) bool {
}
return true
}
return false
}
// storeCredential caches or removes credentials (represented by HTTP headers)

View File

@@ -25,7 +25,29 @@ func TestCredentialCache(t *testing.T) {
got := &http.Request{Header: make(http.Header)}
ok := loadCredential(got, tc.machine)
if !ok || !reflect.DeepEqual(got.Header, want.Header) {
t.Errorf("loadCredential:\nhave %q\nwant %q", got.Header, want.Header)
t.Errorf("loadCredential(%q):\nhave %q\nwant %q", tc.machine, got.Header, want.Header)
}
}
// Having stored those credentials, we should be able to look up longer URLs too.
extraCases := []netrcLine{
{"https://api.github.com/foo", "user", "pwd"},
{"https://api.github.com/foo/bar/baz", "user", "pwd"},
{"https://example.com/abc", "", ""},
{"https://example.com/?/../api.github.com/", "", ""},
{"https://example.com/?/../api.github.com", "", ""},
{"https://example.com/../api.github.com/", "", ""},
{"https://example.com/../api.github.com", "", ""},
}
for _, tc := range extraCases {
want := http.Request{Header: make(http.Header)}
if tc.login != "" {
want.SetBasicAuth(tc.login, tc.password)
}
got := &http.Request{Header: make(http.Header)}
loadCredential(got, tc.machine)
if !reflect.DeepEqual(got.Header, want.Header) {
t.Errorf("loadCredential(%q):\nhave %q\nwant %q", tc.machine, got.Header, want.Header)
}
}
}

View File

@@ -38,8 +38,8 @@ type Cache interface {
// Get returns the cache entry for the provided ActionID.
// On miss, the error type should be of type *entryNotFoundError.
//
// After a success call to Get, OutputFile(Entry.OutputID) must
// exist on disk for until Close is called (at the end of the process).
// After a successful call to Get, OutputFile(Entry.OutputID) must
// exist on disk until Close is called (at the end of the process).
Get(ActionID) (Entry, error)
// Put adds an item to the cache.
@@ -50,14 +50,14 @@ type Cache interface {
// As a special case, if the ReadSeeker is of type noVerifyReadSeeker,
// the verification from GODEBUG=goverifycache=1 is skipped.
//
// After a success call to Get, OutputFile(Entry.OutputID) must
// exist on disk for until Close is called (at the end of the process).
// After a successful call to Put, OutputFile(OutputID) must
// exist on disk until Close is called (at the end of the process).
Put(ActionID, io.ReadSeeker) (_ OutputID, size int64, _ error)
// Close is called at the end of the go process. Implementations can do
// cache cleanup work at this phase, or wait for and report any errors from
// background cleanup work started earlier. Any cache trimming should in one
// process should not violate cause the invariants of this interface to be
// background cleanup work started earlier. Any cache trimming in one
// process should not cause the invariants of this interface to be
// violated in another process. Namely, a cache trim from one process should
// not delete an ObjectID from disk that was recently Get or Put from
// another process. As a rule of thumb, don't trim things used in the last
@@ -296,19 +296,19 @@ func GetBytes(c Cache, id ActionID) ([]byte, Entry, error) {
// GetMmap looks up the action ID in the cache and returns
// the corresponding output bytes.
// GetMmap should only be used for data that can be expected to fit in memory.
func GetMmap(c Cache, id ActionID) ([]byte, Entry, error) {
func GetMmap(c Cache, id ActionID) ([]byte, Entry, bool, error) {
entry, err := c.Get(id)
if err != nil {
return nil, entry, err
return nil, entry, false, err
}
md, err := mmap.Mmap(c.OutputFile(entry.OutputID))
md, opened, err := mmap.Mmap(c.OutputFile(entry.OutputID))
if err != nil {
return nil, Entry{}, err
return nil, Entry{}, opened, err
}
if int64(len(md.Data)) != entry.Size {
return nil, Entry{}, &entryNotFoundError{Err: errors.New("file incomplete")}
return nil, Entry{}, true, &entryNotFoundError{Err: errors.New("file incomplete")}
}
return md.Data, entry, nil
return md.Data, entry, true, nil
}
// OutputFile returns the name of the cache file storing output with the given OutputID.

View File

@@ -54,8 +54,8 @@ func initDefaultCache() Cache {
base.Fatalf("failed to initialize build cache at %s: %s\n", dir, err)
}
if v := cfg.Getenv("GOCACHEPROG"); v != "" {
return startCacheProg(v, diskCache)
if cfg.GOCACHEPROG != "" {
return startCacheProg(cfg.GOCACHEPROG, diskCache)
}
return diskCache

View File

@@ -7,6 +7,7 @@ package cache
import (
"bufio"
"cmd/go/internal/base"
"cmd/go/internal/cacheprog"
"cmd/internal/quoted"
"context"
"crypto/sha256"
@@ -38,7 +39,7 @@ type ProgCache struct {
// can are the commands that the child process declared that it supports.
// This is effectively the versioning mechanism.
can map[ProgCmd]bool
can map[cacheprog.Cmd]bool
// fuzzDirCache is another Cache implementation to use for the FuzzDir
// method. In practice this is the default GOCACHE disk-based
@@ -55,7 +56,7 @@ type ProgCache struct {
mu sync.Mutex // guards following fields
nextID int64
inFlight map[int64]chan<- *ProgResponse
inFlight map[int64]chan<- *cacheprog.Response
outputFile map[OutputID]string // object => abs path on disk
// writeMu serializes writing to the child process.
@@ -63,95 +64,6 @@ type ProgCache struct {
writeMu sync.Mutex
}
// ProgCmd is a command that can be issued to a child process.
//
// If the interface needs to grow, we can add new commands or new versioned
// commands like "get2".
type ProgCmd string
const (
cmdGet = ProgCmd("get")
cmdPut = ProgCmd("put")
cmdClose = ProgCmd("close")
)
// ProgRequest is the JSON-encoded message that's sent from cmd/go to
// the GOCACHEPROG child process over stdin. Each JSON object is on its
// own line. A ProgRequest of Type "put" with BodySize > 0 will be followed
// by a line containing a base64-encoded JSON string literal of the body.
type ProgRequest struct {
// ID is a unique number per process across all requests.
// It must be echoed in the ProgResponse from the child.
ID int64
// Command is the type of request.
// The cmd/go tool will only send commands that were declared
// as supported by the child.
Command ProgCmd
// ActionID is non-nil for get and puts.
ActionID []byte `json:",omitempty"` // or nil if not used
// OutputID is set for Type "put".
//
// Prior to Go 1.24, when GOCACHEPROG was still an experiment, this was
// accidentally named ObjectID. It was renamed to OutputID in Go 1.24.
OutputID []byte `json:",omitempty"` // or nil if not used
// Body is the body for "put" requests. It's sent after the JSON object
// as a base64-encoded JSON string when BodySize is non-zero.
// It's sent as a separate JSON value instead of being a struct field
// send in this JSON object so large values can be streamed in both directions.
// The base64 string body of a ProgRequest will always be written
// immediately after the JSON object and a newline.
Body io.Reader `json:"-"`
// BodySize is the number of bytes of Body. If zero, the body isn't written.
BodySize int64 `json:",omitempty"`
// ObjectID is the accidental spelling of OutputID that was used prior to Go
// 1.24.
//
// Deprecated: use OutputID. This field is only populated temporarily for
// backwards compatibility with Go 1.23 and earlier when
// GOEXPERIMENT=gocacheprog is set. It will be removed in Go 1.25.
ObjectID []byte `json:",omitempty"`
}
// ProgResponse is the JSON response from the child process to cmd/go.
//
// With the exception of the first protocol message that the child writes to its
// stdout with ID==0 and KnownCommands populated, these are only sent in
// response to a ProgRequest from cmd/go.
//
// ProgResponses can be sent in any order. The ID must match the request they're
// replying to.
type ProgResponse struct {
ID int64 // that corresponds to ProgRequest; they can be answered out of order
Err string `json:",omitempty"` // if non-empty, the error
// KnownCommands is included in the first message that cache helper program
// writes to stdout on startup (with ID==0). It includes the
// ProgRequest.Command types that are supported by the program.
//
// This lets us extend the protocol gracefully over time (adding "get2",
// etc), or fail gracefully when needed. It also lets us verify the program
// wants to be a cache helper.
KnownCommands []ProgCmd `json:",omitempty"`
// For Get requests.
Miss bool `json:",omitempty"` // cache miss
OutputID []byte `json:",omitempty"`
Size int64 `json:",omitempty"` // in bytes
Time *time.Time `json:",omitempty"` // an Entry.Time; when the object was added to the docs
// DiskPath is the absolute path on disk of the ObjectID corresponding
// a "get" request's ActionID (on cache hit) or a "put" request's
// provided ObjectID.
DiskPath string `json:",omitempty"`
}
// startCacheProg starts the prog binary (with optional space-separated flags)
// and returns a Cache implementation that talks to it.
//
@@ -183,6 +95,8 @@ func startCacheProg(progAndArgs string, fuzzDirCache Cache) Cache {
base.Fatalf("StdinPipe to GOCACHEPROG: %v", err)
}
cmd.Stderr = os.Stderr
// On close, we cancel the context. Rather than killing the helper,
// close its stdin.
cmd.Cancel = in.Close
if err := cmd.Start(); err != nil {
@@ -197,14 +111,14 @@ func startCacheProg(progAndArgs string, fuzzDirCache Cache) Cache {
stdout: out,
stdin: in,
bw: bufio.NewWriter(in),
inFlight: make(map[int64]chan<- *ProgResponse),
inFlight: make(map[int64]chan<- *cacheprog.Response),
outputFile: make(map[OutputID]string),
readLoopDone: make(chan struct{}),
}
// Register our interest in the initial protocol message from the child to
// us, saying what it can do.
capResc := make(chan *ProgResponse, 1)
capResc := make(chan *cacheprog.Response, 1)
pc.inFlight[0] = capResc
pc.jenc = json.NewEncoder(pc.bw)
@@ -219,7 +133,7 @@ func startCacheProg(progAndArgs string, fuzzDirCache Cache) Cache {
case <-timer.C:
log.Printf("# still waiting for GOCACHEPROG %v ...", prog)
case capRes := <-capResc:
can := map[ProgCmd]bool{}
can := map[cacheprog.Cmd]bool{}
for _, cmd := range capRes.KnownCommands {
can[cmd] = true
}
@@ -236,9 +150,15 @@ func (c *ProgCache) readLoop(readLoopDone chan<- struct{}) {
defer close(readLoopDone)
jd := json.NewDecoder(c.stdout)
for {
res := new(ProgResponse)
res := new(cacheprog.Response)
if err := jd.Decode(res); err != nil {
if c.closing.Load() {
c.mu.Lock()
for _, ch := range c.inFlight {
close(ch)
}
c.inFlight = nil
c.mu.Unlock()
return // quietly
}
if err == io.EOF {
@@ -261,13 +181,18 @@ func (c *ProgCache) readLoop(readLoopDone chan<- struct{}) {
}
}
func (c *ProgCache) send(ctx context.Context, req *ProgRequest) (*ProgResponse, error) {
resc := make(chan *ProgResponse, 1)
var errCacheprogClosed = errors.New("GOCACHEPROG program closed unexpectedly")
func (c *ProgCache) send(ctx context.Context, req *cacheprog.Request) (*cacheprog.Response, error) {
resc := make(chan *cacheprog.Response, 1)
if err := c.writeToChild(req, resc); err != nil {
return nil, err
}
select {
case res := <-resc:
if res == nil {
return nil, errCacheprogClosed
}
if res.Err != "" {
return nil, errors.New(res.Err)
}
@@ -277,8 +202,11 @@ func (c *ProgCache) send(ctx context.Context, req *ProgRequest) (*ProgResponse,
}
}
func (c *ProgCache) writeToChild(req *ProgRequest, resc chan<- *ProgResponse) (err error) {
func (c *ProgCache) writeToChild(req *cacheprog.Request, resc chan<- *cacheprog.Response) (err error) {
c.mu.Lock()
if c.inFlight == nil {
return errCacheprogClosed
}
c.nextID++
req.ID = c.nextID
c.inFlight[req.ID] = resc
@@ -287,7 +215,9 @@ func (c *ProgCache) writeToChild(req *ProgRequest, resc chan<- *ProgResponse) (e
defer func() {
if err != nil {
c.mu.Lock()
delete(c.inFlight, req.ID)
if c.inFlight != nil {
delete(c.inFlight, req.ID)
}
c.mu.Unlock()
}
}()
@@ -328,7 +258,7 @@ func (c *ProgCache) writeToChild(req *ProgRequest, resc chan<- *ProgResponse) (e
}
func (c *ProgCache) Get(a ActionID) (Entry, error) {
if !c.can[cmdGet] {
if !c.can[cacheprog.CmdGet] {
// They can't do a "get". Maybe they're a write-only cache.
//
// TODO(bradfitz,bcmills): figure out the proper error type here. Maybe
@@ -338,8 +268,8 @@ func (c *ProgCache) Get(a ActionID) (Entry, error) {
// error types on the Cache interface.
return Entry{}, &entryNotFoundError{}
}
res, err := c.send(c.ctx, &ProgRequest{
Command: cmdGet,
res, err := c.send(c.ctx, &cacheprog.Request{
Command: cacheprog.CmdGet,
ActionID: a[:],
})
if err != nil {
@@ -395,7 +325,7 @@ func (c *ProgCache) Put(a ActionID, file io.ReadSeeker) (_ OutputID, size int64,
return OutputID{}, 0, err
}
if !c.can[cmdPut] {
if !c.can[cacheprog.CmdPut] {
// Child is a read-only cache. Do nothing.
return out, size, nil
}
@@ -407,8 +337,8 @@ func (c *ProgCache) Put(a ActionID, file io.ReadSeeker) (_ OutputID, size int64,
deprecatedValue = out[:]
}
res, err := c.send(c.ctx, &ProgRequest{
Command: cmdPut,
res, err := c.send(c.ctx, &cacheprog.Request{
Command: cacheprog.CmdPut,
ActionID: a[:],
OutputID: out[:],
ObjectID: deprecatedValue, // TODO(bradfitz): remove in Go 1.25
@@ -432,10 +362,16 @@ func (c *ProgCache) Close() error {
// First write a "close" message to the child so it can exit nicely
// and clean up if it wants. Only after that exchange do we cancel
// the context that kills the process.
if c.can[cmdClose] {
_, err = c.send(c.ctx, &ProgRequest{Command: cmdClose})
if c.can[cacheprog.CmdClose] {
_, err = c.send(c.ctx, &cacheprog.Request{Command: cacheprog.CmdClose})
if errors.Is(err, errCacheprogClosed) {
// Allow the child to quit without responding to close.
err = nil
}
}
// Cancel the context, which will close the helper's stdin.
c.ctxCancel()
// Wait until the helper closes its stdout.
<-c.readLoopDone
return err
}

View File

@@ -0,0 +1,137 @@
// Copyright 2024 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 cacheprog defines the protocol for a GOCACHEPROG program.
//
// By default, the go command manages a build cache stored in the file system
// itself. GOCACHEPROG can be set to the name of a command (with optional
// space-separated flags) that implements the go command build cache externally.
// This permits defining a different cache policy.
//
// The go command will start the GOCACHEPROG as a subprocess and communicate
// with it via JSON messages over stdin/stdout. The subprocess's stderr will be
// connected to the go command's stderr.
//
// The subprocess should immediately send a [Response] with its capabilities.
// After that, the go command will send a stream of [Request] messages and the
// subprocess should reply to each [Request] with a [Response] message.
package cacheprog
import (
"io"
"time"
)
// Cmd is a command that can be issued to a child process.
//
// If the interface needs to grow, the go command can add new commands or new
// versioned commands like "get2" in the future. The initial [Response] from
// the child process indicates which commands it supports.
type Cmd string
const (
// CmdPut tells the cache program to store an object in the cache.
//
// [Request.ActionID] is the cache key of this object. The cache should
// store [Request.OutputID] and [Request.Body] under this key for a
// later "get" request. It must also store the Body in a file in the local
// file system and return the path to that file in [Response.DiskPath],
// which must exist at least until a "close" request.
CmdPut = Cmd("put")
// CmdGet tells the cache program to retrieve an object from the cache.
//
// [Request.ActionID] specifies the key of the object to get. If the
// cache does not contain this object, it should set [Response.Miss] to
// true. Otherwise, it should populate the fields of [Response],
// including setting [Response.OutputID] to the OutputID of the original
// "put" request and [Response.DiskPath] to the path of a local file
// containing the Body of the original "put" request. That file must
// continue to exist at least until a "close" request.
CmdGet = Cmd("get")
// CmdClose requests that the cache program exit gracefully.
//
// The cache program should reply to this request and then exit
// (thus closing its stdout).
CmdClose = Cmd("close")
)
// Request is the JSON-encoded message that's sent from the go command to
// the GOCACHEPROG child process over stdin. Each JSON object is on its own
// line. A ProgRequest of Type "put" with BodySize > 0 will be followed by a
// line containing a base64-encoded JSON string literal of the body.
type Request struct {
// ID is a unique number per process across all requests.
// It must be echoed in the Response from the child.
ID int64
// Command is the type of request.
// The go command will only send commands that were declared
// as supported by the child.
Command Cmd
// ActionID is the cache key for "put" and "get" requests.
ActionID []byte `json:",omitempty"` // or nil if not used
// OutputID is stored with the body for "put" requests.
//
// Prior to Go 1.24, when GOCACHEPROG was still an experiment, this was
// accidentally named ObjectID. It was renamed to OutputID in Go 1.24.
OutputID []byte `json:",omitempty"` // or nil if not used
// Body is the body for "put" requests. It's sent after the JSON object
// as a base64-encoded JSON string when BodySize is non-zero.
// It's sent as a separate JSON value instead of being a struct field
// send in this JSON object so large values can be streamed in both directions.
// The base64 string body of a Request will always be written
// immediately after the JSON object and a newline.
Body io.Reader `json:"-"`
// BodySize is the number of bytes of Body. If zero, the body isn't written.
BodySize int64 `json:",omitempty"`
// ObjectID is the accidental spelling of OutputID that was used prior to Go
// 1.24.
//
// Deprecated: use OutputID. This field is only populated temporarily for
// backwards compatibility with Go 1.23 and earlier when
// GOEXPERIMENT=gocacheprog is set. It will be removed in Go 1.25.
ObjectID []byte `json:",omitempty"`
}
// Response is the JSON response from the child process to the go command.
//
// With the exception of the first protocol message that the child writes to its
// stdout with ID==0 and KnownCommands populated, these are only sent in
// response to a Request from the go command.
//
// Responses can be sent in any order. The ID must match the request they're
// replying to.
type Response struct {
ID int64 // that corresponds to Request; they can be answered out of order
Err string `json:",omitempty"` // if non-empty, the error
// KnownCommands is included in the first message that cache helper program
// writes to stdout on startup (with ID==0). It includes the
// Request.Command types that are supported by the program.
//
// This lets the go command extend the protocol gracefully over time (adding
// "get2", etc), or fail gracefully when needed. It also lets the go command
// verify the program wants to be a cache helper.
KnownCommands []Cmd `json:",omitempty"`
// For "get" requests.
Miss bool `json:",omitempty"` // cache miss
OutputID []byte `json:",omitempty"` // the ObjectID stored with the body
Size int64 `json:",omitempty"` // body size in bytes
Time *time.Time `json:",omitempty"` // when the object was put in the cache (optional; used for cache expiration)
// For "get" and "put" requests.
// DiskPath is the absolute path on disk of the body corresponding to a
// "get" (on cache hit) or "put" request's ActionID.
DiskPath string `json:",omitempty"`
}

View File

@@ -425,8 +425,9 @@ var (
GOROOTpkg string
GOROOTsrc string
GOBIN = Getenv("GOBIN")
GOMODCACHE, GOMODCACHEChanged = EnvOrAndChanged("GOMODCACHE", gopathDir("pkg/mod"))
GOBIN = Getenv("GOBIN")
GOCACHEPROG, GOCACHEPROGChanged = EnvOrAndChanged("GOCACHEPROG", "")
GOMODCACHE, GOMODCACHEChanged = EnvOrAndChanged("GOMODCACHE", gopathDir("pkg/mod"))
// Used in envcmd.MkEnv and build ID computations.
GOARM64, goARM64Changed = EnvOrAndChanged("GOARM64", buildcfg.DefaultGOARM64)

View File

@@ -85,6 +85,7 @@ func MkEnv() []cfg.EnvVar {
{Name: "GOAUTH", Value: cfg.GOAUTH, Changed: cfg.GOAUTHChanged},
{Name: "GOBIN", Value: cfg.GOBIN},
{Name: "GOCACHE"},
{Name: "GOCACHEPROG", Value: cfg.GOCACHEPROG, Changed: cfg.GOCACHEPROGChanged},
{Name: "GODEBUG", Value: os.Getenv("GODEBUG")},
{Name: "GOENV", Value: envFile, Changed: envFileChanged},
{Name: "GOEXE", Value: cfg.ExeSuffix},

View File

@@ -40,14 +40,8 @@
//
// GOFIPS140=latest go build -work my/binary
//
// will leave fips.o behind in $WORK/b001. Auditors like to be able to
// see that file. Accordingly, when [Enabled] returns true,
// [cmd/go/internal/work.Builder.useCache] arranges never to cache linker
// output, so that the link step always runs, and fips.o is always left
// behind in the link step. If this proves too slow, we could always
// cache fips.o as an extra link output and then restore it when -work is
// set, but we went a very long time never caching link steps at all, so
// not caching them in FIPS mode seems perfectly fine.
// will leave fips.o behind in $WORK/b001
// (unless the build result is cached, of course).
//
// When GOFIPS140 is set to something besides off and latest, [Snapshot]
// returns true, indicating that the build should replace the latest copy
@@ -119,6 +113,10 @@ func Init() {
if Snapshot() {
fsys.Bind(Dir(), filepath.Join(cfg.GOROOT, "src/crypto/internal/fips140"))
}
if cfg.Experiment.BoringCrypto && Enabled() {
base.Fatalf("go: cannot use GOFIPS140 with GOEXPERIMENT=boringcrypto")
}
}
var initDone bool

View File

@@ -17,7 +17,7 @@ information on how to use it see the cgo documentation (go doc cmd/cgo).
The second is the SWIG program, which is a general tool for
interfacing between languages. For information on SWIG see
http://swig.org/. When running go build, any file with a .swig
https://swig.org/. When running go build, any file with a .swig
extension will be passed to SWIG. Any file with a .swigcxx extension
will be passed to SWIG with the -c++ option.
@@ -270,11 +270,7 @@ the go tool will verify that https://example.org/?go-get=1 contains the
same meta tag and then git clone https://code.org/r/p/exproj into
GOPATH/src/example.org.
When using GOPATH, downloaded packages are written to the first directory
listed in the GOPATH environment variable.
(See 'go help gopath-get' and 'go help gopath'.)
When using modules, downloaded packages are stored in the module cache.
Downloaded packages are stored in the module cache.
See https://golang.org/ref/mod#module-cache.
When using modules, an additional variant of the go-import meta tag is
@@ -510,6 +506,10 @@ General-purpose environment variables:
GOCACHE
The directory where the go command will store cached
information for reuse in future builds.
GOCACHEPROG
A command (with optional space-separated flags) that implements an
external go command build cache.
See 'go doc cmd/go/internal/cacheprog'.
GODEBUG
Enable various debugging facilities. See https://go.dev/doc/godebug
for details.
@@ -620,6 +620,11 @@ Architecture-specific environment variables:
GOARM
For GOARCH=arm, the ARM architecture for which to compile.
Valid values are 5, 6, 7.
When the Go tools are built on an arm system,
the default value is set based on what the build system supports.
When the Go tools are not built on an arm system
(that is, when building a cross-compiler),
the default value is 7.
The value can be followed by an option specifying how to implement floating point instructions.
Valid options are ,softfloat (default for 5) and ,hardfloat (default for 6 and 7).
GOARM64
@@ -1029,7 +1034,7 @@ command
Example: Data
If the server responds with any 4xx code, the go command will write the
following to the programs' stdin:
following to the program's stdin:
Response = StatusLine { HeaderLine } BlankLine .
StatusLine = Protocol Space Status '\n' .
Protocol = /* HTTP protocol */ .
@@ -1097,7 +1102,7 @@ Furthermore, as with TestEvent, parsers can simply concatenate the Output
fields of all events to reconstruct the text format output, as it would
have appeared from go build without the -json flag.
Note that there may also be non-JSON error text on stdnard error, even
Note that there may also be non-JSON error text on standard error, even
with the -json flag. Typically, this indicates an early, serious error.
Consumers should be robust to this.
`,

View File

@@ -3068,7 +3068,15 @@ func setPGOProfilePath(pkgs []*Package) {
// CheckPackageErrors prints errors encountered loading pkgs and their
// dependencies, then exits with a non-zero status if any errors were found.
func CheckPackageErrors(pkgs []*Package) {
var anyIncomplete bool
PackageErrors(pkgs, func(p *Package) {
DefaultPrinter().Errorf(p, "%v", p.Error)
})
base.ExitIfErrors()
}
// PackageErrors calls report for errors encountered loading pkgs and their dependencies.
func PackageErrors(pkgs []*Package, report func(*Package)) {
var anyIncomplete, anyErrors bool
for _, pkg := range pkgs {
if pkg.Incomplete {
anyIncomplete = true
@@ -3078,11 +3086,14 @@ func CheckPackageErrors(pkgs []*Package) {
all := PackageList(pkgs)
for _, p := range all {
if p.Error != nil {
DefaultPrinter().Errorf(p, "%v", p.Error)
report(p)
anyErrors = true
}
}
}
base.ExitIfErrors()
if anyErrors {
return
}
// Check for duplicate loads of the same package.
// That should be impossible, but if it does happen then
@@ -3105,7 +3116,9 @@ func CheckPackageErrors(pkgs []*Package) {
}
seen[key] = true
}
base.ExitIfErrors()
if len(reported) > 0 {
base.ExitIfErrors()
}
}
// mainPackagesOnly filters out non-main packages matched only by arguments

View File

@@ -22,10 +22,11 @@ type Data struct {
}
// Mmap maps the given file into memory.
func Mmap(file string) (Data, error) {
func Mmap(file string) (Data, bool, error) {
f, err := os.Open(file)
if err != nil {
return Data{}, err
return Data{}, false, err
}
return mmapFile(f)
data, err := mmapFile(f)
return data, true, err
}

View File

@@ -125,11 +125,6 @@ suggested Go toolchain, see https://go.dev/doc/toolchain.
For more about specifying packages, see 'go help packages'.
This text describes the behavior of get using modules to manage source
code and dependencies. If instead the go command is running in GOPATH
mode, the details of get's flags and effects change, as does 'go help get'.
See 'go help gopath-get'.
See also: go build, go install, go clean, go mod.
`,
}

View File

@@ -183,16 +183,21 @@ func openIndexModule(modroot string, ismodcache bool) (*Module, error) {
if err != nil {
return nil, err
}
data, _, err := cache.GetMmap(cache.Default(), id)
data, _, opened, err := cache.GetMmap(cache.Default(), id)
if err != nil {
// Couldn't read from modindex. Assume we couldn't read from
// the index because the module hasn't been indexed yet.
// But double check on Windows that we haven't opened the file yet,
// because once mmap opens the file, we can't close it, and
// Windows won't let us open an already opened file.
data, err = indexModule(modroot)
if err != nil {
return nil, err
}
if err = cache.PutBytes(cache.Default(), id, data); err != nil {
return nil, err
if runtime.GOOS != "windows" || !opened {
if err = cache.PutBytes(cache.Default(), id, data); err != nil {
return nil, err
}
}
}
mi, err := fromBytes(modroot, data)
@@ -212,13 +217,18 @@ func openIndexPackage(modroot, pkgdir string) (*IndexPackage, error) {
if err != nil {
return nil, err
}
data, _, err := cache.GetMmap(cache.Default(), id)
data, _, opened, err := cache.GetMmap(cache.Default(), id)
if err != nil {
// Couldn't read from index. Assume we couldn't read from
// the index because the package hasn't been indexed yet.
// But double check on Windows that we haven't opened the file yet,
// because once mmap opens the file, we can't close it, and
// Windows won't let us open an already opened file.
data = indexPackage(modroot, pkgdir)
if err = cache.PutBytes(cache.Default(), id, data); err != nil {
return nil, err
if runtime.GOOS != "windows" || !opened {
if err = cache.PutBytes(cache.Default(), id, data); err != nil {
return nil, err
}
}
}
pkg, err := packageFromBytes(modroot, data)

View File

@@ -994,14 +994,15 @@ func runTest(ctx context.Context, cmd *base.Command, args []string) {
// Prepare build + run + print actions for all packages being tested.
for _, p := range pkgs {
buildTest, runTest, printTest, perr, err := builderTest(b, ctx, pkgOpts, p, allImports[p], writeCoverMetaAct)
if err != nil {
reportErr := func(perr *load.Package, err error) {
str := err.Error()
if p.ImportPath != "" {
load.DefaultPrinter().Errorf(perr, "# %s\n%s", p.ImportPath, str)
} else {
load.DefaultPrinter().Errorf(perr, "%s", str)
}
}
reportSetupFailed := func(perr *load.Package, err error) {
var stdout io.Writer = os.Stdout
if testJSON {
json := test2json.NewConverter(stdout, p.ImportPath, test2json.Timestamp)
@@ -1009,11 +1010,34 @@ func runTest(ctx context.Context, cmd *base.Command, args []string) {
json.Exited(err)
json.Close()
}()
json.SetFailedBuild(perr.Desc())
if gotestjsonbuildtext.Value() == "1" {
// While this flag is about go build -json, the other effect
// of that change was to include "FailedBuild" in the test JSON.
gotestjsonbuildtext.IncNonDefault()
} else {
json.SetFailedBuild(perr.Desc())
}
stdout = json
}
fmt.Fprintf(stdout, "FAIL\t%s [setup failed]\n", p.ImportPath)
base.SetExitStatus(1)
}
var firstErrPkg *load.Package // arbitrarily report setup failed error for first error pkg reached in DFS
load.PackageErrors([]*load.Package{p}, func(p *load.Package) {
reportErr(p, p.Error)
if firstErrPkg == nil {
firstErrPkg = p
}
})
if firstErrPkg != nil {
reportSetupFailed(firstErrPkg, firstErrPkg.Error)
continue
}
buildTest, runTest, printTest, perr, err := builderTest(b, ctx, pkgOpts, p, allImports[p], writeCoverMetaAct)
if err != nil {
reportErr(perr, err)
reportSetupFailed(perr, err)
continue
}
builds = append(builds, buildTest)
@@ -1437,7 +1461,11 @@ func (r *runTestActor) Act(b *work.Builder, ctx context.Context, a *work.Action)
if a.Failed != nil {
// We were unable to build the binary.
if json != nil && a.Failed.Package != nil {
json.SetFailedBuild(a.Failed.Package.Desc())
if gotestjsonbuildtext.Value() == "1" {
gotestjsonbuildtext.IncNonDefault()
} else {
json.SetFailedBuild(a.Failed.Package.Desc())
}
}
a.Failed = nil
fmt.Fprintf(stdout, "FAIL\t%s [build failed]\n", a.Package.ImportPath)

View File

@@ -169,7 +169,7 @@ func Select() {
}
gotoolchain = minToolchain
if (mode == "auto" || mode == "path") && !goInstallVersion() {
if (mode == "auto" || mode == "path") && !goInstallVersion(minVers) {
// Read go.mod to find new minimum and suggested toolchain.
file, goVers, toolchain := modGoToolchain()
gover.Startup.AutoFile = file
@@ -549,7 +549,7 @@ func modGoToolchain() (file, goVers, toolchain string) {
// goInstallVersion reports whether the command line is go install m@v or go run m@v.
// If so, Select must not read the go.mod or go.work file in "auto" or "path" mode.
func goInstallVersion() bool {
func goInstallVersion(minVers string) bool {
// Note: We assume there are no flags between 'go' and 'install' or 'run'.
// During testing there are some debugging flags that are accepted
// in that position, but in production go binaries there are not.
@@ -708,7 +708,11 @@ func goInstallVersion() bool {
if errors.Is(err, gover.ErrTooNew) {
// Run early switch, same one go install or go run would eventually do,
// if it understood all the command-line flags.
SwitchOrFatal(ctx, err)
var s Switcher
s.Error(err)
if s.TooNew != nil && gover.Compare(s.TooNew.GoVersion, minVers) > 0 {
SwitchOrFatal(ctx, err)
}
}
return true // pkg@version found

View File

@@ -63,6 +63,7 @@ func (h *authHandler) Handler(dir string, env []string, logger *log.Logger) (htt
var err error
accessFile, err = fs.Open(path.Join(accessDir, ".access"))
if err == nil {
defer accessFile.Close()
break
}

View File

@@ -15,7 +15,6 @@ import (
"cmd/go/internal/base"
"cmd/go/internal/cache"
"cmd/go/internal/cfg"
"cmd/go/internal/fips140"
"cmd/go/internal/fsys"
"cmd/go/internal/str"
"cmd/internal/buildid"
@@ -447,19 +446,6 @@ func (b *Builder) useCache(a *Action, actionHash cache.ActionID, target string,
a.buildID = actionID + buildIDSeparator + mainpkg.buildID + buildIDSeparator + contentID
}
// In FIPS mode, we disable any link caching,
// so that we always leave fips.o in $WORK/b001.
// This makes sure that labs validating the FIPS
// implementation can always run 'go build -work'
// and then find fips.o in $WORK/b001/fips.o.
// We could instead also save the fips.o and restore it
// to $WORK/b001 from the cache,
// but we went years without caching binaries anyway,
// so not caching them for FIPS will be fine, at least to start.
if a.Mode == "link" && fips140.Enabled() && a.Package != nil && !strings.HasSuffix(a.Package.ImportPath, ".test") {
return false
}
// If user requested -a, we force a rebuild, so don't use the cache.
if cfg.BuildA {
if p := a.Package; p != nil && !p.Stale {
@@ -519,7 +505,7 @@ func (b *Builder) useCache(a *Action, actionHash cache.ActionID, target string,
oldBuildID := a.buildID
a.buildID = id[1] + buildIDSeparator + id[2]
linkID := buildid.HashToString(b.linkActionID(a.triggers[0]))
if id[0] == linkID && !fips140.Enabled() {
if id[0] == linkID {
// Best effort attempt to display output from the compile and link steps.
// If it doesn't work, it doesn't work: reusing the cached binary is more
// important than reprinting diagnostic information.

View File

@@ -1374,6 +1374,7 @@ func (b *Builder) linkActionID(a *Action) cache.ActionID {
fmt.Fprintf(h, "buildmode %s goos %s goarch %s\n", cfg.BuildBuildmode, cfg.Goos, cfg.Goarch)
fmt.Fprintf(h, "import %q\n", p.ImportPath)
fmt.Fprintf(h, "omitdebug %v standard %v local %v prefix %q\n", p.Internal.OmitDebug, p.Standard, p.Internal.Local, p.Internal.LocalPrefix)
fmt.Fprintf(h, "defaultgodebug %q\n", p.DefaultGODEBUG)
if cfg.BuildTrimpath {
fmt.Fprintln(h, "trimpath")
}

View File

@@ -201,23 +201,23 @@ var validLinkerFlags = []*lazyregexp.Regexp{
re(`-Wl,--end-group`),
re(`-Wl,--(no-)?export-dynamic`),
re(`-Wl,-E`),
re(`-Wl,-framework,[^,@\-][^,]+`),
re(`-Wl,-framework,[^,@\-][^,]*`),
re(`-Wl,--hash-style=(sysv|gnu|both)`),
re(`-Wl,-headerpad_max_install_names`),
re(`-Wl,--no-undefined`),
re(`-Wl,--pop-state`),
re(`-Wl,--push-state`),
re(`-Wl,-R,?([^@\-,][^,@]*$)`),
re(`-Wl,--just-symbols[=,]([^,@\-][^,@]+)`),
re(`-Wl,-rpath(-link)?[=,]([^,@\-][^,]+)`),
re(`-Wl,--just-symbols[=,]([^,@\-][^,@]*)`),
re(`-Wl,-rpath(-link)?[=,]([^,@\-][^,]*)`),
re(`-Wl,-s`),
re(`-Wl,-search_paths_first`),
re(`-Wl,-sectcreate,([^,@\-][^,]+),([^,@\-][^,]+),([^,@\-][^,]+)`),
re(`-Wl,-sectcreate,([^,@\-][^,]*),([^,@\-][^,]*),([^,@\-][^,]*)`),
re(`-Wl,--start-group`),
re(`-Wl,-?-static`),
re(`-Wl,-?-subsystem,(native|windows|console|posix|xbox)`),
re(`-Wl,-syslibroot[=,]([^,@\-][^,]+)`),
re(`-Wl,-undefined[=,]([^,@\-][^,]+)`),
re(`-Wl,-syslibroot[=,]([^,@\-][^,]*)`),
re(`-Wl,-undefined[=,]([^,@\-][^,]*)`),
re(`-Wl,-?-unresolved-symbols=[^,]+`),
re(`-Wl,--(no-)?warn-([^,]+)`),
re(`-Wl,-?-wrap[=,][^,@\-][^,]*`),
@@ -227,6 +227,21 @@ var validLinkerFlags = []*lazyregexp.Regexp{
re(`\./.*\.(a|o|obj|dll|dylib|so|tbd)`),
}
var validLinkerFlagsOnDarwin = []*lazyregexp.Regexp{
// The GNU linker interprets `@file` as "read command-line options from
// file". Thus, we forbid values starting with `@` on linker flags.
// However, this causes a problem when targeting Darwin.
// `@executable_path`, `@loader_path`, and `@rpath` are special values
// used in Mach-O to change the library search path and can be used in
// conjunction with the `-install_name` and `-rpath` linker flags.
// Since the GNU linker does not support Mach-O, targeting Darwin
// implies not using the GNU linker. Therefore, we allow @ in the linker
// flags if and only if cfg.Goos == "darwin" || cfg.Goos == "ios".
re(`-Wl,-dylib_install_name,@rpath(/[^,]*)?`),
re(`-Wl,-install_name,@rpath(/[^,]*)?`),
re(`-Wl,-rpath,@(executable_path|loader_path)(/[^,]*)?`),
}
var validLinkerFlagsWithNextArg = []string{
"-arch",
"-F",
@@ -249,8 +264,13 @@ func checkCompilerFlags(name, source string, list []string) error {
}
func checkLinkerFlags(name, source string, list []string) error {
validLinkerFlagsForPlatform := validLinkerFlags
if cfg.Goos == "darwin" || cfg.Goos == "ios" {
validLinkerFlagsForPlatform = append(validLinkerFlags, validLinkerFlagsOnDarwin...)
}
checkOverrides := true
return checkFlags(name, source, list, invalidLinkerFlags, validLinkerFlags, validLinkerFlagsWithNextArg, checkOverrides)
return checkFlags(name, source, list, invalidLinkerFlags, validLinkerFlagsForPlatform, validLinkerFlagsWithNextArg, checkOverrides)
}
// checkCompilerFlagsForInternalLink returns an error if 'list'

View File

@@ -8,6 +8,8 @@ import (
"os"
"strings"
"testing"
"cmd/go/internal/cfg"
)
var goodCompilerFlags = [][]string{
@@ -182,6 +184,13 @@ var goodLinkerFlags = [][]string{
{"-Wl,--pop-state"},
{"-Wl,--push-state,--as-needed"},
{"-Wl,--push-state,--no-as-needed,-Bstatic"},
{"-Wl,--just-symbols,."},
{"-Wl,-framework,."},
{"-Wl,-rpath,."},
{"-Wl,-rpath-link,."},
{"-Wl,-sectcreate,.,.,."},
{"-Wl,-syslibroot,."},
{"-Wl,-undefined,."},
}
var badLinkerFlags = [][]string{
@@ -238,6 +247,8 @@ var badLinkerFlags = [][]string{
{"-Wl,--hash-style=foo"},
{"-x", "--c"},
{"-x", "@obj"},
{"-Wl,-dylib_install_name,@foo"},
{"-Wl,-install_name,@foo"},
{"-Wl,-rpath,@foo"},
{"-Wl,-R,foo,bar"},
{"-Wl,-R,@foo"},
@@ -254,6 +265,21 @@ var badLinkerFlags = [][]string{
{"./-Wl,--push-state,-R.c"},
}
var goodLinkerFlagsOnDarwin = [][]string{
{"-Wl,-dylib_install_name,@rpath"},
{"-Wl,-dylib_install_name,@rpath/"},
{"-Wl,-dylib_install_name,@rpath/foo"},
{"-Wl,-install_name,@rpath"},
{"-Wl,-install_name,@rpath/"},
{"-Wl,-install_name,@rpath/foo"},
{"-Wl,-rpath,@executable_path"},
{"-Wl,-rpath,@executable_path/"},
{"-Wl,-rpath,@executable_path/foo"},
{"-Wl,-rpath,@loader_path"},
{"-Wl,-rpath,@loader_path/"},
{"-Wl,-rpath,@loader_path/foo"},
}
func TestCheckLinkerFlags(t *testing.T) {
for _, f := range goodLinkerFlags {
if err := checkLinkerFlags("test", "test", f); err != nil {
@@ -265,6 +291,31 @@ func TestCheckLinkerFlags(t *testing.T) {
t.Errorf("missing error for %q", f)
}
}
goos := cfg.Goos
cfg.Goos = "darwin"
for _, f := range goodLinkerFlagsOnDarwin {
if err := checkLinkerFlags("test", "test", f); err != nil {
t.Errorf("unexpected error for %q: %v", f, err)
}
}
cfg.Goos = "ios"
for _, f := range goodLinkerFlagsOnDarwin {
if err := checkLinkerFlags("test", "test", f); err != nil {
t.Errorf("unexpected error for %q: %v", f, err)
}
}
cfg.Goos = "linux"
for _, f := range goodLinkerFlagsOnDarwin {
if err := checkLinkerFlags("test", "test", f); err == nil {
t.Errorf("missing error for %q", f)
}
}
cfg.Goos = goos
}
func TestCheckFlagAllowDisallow(t *testing.T) {

View File

@@ -0,0 +1,27 @@
[short] skip 'builds go programs'
go build -o cacheprog$GOEXE cacheprog.go
env GOCACHEPROG=$GOPATH/src/cacheprog$GOEXE
# This should not deadlock
go build simple.go
! stderr 'cacheprog closed'
-- simple.go --
package main
func main() {}
-- cacheprog.go --
// This is a minimal GOCACHEPROG program that doesn't respond to close.
package main
import (
"encoding/json"
"os"
)
func main() {
json.NewEncoder(os.Stdout).Encode(map[string][]string{"KnownCommands": {"close"}})
var res struct{}
json.NewDecoder(os.Stdin).Decode(&res)
}

View File

@@ -51,7 +51,7 @@ go version -m example$GOEXE
stdout '\s+mod\s+example\s+v1.0.1\s+'
rm example$GOEXE
# Use tag+dirty when there are uncomitted changes present.
# Use tag+dirty when there are uncommitted changes present.
cp $WORK/copy/README $WORK/repo/README
go build
go version -m example$GOEXE
@@ -82,7 +82,7 @@ go version -m example$GOEXE
stdout '\s+mod\s+example\s+v1.0.3-0.20220719150702-deaeab06f7fe\s+'
rm example$GOEXE
# Use pseudo+dirty when uncomitted changes are present.
# Use pseudo+dirty when uncommitted changes are present.
mv README2 README3
go build
go version -m example$GOEXE

View File

@@ -1,5 +1,8 @@
# Test query for non-defaults in the env
# Go+BoringCrypto conflicts with GOFIPS140.
[GOEXPERIMENT:boringcrypto] skip
env GOROOT=./a
env GOTOOLCHAIN=local
env GOSUMDB=nodefault

View File

@@ -0,0 +1,42 @@
# GOCACHEPROG unset
env GOCACHEPROG=
go env
stdout 'GOCACHEPROG=''?''?'
go env -changed
! stdout 'GOCACHEPROG'
go env -changed -json
! stdout 'GOCACHEPROG'
# GOCACHEPROG set
[short] skip 'compiles and runs a go program'
go build -o cacheprog$GOEXE cacheprog.go
env GOCACHEPROG=$GOPATH/src/cacheprog$GOEXE
go env
stdout 'GOCACHEPROG=''?'$GOCACHEPROG'''?'
go env -changed
stdout 'GOCACHEPROG=''?'$GOCACHEPROG'''?'
go env -changed -json
stdout '"GOCACHEPROG": ".*cacheprog'$GOEXE'"'
-- cacheprog.go --
// This is a minimal GOCACHEPROG program that can't actually do anything but exit.
package main
import (
"encoding/json"
"os"
)
func main() {
json.NewEncoder(os.Stdout).Encode(map[string][]string{"KnownCommands": {"close"}})
var res struct{}
json.NewDecoder(os.Stdin).Decode(&res)
}

View File

@@ -1,3 +1,6 @@
# Go+BoringCrypto conflicts with GOFIPS140.
[GOEXPERIMENT:boringcrypto] skip
# list with GOFIPS140=off
env GOFIPS140=off
go list -f '{{.DefaultGODEBUG}}'
@@ -17,12 +20,12 @@ go build -x -o x.exe
go build -x -o x.exe
! stderr link
# build with GOFIPS140=latest is NOT cached (need fipso)
# build with GOFIPS140=latest is cached too
env GOFIPS140=latest
go build -x -o x.exe
stderr link.*-fipso
go build -x -o x.exe
stderr link.*-fipso
! stderr link.*-fipso
# build test with GOFIPS140=off is cached
env GOFIPS140=off
@@ -38,8 +41,6 @@ stderr link.*-fipso
go test -x -c
! stderr link
-- go.mod --
module m
-- x.go --

View File

@@ -7,6 +7,9 @@ env alias=inprocess
skip 'no snapshots yet'
env GOFIPS140=$snap
# Go+BoringCrypto conflicts with GOFIPS140.
[GOEXPERIMENT:boringcrypto] skip
# default GODEBUG includes fips140=on
go list -f '{{.DefaultGODEBUG}}'
stdout fips140=on
@@ -44,11 +47,11 @@ stdout crypto/internal/fips140/$snap/sha256
[short] skip
# build with GOFIPS140=snap is NOT cached (need fipso)
# build with GOFIPS140=snap is cached
go build -x -o x.exe
stderr link.*-fipso
go build -x -o x.exe
stderr link.*-fipso
! stderr link.*-fipso
# build test with GOFIPS140=snap is cached
go test -x -c

View File

@@ -2,8 +2,6 @@
# credentials passed in HTTPS requests to VCS servers.
# See golang.org/issue/26232
[short] skip
env GOPROXY=direct
env GOSUMDB=off
@@ -55,7 +53,6 @@ go get vcs-test.golang.org/auth/or401
env NETRC=$WORK/missing
! go get vcs-test.golang.org/auth/or401
stderr '^\tserver response: ACCESS DENIED, buddy$'
-- go.mod --
module private.example.com
-- $WORK/empty --
@@ -63,3 +60,7 @@ module private.example.com
machine vcs-test.golang.org
login aladdin
password opensesame
# first one should override this one
machine vcs-test.golang.org
login aladdin
password ignored

View File

@@ -3,13 +3,8 @@
env GOPROXY=direct
env GOSUMDB=off
# Use a custom authenticator to provide custom credentials
mkdir $WORK/bin
env PATH=$WORK/bin${:}$PATH
cd auth
go build -o $WORK/bin/my-auth$GOEXE .
cd ..
# Without credentials, downloading a module from a path that requires HTTPS
# basic auth should fail.
@@ -21,8 +16,10 @@ stderr '^\tserver response: ACCESS DENIED, buddy$'
! go mod tidy
stderr '^\tserver response: ACCESS DENIED, buddy$'
# With credentials from the my-auth binary, it should succeed.
env GOAUTH='my-auth'$GOEXE' --arg1 "value with spaces"'
# Initial invocation of authenticator is successful.
go build -o $WORK/bin/basic$GOEXE scripts/basic.go
# With credentials from the binary, it should succeed.
env GOAUTH='basic'$GOEXE
cp go.mod.orig go.mod
go get vcs-test.golang.org/auth/or401
# go imports should resolve correctly as well.
@@ -30,7 +27,54 @@ go mod tidy
go list all
stdout vcs-test.golang.org/auth/or401
-- auth/main.go --
# Second invocation of authenticator is successful.
go build -o $WORK/bin/reinvocation$GOEXE scripts/reinvocation.go
# With credentials from the binary, it should succeed.
env GOAUTH='reinvocation'$GOEXE
cp go.mod.orig go.mod
go get vcs-test.golang.org/auth/or401
# go imports should resolve correctly as well.
go mod tidy
go list all
stdout vcs-test.golang.org/auth/or401
# Authenticator can parse arguments correctly.
go build -o $WORK/bin/arguments$GOEXE scripts/arguments.go
# With credentials from the binary, it should succeed.
env GOAUTH='arguments'$GOEXE' --arg1 "value with spaces"'
cp go.mod.orig go.mod
go get vcs-test.golang.org/auth/or401
# go imports should resolve correctly as well.
go mod tidy
go list all
stdout vcs-test.golang.org/auth/or401
# Authenticator provides bad credentials.
go build -o $WORK/bin/invalid$GOEXE scripts/invalid.go
# With credentials from the binary, it should fail.
env GOAUTH='invalid'$GOEXE
cp go.mod.orig go.mod
! go get vcs-test.golang.org/auth/or401
stderr '^\tserver response: ACCESS DENIED, buddy$'
# go imports should fail as well.
! go mod tidy
stderr '^\tserver response: ACCESS DENIED, buddy$'
-- go.mod.orig --
module private.example.com
-- main.go --
package useprivate
import "vcs-test.golang.org/auth/or401"
-- scripts/basic.go --
package main
import "fmt"
func main() {
fmt.Printf("https://vcs-test.golang.org\n\nAuthorization: Basic YWxhZGRpbjpvcGVuc2VzYW1l\n\n")
}
-- scripts/reinvocation.go --
package main
import(
@@ -45,11 +89,7 @@ import(
)
func main() {
arg1 := flag.String("arg1", "", "")
flag.Parse()
if *arg1 != "value with spaces" {
log.Fatal("argument with spaces does not work")
}
// wait for re-invocation
if !strings.HasPrefix(flag.Arg(0), "https://vcs-test.golang.org") {
return
@@ -68,12 +108,28 @@ func main() {
}
fmt.Printf("https://vcs-test.golang.org\n\nAuthorization: Basic YWxhZGRpbjpvcGVuc2VzYW1l\n\n")
}
-- scripts/arguments.go --
package main
-- auth/go.mod --
module my-auth
-- go.mod.orig --
module private.example.com
-- main.go --
package useprivate
import(
"flag"
"fmt"
"log"
)
import "vcs-test.golang.org/auth/or401"
func main() {
arg1 := flag.String("arg1", "", "")
flag.Parse()
if *arg1 != "value with spaces" {
log.Fatal("argument with spaces does not work")
}
fmt.Printf("https://vcs-test.golang.org\n\nAuthorization: Basic YWxhZGRpbjpvcGVuc2VzYW1l\n\n")
}
-- scripts/invalid.go --
package main
import "fmt"
func main() {
fmt.Printf("https://vcs-test.golang.org\n\nAuthorization: Basic invalid\n\n")
}

View File

@@ -197,6 +197,17 @@ go mod edit -go=1.501 -toolchain=none
go version
stdout go1.501
# avoid two-step switch, first from install target requirement, then from GOTOOLCHAIN min
# instead, just jump directly to GOTOOLCHAIN min
env TESTGO_VERSION=go1.2.3
env GODEBUG=toolchaintrace=1
env GOTOOLCHAIN=go1.23.0+auto
! go install rsc.io/fortune/nonexist@v0.0.1
! stderr 'switching to go1.22.9'
stderr 'using go1.23.0'
env GODEBUG=
env GOTOOLCHAIN=auto
# go install m@v and go run m@v should ignore go.mod and use m@v
env TESTGO_VERSION=go1.2.3
go mod edit -go=1.999 -toolchain=go1.998

View File

@@ -3,4 +3,4 @@ env GO111MODULE=on
# go help get shows usage for get
go help get
stdout 'usage: go get'
stdout 'get using modules to manage source'
stdout 'updates go.mod to require those versions'

View File

@@ -15,8 +15,8 @@ stdout '\Aok\s+example.com/x\s+[0-9.s]+\n\z'
# Even though ./x looks like a package path, the real package should be
# the implicit '.'.
! go test --answer=42 ./x
stdout '^FAIL\t. \[build failed\]'
stderr '^\.: no Go files in '$PWD'$'
stdout '^FAIL\t. \[setup failed\]'
stderr '^# \.\nno Go files in '$PWD'$'
# However, *flags* that appear after unrecognized flags should still be
# interpreted as flags, under the (possibly-erroneous) assumption that

View File

@@ -0,0 +1,47 @@
[!fuzz] skip
[short] skip
env GOCACHE=$WORK/cache
# Test fuzz.Context.
go test -vet=off context_fuzz_test.go
stdout ^ok
! stdout FAIL
go test -vet=off -fuzz=Fuzz -fuzztime=1x context_fuzz_test.go
stdout ok
! stdout FAIL
-- context_fuzz_test.go --
package context_fuzz
import (
"context"
"errors"
"testing"
)
func Fuzz(f *testing.F) {
ctx := f.Context()
if err := ctx.Err(); err != nil {
f.Fatalf("expected non-canceled context, got %v", err)
}
f.Fuzz(func(t *testing.T, data []byte) {
innerCtx := t.Context()
if err := innerCtx.Err(); err != nil {
t.Fatalf("expected inner test to not inherit canceled context, got %v", err)
}
t.Cleanup(func() {
if !errors.Is(innerCtx.Err(), context.Canceled) {
t.Fatal("expected context of inner test to be canceled after its fuzz function finished")
}
})
})
f.Cleanup(func() {
if !errors.Is(ctx.Err(), context.Canceled) {
f.Fatal("expected context canceled before cleanup")
}
})
}

View File

@@ -40,6 +40,18 @@ stdout '"Action":"output","Package":"m/loaderror","Output":"FAIL\\tm/loaderror \
stdout '"Action":"fail","Package":"m/loaderror","Elapsed":.*,"FailedBuild":"x"'
! stderr '.'
# Test an import cycle loading error in a non test file. (#70820)
! go test -json -o=$devnull ./cycle/p
stdout '"ImportPath":"m/cycle/q","Action":"build-output","Output":"# m/cycle/p\\n"'
stdout '"ImportPath":"m/cycle/q","Action":"build-output","Output":"package m/cycle/p\\n"'
stdout '"ImportPath":"m/cycle/q","Action":"build-output","Output":"\\timports m/cycle/q from p.go\\n"'
stdout '"ImportPath":"m/cycle/q","Action":"build-output","Output":"\\timports m/cycle/q from q.go: import cycle not allowed\\n"'
stdout '"ImportPath":"m/cycle/q","Action":"build-fail"'
stdout '"Action":"start","Package":"m/cycle/p"'
stdout '"Action":"output","Package":"m/cycle/p","Output":"FAIL\\tm/cycle/p \[setup failed\]\\n"'
stdout '"Action":"fail","Package":"m/cycle/p","Elapsed":.*,"FailedBuild":"m/cycle/q"'
! stderr '.'
# Test a vet error
! go test -json -o=$devnull ./veterror
stdout '"ImportPath":"m/veterror \[m/veterror.test\]","Action":"build-output","Output":"# m/veterror\\n"'
@@ -58,8 +70,9 @@ stderr '# m/builderror \[m/builderror.test\]\n'
stderr 'builderror'${/}'main_test.go:3:11: undefined: y\n'
stdout '"Action":"start","Package":"m/builderror"'
stdout '"Action":"output","Package":"m/builderror","Output":"FAIL\\tm/builderror \[build failed\]\\n"'
stdout '"Action":"fail","Package":"m/builderror","Elapsed":.*,"FailedBuild":"m/builderror \[m/builderror\.test\]"'
stdout '"Action":"fail","Package":"m/builderror","Elapsed":[0-9.]+\}'
# FailedBuild should NOT appear in the output in this mode.
! stdout '"FailedBuild"'
-- go.mod --
module m
@@ -98,3 +111,13 @@ import (
func TestVetError(t *testing.T) {
fmt.Printf("%s")
}
-- cycle/p/p.go --
package p
import "m/cycle/q"
-- cycle/q/q.go --
package q
import (
"m/cycle/q"
)

View File

@@ -33,10 +33,23 @@ stderr '# m/t2/p\n.*package x is not in std'
stdout 'FAIL m/t2/p \[setup failed\]'
stdout 'ok m/t'
# Finally, this one is a build error, but produced by cmd/go directly
# Test that an import cycle error is reported. Test for #70820
! go test -o=$devnull ./cycle/p ./t
stderr '# m/cycle/p\n.*package m/cycle/p\n\timports m/cycle/p from p\.go: import cycle not allowed'
stdout 'FAIL m/cycle/p \[setup failed\]'
stdout 'ok m/t'
# Test that multiple errors for the same package under test are reported.
! go test -o=$devnull ./cycle/q ./t
stderr '# m/cycle/q\n.*package m/cycle/q\n\timports m/cycle/p from q\.go\n\timports m/cycle/p from p\.go: import cycle not allowed'
stdout 'FAIL m/cycle/q \[setup failed\]'
stdout 'ok m/t'
# Finally, this one is a non-import-cycle load error that
# is produced for the package under test.
! go test -o=$devnull . ./t
stderr '^\.: no Go files in '$PWD'$'
stdout 'FAIL . \[build failed\]'
stderr '# \.\n.*no Go files in '$PWD'$'
stdout 'FAIL . \[setup failed\]'
stdout 'ok m/t'
-- go.mod --
@@ -68,6 +81,17 @@ package p
package p
import "m/bad"
-- cycle/p/p.go --
package p
import "m/cycle/p"
-- cycle/q/q.go --
package q
import (
"m/bad"
"m/cycle/p"
)
-- bad/bad.go --
package bad

View File

@@ -2,13 +2,16 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package objfile
// Package disasm provides disassembly routines.
//
// It is broken out from cmd/internal/objfile so tools that don't need
// disassembling don't need to depend on x/arch disassembler code.
package disasm
import (
"bufio"
"bytes"
"container/list"
"debug/gosym"
"encoding/binary"
"fmt"
"io"
@@ -19,6 +22,7 @@ import (
"strings"
"text/tabwriter"
"cmd/internal/objfile"
"cmd/internal/src"
"golang.org/x/arch/arm/armasm"
@@ -32,8 +36,8 @@ import (
// Disasm is a disassembler for a given File.
type Disasm struct {
syms []Sym //symbols in file, sorted by address
pcln Liner // pcln table
syms []objfile.Sym // symbols in file, sorted by address
pcln objfile.Liner // pcln table
text []byte // bytes of text segment (actual instructions)
textStart uint64 // start PC of text
textEnd uint64 // end PC of text
@@ -42,8 +46,12 @@ type Disasm struct {
byteOrder binary.ByteOrder // byte order for goarch
}
// Disasm returns a disassembler for the file f.
func (e *Entry) Disasm() (*Disasm, error) {
// DisasmForFile returns a disassembler for the file f.
func DisasmForFile(f *objfile.File) (*Disasm, error) {
return disasmForEntry(f.Entries()[0])
}
func disasmForEntry(e *objfile.Entry) (*Disasm, error) {
syms, err := e.Symbols()
if err != nil {
return nil, err
@@ -269,7 +277,7 @@ func (d *Disasm) Print(w io.Writer, filter *regexp.Regexp, start, end uint64, pr
}
// Decode disassembles the text segment range [start, end), calling f for each instruction.
func (d *Disasm) Decode(start, end uint64, relocs []Reloc, gnuAsm bool, f func(pc, size uint64, file string, line int, text string)) {
func (d *Disasm) Decode(start, end uint64, relocs []objfile.Reloc, gnuAsm bool, f func(pc, size uint64, file string, line int, text string)) {
if start < d.textStart {
start = d.textStart
}
@@ -402,14 +410,16 @@ func disasm_ppc64(code []byte, pc uint64, lookup lookupFunc, byteOrder binary.By
func disasm_riscv64(code []byte, pc uint64, lookup lookupFunc, byteOrder binary.ByteOrder, gnuAsm bool) (string, int) {
inst, err := riscv64asm.Decode(code)
var text string
size := inst.Len
if err != nil || inst.Op == 0 {
size = 2
text = "?"
} else if gnuAsm {
text = fmt.Sprintf("%-36s // %s", riscv64asm.GoSyntax(inst, pc, lookup, textReader{code, pc}), riscv64asm.GNUSyntax(inst))
} else {
text = riscv64asm.GoSyntax(inst, pc, lookup, textReader{code, pc})
}
return text, 4
return text, size
}
func disasm_s390x(code []byte, pc uint64, lookup lookupFunc, _ binary.ByteOrder, gnuAsm bool) (string, int) {
@@ -452,9 +462,3 @@ var byteOrders = map[string]binary.ByteOrder{
"riscv64": binary.LittleEndian,
"s390x": binary.BigEndian,
}
type Liner interface {
// Given a pc, returns the corresponding file, line, and function data.
// If unknown, returns "",0,nil.
PCToLine(uint64) (string, int, *gosym.Func)
}

View File

@@ -5,22 +5,33 @@
// Package hash implements hash functions used in the compiler toolchain.
package hash
// TODO(rsc): Delete the 16 and 20 forms and use 32 at all call sites.
import (
"crypto/md5"
"crypto/sha1"
"crypto/sha256"
"hash"
)
const (
// Size32 is the size of 32 bytes hash checksum.
Size32 = sha256.Size
// Size20 is the size of 20 bytes hash checksum.
Size20 = sha1.Size
// Size16 is the size of 16 bytes hash checksum.
Size16 = md5.Size
// Size32 is the size of the 32-byte hash checksum.
Size32 = 32
// Size20 is the size of the 20-byte hash checksum.
Size20 = 20
// Size16 is the size of the 16-byte hash checksum.
Size16 = 16
)
type shortHash struct {
hash.Hash
n int
}
func (h *shortHash) Sum(b []byte) []byte {
old := b
sum := h.Hash.Sum(b)
return sum[:len(old)+h.n]
}
// New32 returns a new [hash.Hash] computing the 32 bytes hash checksum.
func New32() hash.Hash {
h := sha256.New()
@@ -30,12 +41,12 @@ func New32() hash.Hash {
// New20 returns a new [hash.Hash] computing the 20 bytes hash checksum.
func New20() hash.Hash {
return sha1.New()
return &shortHash{New32(), 20}
}
// New16 returns a new [hash.Hash] computing the 16 bytes hash checksum.
func New16() hash.Hash {
return md5.New()
return &shortHash{New32(), 16}
}
// Sum32 returns the 32 bytes checksum of the data.
@@ -47,10 +58,16 @@ func Sum32(data []byte) [Size32]byte {
// Sum20 returns the 20 bytes checksum of the data.
func Sum20(data []byte) [Size20]byte {
return sha1.Sum(data)
sum := Sum32(data)
var short [Size20]byte
copy(short[:], sum[4:])
return short
}
// Sum16 returns the 16 bytes checksum of the data.
func Sum16(data []byte) [Size16]byte {
return md5.Sum(data)
sum := Sum32(data)
var short [Size16]byte
copy(short[:], sum[8:])
return short
}

View File

@@ -320,7 +320,7 @@ func (ctxt *Link) NumberSyms() {
// Assign special index for builtin symbols.
// Don't do it when linking against shared libraries, as the runtime
// may be in a different library.
if i := goobj.BuiltinIdx(rs.Name, int(rs.ABI())); i != -1 {
if i := goobj.BuiltinIdx(rs.Name, int(rs.ABI())); i != -1 && !rs.IsLinkname() {
rs.PkgIdx = goobj.PkgIdxBuiltin
rs.SymIdx = int32(i)
rs.Set(AttrIndexed, true)

View File

@@ -119,10 +119,6 @@ func (f *File) DWARF() (*dwarf.Data, error) {
return f.entries[0].DWARF()
}
func (f *File) Disasm() (*Disasm, error) {
return f.entries[0].Disasm()
}
func (e *Entry) Name() string {
return e.name
}
@@ -181,3 +177,9 @@ func (e *Entry) LoadAddress() (uint64, error) {
func (e *Entry) DWARF() (*dwarf.Data, error) {
return e.raw.dwarf()
}
type Liner interface {
// Given a pc, returns the corresponding file, line, and function data.
// If unknown, returns "",0,nil.
PCToLine(uint64) (string, int, *gosym.Func)
}

View File

@@ -118,6 +118,7 @@ Flags:
Link with race detection libraries.
-s
Omit the symbol table and debug information.
Implies the -w flag, which can be negated with -w=0.
-tmpdir dir
Write temporary files to dir.
Temporary files are only used in external linking mode.

View File

@@ -55,17 +55,31 @@ import (
)
// isRuntimeDepPkg reports whether pkg is the runtime package or its dependency.
// TODO: just compute from the runtime package, and remove this hardcoded list.
func isRuntimeDepPkg(pkg string) bool {
switch pkg {
case "runtime",
"sync/atomic", // runtime may call to sync/atomic, due to go:linkname
"internal/abi", // used by reflectcall (and maybe more)
"internal/bytealg", // for IndexByte
"sync/atomic", // runtime may call to sync/atomic, due to go:linkname // TODO: this is not true?
"internal/abi", // used by reflectcall (and maybe more)
"internal/asan",
"internal/bytealg", // for IndexByte
"internal/byteorder",
"internal/chacha8rand", // for rand
"internal/cpu": // for cpu features
"internal/coverage/rtcov",
"internal/cpu", // for cpu features
"internal/goarch",
"internal/godebugs",
"internal/goexperiment",
"internal/goos",
"internal/msan",
"internal/profilerecord",
"internal/race",
"internal/stringslite",
"unsafe":
return true
}
return strings.HasPrefix(pkg, "runtime/internal/") && !strings.HasSuffix(pkg, "_test")
return (strings.HasPrefix(pkg, "runtime/internal/") || strings.HasPrefix(pkg, "internal/runtime/")) &&
!strings.HasSuffix(pkg, "_test")
}
// Estimate the max size needed to hold any new trampolines created for this function. This
@@ -410,6 +424,9 @@ func (st *relocSymState) relocsym(s loader.Sym, P []byte) {
// FIXME: It should be forbidden to have R_ADDR from a
// symbol which isn't in .data. However, as .text has the
// same address once loaded, this is possible.
// TODO: .text (including rodata) to .data relocation
// doesn't work correctly, so we should really disallow it.
// See also aixStaticDataBase in symtab.go and in runtime.
if ldr.SymSect(s).Seg == &Segdata {
Xcoffadddynrel(target, ldr, syms, s, r, ri)
}

View File

@@ -520,7 +520,7 @@ func (d *dwctxt) defgotype(gotype loader.Sym) loader.Sym {
d.linkctxt.Errorf(gotype, "dwarf: type name doesn't start with \"type:\"")
return d.mustFind("<unspecified>")
}
name := sn[5:] // could also decode from Type.string
name := sn[len("type:"):] // could also decode from Type.string
sdie := d.find(name)
if sdie != 0 {
@@ -534,7 +534,7 @@ func (d *dwctxt) defgotype(gotype loader.Sym) loader.Sym {
func (d *dwctxt) newtype(gotype loader.Sym) *dwarf.DWDie {
sn := d.ldr.SymName(gotype)
name := sn[5:] // could also decode from Type.string
name := sn[len("type:"):] // could also decode from Type.string
tdata := d.ldr.Data(gotype)
if len(tdata) == 0 {
d.linkctxt.Errorf(gotype, "missing type")

View File

@@ -707,6 +707,17 @@ func (ctxt *Link) symtab(pcln *pclntab) []sym.SymKind {
// except go:buildid which is generated late and not used by the program.
addRef("go:buildid")
}
if ctxt.IsAIX() {
// On AIX, an R_ADDR relocation from an RODATA symbol to a DATA symbol
// does not work. See data.go:relocsym, case R_ADDR.
// Here we record the unrelocated address in aixStaticDataBase (it is
// unrelocated as it is in RODATA) so we can compute the delta at
// run time.
sb := ldr.CreateSymForUpdate("runtime.aixStaticDataBase", 0)
sb.SetSize(0)
sb.AddAddr(ctxt.Arch, ldr.Lookup("runtime.data", 0))
sb.SetType(sym.SRODATA)
}
// text section information
slice(textsectionmapSym, uint64(nsections))

View File

@@ -2338,6 +2338,45 @@ var blockedLinknames = map[string][]string{
"runtime.newcoro": {"iter"},
// fips info
"go:fipsinfo": {"crypto/internal/fips140/check"},
// New internal linknames in Go 1.24
// Pushed from runtime
"crypto/internal/fips140.fatal": {"crypto/internal/fips140"},
"crypto/internal/fips140.getIndicator": {"crypto/internal/fips140"},
"crypto/internal/fips140.setIndicator": {"crypto/internal/fips140"},
"crypto/internal/sysrand.fatal": {"crypto/internal/sysrand"},
"crypto/rand.fatal": {"crypto/rand"},
"internal/runtime/maps.errNilAssign": {"internal/runtime/maps"},
"internal/runtime/maps.fatal": {"internal/runtime/maps"},
"internal/runtime/maps.mapKeyError": {"internal/runtime/maps"},
"internal/runtime/maps.newarray": {"internal/runtime/maps"},
"internal/runtime/maps.newobject": {"internal/runtime/maps"},
"internal/runtime/maps.typedmemclr": {"internal/runtime/maps"},
"internal/runtime/maps.typedmemmove": {"internal/runtime/maps"},
"internal/sync.fatal": {"internal/sync"},
"internal/sync.runtime_canSpin": {"internal/sync"},
"internal/sync.runtime_doSpin": {"internal/sync"},
"internal/sync.runtime_nanotime": {"internal/sync"},
"internal/sync.runtime_Semrelease": {"internal/sync"},
"internal/sync.runtime_SemacquireMutex": {"internal/sync"},
"internal/sync.throw": {"internal/sync"},
"internal/synctest.Run": {"internal/synctest"},
"internal/synctest.Wait": {"internal/synctest"},
"internal/synctest.acquire": {"internal/synctest"},
"internal/synctest.release": {"internal/synctest"},
"internal/synctest.inBubble": {"internal/synctest"},
"runtime.getStaticuint64s": {"reflect"},
"sync.runtime_SemacquireWaitGroup": {"sync"},
"time.runtimeNow": {"time"},
"time.runtimeNano": {"time"},
// Pushed to runtime from internal/runtime/maps
// (other map functions are already linknamed in Go 1.23)
"runtime.mapaccess1": {"runtime"},
"runtime.mapaccess1_fast32": {"runtime"},
"runtime.mapaccess1_fast64": {"runtime"},
"runtime.mapaccess1_faststr": {"runtime"},
"runtime.mapdelete_fast32": {"runtime"},
"runtime.mapdelete_fast64": {"runtime"},
"runtime.mapdelete_faststr": {"runtime"},
}
// check if a linkname reference to symbol s from pkg is allowed

View File

@@ -1518,6 +1518,8 @@ func TestCheckLinkname(t *testing.T) {
{"coro_asm", false},
// pull-only linkname is not ok
{"coro2.go", false},
// pull linkname of a builtin symbol is not ok
{"builtin.go", false},
// legacy bad linkname is ok, for now
{"fastrand.go", true},
{"badlinkname.go", true},

View File

@@ -0,0 +1,17 @@
// Copyright 2024 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.
// Linkname builtin symbols (that is not already linknamed,
// e.g. mapaccess1) is not allowed.
package main
import "unsafe"
func main() {
mapaccess1(nil, nil, nil)
}
//go:linkname mapaccess1 runtime.mapaccess1
func mapaccess1(t, m, k unsafe.Pointer) unsafe.Pointer

View File

@@ -40,6 +40,7 @@ import (
"strconv"
"strings"
"cmd/internal/disasm"
"cmd/internal/objfile"
"cmd/internal/telemetry/counter"
)
@@ -82,7 +83,7 @@ func main() {
}
defer f.Close()
dis, err := f.Disasm()
dis, err := disasm.DisasmForFile(f)
if err != nil {
log.Fatalf("disassemble %s: %v", flag.Arg(0), err)
}

View File

@@ -24,6 +24,7 @@ import (
"sync"
"time"
"cmd/internal/disasm"
"cmd/internal/objfile"
"cmd/internal/telemetry/counter"
@@ -162,7 +163,7 @@ func adjustURL(source string, duration, timeout time.Duration) (string, time.Dur
// (instead of invoking GNU binutils).
type objTool struct {
mu sync.Mutex
disasmCache map[string]*objfile.Disasm
disasmCache map[string]*disasm.Disasm
}
func (*objTool) Open(name string, start, limit, offset uint64, relocationSymbol string) (driver.ObjFile, error) {
@@ -202,11 +203,11 @@ func (t *objTool) Disasm(file string, start, end uint64, intelSyntax bool) ([]dr
return asm, nil
}
func (t *objTool) cachedDisasm(file string) (*objfile.Disasm, error) {
func (t *objTool) cachedDisasm(file string) (*disasm.Disasm, error) {
t.mu.Lock()
defer t.mu.Unlock()
if t.disasmCache == nil {
t.disasmCache = make(map[string]*objfile.Disasm)
t.disasmCache = make(map[string]*disasm.Disasm)
}
d := t.disasmCache[file]
if d != nil {
@@ -216,7 +217,7 @@ func (t *objTool) cachedDisasm(file string) (*objfile.Disasm, error) {
if err != nil {
return nil, err
}
d, err = f.Disasm()
d, err = disasm.DisasmForFile(f)
f.Close()
if err != nil {
return nil, err

View File

@@ -108,7 +108,7 @@ func TestVet(t *testing.T) {
// is a no-op for files whose version >= go1.22, so we use a
// go.mod file in the rangeloop directory to "downgrade".
//
// TOOD(adonovan): delete when go1.21 goes away.
// TODO(adonovan): delete when go1.21 goes away.
t.Run("loopclosure", func(t *testing.T) {
cmd := testenv.Command(t, testenv.GoToolPath(t), "vet", "-vettool="+vetPath(t), ".")
cmd.Env = append(os.Environ(), "GOWORK=off")

View File

@@ -10,23 +10,25 @@
// calls to servers should accept a Context. The chain of function
// calls between them must propagate the Context, optionally replacing
// it with a derived Context created using [WithCancel], [WithDeadline],
// [WithTimeout], or [WithValue]. When a Context is canceled, all
// Contexts derived from it are also canceled.
// [WithTimeout], or [WithValue].
//
// A Context may be canceled to indicate that work done on its behalf should stop.
// A Context with a deadline is canceled after the deadline passes.
// When a Context is canceled, all Contexts derived from it are also canceled.
//
// The [WithCancel], [WithDeadline], and [WithTimeout] functions take a
// Context (the parent) and return a derived Context (the child) and a
// [CancelFunc]. Calling the CancelFunc cancels the child and its
// [CancelFunc]. Calling the CancelFunc directly cancels the child and its
// children, removes the parent's reference to the child, and stops
// any associated timers. Failing to call the CancelFunc leaks the
// child and its children until the parent is canceled or the timer
// fires. The go vet tool checks that CancelFuncs are used on all
// control-flow paths.
// child and its children until the parent is canceled. The go vet tool
// checks that CancelFuncs are used on all control-flow paths.
//
// The [WithCancelCause] function returns a [CancelCauseFunc], which
// takes an error and records it as the cancellation cause. Calling
// [Cause] on the canceled context or any of its children retrieves
// the cause. If no cause is specified, Cause(ctx) returns the same
// value as ctx.Err().
// The [WithCancelCause], [WithDeadlineCause], and [WithTimeoutCause] functions
// return a [CancelCauseFunc], which takes an error and records it as
// the cancellation cause. Calling [Cause] on the canceled context
// or any of its children retrieves the cause. If no cause is specified,
// Cause(ctx) returns the same value as ctx.Err().
//
// Programs that use Contexts should follow these rules to keep interfaces
// consistent across packages and enable static analysis tools to check context
@@ -107,8 +109,8 @@ type Context interface {
// If Done is not yet closed, Err returns nil.
// If Done is closed, Err returns a non-nil error explaining why:
// Canceled if the context was canceled
// or DeadlineExceeded if the context's deadline passed.
// DeadlineExceeded if the context's deadline passed,
// or Canceled if the context was canceled for some other reason.
// After Err returns a non-nil error, successive calls to Err return the same error.
Err() error
@@ -160,11 +162,12 @@ type Context interface {
Value(key any) any
}
// Canceled is the error returned by [Context.Err] when the context is canceled.
// Canceled is the error returned by [Context.Err] when the context is canceled
// for some reason other than its deadline passing.
var Canceled = errors.New("context canceled")
// DeadlineExceeded is the error returned by [Context.Err] when the context's
// deadline passes.
// DeadlineExceeded is the error returned by [Context.Err] when the context is canceled
// due to its deadline passing.
var DeadlineExceeded error = deadlineExceededError{}
type deadlineExceededError struct{}
@@ -296,9 +299,8 @@ func Cause(c Context) error {
return c.Err()
}
// AfterFunc arranges to call f in its own goroutine after ctx is done
// (canceled or timed out).
// If ctx is already done, AfterFunc calls f immediately in its own goroutine.
// AfterFunc arranges to call f in its own goroutine after ctx is canceled.
// If ctx is already canceled, AfterFunc calls f immediately in its own goroutine.
//
// Multiple calls to AfterFunc on a context operate independently;
// one does not replace another.
@@ -306,7 +308,7 @@ func Cause(c Context) error {
// Calling the returned stop function stops the association of ctx with f.
// It returns true if the call stopped f from being run.
// If stop returns false,
// either the context is done and f has been started in its own goroutine;
// either the context is canceled and f has been started in its own goroutine;
// or f was already stopped.
// The stop function does not wait for f to complete before returning.
// If the caller needs to know whether f is completed,

View File

@@ -146,8 +146,8 @@ func ExampleAfterFunc_cond() {
defer stopf()
// Since the wakeups are using Broadcast instead of Signal, this call to
// Wait may unblock due to some other goroutine's context becoming done,
// so to be sure that ctx is actually done we need to check it in a loop.
// Wait may unblock due to some other goroutine's context being canceled,
// so to be sure that ctx is actually canceled we need to check it in a loop.
for !conditionMet() {
cond.Wait()
if ctx.Err() != nil {

View File

@@ -15,6 +15,7 @@ import (
"bytes"
"crypto/internal/fips140/aes"
"crypto/internal/fips140/alias"
"crypto/internal/fips140only"
"crypto/subtle"
)
@@ -53,6 +54,9 @@ func NewCBCEncrypter(b Block, iv []byte) BlockMode {
if b, ok := b.(*aes.Block); ok {
return aes.NewCBCEncrypter(b, [16]byte(iv))
}
if fips140only.Enabled {
panic("crypto/cipher: use of CBC with non-AES ciphers is not allowed in FIPS 140-only mode")
}
if cbc, ok := b.(cbcEncAble); ok {
return cbc.NewCBCEncrypter(iv)
}
@@ -129,6 +133,9 @@ func NewCBCDecrypter(b Block, iv []byte) BlockMode {
if b, ok := b.(*aes.Block); ok {
return aes.NewCBCDecrypter(b, [16]byte(iv))
}
if fips140only.Enabled {
panic("crypto/cipher: use of CBC with non-AES ciphers is not allowed in FIPS 140-only mode")
}
if cbc, ok := b.(cbcDecAble); ok {
return cbc.NewCBCDecrypter(iv)
}

View File

@@ -16,6 +16,7 @@ import (
"bytes"
"crypto/internal/fips140/aes"
"crypto/internal/fips140/alias"
"crypto/internal/fips140only"
"crypto/subtle"
)
@@ -41,6 +42,9 @@ func NewCTR(block Block, iv []byte) Stream {
if block, ok := block.(*aes.Block); ok {
return aesCtrWrapper{aes.NewCTR(block, iv)}
}
if fips140only.Enabled {
panic("crypto/cipher: use of CTR with non-AES ciphers is not allowed in FIPS 140-only mode")
}
if ctr, ok := block.(ctrAble); ok {
return ctr.NewCTR(iv)
}

View File

@@ -8,6 +8,7 @@ import (
"bytes"
"crypto/internal/boring"
"crypto/internal/fips140/ecdh"
"crypto/internal/fips140only"
"errors"
"io"
)
@@ -43,6 +44,10 @@ func (c *nistCurve) GenerateKey(rand io.Reader) (*PrivateKey, error) {
return k, nil
}
if fips140only.Enabled && !fips140only.ApprovedRandomReader(rand) {
return nil, errors.New("crypto/ecdh: only crypto/rand.Reader is allowed in FIPS 140-only mode")
}
privateKey, err := c.generate(rand)
if err != nil {
return nil, err

View File

@@ -3,7 +3,7 @@
// license that can be found in the LICENSE file.
// Package ecdsa implements the Elliptic Curve Digital Signature Algorithm, as
// defined in FIPS 186-5 and SEC 1, Version 2.0.
// defined in [FIPS 186-5].
//
// Signatures generated by this package are not deterministic, but entropy is
// mixed with the private key and the message, achieving the same level of
@@ -12,6 +12,8 @@
// Operations involving private keys are implemented using constant-time
// algorithms, as long as an [elliptic.Curve] returned by [elliptic.P224],
// [elliptic.P256], [elliptic.P384], or [elliptic.P521] is used.
//
// [FIPS 186-5]: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-5.pdf
package ecdsa
import (
@@ -21,6 +23,7 @@ import (
"crypto/internal/boring"
"crypto/internal/boring/bbig"
"crypto/internal/fips140/ecdsa"
"crypto/internal/fips140only"
"crypto/internal/randutil"
"crypto/sha512"
"crypto/subtle"
@@ -182,6 +185,9 @@ func GenerateKey(c elliptic.Curve, rand io.Reader) (*PrivateKey, error) {
}
func generateFIPS[P ecdsa.Point[P]](curve elliptic.Curve, c *ecdsa.Curve[P], rand io.Reader) (*PrivateKey, error) {
if fips140only.Enabled && !fips140only.ApprovedRandomReader(rand) {
return nil, errors.New("crypto/ecdsa: only crypto/rand.Reader is allowed in FIPS 140-only mode")
}
privateKey, err := ecdsa.GenerateKey(c, rand)
if err != nil {
return nil, err
@@ -228,6 +234,9 @@ func SignASN1(rand io.Reader, priv *PrivateKey, hash []byte) ([]byte, error) {
}
func signFIPS[P ecdsa.Point[P]](c *ecdsa.Curve[P], priv *PrivateKey, rand io.Reader, hash []byte) ([]byte, error) {
if fips140only.Enabled && !fips140only.ApprovedRandomReader(rand) {
return nil, errors.New("crypto/ecdsa: only crypto/rand.Reader is allowed in FIPS 140-only mode")
}
// privateKeyToFIPS is very slow in FIPS mode because it performs a
// Sign+Verify cycle per FIPS 140-3 IG 10.3.A. We should find a way to cache
// it or attach it to the PrivateKey.

View File

@@ -26,7 +26,7 @@ func Enabled() bool {
if currentlyEnabled != fips140.Enabled {
panic("crypto/fips140: GODEBUG setting changed after program start")
}
if fips140.Enabled && !check.Enabled() {
if fips140.Enabled && !check.Verified {
panic("crypto/fips140: FIPS 140-3 mode enabled, but integrity check didn't pass")
}
return fips140.Enabled

View File

@@ -16,6 +16,7 @@ import "C"
import (
"crypto/internal/boring/sig"
_ "crypto/internal/boring/syso"
"crypto/internal/fips140"
"internal/stringslite"
"math/bits"
"unsafe"
@@ -31,6 +32,12 @@ func init() {
sig.BoringCrypto()
}
func init() {
if fips140.Enabled {
panic("boringcrypto: cannot use GODEBUG=fips140 with GOEXPERIMENT=boringcrypto")
}
}
// Unreachable marks code that should be unreachable
// when BoringCrypto is in use. It panics.
func Unreachable() {

View File

@@ -32,6 +32,12 @@ func SkipTestAllocations(t *testing.T) {
t.Skip("skipping allocations test on plan9")
}
// s390x deviates from other assembly implementations and is very hard to
// test due to the lack of LUCI builders. See #67307.
if runtime.GOARCH == "s390x" {
t.Skip("skipping allocations test on s390x")
}
// Some APIs rely on inliner and devirtualization to allocate on the stack.
testenv.SkipIfOptimizationOff(t)
}

View File

@@ -94,6 +94,8 @@ func newBlockExpanded(c *blockExpanded, key []byte) {
func (c *Block) BlockSize() int { return BlockSize }
func (c *Block) Encrypt(dst, src []byte) {
// AES-ECB is not approved in FIPS 140-3 mode.
fips140.RecordNonApproved()
if len(src) < BlockSize {
panic("crypto/aes: input not full block")
}
@@ -103,11 +105,12 @@ func (c *Block) Encrypt(dst, src []byte) {
if alias.InexactOverlap(dst[:BlockSize], src[:BlockSize]) {
panic("crypto/aes: invalid buffer overlap")
}
fips140.RecordApproved()
encryptBlock(c, dst, src)
}
func (c *Block) Decrypt(dst, src []byte) {
// AES-ECB is not approved in FIPS 140-3 mode.
fips140.RecordNonApproved()
if len(src) < BlockSize {
panic("crypto/aes: input not full block")
}
@@ -117,6 +120,12 @@ func (c *Block) Decrypt(dst, src []byte) {
if alias.InexactOverlap(dst[:BlockSize], src[:BlockSize]) {
panic("crypto/aes: invalid buffer overlap")
}
fips140.RecordApproved()
decryptBlock(c, dst, src)
}
// EncryptBlockInternal applies the AES encryption function to one block.
//
// It is an internal function meant only for the gcm package.
func EncryptBlockInternal(c *Block, dst, src []byte) {
encryptBlock(c, dst, src)
}

View File

@@ -50,7 +50,7 @@ func cryptBlocksEncGeneric(b *Block, civ *[BlockSize]byte, dst, src []byte) {
for len(src) > 0 {
// Write the xor to dst, then encrypt in place.
subtle.XORBytes(dst[:BlockSize], src[:BlockSize], iv)
b.Encrypt(dst[:BlockSize], dst[:BlockSize])
encryptBlock(b, dst[:BlockSize], dst[:BlockSize])
// Move to the next block with this block as the next iv.
iv = dst[:BlockSize]
@@ -111,7 +111,7 @@ func cryptBlocksDecGeneric(b *Block, civ *[BlockSize]byte, dst, src []byte) {
copy(civ[:], src[start:end])
for start >= 0 {
b.Decrypt(dst[start:end], src[start:end])
decryptBlock(b, dst[start:end], src[start:end])
if start > 0 {
subtle.XORBytes(dst[start:end], dst[start:end], src[prev:start])

View File

@@ -132,7 +132,7 @@ func ctrBlocks(b *Block, dst, src []byte, ivlo, ivhi uint64) {
byteorder.BEPutUint64(buf[i:], ivhi)
byteorder.BEPutUint64(buf[i+8:], ivlo)
ivlo, ivhi = add128(ivlo, ivhi, 1)
b.Encrypt(buf[i:], buf[i:])
encryptBlock(b, buf[i:], buf[i:])
}
// XOR into buf first, in case src and dst overlap (see above).
subtle.XORBytes(buf, src, buf)

View File

@@ -28,7 +28,7 @@ func NewCMAC(b *aes.Block) *CMAC {
}
func (c *CMAC) deriveSubkeys() {
c.b.Encrypt(c.k1[:], c.k1[:])
aes.EncryptBlockInternal(&c.b, c.k1[:], c.k1[:])
msb := shiftLeft(&c.k1)
c.k1[len(c.k1)-1] ^= msb * 0b10000111
@@ -45,7 +45,7 @@ func (c *CMAC) MAC(m []byte) [aes.BlockSize]byte {
// Special-cased as a single empty partial final block.
x = c.k2
x[len(m)] ^= 0b10000000
c.b.Encrypt(x[:], x[:])
aes.EncryptBlockInternal(&c.b, x[:], x[:])
return x
}
for len(m) >= aes.BlockSize {
@@ -54,7 +54,7 @@ func (c *CMAC) MAC(m []byte) [aes.BlockSize]byte {
// Final complete block.
subtle.XORBytes(x[:], c.k1[:], x[:])
}
c.b.Encrypt(x[:], x[:])
aes.EncryptBlockInternal(&c.b, x[:], x[:])
m = m[aes.BlockSize:]
}
if len(m) > 0 {
@@ -62,7 +62,7 @@ func (c *CMAC) MAC(m []byte) [aes.BlockSize]byte {
subtle.XORBytes(x[:], m, x[:])
subtle.XORBytes(x[:], c.k2[:], x[:])
x[len(m)] ^= 0b10000000
c.b.Encrypt(x[:], x[:])
aes.EncryptBlockInternal(&c.b, x[:], x[:])
}
return x
}

View File

@@ -81,7 +81,7 @@ func seal(out []byte, g *GCM, nonce, plaintext, data []byte) {
gcmAesFinish(&g.productTable, &tagMask, &counter, uint64(len(nonce)), uint64(0))
}
g.cipher.Encrypt(tagMask[:], counter[:])
aes.EncryptBlockInternal(&g.cipher, tagMask[:], counter[:])
var tagOut [gcmTagSize]byte
gcmAesData(&g.productTable, data, &tagOut)
@@ -114,7 +114,7 @@ func open(out []byte, g *GCM, nonce, ciphertext, data []byte) error {
gcmAesFinish(&g.productTable, &tagMask, &counter, uint64(len(nonce)), uint64(0))
}
g.cipher.Encrypt(tagMask[:], counter[:])
aes.EncryptBlockInternal(&g.cipher, tagMask[:], counter[:])
var expectedTag [gcmTagSize]byte
gcmAesData(&g.productTable, data, &expectedTag)

View File

@@ -12,7 +12,7 @@ import (
func sealGeneric(out []byte, g *GCM, nonce, plaintext, additionalData []byte) {
var H, counter, tagMask [gcmBlockSize]byte
g.cipher.Encrypt(H[:], H[:])
aes.EncryptBlockInternal(&g.cipher, H[:], H[:])
deriveCounterGeneric(&H, &counter, nonce)
gcmCounterCryptGeneric(&g.cipher, tagMask[:], tagMask[:], &counter)
@@ -25,7 +25,7 @@ func sealGeneric(out []byte, g *GCM, nonce, plaintext, additionalData []byte) {
func openGeneric(out []byte, g *GCM, nonce, ciphertext, additionalData []byte) error {
var H, counter, tagMask [gcmBlockSize]byte
g.cipher.Encrypt(H[:], H[:])
aes.EncryptBlockInternal(&g.cipher, H[:], H[:])
deriveCounterGeneric(&H, &counter, nonce)
gcmCounterCryptGeneric(&g.cipher, tagMask[:], tagMask[:], &counter)
@@ -70,7 +70,7 @@ func gcmCounterCryptGeneric(b *aes.Block, out, src []byte, counter *[gcmBlockSiz
var mask [gcmBlockSize]byte
for len(src) >= gcmBlockSize {
b.Encrypt(mask[:], counter[:])
aes.EncryptBlockInternal(b, mask[:], counter[:])
gcmInc32(counter)
subtle.XORBytes(out, src, mask[:])
@@ -79,7 +79,7 @@ func gcmCounterCryptGeneric(b *aes.Block, out, src []byte, counter *[gcmBlockSiz
}
if len(src) > 0 {
b.Encrypt(mask[:], counter[:])
aes.EncryptBlockInternal(b, mask[:], counter[:])
gcmInc32(counter)
subtle.XORBytes(out, src, mask[:])
}

View File

@@ -51,7 +51,7 @@ func initGCM(g *GCM) {
}
hle := make([]byte, gcmBlockSize)
g.cipher.Encrypt(hle, hle)
aes.EncryptBlockInternal(&g.cipher, hle, hle)
// Reverse the bytes in each 8 byte chunk
// Load little endian, store big endian
@@ -133,7 +133,7 @@ func seal(out []byte, g *GCM, nonce, plaintext, data []byte) {
var counter, tagMask [gcmBlockSize]byte
deriveCounter(&counter, nonce, &g.productTable)
g.cipher.Encrypt(tagMask[:], counter[:])
aes.EncryptBlockInternal(&g.cipher, tagMask[:], counter[:])
gcmInc32(&counter)
counterCrypt(&g.cipher, out, plaintext, &counter)
@@ -151,7 +151,7 @@ func open(out []byte, g *GCM, nonce, ciphertext, data []byte) error {
var counter, tagMask [gcmBlockSize]byte
deriveCounter(&counter, nonce, &g.productTable)
g.cipher.Encrypt(tagMask[:], counter[:])
aes.EncryptBlockInternal(&g.cipher, tagMask[:], counter[:])
gcmInc32(&counter)
var expectedTag [gcmTagSize]byte

View File

@@ -55,7 +55,7 @@ func initGCM(g *GCM) {
return
}
// Note that hashKey is also used in the KMA codepath to hash large nonces.
g.cipher.Encrypt(g.hashKey[:], g.hashKey[:])
aes.EncryptBlockInternal(&g.cipher, g.hashKey[:], g.hashKey[:])
}
// ghashAsm uses the GHASH algorithm to hash data with the given key. The initial
@@ -115,7 +115,7 @@ func counterCrypt(g *GCM, dst, src []byte, cnt *[gcmBlockSize]byte) {
}
if len(src) > 0 {
var x [16]byte
g.cipher.Encrypt(x[:], cnt[:])
aes.EncryptBlockInternal(&g.cipher, x[:], cnt[:])
for i := range src {
dst[i] = src[i] ^ x[i]
}

View File

@@ -4,6 +4,6 @@
//go:build asan
package check
package fips140
const asanEnabled = true

View File

@@ -134,6 +134,13 @@ func (x *Nat) set(y *Nat) *Nat {
return x
}
// Bits returns x as a little-endian slice of uint. The length of the slice
// matches the announced length of x. The result and x share the same underlying
// array.
func (x *Nat) Bits() []uint {
return x.limbs
}
// Bytes returns x as a zero-extended big-endian byte slice. The size of the
// slice will match the size of m.
//
@@ -1058,6 +1065,34 @@ func (out *Nat) ExpShortVarTime(x *Nat, e uint, m *Modulus) *Nat {
//
//go:norace
func (x *Nat) InverseVarTime(a *Nat, m *Modulus) (*Nat, bool) {
u, A, err := extendedGCD(a, m.nat)
if err != nil {
return x, false
}
if u.IsOne() == no {
return x, false
}
return x.set(A), true
}
// GCDVarTime calculates x = GCD(a, b) where at least one of a or b is odd, and
// both are non-zero. If GCDVarTime returns an error, x is not modified.
//
// The output will be resized to the size of the larger of a and b.
func (x *Nat) GCDVarTime(a, b *Nat) (*Nat, error) {
u, _, err := extendedGCD(a, b)
if err != nil {
return nil, err
}
return x.set(u), nil
}
// extendedGCD computes u and A such that a = GCD(a, m) and u = A*a - B*m.
//
// u will have the size of the larger of a and m, and A will have the size of m.
//
// It is an error if either a or m is zero, or if they are both even.
func extendedGCD(a, m *Nat) (u, A *Nat, err error) {
// This is the extended binary GCD algorithm described in the Handbook of
// Applied Cryptography, Algorithm 14.61, adapted by BoringSSL to bound
// coefficients and avoid negative numbers. For more details and proof of
@@ -1068,7 +1103,7 @@ func (x *Nat) InverseVarTime(a *Nat, m *Modulus) (*Nat, bool) {
// 1. Negate [B] and [C] so they are positive. The invariant now involves a
// subtraction.
// 2. If step 2 (both [x] and [y] are even) runs, abort immediately. This
// algorithm only cares about [x] and [y] relatively prime.
// case needs to be handled by the caller.
// 3. Subtract copies of [x] and [y] as needed in step 6 (both [u] and [v]
// are odd) so coefficients stay in bounds.
// 4. Replace the [u >= v] check with [u > v]. This changes the end
@@ -1082,21 +1117,21 @@ func (x *Nat) InverseVarTime(a *Nat, m *Modulus) (*Nat, bool) {
//
// Note this algorithm does not handle either input being zero.
if a.IsZero() == yes {
return x, false
if a.IsZero() == yes || m.IsZero() == yes {
return nil, nil, errors.New("extendedGCD: a or m is zero")
}
if a.IsOdd() == no && !m.odd {
// a and m are not coprime, as they are both even.
return x, false
if a.IsOdd() == no && m.IsOdd() == no {
return nil, nil, errors.New("extendedGCD: both a and m are even")
}
u := NewNat().set(a).ExpandFor(m)
v := m.Nat()
size := max(len(a.limbs), len(m.limbs))
u = NewNat().set(a).expand(size)
v := NewNat().set(m).expand(size)
A := NewNat().reset(len(m.nat.limbs))
A = NewNat().reset(len(m.limbs))
A.limbs[0] = 1
B := NewNat().reset(len(a.limbs))
C := NewNat().reset(len(m.nat.limbs))
C := NewNat().reset(len(m.limbs))
D := NewNat().reset(len(a.limbs))
D.limbs[0] = 1
@@ -1119,11 +1154,11 @@ func (x *Nat) InverseVarTime(a *Nat, m *Modulus) (*Nat, bool) {
if u.IsOdd() == yes && v.IsOdd() == yes {
if v.cmpGeq(u) == no {
u.sub(v)
A.Add(C, m)
A.Add(C, &Modulus{nat: m})
B.Add(D, &Modulus{nat: a})
} else {
v.sub(u)
C.Add(A, m)
C.Add(A, &Modulus{nat: m})
D.Add(B, &Modulus{nat: a})
}
}
@@ -1137,7 +1172,7 @@ func (x *Nat) InverseVarTime(a *Nat, m *Modulus) (*Nat, bool) {
if u.IsOdd() == no {
rshift1(u, 0)
if A.IsOdd() == yes || B.IsOdd() == yes {
rshift1(A, A.add(m.nat))
rshift1(A, A.add(m))
rshift1(B, B.add(a))
} else {
rshift1(A, 0)
@@ -1146,7 +1181,7 @@ func (x *Nat) InverseVarTime(a *Nat, m *Modulus) (*Nat, bool) {
} else { // v.IsOdd() == no
rshift1(v, 0)
if C.IsOdd() == yes || D.IsOdd() == yes {
rshift1(C, C.add(m.nat))
rshift1(C, C.add(m))
rshift1(D, D.add(a))
} else {
rshift1(C, 0)
@@ -1155,10 +1190,7 @@ func (x *Nat) InverseVarTime(a *Nat, m *Modulus) (*Nat, bool) {
}
if v.IsZero() == yes {
if u.IsOne() == no {
return x, false
}
return x.set(A), true
return u, A, nil
}
}
}
@@ -1177,3 +1209,20 @@ func rshift1(a *Nat, carry uint) {
}
}
}
// DivShortVarTime calculates x = x / y and returns the remainder.
//
// It panics if y is zero.
//
//go:norace
func (x *Nat) DivShortVarTime(y uint) uint {
if y == 0 {
panic("bigmod: division by zero")
}
var r uint
for i := len(x.limbs) - 1; i >= 0; i-- {
x.limbs[i], r = bits.Div(r, x.limbs[i], y)
}
return r
}

View File

@@ -0,0 +1,10 @@
// Copyright 2024 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.
// Keep in sync with notboring.go and crypto/internal/boring/boring.go.
//go:build boringcrypto && linux && (amd64 || arm64) && !android && !msan && cgo
package fips140
const boringEnabled = true

View File

@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package check implements the FIPS-140 load-time code+data verification.
// Package check implements the FIPS 140 load-time code+data verification.
// Every FIPS package providing cryptographic functionality except hmac and sha256
// must import crypto/internal/fips140/check, so that the verification happens
// before initialization of package global variables.
@@ -13,37 +13,18 @@
package check
import (
"crypto/internal/fips140"
"crypto/internal/fips140/hmac"
"crypto/internal/fips140/sha256"
"crypto/internal/fips140deps/byteorder"
"crypto/internal/fips140deps/godebug"
"io"
"runtime"
"unsafe"
)
// Enabled reports whether verification was enabled.
// If Enabled returns true, then verification succeeded,
// because if it failed the binary would have panicked at init time.
func Enabled() bool {
return enabled
}
var enabled bool // set when verification is enabled
var Verified bool // set when verification succeeds, for testing
// Supported reports whether the current GOOS/GOARCH is Supported at all.
func Supported() bool {
// See cmd/internal/obj/fips.go's EnableFIPS for commentary.
switch {
case runtime.GOARCH == "wasm",
runtime.GOOS == "windows" && runtime.GOARCH == "386",
runtime.GOOS == "windows" && runtime.GOARCH == "arm",
runtime.GOOS == "aix":
return false
}
return true
}
// Verified is set when verification succeeded. It can be expected to always be
// true when [fips140.Enabled] is true, or init would have panicked.
var Verified bool
// Linkinfo holds the go:fipsinfo symbol prepared by the linker.
// See cmd/link/internal/ld/fips.go for details.
@@ -71,32 +52,12 @@ const fipsMagic = " Go fipsinfo \xff\x00"
var zeroSum [32]byte
func init() {
v := godebug.Value("#fips140")
enabled = v != "" && v != "off"
if !enabled {
if !fips140.Enabled {
return
}
if asanEnabled {
// ASAN disapproves of reading swaths of global memory below.
// One option would be to expose runtime.asanunpoison through
// crypto/internal/fips140deps and then call it to unpoison the range
// before reading it, but it is unclear whether that would then cause
// false negatives. For now, FIPS+ASAN doesn't need to work.
// If this is made to work, also re-enable the test in check_test.go
// and in cmd/dist/test.go.
panic("fips140: cannot verify in asan mode")
}
switch v {
case "on", "only", "debug":
// ok
default:
panic("fips140: unknown GODEBUG setting fips140=" + v)
}
if !Supported() {
panic("fips140: unavailable on " + runtime.GOOS + "-" + runtime.GOARCH)
if err := fips140.Supported(); err != nil {
panic("fips140: " + err.Error())
}
if Linkinfo.Magic[0] != 0xff || string(Linkinfo.Magic[1:]) != fipsMagic || Linkinfo.Sum == zeroSum {
@@ -132,7 +93,14 @@ func init() {
panic("fips140: verification mismatch")
}
if v == "debug" {
// "The temporary value(s) generated during the integrity test of the
// modules software or firmware shall [05.10] be zeroised from the module
// upon completion of the integrity test"
clear(sum)
clear(nbuf[:])
h.Reset()
if godebug.Value("#fips140") == "debug" {
println("fips140: verified code+data")
}

View File

@@ -7,12 +7,21 @@ package drbg
import (
"crypto/internal/entropy"
"crypto/internal/fips140"
"crypto/internal/randutil"
"crypto/internal/sysrand"
"io"
"sync"
)
var mu sync.Mutex
var drbg *Counter
var drbgs = sync.Pool{
New: func() any {
var c *Counter
entropy.Depleted(func(seed *[48]byte) {
c = NewCounter(seed)
})
return c
},
}
// Read fills b with cryptographically secure random bytes. In FIPS mode, it
// uses an SP 800-90A Rev. 1 Deterministic Random Bit Generator (DRBG).
@@ -31,14 +40,8 @@ func Read(b []byte) {
additionalInput := new([SeedSize]byte)
sysrand.Read(additionalInput[:16])
mu.Lock()
defer mu.Unlock()
if drbg == nil {
entropy.Depleted(func(seed *[48]byte) {
drbg = NewCounter(seed)
})
}
drbg := drbgs.Get().(*Counter)
defer drbgs.Put(drbg)
for len(b) > 0 {
size := min(len(b), maxRequestSize)
@@ -56,3 +59,38 @@ func Read(b []byte) {
b = b[size:]
}
}
// DefaultReader is a sentinel type, embedded in the default
// [crypto/rand.Reader], used to recognize it when passed to
// APIs that accept a rand io.Reader.
type DefaultReader interface{ defaultReader() }
// ReadWithReader uses Reader to fill b with cryptographically secure random
// bytes. It is intended for use in APIs that expose a rand io.Reader.
//
// If Reader is not the default Reader from crypto/rand,
// [randutil.MaybeReadByte] and [fips140.RecordNonApproved] are called.
func ReadWithReader(r io.Reader, b []byte) error {
if _, ok := r.(DefaultReader); ok {
Read(b)
return nil
}
fips140.RecordNonApproved()
randutil.MaybeReadByte(r)
_, err := io.ReadFull(r, b)
return err
}
// ReadWithReaderDeterministic is like ReadWithReader, but it doesn't call
// [randutil.MaybeReadByte] on non-default Readers.
func ReadWithReaderDeterministic(r io.Reader, b []byte) error {
if _, ok := r.(DefaultReader); ok {
Read(b)
return nil
}
fips140.RecordNonApproved()
_, err := io.ReadFull(r, b)
return err
}

View File

@@ -0,0 +1,27 @@
// Copyright 2025 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 drbg
import (
"crypto/internal/fips140"
"testing"
)
func BenchmarkDBRG(b *testing.B) {
old := fips140.Enabled
defer func() {
fips140.Enabled = old
}()
fips140.Enabled = true
const N = 64
b.SetBytes(N)
b.RunParallel(func(pb *testing.PB) {
buf := make([]byte, N)
for pb.Next() {
Read(buf)
}
})
}

View File

@@ -10,7 +10,6 @@ import (
"crypto/internal/fips140/drbg"
"crypto/internal/fips140/nistec"
"crypto/internal/fips140deps/byteorder"
"crypto/internal/randutil"
"errors"
"io"
"math/bits"
@@ -137,8 +136,6 @@ var p521Order = []byte{0x01, 0xff,
}
// GenerateKey generates a new ECDSA private key pair for the specified curve.
//
// In FIPS mode, rand is ignored.
func GenerateKey[P Point[P]](c *Curve[P], rand io.Reader) (*PrivateKey, error) {
fips140.RecordApproved()
// This procedure is equivalent to Key Pair Generation by Testing
@@ -146,18 +143,13 @@ func GenerateKey[P Point[P]](c *Curve[P], rand io.Reader) (*PrivateKey, error) {
for {
key := make([]byte, len(c.N))
if fips140.Enabled {
drbg.Read(key)
} else {
randutil.MaybeReadByte(rand)
if _, err := io.ReadFull(rand, key); err != nil {
return nil, err
}
// In tests, rand will return all zeros and NewPrivateKey will reject
// the zero key as it generates the identity as a public key. This also
// makes this function consistent with crypto/elliptic.GenerateKey.
key[1] ^= 0x42
if err := drbg.ReadWithReader(rand, key); err != nil {
return nil, err
}
// In tests, rand will return all zeros and NewPrivateKey will reject
// the zero key as it generates the identity as a public key. This also
// makes this function consistent with crypto/elliptic.GenerateKey.
key[1] ^= 0x42
// Mask off any excess bits if the size of the underlying field is not a
// whole number of bytes, which is only the case for P-521.

View File

@@ -54,7 +54,8 @@ func testHash() []byte {
func fipsPCT[P Point[P]](c *Curve[P], k *PrivateKey) error {
return fips140.PCT("ECDSA PCT", func() error {
hash := testHash()
sig, err := Sign(c, sha512.New, k, nil, hash)
drbg := newDRBG(sha512.New, k.d, bits2octets(P256(), hash), nil)
sig, err := sign(c, k, drbg, hash)
if err != nil {
return err
}

View File

@@ -10,7 +10,6 @@ import (
"crypto/internal/fips140/bigmod"
"crypto/internal/fips140/drbg"
"crypto/internal/fips140/nistec"
"crypto/internal/randutil"
"errors"
"io"
"sync"
@@ -22,7 +21,7 @@ import (
type PrivateKey struct {
pub PublicKey
d []byte // bigmod.(*Nat).Bytes output (fixed length)
d []byte // bigmod.(*Nat).Bytes output (same length as the curve order)
}
func (priv *PrivateKey) Bytes() []byte {
@@ -187,20 +186,11 @@ func NewPublicKey[P Point[P]](c *Curve[P], Q []byte) (*PublicKey, error) {
}
// GenerateKey generates a new ECDSA private key pair for the specified curve.
//
// In FIPS mode, rand is ignored.
func GenerateKey[P Point[P]](c *Curve[P], rand io.Reader) (*PrivateKey, error) {
fips140.RecordApproved()
k, Q, err := randomPoint(c, func(b []byte) error {
if fips140.Enabled {
drbg.Read(b)
return nil
} else {
randutil.MaybeReadByte(rand)
_, err := io.ReadFull(rand, b)
return err
}
return drbg.ReadWithReader(rand, b)
})
if err != nil {
return nil, err
@@ -272,7 +262,7 @@ func randomPoint[P Point[P]](c *Curve[P], generate func([]byte) error) (k *bigmo
var testingOnlyRejectionSamplingLooped func()
// Signature is an ECDSA signature, where r and s are represented as big-endian
// fixed-length byte slices.
// byte slices of the same length as the curve order.
type Signature struct {
R, S []byte
}
@@ -281,8 +271,6 @@ type Signature struct {
// the hash function H) using the private key, priv. If the hash is longer than
// the bit-length of the private key's curve order, the hash will be truncated
// to that length.
//
// The signature is randomized. If FIPS mode is enabled, rand is ignored.
func Sign[P Point[P], H fips140.Hash](c *Curve[P], h func() H, priv *PrivateKey, rand io.Reader, hash []byte) (*Signature, error) {
if priv.pub.curve != c.curve {
return nil, errors.New("ecdsa: private key does not match curve")
@@ -296,13 +284,8 @@ func Sign[P Point[P], H fips140.Hash](c *Curve[P], h func() H, priv *PrivateKey,
// advantage of closely resembling Deterministic ECDSA.
Z := make([]byte, len(priv.d))
if fips140.Enabled {
drbg.Read(Z)
} else {
randutil.MaybeReadByte(rand)
if _, err := io.ReadFull(rand, Z); err != nil {
return nil, err
}
if err := drbg.ReadWithReader(rand, Z); err != nil {
return nil, err
}
// See https://github.com/cfrg/draft-irtf-cfrg-det-sigs-with-noise/issues/6

View File

@@ -47,15 +47,34 @@ func canUseKDSA(c curveID) (functionCode uint64, blockSize int, ok bool) {
case p384:
return 2, 48, true
case p521:
// Note that the block size doesn't match the field size for P-521.
return 3, 80, true
}
return 0, 0, false // A mismatch
}
func hashToBytes[P Point[P]](c *Curve[P], dst, hash []byte) {
func hashToBytes[P Point[P]](c *Curve[P], hash []byte) []byte {
e := bigmod.NewNat()
hashToNat(c, e, hash)
copy(dst, e.Bytes(c.N))
return e.Bytes(c.N)
}
func appendBlock(p []byte, blocksize int, b []byte) []byte {
if len(b) > blocksize {
panic("ecdsa: internal error: appendBlock input larger than block")
}
padding := blocksize - len(b)
p = append(p, make([]byte, padding)...)
return append(p, b...)
}
func trimBlock(p []byte, size int) ([]byte, error) {
for _, b := range p[:len(p)-size] {
if b != 0 {
return nil, errors.New("ecdsa: internal error: KDSA produced invalid signature")
}
}
return p[len(p)-size:], nil
}
func sign[P Point[P]](c *Curve[P], priv *PrivateKey, drbg *hmacDRBG, hash []byte) (*Signature, error) {
@@ -95,17 +114,27 @@ func sign[P Point[P]](c *Curve[P], priv *PrivateKey, drbg *hmacDRBG, hash []byte
// Copy content into the parameter block. In the sign case,
// we copy hashed message, private key and random number into
// the parameter block.
hashToBytes(c, params[2*blockSize:3*blockSize], hash)
copy(params[3*blockSize+blockSize-len(priv.d):], priv.d)
copy(params[4*blockSize:5*blockSize], k.Bytes(c.N))
// the parameter block. We skip the signature slots.
p := params[:2*blockSize]
p = appendBlock(p, blockSize, hashToBytes(c, hash))
p = appendBlock(p, blockSize, priv.d)
p = appendBlock(p, blockSize, k.Bytes(c.N))
// Convert verify function code into a sign function code by adding 8.
// We also need to set the 'deterministic' bit in the function code, by
// adding 128, in order to stop the instruction using its own random number
// generator in addition to the random number we supply.
switch kdsa(functionCode+136, &params) {
case 0: // success
return &Signature{R: params[:blockSize], S: params[blockSize : 2*blockSize]}, nil
elementSize := (c.N.BitLen() + 7) / 8
r, err := trimBlock(params[:blockSize], elementSize)
if err != nil {
return nil, err
}
s, err := trimBlock(params[blockSize:2*blockSize], elementSize)
if err != nil {
return nil, err
}
return &Signature{R: r, S: s}, nil
case 1: // error
return nil, errors.New("zero parameter")
case 2: // retry
@@ -149,10 +178,12 @@ func verify[P Point[P]](c *Curve[P], pub *PublicKey, hash []byte, sig *Signature
// Copy content into the parameter block. In the verify case,
// we copy signature (r), signature(s), hashed message, public key x component,
// and public key y component into the parameter block.
copy(params[0*blockSize+blockSize-len(r):], r)
copy(params[1*blockSize+blockSize-len(s):], s)
hashToBytes(c, params[2*blockSize:3*blockSize], hash)
copy(params[3*blockSize:5*blockSize], pub.q[1:]) // strip 0x04 prefix
p := params[:0]
p = appendBlock(p, blockSize, r)
p = appendBlock(p, blockSize, s)
p = appendBlock(p, blockSize, hashToBytes(c, hash))
p = appendBlock(p, blockSize, pub.q[1:1+len(pub.q)/2])
p = appendBlock(p, blockSize, pub.q[1+len(pub.q)/2:])
if kdsa(functionCode, &params) != 0 {
return errors.New("invalid signature")
}

View File

@@ -11,7 +11,6 @@ import (
"crypto/internal/fips140/edwards25519"
"crypto/internal/fips140/sha512"
"errors"
"io"
"strconv"
)
@@ -61,24 +60,14 @@ func (pub *PublicKey) Bytes() []byte {
}
// GenerateKey generates a new Ed25519 private key pair.
//
// In FIPS mode, rand is ignored. Otherwise, the output of this function is
// deterministic, and equivalent to reading 32 bytes from rand, and passing them
// to [NewKeyFromSeed].
func GenerateKey(rand io.Reader) (*PrivateKey, error) {
func GenerateKey() (*PrivateKey, error) {
priv := &PrivateKey{}
return generateKey(priv, rand)
return generateKey(priv)
}
func generateKey(priv *PrivateKey, rand io.Reader) (*PrivateKey, error) {
func generateKey(priv *PrivateKey) (*PrivateKey, error) {
fips140.RecordApproved()
if fips140.Enabled {
drbg.Read(priv.seed[:])
} else {
if _, err := io.ReadFull(rand, priv.seed[:]); err != nil {
return nil, err
}
}
drbg.Read(priv.seed[:])
precomputePrivateKey(priv)
if err := fipsPCT(priv); err != nil {
// This clearly can't happen, but FIPS 140-3 requires that we check.

View File

@@ -4,18 +4,64 @@
package fips140
import "crypto/internal/fips140deps/godebug"
import (
"crypto/internal/fips140deps/godebug"
"errors"
"runtime"
)
var Enabled bool
var debug bool
func init() {
switch godebug.Value("#fips140") {
v := godebug.Value("#fips140")
switch v {
case "on", "only":
Enabled = true
case "debug":
Enabled = true
debug = true
case "off", "":
default:
panic("fips140: unknown GODEBUG setting fips140=" + v)
}
}
// Supported returns an error if FIPS 140-3 mode can't be enabled.
func Supported() error {
// Keep this in sync with fipsSupported in cmd/dist/test.go.
// ASAN disapproves of reading swaths of global memory in fips140/check.
// One option would be to expose runtime.asanunpoison through
// crypto/internal/fips140deps and then call it to unpoison the range
// before reading it, but it is unclear whether that would then cause
// false negatives. For now, FIPS+ASAN doesn't need to work.
if asanEnabled {
return errors.New("FIPS 140-3 mode is incompatible with ASAN")
}
// See EnableFIPS in cmd/internal/obj/fips.go for commentary.
switch {
case runtime.GOARCH == "wasm",
runtime.GOOS == "windows" && runtime.GOARCH == "386",
runtime.GOOS == "windows" && runtime.GOARCH == "arm",
runtime.GOOS == "openbsd", // due to -fexecute-only, see #70880
runtime.GOOS == "aix":
return errors.New("FIPS 140-3 mode is not supported on " + runtime.GOOS + "-" + runtime.GOARCH)
}
if boringEnabled {
return errors.New("FIPS 140-3 mode is incompatible with GOEXPERIMENT=boringcrypto")
}
return nil
}
func Name() string {
return "Go Cryptographic Module"
}
func Version() string {
return "v1.0"
}

View File

@@ -40,7 +40,7 @@ func init() {
dk := &DecapsulationKey768{}
kemKeyGen(dk, d, z)
ek := dk.EncapsulationKey()
c, Ke := ek.EncapsulateInternal(m)
Ke, c := ek.EncapsulateInternal(m)
Kd, err := dk.Decapsulate(c)
if err != nil {
return err

View File

@@ -189,7 +189,7 @@ func kemKeyGen1024(dk *DecapsulationKey1024, d, z *[32]byte) {
// the first operational use (if not exported before the first use)."
func kemPCT1024(dk *DecapsulationKey1024) error {
ek := dk.EncapsulationKey()
c, K := ek.Encapsulate()
K, c := ek.Encapsulate()
K1, err := dk.Decapsulate(c)
if err != nil {
return err
@@ -204,13 +204,13 @@ func kemPCT1024(dk *DecapsulationKey1024) error {
// encapsulation key, drawing random bytes from a DRBG.
//
// The shared key must be kept secret.
func (ek *EncapsulationKey1024) Encapsulate() (ciphertext, sharedKey []byte) {
func (ek *EncapsulationKey1024) Encapsulate() (sharedKey, ciphertext []byte) {
// The actual logic is in a separate function to outline this allocation.
var cc [CiphertextSize1024]byte
return ek.encapsulate(&cc)
}
func (ek *EncapsulationKey1024) encapsulate(cc *[CiphertextSize1024]byte) (ciphertext, sharedKey []byte) {
func (ek *EncapsulationKey1024) encapsulate(cc *[CiphertextSize1024]byte) (sharedKey, ciphertext []byte) {
var m [messageSize]byte
drbg.Read(m[:])
// Note that the modulus check (step 2 of the encapsulation key check from
@@ -221,7 +221,7 @@ func (ek *EncapsulationKey1024) encapsulate(cc *[CiphertextSize1024]byte) (ciphe
// EncapsulateInternal is a derandomized version of Encapsulate, exclusively for
// use in tests.
func (ek *EncapsulationKey1024) EncapsulateInternal(m *[32]byte) (ciphertext, sharedKey []byte) {
func (ek *EncapsulationKey1024) EncapsulateInternal(m *[32]byte) (sharedKey, ciphertext []byte) {
cc := &[CiphertextSize1024]byte{}
return kemEncaps1024(cc, ek, m)
}
@@ -229,14 +229,14 @@ func (ek *EncapsulationKey1024) EncapsulateInternal(m *[32]byte) (ciphertext, sh
// kemEncaps1024 generates a shared key and an associated ciphertext.
//
// It implements ML-KEM.Encaps_internal according to FIPS 203, Algorithm 17.
func kemEncaps1024(cc *[CiphertextSize1024]byte, ek *EncapsulationKey1024, m *[messageSize]byte) (c, K []byte) {
func kemEncaps1024(cc *[CiphertextSize1024]byte, ek *EncapsulationKey1024, m *[messageSize]byte) (K, c []byte) {
g := sha3.New512()
g.Write(m[:])
g.Write(ek.h[:])
G := g.Sum(nil)
K, r := G[:SharedKeySize], G[SharedKeySize:]
c = pkeEncrypt1024(cc, &ek.encryptionKey1024, m, r)
return c, K
return K, c
}
// NewEncapsulationKey1024 parses an encapsulation key from its encoded form.

View File

@@ -246,7 +246,7 @@ func kemKeyGen(dk *DecapsulationKey768, d, z *[32]byte) {
// the first operational use (if not exported before the first use)."
func kemPCT(dk *DecapsulationKey768) error {
ek := dk.EncapsulationKey()
c, K := ek.Encapsulate()
K, c := ek.Encapsulate()
K1, err := dk.Decapsulate(c)
if err != nil {
return err
@@ -261,13 +261,13 @@ func kemPCT(dk *DecapsulationKey768) error {
// encapsulation key, drawing random bytes from a DRBG.
//
// The shared key must be kept secret.
func (ek *EncapsulationKey768) Encapsulate() (ciphertext, sharedKey []byte) {
func (ek *EncapsulationKey768) Encapsulate() (sharedKey, ciphertext []byte) {
// The actual logic is in a separate function to outline this allocation.
var cc [CiphertextSize768]byte
return ek.encapsulate(&cc)
}
func (ek *EncapsulationKey768) encapsulate(cc *[CiphertextSize768]byte) (ciphertext, sharedKey []byte) {
func (ek *EncapsulationKey768) encapsulate(cc *[CiphertextSize768]byte) (sharedKey, ciphertext []byte) {
var m [messageSize]byte
drbg.Read(m[:])
// Note that the modulus check (step 2 of the encapsulation key check from
@@ -278,7 +278,7 @@ func (ek *EncapsulationKey768) encapsulate(cc *[CiphertextSize768]byte) (ciphert
// EncapsulateInternal is a derandomized version of Encapsulate, exclusively for
// use in tests.
func (ek *EncapsulationKey768) EncapsulateInternal(m *[32]byte) (ciphertext, sharedKey []byte) {
func (ek *EncapsulationKey768) EncapsulateInternal(m *[32]byte) (sharedKey, ciphertext []byte) {
cc := &[CiphertextSize768]byte{}
return kemEncaps(cc, ek, m)
}
@@ -286,14 +286,14 @@ func (ek *EncapsulationKey768) EncapsulateInternal(m *[32]byte) (ciphertext, sha
// kemEncaps generates a shared key and an associated ciphertext.
//
// It implements ML-KEM.Encaps_internal according to FIPS 203, Algorithm 17.
func kemEncaps(cc *[CiphertextSize768]byte, ek *EncapsulationKey768, m *[messageSize]byte) (c, K []byte) {
func kemEncaps(cc *[CiphertextSize768]byte, ek *EncapsulationKey768, m *[messageSize]byte) (K, c []byte) {
g := sha3.New512()
g.Write(m[:])
g.Write(ek.h[:])
G := g.Sum(nil)
K, r := G[:SharedKeySize], G[SharedKeySize:]
c = pkeEncrypt(cc, &ek.encryptionKey, m, r)
return c, K
return K, c
}
// NewEncapsulationKey768 parses an encapsulation key from its encoded form.

View File

@@ -4,6 +4,6 @@
//go:build !asan
package check
package fips140
const asanEnabled = false

Some files were not shown because too many files have changed in this diff Show More