Compare commits

...

159 Commits

Author SHA1 Message Date
Gopher Robot
752b009010 [release-branch.go1.21] go1.21.10
Change-Id: I655ab537d86a2ec71634a2f4ca5d520834de9fda
Reviewed-on: https://go-review.googlesource.com/c/go/+/583857
Auto-Submit: Gopher Robot <gobot@golang.org>
Reviewed-by: Cherry Mui <cherryyz@google.com>
Reviewed-by: David Chase <drchase@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2024-05-07 16:00:50 +00:00
Roland Shoemaker
a79ea27e36 [release-branch.go1.21] cmd/go: disallow -lto_library in LDFLAGS
The darwin linker allows setting the LTO library with the -lto_library
flag. This wasn't caught by our "safe linker flags" check because it
was covered by the -lx flag used for linking libraries. This change
adds a specific check for excluded flags which otherwise satisfy our
existing checks.

Loading a mallicious LTO library would allow an attacker to cause the
linker to execute abritrary code when "go build" was called.

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

Fixes #67119
Fixes #67121
Fixes CVE-2024-24787

Change-Id: I77ac8585efbdbdfd5f39c39ed623b9408a0f9eaf
Reviewed-on: https://go-internal-review.googlesource.com/c/go/+/1380
Reviewed-by: Russ Cox <rsc@google.com>
Reviewed-by: Damien Neil <dneil@google.com>
(cherry picked from commit 9a79141fbbca1105e5c786f15e38741ca7843290)
Reviewed-on: https://go-internal-review.googlesource.com/c/go/+/1401
Reviewed-by: Tatiana Bradley <tatianabradley@google.com>
Reviewed-on: https://go-review.googlesource.com/c/go/+/583795
Reviewed-by: David Chase <drchase@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2024-05-07 15:23:16 +00:00
Cherry Mui
78d89b2b67 [release-branch.go1.21] Revert "cmd/compile: don't combine loads in generated equality functions"
This reverts CL 583303.

Reason for revert: release branch is currently frozen.

Change-Id: Icbdb73b5b40690a875497dd0dc57ca84c728ef6f
Reviewed-on: https://go-review.googlesource.com/c/go/+/582961
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
2024-05-06 21:03:27 +00:00
khr@golang.org
58e77ad9b9 [release-branch.go1.21] cmd/compile: don't combine loads in generated equality functions
... if the architecture can't do unaligned loads.
We already handle this in a few places, but this particular place
was added in CL 399542 and missed this additional restriction.

Fixes #67164

Change-Id: I45988f11ff3ed45df1c4da3f0931ab1fdb22dbfe
Reviewed-on: https://go-review.googlesource.com/c/go/+/583175
Reviewed-by: Cuong Manh Le <cuong.manhle.vn@gmail.com>
Auto-Submit: Keith Randall <khr@google.com>
Reviewed-by: Keith Randall <khr@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Derek Parker <parkerderek86@gmail.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
(cherry picked from commit 3c72dd513c)
Reviewed-on: https://go-review.googlesource.com/c/go/+/583303
2024-05-06 18:10:50 +00:00
Dmitri Shuralyov
891ac91e5c [release-branch.go1.21] net/http: update bundled golang.org/x/net/http2
Pull in CL 578336:

	ef58d90f http2: send correct LastStreamID in stream-caused GOAWAY

For #66668.
Fixes #66697.

Change-Id: I91fc8a67f21fadcb1801ff29d5e2b0453db89617
Reviewed-on: https://go-review.googlesource.com/c/go/+/578357
Reviewed-by: Carlos Amedee <carlos@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2024-04-12 22:24:05 +00:00
Dmitri Shuralyov
7450117243 [release-branch.go1.21] all: tidy dependency versioning after release
Done with:

go get golang.org/x/net@internal-branch.go1.21-vendor
go mod tidy
go mod vendor
go generate net/http  # zero diff since CL 576075 already did this

For CVE-2023-45288.
For #65051.
For #65387.

Change-Id: I336670bdb3df2496c1e8d322c20794042fbc0d02
Reviewed-on: https://go-review.googlesource.com/c/go/+/576275
TryBot-Bypass: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Than McIntosh <thanm@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Auto-Submit: Dmitri Shuralyov <dmitshur@google.com>
2024-04-03 18:01:56 +00:00
Gopher Robot
d8392e6997 [release-branch.go1.21] go1.21.9
Change-Id: I6c69376d434dcf310336a0344051037bf58a4cf7
Reviewed-on: https://go-review.googlesource.com/c/go/+/576117
Commit-Queue: Gopher Robot <gobot@golang.org>
Reviewed-by: Than McIntosh <thanm@google.com>
TryBot-Bypass: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Auto-Submit: Gopher Robot <gobot@golang.org>
2024-04-03 15:35:16 +00:00
Damien Neil
ae5913347d [release-branch.go1.21] net/http: update bundled golang.org/x/net/http2
Disable cmd/internal/moddeps test, since this update includes PRIVATE
track fixes.

Fixes CVE-2023-45288
For #65051
Fixes #65387

Change-Id: I17da6da2fe0dd70062b49f94377875acb34829a1
Reviewed-on: https://team-review.git.corp.google.com/c/golang/go-private/+/2197267
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Run-TryBot: Damien Neil <dneil@google.com>
Reviewed-by: Tatiana Bradley <tatianabradley@google.com>
Reviewed-on: https://go-review.googlesource.com/c/go/+/576075
TryBot-Bypass: Dmitri Shuralyov <dmitshur@google.com>
Commit-Queue: Dmitri Shuralyov <dmitshur@golang.org>
Auto-Submit: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Than McIntosh <thanm@google.com>
2024-04-03 15:10:22 +00:00
Damien Neil
30d8550669 [release-branch.go1.21] all: update golang.org/x/net
Pulls in one HTTP/2 fix:

	0b0455d2c9 http2: reject DATA frames after 1xx and before final headers

For golang/go#65927
Fixes golang/go#66254

Change-Id: I257b2634f63e8c6039c44dea24c345043c23c8d2
Reviewed-on: https://go-review.googlesource.com/c/go/+/574916
Reviewed-by: Than McIntosh <thanm@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2024-03-28 19:12:36 +00:00
Robert Griesemer
efb7cc4275 [release-branch.go1.21] go/types, types2: don't do version checks for embedded types of imported interfaces
[This is a re-apply of CL 571075]

Imported interfaces don't have position information for embedded types.
When computing the type set of such interfaces, doing a version check
may fail because it will rely on the Go version of the current package.

We must not do a version check for features of types from imported
packages - those types have already been typechecked and are "correct".
The version check code does look at packages to avoid such incorrect
version checks, but we don't have the package information available
in an interface type (divorced from its object).

Instead, for now rely on the fact that imported interfaces don't have
position information for embedded types: if the position is unknown,
don't do a version check.

We may want to assert that positions are known in all other cases,
but since this is an older release, don't add such additional changes
to avoid introducing other bugs.

Fixes #66326.
Updates #66064.

Change-Id: I158cf51aa382f85d612ab958ba4b591de1c5fdb2
Reviewed-on: https://go-review.googlesource.com/c/go/+/574736
Reviewed-by: Cherry Mui <cherryyz@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2024-03-27 19:24:11 +00:00
Paul E. Murphy
0bd1a2289d [release-branch.go1.21] cmd/internal/obj/ppc64: don't modify runtime.elf_* symbols
The runtime.elf_* symbols are assembly functions which are used
to support the gcc/llvm -Os option when used with cgo.

When compiling Go for shared code, we attempt to strip out the
TOC regenation code added by the go assembler for these symbols.

This causes the symbol to no longer appear as an assembly
function which causes problems later on when handling other
implicit symbols.

Avoid adding a TOC regeneration prologue to these functions
to avoid this issue.

Fixes #66411

Change-Id: Icbf8e4438d177082a57bb228e39b232e7a0d7ada
Reviewed-on: https://go-review.googlesource.com/c/go/+/571835
Reviewed-by: Than McIntosh <thanm@google.com>
Run-TryBot: Paul Murphy <murp@ibm.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Lynn Boger <laboger@linux.vnet.ibm.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-on: https://go-review.googlesource.com/c/go/+/572876
2024-03-26 19:16:20 +00:00
Cherry Mui
140b37d659 [release-branch.go1.21] Revert "go/types, types2: don't do version checks for embedded types of imported interfaces"
This reverts CL 571075.

Reason for revert: We might want to do a security-only minor release. Back off the release branch to a clean state from the previous minor release. Sorry for the inconvenience.

Change-Id: Ifc8c7e00e6faea3aa547b883eed44180ddb447de
Reviewed-on: https://go-review.googlesource.com/c/go/+/571355
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Robert Findley <rfindley@google.com>
2024-03-13 19:10:25 +00:00
Robert Griesemer
6d229889d8 [release-branch.go1.21] go/types, types2: don't do version checks for embedded types of imported interfaces
Imported interfaces don't have position information for embedded types.
When computing the type set of such interfaces, doing a version check
may fail because it will rely on the Go version of the current package.

We must not do a version check for features of types from imported
packages - those types have already been typechecked and are "correct".
The version check code does look at packages to avoid such incorrect
version checks, but we don't have the package information available
in an interface type (divorced from its object).

Instead, for now rely on the fact that imported interfaces don't have
position information for embedded types: if the position is unknown,
don't do a version check.

We may want to assert that positions are known in all other cases,
but since this is an older release, don't add such additional changes
to avoid introducing other bugs.

Fixes #66064.

Change-Id: I773d57e5410c3d4a911ab3e018b3233c2972b3c9
Reviewed-on: https://go-review.googlesource.com/c/go/+/571075
Reviewed-by: Robert Findley <rfindley@google.com>
Auto-Submit: Robert Griesemer <gri@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Robert Griesemer <gri@google.com>
2024-03-12 20:30:58 +00:00
Gopher Robot
63992defa8 [release-branch.go1.21] go1.21.8
Change-Id: I44203158172ca3e66f8ce4ab84f54c9247dacb28
Reviewed-on: https://go-review.googlesource.com/c/go/+/569256
Reviewed-by: Carlos Amedee <carlos@golang.org>
Reviewed-by: Michael Knyszek <mknyszek@google.com>
Auto-Submit: Gopher Robot <gobot@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2024-03-05 17:38:51 +00:00
Damien Neil
bf80213b12 [release-branch.go1.21] net/textproto, mime/multipart: avoid unbounded read in MIME header
mime/multipart.Reader.ReadForm allows specifying the maximum amount
of memory that will be consumed by the form. While this limit is
correctly applied to the parsed form data structure, it was not
being applied to individual header lines in a form.

For example, when presented with a form containing a header line
that never ends, ReadForm will continue to read the line until it
runs out of memory.

Limit the amount of data consumed when reading a header.

Fixes CVE-2023-45290
Fixes #65389
For #65383

Change-Id: I7f9264d25752009e95f6b2c80e3d76aaf321d658
Reviewed-on: https://team-review.git.corp.google.com/c/golang/go-private/+/2134435
Reviewed-by: Roland Shoemaker <bracewell@google.com>
Reviewed-by: Tatiana Bradley <tatianabradley@google.com>
Reviewed-on: https://team-review.git.corp.google.com/c/golang/go-private/+/2173776
Reviewed-by: Carlos Amedee <amedee@google.com>
Reviewed-on: https://go-review.googlesource.com/c/go/+/569240
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>
2024-03-05 16:51:36 +00:00
Damien Neil
20586c0dbe [release-branch.go1.21] net/http, net/http/cookiejar: avoid subdomain matches on IPv6 zones
When deciding whether to forward cookies or sensitive headers
across a redirect, do not attempt to interpret an IPv6 address
as a domain name.

Avoids a case where a maliciously-crafted redirect to an
IPv6 address with a scoped addressing zone could be
misinterpreted as a within-domain redirect. For example,
we could interpret "::1%.www.example.com" as a subdomain
of "www.example.com".

Thanks to Juho Nurminen of Mattermost for reporting this issue.

Fixes CVE-2023-45289
Fixes #65385
For #65065

Change-Id: I8f463f59f0e700c8a18733d2b264a8bcb3a19599
Reviewed-on: https://team-review.git.corp.google.com/c/golang/go-private/+/2131938
Reviewed-by: Tatiana Bradley <tatianabradley@google.com>
Reviewed-by: Roland Shoemaker <bracewell@google.com>
Reviewed-on: https://team-review.git.corp.google.com/c/golang/go-private/+/2173775
Reviewed-by: Carlos Amedee <amedee@google.com>
Reviewed-on: https://go-review.googlesource.com/c/go/+/569239
Reviewed-by: Carlos Amedee <carlos@golang.org>
Auto-Submit: Michael Knyszek <mknyszek@google.com>
TryBot-Bypass: Michael Knyszek <mknyszek@google.com>
2024-03-05 16:51:34 +00:00
Roland Shoemaker
be5b52bea6 [release-branch.go1.21] crypto/x509: make sure pub key is non-nil before interface conversion
alreadyInChain assumes all keys fit a interface which contains the
Equal method (which they do), but this ignores that certificates may
have a nil key when PublicKeyAlgorithm is UnknownPublicKeyAlgorithm. In
this case alreadyInChain panics.

Check that the key is non-nil as part of considerCandidate (we are never
going to build a chain containing UnknownPublicKeyAlgorithm anyway).

For #65390
Fixes #65392
Fixes CVE-2024-24783

Change-Id: Ibdccc0a487e3368b6812be35daad2512220243f3
Reviewed-on: https://team-review.git.corp.google.com/c/golang/go-private/+/2137282
Reviewed-by: Damien Neil <dneil@google.com>
Run-TryBot: Roland Shoemaker <bracewell@google.com>
Reviewed-by: Tatiana Bradley <tatianabradley@google.com>
Reviewed-on: https://team-review.git.corp.google.com/c/golang/go-private/+/2173774
Reviewed-by: Roland Shoemaker <bracewell@google.com>
Reviewed-by: Carlos Amedee <amedee@google.com>
Reviewed-on: https://go-review.googlesource.com/c/go/+/569238
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>
2024-03-05 16:44:27 +00:00
Roland Shoemaker
3643147a29 [release-branch.go1.21] html/template: escape additional tokens in MarshalJSON errors
Escape "</script" and "<!--" in errors returned from MarshalJSON errors
when attempting to marshal types in script blocks. This prevents any
user controlled content from prematurely terminating the script block.

Updates #65697
Fixes #65968

Change-Id: Icf0e26c54ea7d9c1deed0bff11b6506c99ddef1b
Reviewed-on: https://go-review.googlesource.com/c/go/+/564196
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Damien Neil <dneil@google.com>
(cherry picked from commit ccbc725f2d)
Reviewed-on: https://go-review.googlesource.com/c/go/+/567515
Reviewed-by: Carlos Amedee <carlos@golang.org>
2024-02-28 19:53:41 +00:00
Bryan C. Mills
3a588774a5 [release-branch.go1.21] internal/syscall/windows: fix the signature of SetFileInformationByHandle
Also fix its call site in internal/poll to pass the length of the
actual buffer instead of an unrelated variable, and update the
definition of FILE_BASIC_INFO to match the documented field types
and add padding that is empirically needed on the 386 architecture.

Passing a pointer to a Go-allocated buffer as type uintptr violates
the unsafe.Pointer conversion rules, which allow such a conversion
only in the call expression itself for a call to syscall.Syscall or
equivalent. That can allow the buffer to be corrupted arbitrarily if
the Go runtime happens to garbage-collect it while the call to
SetFileInformationByHandle is in progress.

The Microsoft documentation for SetFileInformationByHandle specifies
its third argument type as LPVOID, which corresponds to Go's
unsafe.Pointer, not uintptr.

Fixes #65882.
Updates #58933.

Change-Id: If577b57adea9922f5fcca55e46030c703d8f035c
Cq-Include-Trybots: luci.golang.try:go1.21-windows-amd64-longtest
Reviewed-on: https://go-review.googlesource.com/c/go/+/549256
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Than McIntosh <thanm@google.com>
Auto-Submit: Bryan Mills <bcmills@google.com>
Reviewed-by: Quim Muntal <quimmuntal@gmail.com>
Reviewed-by: Alex Brainman <alex.brainman@gmail.com>
(cherry picked from commit a7097243e4)
Reviewed-on: https://go-review.googlesource.com/c/go/+/566155
Reviewed-by: Bryan Mills <bcmills@google.com>
2024-02-28 19:46:24 +00:00
Roland Shoemaker
263c059b09 [release-branch.go1.21] net/mail: properly handle special characters in phrase and obs-phrase
Fixes a couple of misalignments with RFC 5322 which introduce
significant diffs between (mostly) conformant parsers.

This change reverts the changes made in CL50911, which allowed certain
special RFC 5322 characters to appear unquoted in the "phrase" syntax.
It is unclear why this change was made in the first place, and created
a divergence from comformant parsers. In particular this resulted in
treating comments in display names incorrectly.

Additionally properly handle trailing malformed comments in the group
syntax.

For #65083
Fixes #65848

Change-Id: I00dddc044c6ae3381154e43236632604c390f672
Reviewed-on: https://go-review.googlesource.com/c/go/+/555596
Reviewed-by: Damien Neil <dneil@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-on: https://go-review.googlesource.com/c/go/+/566195
Reviewed-by: Carlos Amedee <carlos@golang.org>
2024-02-28 19:10:06 +00:00
Michael Matloob
99e44c71f6 [release-branch.go1.21] cmd/go/internal/modcmd: correctly filter out main modules in verify
This change fixes a bug where we incorrectly filtered out the main
modules from the beginning of the build list before verifying them. We
made the assumption that the first MainModules.Len() entries of the
build list were the main modules, but now it can contain the go and
toolchain version entries, so removing the first MainModules.Len()
entries could leave main module names in the build list if any of
their names sorted after the string 'go'.

For #62663
Fixes #65851

Change-Id: I35ab6857a556f58d306303322afe24c48fc8b38f
Reviewed-on: https://go-review.googlesource.com/c/go/+/565378
Reviewed-by: Bryan Mills <bcmills@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
(cherry picked from commit 3f60da7944)
Reviewed-on: https://go-review.googlesource.com/c/go/+/565755
Run-TryBot: Michael Matloob <matloob@golang.org>
TryBot-Result: Gopher Robot <gobot@golang.org>
2024-02-28 17:54:30 +00:00
Ian Lance Taylor
6d31b27150 [release-branch.go1.21] runtime: don't let the tests leave core files behind
Also add a check that we didn't leave any core files behind.

For #65476.
Fixes #65478. 

Change-Id: I30444ef43ad1a8cc1cacd3b75280f2128e104939
Reviewed-on: https://go-review.googlesource.com/c/go/+/525175
Reviewed-by: Ian Lance Taylor <iant@google.com>
Reviewed-by: Keith Randall <khr@google.com>
Auto-Submit: Ian Lance Taylor <iant@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Keith Randall <khr@golang.org>
(cherry picked from commit cffdfe8d2c)
Reviewed-on: https://go-review.googlesource.com/c/go/+/560896
2024-02-27 21:42:04 +00:00
Michael Anthony Knyszek
f38fca30a7 [release-branch.go1.21] cmd/cgo/internal/testsanitizers: disable location checking for clang
Pending a resolution to #65606, this CL marks clang's ASAN runtime as
unable to symbolize stack traces to unblock the LUCI clang builder.

For #65606.
For #65469.
Fixes #65640.

Change-Id: I649773085aff30e5703e7f7ac2c72a0430a015c2
Cq-Include-Trybots: luci.golang.try:go1.21-linux-amd64-clang15
Reviewed-on: https://go-review.googlesource.com/c/go/+/562675
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
(cherry picked from commit d94ab597af)
Reviewed-on: https://go-review.googlesource.com/c/go/+/562999
2024-02-16 15:51:02 +00:00
Michael Anthony Knyszek
b214108e72 [release-branch.go1.21] internal/testenv: support the LUCI mobile builders in tests
This change updates the testenv tests to correctly match on future LUCI
builder names for mobile builders. This isn't a problem today because
those haven't been set up yet, but the builder names are structured and
it's clear where the modifiers will appear. Might as well set them up
now.

For #65473.
Fixes #65475.

Change-Id: I244b88a62a90312c0f3ff2360527d58531070362
Reviewed-on: https://go-review.googlesource.com/c/go/+/558597
Reviewed-by: Dmitri Shuralyov <dmitshur@golang.org>
Reviewed-by: Bryan Mills <bcmills@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
(cherry picked from commit 5c7c24ce82)
Reviewed-on: https://go-review.googlesource.com/c/go/+/560895
2024-02-08 16:19:05 +00:00
Michael Anthony Knyszek
f997dfd33a [release-branch.go1.21] internal/testenv: allow "-noopt" anywhere in builder name in test
testenv's TestHasGoBuild test is supposed to allow noopt builders to not
have go build, but the pattern match is failing on the LUCI builders
where a test shard might have an additional "-test_only" suffix in the
builder name. Furthermore, in the LUCI world, "run mods" (the builder
type suffixes) are supposed to be well-defined and composable, so it
doesn't make sense to restrict "-noopt" to the builder suffix anyway.

This change modifies the test to allow "-noopt" to appear anywhere in
the builder name when checking if it's running on a noopt builder.

For #65470.
Fixes #65472.

Change-Id: I393818e3e8e452c7b0927cbc65726d552aa8ff8e
Reviewed-on: https://go-review.googlesource.com/c/go/+/558596
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>
Reviewed-by: Bryan Mills <bcmills@google.com>
(cherry picked from commit 93f0c0b25e)
Reviewed-on: https://go-review.googlesource.com/c/go/+/560518
2024-02-08 16:18:55 +00:00
Gopher Robot
f29208030a [release-branch.go1.21] go1.21.7
Change-Id: I2c0bbd094a1e9a12576869437a362da40f76f22d
Reviewed-on: https://go-review.googlesource.com/c/go/+/562117
Reviewed-by: Michael Knyszek <mknyszek@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Gopher Robot <gobot@golang.org>
Reviewed-by: David Chase <drchase@google.com>
2024-02-06 18:00:12 +00:00
Keith Randall
2fdad8af6d [release-branch.go1.21] cmd/internal/obj/arm64: fix frame pointer restore in epilogue
For leaf but nonzero-frame functions.

Currently we're not restoring it properly. We also need to restore
it before popping the stack frame, so that the frame won't get
clobbered by a signal handler in the meantime.

For #63830
Fixes #65449

Needs a test, but I'm not at all sure how we would actually do that. Leaving for inspiration.

Change-Id: I273a25f2a838f05a959c810145cccc5428eaf164
Reviewed-on: https://go-review.googlesource.com/c/go/+/538635
Reviewed-by: Cherry Mui <cherryyz@google.com>
Reviewed-by: Eric Fang <eric.fang@arm.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: David Chase <drchase@google.com>
(cherry picked from commit c9888bdfe2)
Reviewed-on: https://go-review.googlesource.com/c/go/+/560735
TryBot-Bypass: Michael Knyszek <mknyszek@google.com>
Reviewed-by: Keith Randall <khr@golang.org>
2024-02-02 16:26:24 +00:00
Michael Matloob
01c93ad049 [release-branch.go1.21] cmd/go/internal/generate: call modload.InitWorkFile
This is necessary for go generate to enter workspace mode for
recognizing package paths in the workspace.

For #56098
Fixes #65351

Change-Id: I25f68de24f4189259353f63194823516e9d3d505
Reviewed-on: https://go-review.googlesource.com/c/go/+/559195
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Bryan Mills <bcmills@google.com>
(cherry picked from commit b91bad7819)
Reviewed-on: https://go-review.googlesource.com/c/go/+/559235
2024-02-01 20:19:50 +00:00
Filippo Valsorda
db74bfba18 [release-branch.go1.21] Revert "crypto/internal/boring: upgrade module to fips-20220613" +1
This reverts CL 553855 ("crypto/internal/boring: upgrade module to
fips-20220613") and CL 553856 ("crypto/tls: align FIPS-only mode with
BoringSSL policy").

Fixes #65323
Updates #65321
Updates #64717
Updates #62372

Change-Id: I0938b97e5b4904e6532448b8ae76e920d03d0508
Reviewed-on: https://go-review.googlesource.com/c/go/+/558796
Reviewed-by: Michael Knyszek <mknyszek@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>
(cherry picked from commit 09b5de48e6)
Reviewed-on: https://go-review.googlesource.com/c/go/+/560275
2024-02-01 18:25:33 +00:00
qiulaidongfeng
916e6cddf1 [release-branch.go1.21] runtime: fix Pinner.Pin documentation
Fixes #63768

Change-Id: I01a9bb8f9af22a6b3f6534d431e3ea623875ed48
GitHub-Last-Rev: 7c5dd4edb1
GitHub-Pull-Request: golang/go#64920
Reviewed-on: https://go-review.googlesource.com/c/go/+/553395
Reviewed-by: Michael Knyszek <mknyszek@google.com>
Auto-Submit: Michael Knyszek <mknyszek@google.com>
Reviewed-by: 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>
2024-01-31 21:20:32 +00:00
Bryan C. Mills
6552f3d4ac [release-branch.go1.21] cmd/go/internal/toolchain: apply the -modcacherw flag when downloading a module to determine what toolchain it needs
Fixes #64497.
Updates #64282.

Change-Id: I3f211c599ee70cb58254d0bc07eeb3c135124e58
Reviewed-on: https://go-review.googlesource.com/c/go/+/555436
Auto-Submit: Bryan Mills <bcmills@google.com>
Reviewed-by: Russ Cox <rsc@golang.org>
(cherry picked from commit cc38c68ae0)
Reviewed-on: https://go-review.googlesource.com/c/go/+/559198
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2024-01-31 17:34:35 +00:00
Roland Shoemaker
3960318b87 [release-branch.go1.21] crypto/x509: properly gate test on macos version
Fixes the gating of TestIssue51759 by shelling out to sw_vers to check
what version of macOS we are on.

For #64677
Fixes #65380

Change-Id: I5eef4fa39e5449e7b2aa73864625c3abf002aef8
Reviewed-on: https://go-review.googlesource.com/c/go/+/549195
Reviewed-by: Bryan Mills <bcmills@google.com>
Auto-Submit: Roland Shoemaker <roland@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
(cherry picked from commit 400e24a8be)
Reviewed-on: https://go-review.googlesource.com/c/go/+/559517
Auto-Submit: Michael Pratt <mpratt@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
2024-01-31 17:30:51 +00:00
Robert Griesemer
00f974eb1f [release-branch.go1.21] go/types, types2: don't lose position info of interface embeddings
Accurate position information for embedded types in interfaces is
crucial to identify the corresponding source file, and with that
the Go language version associated with that file. (The position
information is also important for proper error messages.)

Before this CL, the position information for embedded types was
discarded after type set computation, in the assumption that it
was not needed anymore. However, substitutions that update the
interface may lead to repeated type set computations which then
won't have the correct position information.

This CL does preserve the position information for embedded
types until the end of type checking (cleanup phase), and also
copy the position information during a substitution of the
interface.

The respective bug (#64759) doesn't seem to appear in 1.22 (most
likely because it's hidden by some of the changes made with respect
to the file version logic), but the existing code is still wrong.
The backport of this code to 1.21 and 1.20 fixes the issue in those
releases.

For #64759.
Fixes #65053.

Change-Id: I80f4004c9d79cb02eac6739c324c477706615102
Reviewed-on: https://go-review.googlesource.com/c/go/+/555296
Run-TryBot: Robert Griesemer <gri@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Robert Findley <rfindley@google.com>
Reviewed-by: Robert Griesemer <gri@google.com>
Reviewed-on: https://go-review.googlesource.com/c/go/+/555415
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2024-01-25 17:49:05 +00:00
Michael Pratt
2f91c16e68 [release-branch.go1.21] runtime: properly model rwmutex in lock ranking
(This cherry-pick combines CL 549536 and the follow-up fix CL 555055.)

Currently, lock ranking doesn't really try to model rwmutex. It records
the internal locks rLock and wLock, but in a subpar fashion:

1. wLock is held from lock to unlock, so it works OK, but it conflates
   write locks of all rwmutexes as rwmutexW, rather than allowing
   different rwmutexes to have different rankings.
2. rLock is an internal implementation detail that is only taken when
   there is contention in rlock. As as result, the reader lock path is
   almost never checked.

Add proper modeling. rwmutexR and rwmutexW remain as the ranks of the
internal locks, which have their own ordering. The new init method is
passed the ranks of the higher level lock that this represents, just
like lockInit for mutex.

execW ordered before MALLOC captures the case from #64722. i.e., there
can be allocation between BeforeFork and AfterFork.

For #64722.
Fixes #64761.

------

runtime: replace rwmutexR/W with per-rwmutex lock rank

CL 549536 intended to decouple the internal implementation of rwmutex
from the semantic meaning of an rwmutex read/write lock in the static
lock ranking.

Unfortunately, it was not thought through well enough. The internals
were represented with the rwmutexR and rwmutexW lock ranks. The idea was
that the internal lock ranks need not model the higher-level ordering,
since those have separate rankings. That is incorrect; rwmutexW is held
for the duration of a write lock, so it must be ranked before any lock
taken while any write lock is held, which is precisely what we were
trying to avoid.

This is visible in violations like:

        0 : execW 11 0x0
        1 : rwmutexW 51 0x111d9c8
        2 : fin 30 0x111d3a0
        fatal error: lock ordering problem

execW < fin is modeled, but rwmutexW < fin is missing.

Fix this by eliminating the rwmutexR/W lock ranks shared across
different types of rwmutex. Instead require users to define an
additional "internal" lock rank to represent the implementation details
of rwmutex.rLock. We can avoid an additional "internal" lock rank for
rwmutex.wLock because the existing writeRank has the same semantics for
semantic and internal locking. i.e., writeRank is held for the duration
of a write lock, which is exactly how rwmutex.wLock is used, so we can
use writeRank directly on wLock.

For #64722.

Cq-Include-Trybots: luci.golang.try:go1.21-linux-amd64-staticlockranking
Change-Id: I23335b28faa42fb04f1bc9da02fdf54d1616cd28
Reviewed-on: https://go-review.googlesource.com/c/go/+/549536
Reviewed-by: Michael Knyszek <mknyszek@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
(cherry picked from commit 9b4b3e5acc)
(cherry picked from commit dcbe772469)
Reviewed-on: https://go-review.googlesource.com/c/go/+/554976
2024-01-25 17:20:02 +00:00
Alan Donovan
2540b1436f [release-branch.go1.21] slices: explicitly discard results of some functions
This will otherwise trigger an "unusedresult" vet check.

For #64978.
Fixes #65023.
Fixes #60058.

Change-Id: Ie19aded0f808d394f389452c3ff7f3edc1ed710d
Reviewed-on: https://go-review.googlesource.com/c/go/+/554196
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Bryan Mills <bcmills@google.com>
(cherry picked from commit 8088b6db23)
Reviewed-on: https://go-review.googlesource.com/c/go/+/554756
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Auto-Submit: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Alan Donovan <adonovan@google.com>
2024-01-10 20:16:07 +00:00
Michael Pratt
7e34c4308f [release-branch.go1.21] runtime: clear g0 stack bounds in dropm
After CL 527715, needm uses callbackUpdateSystemStack to set the stack
bounds for g0 on an M from the extra M list. Since
callbackUpdateSystemStack is also used for recursive cgocallback, it
does nothing if the stack is already in bounds.

Currently, the stack bounds in an extra M may contain stale bounds from
a previous thread that used this M and then returned it to the extra
list in dropm.

Typically a new thread will not have an overlapping stack with an old
thread, but because the old thread has exited there is a small chance
that the C memory allocator will allocate the new thread's stack
partially or fully overlapping with the old thread's stack.

If this occurs, then callbackUpdateSystemStack will not update the stack
bounds. If in addition, the overlap is partial such that SP on
cgocallback is close to the recorded stack lower bound, then Go may
quickly "overflow" the stack and crash with "morestack on g0".

Fix this by clearing the stack bounds in dropm, which ensures that
callbackUpdateSystemStack will unconditionally update the bounds in
needm.

For #62440.
Fixes #63209.

Change-Id: Ic9e2052c2090dd679ed716d1a23a86d66cbcada7
Reviewed-on: https://go-review.googlesource.com/c/go/+/537695
Reviewed-by: Cherry Mui <cherryyz@google.com>
Run-TryBot: Michael Pratt <mpratt@google.com>
Auto-Submit: Michael Pratt <mpratt@google.com>
TryBot-Bypass: Michael Pratt <mpratt@google.com>
(cherry picked from commit 1af424c196)
Reviewed-on: https://go-review.googlesource.com/c/go/+/549495
Auto-Submit: Dmitri Shuralyov <dmitshur@google.com>
2024-01-10 19:40:22 +00:00
Michael Pratt
491c1e7e95 [release-branch.go1.21] runtime: allow update of system stack bounds on callback from C thread
[This cherry-pick combines CL 527715, CL 527775, CL 527797, and
CL 529216.]

[This is a redo of CL 525455 with the test fixed on darwin by defining
_XOPEN_SOURCE, and disabled with android, musl, and openbsd, which do
not provide getcontext.]

Since CL 495855, Ms are cached for C threads calling into Go, including
the stack bounds of the system stack.

Some C libraries (e.g., coroutine libraries) do manual stack management
and may change stacks between calls to Go on the same thread.

Changing the stack if there is more Go up the stack would be
problematic. But if the calls are completely independent there is no
particular reason for Go to care about the changing stack boundary.

Thus, this CL allows the stack bounds to change in such cases. The
primary downside here (besides additional complexity) is that normal
systems that do not manipulate the stack may not notice unintentional
stack corruption as quickly as before.

Note that callbackUpdateSystemStack is written to be usable for the
initial setup in needm as well as updating the stack in cgocallbackg.

For #62440.
For #62130.
For #63209.

Change-Id: I0fe0134f865932bbaff1fc0da377c35c013bd768
Reviewed-on: https://go-review.googlesource.com/c/go/+/527715
Run-TryBot: Michael Pratt <mpratt@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Auto-Submit: Michael Pratt <mpratt@google.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
(cherry picked from commit 4f9fe6d509)
(cherry picked from commit e8ba0579e2)
(cherry picked from commit a843991fdd)
(cherry picked from commit d110d7c42d)
Reviewed-on: https://go-review.googlesource.com/c/go/+/530480
Auto-Submit: Dmitri Shuralyov <dmitshur@google.com>
TryBot-Bypass: Michael Pratt <mpratt@google.com>
2024-01-10 19:40:13 +00:00
Cherry Mui
caafb50c0d [release-branch.go1.21] runtime: don't print "unexpected SPWRITE" when printing traceback
The system stack often starts with a stack transition function
like "systemstack" or "mcall", which is marked as SPWRITE. When
unwinding a system stack for printing, we want the traceback stop
at the stack switching frame, but not print the "unexpected
SPWRITE" message.

Previously before CL 525835, we don't print the "unexpected
SPWRITE" message if unwindPrintErrors is set, i.e. printing a
stack trace. This CL restores this behavior.

Another possibility is not printing the message only on the system
stack. We don't expect a stack transition function to appear in a
user G.

Fixes #64935.

Change-Id: I173e89ead2cd4fbf1f0f8cca225f28718b5baebe
Reviewed-on: https://go-review.googlesource.com/c/go/+/531815
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Michael Pratt <mpratt@google.com>
Reviewed-by: Michael Knyszek <mknyszek@google.com>
(cherry picked from commit 15a274b621)
Reviewed-on: https://go-review.googlesource.com/c/go/+/553476
Reviewed-by: Cherry Mui <cherryyz@google.com>
Auto-Submit: Dmitri Shuralyov <dmitshur@google.com>
TryBot-Bypass: Dmitri Shuralyov <dmitshur@golang.org>
2024-01-10 19:17:07 +00:00
Gopher Robot
cc85462b3d [release-branch.go1.21] go1.21.6
Change-Id: I85e48d54e6938b3882a0bb8f2de75fee6ecb2668
Reviewed-on: https://go-review.googlesource.com/c/go/+/554839
Commit-Queue: Gopher Robot <gobot@golang.org>
Reviewed-by: Matthew Dempsky <mdempsky@google.com>
Auto-Submit: Gopher Robot <gobot@golang.org>
TryBot-Bypass: Dmitri Shuralyov <dmitshur@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
2024-01-09 18:17:19 +00:00
Filippo Valsorda
d2cb140194 [release-branch.go1.21] crypto/tls: align FIPS-only mode with BoringSSL policy
This enables TLS 1.3, disables P-521, and disables non-ECDHE suites.

Updates #64717
Updates #62372
Fixes #64719

Change-Id: I3a65b239ef0198bbdbe5e55e0810e7128f90a091
Reviewed-on: https://go-review.googlesource.com/c/go/+/549975
Reviewed-by: Roland Shoemaker <roland@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Than McIntosh <thanm@google.com>
Reviewed-on: https://go-review.googlesource.com/c/go/+/553856
Auto-Submit: Matthew Dempsky <mdempsky@google.com>
Reviewed-by: Matthew Dempsky <mdempsky@google.com>
2024-01-04 23:16:07 +00:00
Filippo Valsorda
368e2a9461 [release-branch.go1.21] crypto/internal/boring: upgrade module to fips-20220613
Also, add EVP_aead_aes_*_gcm_tls13 to the build, which we will need in a
following CL, to avoid rebuilding the syso twice.

Updates #64717
Updates #62372
Updates #64719

Change-Id: Ie4d853ad9b914c1095cad60694a1ae6f77dc22ce
Cq-Include-Trybots: luci.golang.try:go1.21-linux-amd64-boringcrypto
Reviewed-on: https://go-review.googlesource.com/c/go/+/549695
Reviewed-by: Than McIntosh <thanm@google.com>
Reviewed-by: Roland Shoemaker <roland@golang.org>
Reviewed-on: https://go-review.googlesource.com/c/go/+/553855
Auto-Submit: Matthew Dempsky <mdempsky@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Run-TryBot: Matthew Dempsky <mdempsky@google.com>
Reviewed-by: Matthew Dempsky <mdempsky@google.com>
2024-01-04 23:16:05 +00:00
David Chase
8c6078adfb [release-branch.go1.21] runtime: add race annotations in IncNonDefault
Also use CompareAndSwap to make the code actually less racy.

Added a test which will be meaningful when run under the race
detector (tested it -race with broken fix in runtime, it failed).

This backport incorporates the correction in CL 551856,
using racereleasemerge instead of racerelease. 

Fixes #64757

Change-Id: I5972e08901d1adc8ba74858edad7eba91be1b0ce
Reviewed-on: https://go-review.googlesource.com/c/go/+/549796
Run-TryBot: David Chase <drchase@google.com>
Reviewed-by: Mauri de Souza Meneguzzo <mauri870@gmail.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
(cherry picked from commit 3313bbb405)
Reviewed-on: https://go-review.googlesource.com/c/go/+/550236
Auto-Submit: Matthew Dempsky <mdempsky@google.com>
TryBot-Bypass: Matthew Dempsky <mdempsky@google.com>
Reviewed-by: Michael Knyszek <mknyszek@google.com>
Reviewed-by: Matthew Dempsky <mdempsky@google.com>
2024-01-04 21:37:29 +00:00
Keith Randall
f6b203c828 [release-branch.go1.21] maps: fix aliasing problems with Clone
Make sure to alloc+copy large keys and values instead of aliasing them,
when they might be updated by a future assignment.

Fixes #64475

Change-Id: Ie2226a81cf3897e4e2ee24472f2966d397ace53f
Reviewed-on: https://go-review.googlesource.com/c/go/+/546515
Reviewed-by: Cherry Mui <cherryyz@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Keith Randall <khr@google.com>
Reviewed-by: Mauri de Souza Meneguzzo <mauri870@gmail.com>
(cherry picked from commit 16d3040a84)
Reviewed-on: https://go-review.googlesource.com/c/go/+/547375
TryBot-Bypass: Matthew Dempsky <mdempsky@google.com>
Reviewed-by: Matthew Dempsky <mdempsky@google.com>
Auto-Submit: Matthew Dempsky <mdempsky@google.com>
2024-01-04 21:37:00 +00:00
Michael Anthony Knyszek
43818206dc [release-branch.go1.21] runtime: put ReadMemStats debug assertions behind a double-check mode
ReadMemStats has a few assertions it makes about the consistency of the
stats it's about to produce. Specifically, how those stats line up with
runtime-internal stats. These checks are generally useful, but crashing
just because some stats are wrong is a heavy price to pay.

For a long time this wasn't a problem, but very recently it became a
real problem. It turns out that there's real benign skew that can happen
wherein sysmon (which doesn't synchronize with a STW) generates a trace
event when tracing is enabled, and may mutate some stats while
ReadMemStats is running its checks.

Fix this by synchronizing with both sysmon and the tracer. This is a bit
heavy-handed, but better that than false positives.

Also, put the checks behind a debug mode. We want to reduce the risk of
backporting this change, and again, it's not great to crash just because
user-facing stats are off. Still, enable this debug mode during the
runtime tests so we don't lose quite as much coverage from disabling
these checks by default.

For #64401.
Fixes #64410.

Change-Id: I9adb3e5c7161d207648d07373a11da8a5f0fda9a
Reviewed-on: https://go-review.googlesource.com/c/go/+/545277
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Michael Pratt <mpratt@google.com>
Reviewed-by: Felix Geisendörfer <felix.geisendoerfer@datadoghq.com>
(cherry picked from commit b2efd1de97)
Reviewed-on: https://go-review.googlesource.com/c/go/+/545557
Auto-Submit: Matthew Dempsky <mdempsky@google.com>
TryBot-Bypass: Matthew Dempsky <mdempsky@google.com>
2024-01-04 21:34:32 +00:00
Michael Anthony Knyszek
cf65d74bc5 [release-branch.go1.21] runtime: add the disablethp GODEBUG setting
Go 1.21.1 and Go 1.22 have ceased working around an issue with Linux
kernel defaults for transparent huge pages that can result in excessive
memory overheads. (https://bugzilla.kernel.org/show_bug.cgi?id=93111)

Many Linux distributions disable huge pages altogether these days, so
this problem isn't quite as far-reaching as it used to be. Also, the
problem only affects Go programs with very particular memory usage
patterns.

That being said, because the runtime used to actively deal with this
problem (but with some unpredictable behavior), it's preventing users
that don't have a lot of control over their execution environment from
upgrading to Go beyond Go 1.20.

This change adds a GODEBUG to smooth over the transition. The GODEBUG
setting disables transparent huge pages for all heap memory on Linux,
which is much more predictable than restoring the old behavior.

For #64332.
Fixes #64561.

Change-Id: I73b1894337f0f0b1a5a17b90da1221e118e0b145
Reviewed-on: https://go-review.googlesource.com/c/go/+/547475
Reviewed-by: Michael Pratt <mpratt@google.com>
Auto-Submit: Michael Knyszek <mknyszek@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
(cherry picked from commit c915215af6)
Reviewed-on: https://go-review.googlesource.com/c/go/+/547636
Reviewed-by: Mauri de Souza Meneguzzo <mauri870@gmail.com>
TryBot-Bypass: Michael Knyszek <mknyszek@google.com>
Auto-Submit: Matthew Dempsky <mdempsky@google.com>
2024-01-04 17:32:44 +00:00
Tolya Korniltsev
ad1ec60a5b [release-branch.go1.21] runtime/pprof: fix generics function names
profileBuilder is using Frame->Function as key for checking if we already
emitted a function. However for generics functions it has dots there [...],
so sometimes for different functions with different generics types,
the profileBuilder emits wrong functions.

For #64528
For #64609

Change-Id: I8b39245e0b18f4288ce758c912c6748f87cba39a
Reviewed-on: https://go-review.googlesource.com/c/go/+/546815
Reviewed-by: Cherry Mui <cherryyz@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Michael Pratt <mpratt@google.com>
(cherry picked from commit 20a03fc713)
Reviewed-on: https://go-review.googlesource.com/c/go/+/549535
Auto-Submit: Matthew Dempsky <mdempsky@google.com>
2024-01-04 17:22:01 +00:00
Michael Pratt
bbab863ada [release-branch.go1.21] os/signal: skip nohup tests on darwin builders
The new LUCI builders have a temporary limitation that breaks nohup.
Skip nohup tests there.

For #63875.
Fixes #63911.

Cq-Include-Trybots: luci.golang.try:go1.21-darwin-amd64_13
Change-Id: Ia9ffecea7310f84a21f6138d8f8cdfc5e1392307
Reviewed-on: https://go-review.googlesource.com/c/go/+/538698
Reviewed-by: Dmitri Shuralyov <dmitshur@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Bryan Mills <bcmills@google.com>
(cherry picked from commit a334c45273)
Reviewed-on: https://go-review.googlesource.com/c/go/+/546022
2023-12-08 18:47:59 +00:00
Michael Pratt
7dc67e8f29 [release-branch.go1.21] os/signal: remove go t.Run from TestNohup
Since CL 226138, TestNohup has a bit of a strange construction: it wants
to run the "uncaught" subtests in parallel with each other, and the
"nohup" subtests in parallel with each other, but also needs join
between "uncaught" and "nohop" so it can Stop notifying for SIGHUP.

It achieves this by doing `go t.Run` with a WaitGroup rather than using
`t.Parallel` in the subtest (which would make `t.Run` return immediately).

However, this makes things more difficult to understand than necessary.
As noted on https://pkg.go.dev/testing#hdr-Subtests_and_Sub_benchmarks,
a second layer of subtest can be used to join parallel subtests.

Switch to this form, which makes the test simpler to follow
(particularly the cleanup that goes with "uncaught").

For #63799.
For #63911.

Change-Id: Ibfce0f439508a7cfca848c7ccfd136c9c453ad8b
Reviewed-on: https://go-review.googlesource.com/c/go/+/538899
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Bryan Mills <bcmills@google.com>
(cherry picked from commit 5622a4b205)
Reviewed-on: https://go-review.googlesource.com/c/go/+/546021
2023-12-07 20:35:27 +00:00
Matthew Dempsky
9f8b3ac8c4 [release-branch.go1.21] cmd/compile: fix escape analysis of string min/max
When I was plumbing min/max support through the compiler, I was
thinking mostly about numeric argument types. As a result, I forgot
that escape analysis would need to be aware that min/max can operate
on string values, which contain pointers.

Updates #64565.
Fixes #64567.

Change-Id: I36127ce5a2da942401910fa0f9de922726c9f94d
Reviewed-on: https://go-review.googlesource.com/c/go/+/547715
Reviewed-by: Keith Randall <khr@google.com>
Reviewed-by: Mauri de Souza Meneguzzo <mauri870@gmail.com>
Auto-Submit: Matthew Dempsky <mdempsky@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
(cherry picked from commit 34416d7f6f)
Reviewed-on: https://go-review.googlesource.com/c/go/+/547757
Reviewed-by: Cuong Manh Le <cuong.manhle.vn@gmail.com>
Reviewed-by: Keith Randall <khr@golang.org>
2023-12-06 21:31:12 +00:00
Keith Randall
8c840b10d0 [release-branch.go1.21] cmd/compile: fix memcombine pass for big endian, > 1 byte elements
The shift amounts were wrong in this case, leading to miscompilation
of load combining.

Also the store combining was not triggering when it should.

Fixes #64472

Change-Id: Iaeb08972c5fc1d6f628800334789c6af7216e87b
Reviewed-on: https://go-review.googlesource.com/c/go/+/546355
Reviewed-by: David Chase <drchase@google.com>
Reviewed-by: Mauri de Souza Meneguzzo <mauri870@gmail.com>
Reviewed-by: Keith Randall <khr@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-on: https://go-review.googlesource.com/c/go/+/546356
2023-12-06 21:29:58 +00:00
Gopher Robot
6018ad99a4 [release-branch.go1.21] go1.21.5
Change-Id: I203463900d2c63bc398c22593d0908c4f33a6990
Reviewed-on: https://go-review.googlesource.com/c/go/+/547416
Reviewed-by: Carlos Amedee <carlos@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Gopher Robot <gobot@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
2023-12-05 18:12:56 +00:00
Damien Neil
ec8c526e4b [release-branch.go1.21] net/http: limit chunked data overhead
The chunked transfer encoding adds some overhead to
the content transferred. When writing one byte per
chunk, for example, there are five bytes of overhead
per byte of data transferred: "1\r\nX\r\n" to send "X".

Chunks may include "chunk extensions",
which we skip over and do not use.
For example: "1;chunk extension here\r\nX\r\n".

A malicious sender can use chunk extensions to add
about 4k of overhead per byte of data.
(The maximum chunk header line size we will accept.)

Track the amount of overhead read in chunked data,
and produce an error if it seems excessive.

Updates #64433
Fixes #64435
Fixes CVE-2023-39326

Change-Id: I40f8d70eb6f9575fb43f506eb19132ccedafcf39
Reviewed-on: https://team-review.git.corp.google.com/c/golang/go-private/+/2076135
Reviewed-by: Tatiana Bradley <tatianabradley@google.com>
Reviewed-by: Roland Shoemaker <bracewell@google.com>
(cherry picked from commit 3473ae72ee66c60744665a24b2fde143e8964d4f)
Reviewed-on: https://team-review.git.corp.google.com/c/golang/go-private/+/2095408
Run-TryBot: Roland Shoemaker <bracewell@google.com>
Reviewed-by: Damien Neil <dneil@google.com>
Reviewed-on: https://go-review.googlesource.com/c/go/+/547356
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2023-12-05 17:18:23 +00:00
Jorropo
f7a79cb5fc [release-branch.go1.21] cmd/compile: fix findIndVar so it does not match disjointed loop headers
Fix #63984

parseIndVar, prove and maybe more are on the assumption that the loop header
is a single block. This can be wrong, ensure we don't match theses cases we
don't know how to handle.

In the future we could update them so that they know how to handle such cases
but theses cases seems rare so I don't think the value would be really high.
We could also run a loop canonicalization pass first which could handle this.

The repro case looks weird because I massaged it so it would crash with the
previous compiler.

Change-Id: I4aa8afae9e90a17fa1085832250fc1139c97faa6
Reviewed-on: https://go-review.googlesource.com/c/go/+/539977
Reviewed-by: Heschi Kreinick <heschi@google.com>
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>
(cherry picked from commit 8b4e1259d0)
Reviewed-on: https://go-review.googlesource.com/c/go/+/540535
Reviewed-by: Jorropo <jorropo.pgm@gmail.com>
Reviewed-by: Mauri de Souza Meneguzzo <mauri870@gmail.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@golang.org>
Auto-Submit: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Michael Knyszek <mknyszek@google.com>
2023-11-28 20:12:59 +00:00
Michael Anthony Knyszek
3684d19c20 [release-branch.go1.21] runtime: call enableMetadataHugePages and its callees on the systemstack
These functions acquire the heap lock. If they're not called on the
systemstack, a stack growth could cause a self-deadlock since stack
growth may allocate memory from the page heap.

This has been a problem for a while. If this is what's plaguing the
ppc64 port right now, it's very surprising (and probably just
coincidental) that it's showing up now.

For #64050.
For #64062.
For #64067.
Fixes #64073.

Change-Id: I2b95dc134d17be63b9fe8f7a3370fe5b5438682f
Reviewed-on: https://go-review.googlesource.com/c/go/+/541635
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Run-TryBot: Michael Knyszek <mknyszek@google.com>
Auto-Submit: Michael Knyszek <mknyszek@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Michael Pratt <mpratt@google.com>
Reviewed-by: Paul Murphy <murp@ibm.com>
(cherry picked from commit 5f08b44799)
Reviewed-on: https://go-review.googlesource.com/c/go/+/541955
Reviewed-by: Dmitri Shuralyov <dmitshur@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Auto-Submit: Dmitri Shuralyov <dmitshur@google.com>
2023-11-28 18:46:34 +00:00
Roland Shoemaker
9e43850a32 [release-branch.go1.21] crypto/rand,runtime: switch RtlGenRandom for ProcessPrng
RtlGenRandom is a semi-undocumented API, also known as
SystemFunction036, which we use to generate random data on Windows.
It's definition, in cryptbase.dll, is an opaque wrapper for the
documented API ProcessPrng. Instead of using RtlGenRandom, switch to
using ProcessPrng, since the former is simply a wrapper for the latter,
there should be no practical change on the user side, other than a minor
change in the DLLs we load.

Updates #53192
Fixes #64413

Change-Id: Ie6891bf97b1d47f5368cccbe92f374dba2c2672a
Reviewed-on: https://go-review.googlesource.com/c/go/+/536235
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Quim Muntal <quimmuntal@gmail.com>
Auto-Submit: Roland Shoemaker <roland@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
(cherry picked from commit 693def151a)
Reviewed-on: https://go-review.googlesource.com/c/go/+/545355
Auto-Submit: Dmitri Shuralyov <dmitshur@google.com>
2023-11-28 17:48:47 +00:00
Damien Neil
8caf4bb3e7 [release-branch.go1.21] path/filepath: consider \\?\c: as a volume on Windows
While fixing several bugs in path handling on Windows,
beginning with \\?\.

Prior to #540277, VolumeName considered the first path component
after the \\?\ prefix to be part of the volume name.
After, it considered only the \\? prefix to be the volume name.

Restore the previous behavior.

For #64028.
Fixes #64041.

Change-Id: I6523789e61776342800bd607fb3f29d496257e68
Reviewed-on: https://go-review.googlesource.com/c/go/+/541175
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Roland Shoemaker <roland@golang.org>
(cherry picked from commit eda42f7c60)
Reviewed-on: https://go-review.googlesource.com/c/go/+/541521
Reviewed-by: Damien Neil <dneil@google.com>
Auto-Submit: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
2023-11-28 16:59:27 +00:00
Bryan C. Mills
23c943e529 [release-branch.go1.21] cmd/go/internal/vcs: error out if the requested repo does not support a secure protocol
Updates #63845.
Fixes #63973.

Change-Id: If86d6b13d3b55877b35c087112bd76388c9404b8
Reviewed-on: https://go-review.googlesource.com/c/go/+/539321
Reviewed-by: Michael Matloob <matloob@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Roland Shoemaker <roland@golang.org>
Auto-Submit: Bryan Mills <bcmills@google.com>
(cherry picked from commit be26ae18ca)
Reviewed-on: https://go-review.googlesource.com/c/go/+/540257
Auto-Submit: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
2023-11-27 21:12:17 +00:00
Bryan C. Mills
4952f41180 [release-branch.go1.21] cmd/go: allow 'go mod download' to switch toolchains if called with explicit arguments
Fixes #62055.
Updates #62054.

Change-Id: I4ea24070f7d9aa4964c2f215836602068058f718
(cherry picked from CL 540779 and CL 537480)
Reviewed-on: https://go-review.googlesource.com/c/go/+/539697
Auto-Submit: Heschi Kreinick <heschi@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Michael Matloob <matloob@golang.org>
2023-11-09 21:37:26 +00:00
Bryan C. Mills
f26fa05522 [release-branch.go1.21] os: report IO_REPARSE_TAG_DEDUP files as regular in Stat and Lstat
Prior to CL 460595, Lstat reported most reparse points as regular
files. However, reparse points can in general implement unusual
behaviors (consider IO_REPARSE_TAG_AF_UNIX or IO_REPARSE_TAG_LX_CHR),
and Windows allows arbitrary user-defined reparse points, so in
general we must not assume that an unrecognized reparse tag represents
a regular file; in CL 460595, we began marking them as irregular.

As it turns out, the Data Deduplication service on Windows Server runs
an Optimization job that turns regular files into reparse files with
the tag IO_REPARSE_TAG_DEDUP. Those files still behave more-or-less
like regular files, in that they have well-defined sizes and support
random-access reads and writes, so most programs can treat them as
regular files without difficulty. However, they are still reparse
files: as a result, on servers with the Data Deduplication service
enabled, files could arbitrarily change from “regular” to “irregular”
without explicit user intervention.

Since dedup files are converted in the background and otherwise behave
like regular files, this change adds a special case to report DEDUP
reparse points as regular.

Fixes #63764.
Updates #63429.

No test because to my knowledge we don't have any Windows builders
that have the deduplication service enabled, nor do we have a way to
reliably guarantee the existence of an IO_REPARSE_TAG_DEDUP file.

(In theory we could add a builder with the service enabled on a
specific volume, write a test that encodes knowledge of that volume,
and use the GO_BUILDER_NAME environment variable to run that test only
on the specially-configured builders. However, I don't currently have
the bandwidth to reconfigure the builders in this way, and given the
simplicity of the change I think it is unlikely to regress
accidentally.)

Change-Id: I649e7ef0b67e3939a980339ce7ec6a20b31b23a1
Cq-Include-Trybots: luci.golang.try:go1.21-windows-amd64-longtest
Reviewed-on: https://go-review.googlesource.com/c/go/+/538218
Reviewed-by: Alex Brainman <alex.brainman@gmail.com>
Reviewed-by: David Chase <drchase@google.com>
Auto-Submit: Heschi Kreinick <heschi@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2023-11-08 18:13:06 +00:00
Andy Pan
8ae493b5b8 [release-branch.go1.21] internal/poll: add SPLICE_F_NONBLOCK flag for splice to avoid inconsistency with O_NONBLOCK
Fixes #63801
Updates #59041
Updates #63795

Details: https://github.com/golang/go/issues/59041#issuecomment-1766610087

Change-Id: Id3fc1df6d86b7c4cc383d09f9465fa8f4cc2a559
Reviewed-on: https://go-review.googlesource.com/c/go/+/536015
Reviewed-by: Bryan Mills <bcmills@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>
(cherry picked from commit 40cdf69fc9)
Reviewed-on: https://go-review.googlesource.com/c/go/+/538117
Auto-Submit: Heschi Kreinick <heschi@google.com>
Reviewed-by: Mauri de Souza Meneguzzo <mauri870@gmail.com>
Reviewed-by: Heschi Kreinick <heschi@google.com>
2023-11-08 18:02:42 +00:00
Keith Randall
b9f245b8d3 [release-branch.go1.21] cmd/compile: ensure pointer arithmetic happens after the nil check
Have nil checks return a pointer that is known non-nil. Users of
that pointer can use the result, ensuring that they are ordered
after the nil check itself.

The order dependence goes away after scheduling, when we've fixed
an order. At that point we move uses back to the original pointer
so it doesn't change regalloc any.

This prevents pointer arithmetic on nil from being spilled to the
stack and then observed by a stack scan.

Fixes #63743

Change-Id: I1a5fa4f2e6d9000d672792b4f90dfc1b7b67f6ea
Reviewed-on: https://go-review.googlesource.com/c/go/+/537775
Reviewed-by: David Chase <drchase@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Keith Randall <khr@google.com>
(cherry picked from commit 962ccbef91)
Reviewed-on: https://go-review.googlesource.com/c/go/+/538717
Auto-Submit: Heschi Kreinick <heschi@google.com>
Reviewed-by: Heschi Kreinick <heschi@google.com>
2023-11-07 21:29:46 +00:00
Keith Randall
caacf3a09a [release-branch.go1.21] cmd/compile: handle constant pointer offsets in dead store elimination
Update #63743

Change-Id: I163c6038c13d974dc0ca9f02144472bc05331826
Reviewed-on: https://go-review.googlesource.com/c/go/+/538595
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: David Chase <drchase@google.com>
Reviewed-by: Keith Randall <khr@google.com>
(cherry picked from commit 43b57b8516)
Reviewed-on: https://go-review.googlesource.com/c/go/+/538857
Auto-Submit: Heschi Kreinick <heschi@google.com>
Reviewed-by: Heschi Kreinick <heschi@google.com>
2023-11-07 21:29:17 +00:00
Dmitri Shuralyov
1e91861f67 [release-branch.go1.21] syscall: copy rlimit.go's build constraint to rlimit_test.go
Tests in rlimit_test.go exist to test the behavior of automatically
bumping RLIMIT_NOFILE on Unix implemented in rlimit.go (issue #46279),
with darwin-specific behavior split out into rlimit_darwin.go and
the rest left empty in rlimit_stub.go.

Since the behavior happens only on Unix, it doesn't make sense to test
it on other platforms. Copy rlimit.go's 'unix' build constraint to
rlimit_test.go to accomplish that.

Leave out the simplification of the build constraint in rlimit_stub.go
so that this CL remains a test-only fix.

In particular, this fixes a problem where TestOpenFileLimit was
failing in some environments when testing the wasip1/wasm port.
The RLIMIT_NOFILE bumping behavior isn't implemented there, so
the test was testing the environment and not the Go project.

Updates #46279.
For #61116.
Fixes #63994.

Change-Id: Ic993f9cfc021d4cda4fe3d7fed8e2e180f78a2ca
Cq-Include-Trybots: luci.golang.try:go1.21-wasip1-wasm_wasmtime
Reviewed-on: https://go-review.googlesource.com/c/go/+/539435
Reviewed-by: Johan Brandhorst-Satzkorn <johan.brandhorst@gmail.com>
Reviewed-by: Bryan Mills <bcmills@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Auto-Submit: Dmitri Shuralyov <dmitshur@golang.org>
(cherry picked from commit b7cbcf0c27)
Reviewed-on: https://go-review.googlesource.com/c/go/+/540615
Reviewed-by: Heschi Kreinick <heschi@google.com>
Auto-Submit: Heschi Kreinick <heschi@google.com>
2023-11-07 20:32:49 +00:00
Gopher Robot
ed817f1c40 [release-branch.go1.21] go1.21.4
Change-Id: I3d607ba9f701a76a46f3ab3223fa83e5c517d285
Reviewed-on: https://go-review.googlesource.com/c/go/+/540517
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Gopher Robot <gobot@golang.org>
Reviewed-by: Heschi Kreinick <heschi@google.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
2023-11-07 17:38:04 +00:00
Damien Neil
9e933c189c [release-branch.go1.21] path/filepath: fix various issues in parsing Windows paths
On Windows, A root local device path is a path which begins with
\\?\ or \??\.  A root local device path accesses the DosDevices
object directory, and permits access to any file or device on the
system. For example \??\C:\foo is equivalent to common C:\foo.

The Clean, IsAbs, IsLocal, and VolumeName functions did not
recognize root local device paths beginning with \??\.

Clean could convert a rooted path such as \a\..\??\b into
the root local device path \??\b. It will now convert this
path into .\??\b.

IsAbs now correctly reports paths beginning with \??\
as absolute.

IsLocal now correctly reports paths beginning with \??\
as non-local.

VolumeName now reports the \??\ prefix as a volume name.

Join(`\`, `??`, `b`) could convert a seemingly innocent
sequence of path elements into the root local device path
\??\b. It will now convert this to \.\??\b.

In addition, the IsLocal function did not correctly
detect reserved names in some cases:

  - reserved names followed by spaces, such as "COM1 ".
  - "COM" or "LPT" followed by a superscript 1, 2, or 3.

IsLocal now correctly reports these names as non-local.

For #63713
Fixes #63715
Fixes CVE-2023-45283
Fixes CVE-2023-45284

Change-Id: I446674a58977adfa54de7267d716ac23ab496c54
Reviewed-on: https://team-review.git.corp.google.com/c/golang/go-private/+/2040691
Reviewed-by: Roland Shoemaker <bracewell@google.com>
Reviewed-by: Tatiana Bradley <tatianabradley@google.com>
Run-TryBot: Damien Neil <dneil@google.com>
Reviewed-on: https://team-review.git.corp.google.com/c/golang/go-private/+/2072596
Reviewed-by: Cherry Mui <cherryyz@google.com>
Reviewed-on: https://go-review.googlesource.com/c/go/+/540276
Auto-Submit: Heschi Kreinick <heschi@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2023-11-07 16:36:54 +00:00
Mauri de Souza Meneguzzo
434af8537e [release-branch.go1.21] net/http: pull http2 underflow fix from x/net/http2
After CL 534295 was merged to fix a CVE it introduced
an underflow when we try to decrement sc.curHandlers
in handlerDone.

Pull in a fix from x/net/http2:
http2: fix underflow in http2 server push
https://go-review.googlesource.com/c/net/+/535595

For #63511
Fixes #63560

Change-Id: I5c678ce7dcc53635f3ad5e4999857cb120dfc1ab
GitHub-Last-Rev: 587ffa3caf
GitHub-Pull-Request: golang/go#63561
Reviewed-on: https://go-review.googlesource.com/c/go/+/535575
Run-TryBot: Mauri de Souza Meneguzzo <mauri870@gmail.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: David Chase <drchase@google.com>
Auto-Submit: Dmitri Shuralyov <dmitshur@golang.org>
TryBot-Result: Gopher Robot <gobot@golang.org>
(cherry picked from commit 0046c1414c)
Reviewed-on: https://go-review.googlesource.com/c/go/+/537996
Reviewed-by: Cherry Mui <cherryyz@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2023-10-30 21:11:25 +00:00
Cherry Mui
7b04d81cbc [release-branch.go1.21] runtime/cgo: avoid taking the address of crosscall2 in code
Currently, set_crosscall2 takes the address of crosscall2 without
using the GOT, which, on some architectures, results in a
PC-relative relocation (e.g. R_AARCH64_ADR_PREL_PG_HI21 on ARM64)
to the crosscall2 symbol. But crosscall2 is dynamically exported,
so the C linker thinks it may bind to a symbol from a different
DSO. Some C linker may not like a PC-relative relocation to such a
symbol. Using a local trampoline to avoid taking the address of a
dynamically exported symbol.

It may be possible to not dynamically export crosscall2. But this
CL is safer for backport. Later we may remove the trampolines
after unexport crosscall2, if they are not needed.

Fixes #63509.
Updates #62556.

Change-Id: Id28457f65ef121d3f87d8189803abc65ed453283
Reviewed-on: https://go-review.googlesource.com/c/go/+/533535
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Ian Lance Taylor <iant@google.com>
(cherry picked from commit 872d7181f4)
Reviewed-on: https://go-review.googlesource.com/c/go/+/534915
Reviewed-by: David Chase <drchase@google.com>
2023-10-30 20:36:26 +00:00
Matthew Dempsky
f9a31cda3c [release-branch.go1.21] cmd/compile/internal/typecheck: fix closure field naming
When creating the struct type to hold variables captured by a function
literal, we currently reuse the captured variable names as fields.

However, there's no particular reason to do this: these struct types
aren't visible to users, and it adds extra complexity in making sure
fields belong to the correct packages.

Further, it turns out we were getting that subtly wrong. If two
function literals from different packages capture variables with
identical names starting with an uppercase letter (and in the same
order and with corresponding identical types) end up in the same
function (e.g., due to inlining), then we could end up creating
closure struct types that are "different" (i.e., not types.Identical)
yet end up with equal LinkString representations (which violates
LinkString's contract).

The easy fix is to just always use simple, exported, generated field
names in the struct. This should allow further struct reuse across
packages too, and shrink binary sizes slightly.

For #62498.
Fixes #62545.

Change-Id: I9c973f5087bf228649a8f74f7dc1522d84a26b51
Reviewed-on: https://go-review.googlesource.com/c/go/+/527135
Auto-Submit: Matthew Dempsky <mdempsky@google.com>
Reviewed-by: Cuong Manh Le <cuong.manhle.vn@gmail.com>
Reviewed-by: Keith Randall <khr@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
(cherry picked from commit e3ce312621)
Reviewed-on: https://go-review.googlesource.com/c/go/+/534916
Reviewed-by: Matthew Dempsky <mdempsky@google.com>
Auto-Submit: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
2023-10-13 16:12:31 +00:00
Robert Griesemer
64b6c48107 [release-branch.go1.21] go/types, types2: don't use generics
This fixes cherry-pick CL 531998.

For #63339.

Change-Id: I6dac0909ca85d68684ce36025284d25db32e0b15
Reviewed-on: https://go-review.googlesource.com/c/go/+/535135
Auto-Submit: Dmitri Shuralyov <dmitshur@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Alan Donovan <adonovan@google.com>
2023-10-13 15:10:45 +00:00
Michael Anthony Knyszek
ef6993f327 [release-branch.go1.21] runtime: don't eagerly collapse hugepages
This has caused performance issues in production environments.

MADV_COLLAPSE can go into direct reclaim, but we call it with the heap
lock held. This means that the process could end up stalled fairly
quickly if just one allocating goroutine ends up in the madvise call, at
least until the madvise(MADV_COLLAPSE) call returns. A similar issue
occurred with madvise(MADV_HUGEPAGE), because that could go into direct
reclaim on any page fault for MADV_HUGEPAGE-marked memory.

My understanding was that the calls to madvise(MADV_COLLAPSE) were
fairly rare, and it's "best-effort" nature prevented it from going into
direct reclaim often, but this was wrong. It tends to be fairly
heavyweight even when it doesn't end up in direct reclaim, and it's
almost certainly not worth it.

Disable it until further notice and let the kernel fully dictate
hugepage policy. The updated scavenger policy is still more hugepage
friendly by delaying scavening until hugepages are no longer densely
packed, so we don't lose all that much.

The Sweet benchmarks show a minimal difference. A couple less realistic
benchmarks seem to slow down a bit; they might just be getting unlucky
with what the kernel decides to back with a huge page. Some benchmarks
on the other hand improve. Overall, it's a wash.

name                  old time/op            new time/op            delta
BiogoIgor                        13.1s ± 1%             13.2s ± 2%    ~     (p=0.182 n=9+10)
BiogoKrishna                     12.0s ± 1%             12.1s ± 1%  +1.23%  (p=0.002 n=9+10)
BleveIndexBatch100               4.51s ± 4%             4.56s ± 3%    ~     (p=0.393 n=10+10)
EtcdPut                         20.2ms ± 4%            19.8ms ± 2%    ~     (p=0.079 n=10+9)
EtcdSTM                          109ms ± 3%             111ms ± 3%  +1.63%  (p=0.035 n=10+10)
GoBuildKubelet                   31.2s ± 1%             31.3s ± 1%    ~     (p=0.780 n=9+10)
GoBuildKubeletLink               7.77s ± 0%             7.81s ± 2%    ~     (p=0.237 n=8+10)
GoBuildIstioctl                  31.8s ± 1%             31.7s ± 0%    ~     (p=0.136 n=9+9)
GoBuildIstioctlLink              7.88s ± 1%             7.89s ± 1%    ~     (p=0.720 n=9+10)
GoBuildFrontend                  11.7s ± 1%             11.8s ± 1%    ~     (p=0.278 n=10+9)
GoBuildFrontendLink              1.15s ± 4%             1.15s ± 5%    ~     (p=0.387 n=9+9)
GopherLuaKNucleotide             19.7s ± 1%             20.6s ± 0%  +4.48%  (p=0.000 n=10+10)
MarkdownRenderXHTML              194ms ± 3%             196ms ± 3%    ~     (p=0.356 n=9+10)
Tile38QueryLoad                  633µs ± 2%             629µs ± 2%    ~     (p=0.075 n=10+10)

name                  old average-RSS-bytes  new average-RSS-bytes  delta
BiogoIgor                       69.2MB ± 3%            68.4MB ± 1%    ~     (p=0.190 n=10+10)
BiogoKrishna                    4.40GB ± 0%            4.40GB ± 0%    ~     (p=0.605 n=9+9)
BleveIndexBatch100               195MB ± 3%             195MB ± 2%    ~     (p=0.853 n=10+10)
EtcdPut                          107MB ± 4%             108MB ± 3%    ~     (p=0.190 n=10+10)
EtcdSTM                         91.6MB ± 5%            92.6MB ± 4%    ~     (p=0.481 n=10+10)
GoBuildKubelet                  2.26GB ± 1%            2.28GB ± 1%  +1.22%  (p=0.000 n=10+10)
GoBuildIstioctl                 1.53GB ± 0%            1.53GB ± 0%  +0.21%  (p=0.017 n=9+10)
GoBuildFrontend                  556MB ± 1%             554MB ± 2%    ~     (p=0.497 n=9+10)
GopherLuaKNucleotide            39.0MB ± 3%            39.0MB ± 1%    ~     (p=1.000 n=10+8)
MarkdownRenderXHTML             21.2MB ± 2%            21.4MB ± 3%    ~     (p=0.190 n=10+10)
Tile38QueryLoad                 5.99GB ± 2%            6.02GB ± 0%    ~     (p=0.243 n=10+9)

name                  old peak-RSS-bytes     new peak-RSS-bytes     delta
BiogoIgor                       90.2MB ± 4%            89.2MB ± 2%    ~     (p=0.143 n=10+10)
BiogoKrishna                    4.49GB ± 0%            4.49GB ± 0%    ~     (p=0.190 n=10+10)
BleveIndexBatch100               283MB ± 8%             274MB ± 6%    ~     (p=0.075 n=10+10)
EtcdPut                          147MB ± 4%             149MB ± 2%  +1.55%  (p=0.034 n=10+8)
EtcdSTM                          117MB ± 5%             117MB ± 4%    ~     (p=0.905 n=9+10)
GopherLuaKNucleotide            44.9MB ± 1%            44.6MB ± 1%    ~     (p=0.083 n=8+8)
MarkdownRenderXHTML             22.0MB ± 8%            22.1MB ± 9%    ~     (p=0.436 n=10+10)
Tile38QueryLoad                 6.24GB ± 2%            6.29GB ± 2%    ~     (p=0.218 n=10+10)

name                  old peak-VM-bytes      new peak-VM-bytes      delta
BiogoIgor                       1.33GB ± 0%            1.33GB ± 0%    ~     (p=0.504 n=10+9)
BiogoKrishna                    5.77GB ± 0%            5.77GB ± 0%    ~     (p=1.000 n=10+9)
BleveIndexBatch100              3.53GB ± 0%            3.53GB ± 0%    ~     (p=0.642 n=10+10)
EtcdPut                         12.1GB ± 0%            12.1GB ± 0%    ~     (p=0.564 n=10+10)
EtcdSTM                         12.1GB ± 0%            12.1GB ± 0%    ~     (p=0.633 n=10+10)
GopherLuaKNucleotide            1.26GB ± 0%            1.26GB ± 0%    ~     (p=0.297 n=9+10)
MarkdownRenderXHTML             1.26GB ± 0%            1.26GB ± 0%    ~     (p=0.069 n=10+10)
Tile38QueryLoad                 7.47GB ± 2%            7.53GB ± 2%    ~     (p=0.280 n=10+10)

name                  old p50-latency-ns     new p50-latency-ns     delta
EtcdPut                          19.8M ± 5%             19.3M ± 3%  -2.74%  (p=0.043 n=10+9)
EtcdSTM                          81.4M ± 4%             83.4M ± 4%  +2.46%  (p=0.029 n=10+10)
Tile38QueryLoad                   241k ± 1%              240k ± 1%    ~     (p=0.393 n=10+10)

name                  old p90-latency-ns     new p90-latency-ns     delta
EtcdPut                          30.4M ± 5%             30.6M ± 5%    ~     (p=0.971 n=10+10)
EtcdSTM                           222M ± 3%              226M ± 4%    ~     (p=0.063 n=10+10)
Tile38QueryLoad                   687k ± 2%              691k ± 1%    ~     (p=0.173 n=10+8)

name                  old p99-latency-ns     new p99-latency-ns     delta
EtcdPut                          42.3M ±10%             41.4M ± 7%    ~     (p=0.353 n=10+10)
EtcdSTM                           486M ± 7%              487M ± 4%    ~     (p=0.579 n=10+10)
Tile38QueryLoad                  6.43M ± 2%             6.37M ± 3%    ~     (p=0.280 n=10+10)

name                  old ops/s              new ops/s              delta
EtcdPut                          48.6k ± 3%             49.5k ± 2%    ~     (p=0.065 n=10+9)
EtcdSTM                          9.09k ± 2%             8.95k ± 3%  -1.56%  (p=0.045 n=10+10)
Tile38QueryLoad                  28.4k ± 1%             28.6k ± 1%  +0.87%  (p=0.016 n=9+10)

Fixes #63335.
For #63334.
Related to #61718 and #59960.

Change-Id: If84c5a8685825d43c912a71418f2597e44e867e5
Reviewed-on: https://go-review.googlesource.com/c/go/+/531816
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>
(cherry picked from commit 595deec3dd)
Reviewed-on: https://go-review.googlesource.com/c/go/+/532255
Auto-Submit: Dmitri Shuralyov <dmitshur@google.com>
2023-10-12 23:27:00 +00:00
Robert Griesemer
bae01521f3 [release-branch.go1.21] go/types, types2: don't implicitly modify an argument function's type
See the comment in the (very small) fix for a detailed description.
Use the opportunity to introduce a generic clone function which may
be useful elsewhere.

Fixes #63339.

Change-Id: Ic63c6b8bc443011b1a201908254f7d062e1aec71
Reviewed-on: https://go-review.googlesource.com/c/go/+/532157
Run-TryBot: Robert Griesemer <gri@google.com>
Reviewed-by: Robert Findley <rfindley@google.com>
Reviewed-by: Robert Griesemer <gri@google.com>
Auto-Submit: Robert Griesemer <gri@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-on: https://go-review.googlesource.com/c/go/+/531998
Auto-Submit: Dmitri Shuralyov <dmitshur@google.com>
2023-10-12 23:16:08 +00:00
Than McIntosh
236c07c049 [release-branch.go1.21] cmd/link: split text sections for arm 32-bit
This CL is a roll-forward (tweaked slightly) of CL 467715, which
turned on text section splitting for GOARCH=arm. The intent is to
avoid recurrent problems with external linking where there is a
disagreement between the Go linker and the external linker over
whether a given branch will reach. In the past our approach has been
to tweak the reachability calculations slightly to try to work around
potential linker problems, but this hasn't proven to be very robust;
section splitting seems to offer a better long term fix.

Updates #58425.
Fixes #63317.

Change-Id: I7372d41abce84097906a3d0805b6b9c486f345d6
Reviewed-on: https://go-review.googlesource.com/c/go/+/531795
Reviewed-by: Cherry Mui <cherryyz@google.com>
Run-TryBot: Than McIntosh <thanm@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
(cherry picked from commit 1e69040920)
Reviewed-on: https://go-review.googlesource.com/c/go/+/532096
Auto-Submit: Dmitri Shuralyov <dmitshur@google.com>
2023-10-12 22:36:36 +00:00
Dmitri Shuralyov
9465990e0e [release-branch.go1.21] all: tidy dependency versioning after release
Done with:

go get golang.org/x/net@internal-branch.go1.21-vendor
go mod tidy
go mod vendor
go generate net/http  # zero diff since CL 534235 already did this

For #63417.
For #63427.
For CVE-2023-39325.

Change-Id: Ib258e0d8165760a1082e02c2f4c5ce7d2a3c3c90
Reviewed-on: https://go-review.googlesource.com/c/go/+/534415
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Auto-Submit: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Michael Pratt <mpratt@google.com>
2023-10-10 18:10:52 +00:00
Gopher Robot
883f062fc0 [release-branch.go1.21] go1.21.3
Change-Id: Icdde32852b305006d7064cfe8bbe143128191842
Reviewed-on: https://go-review.googlesource.com/c/go/+/534337
TryBot-Bypass: Dmitri Shuralyov <dmitshur@google.com>
Commit-Queue: Gopher Robot <gobot@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Heschi Kreinick <heschi@google.com>
Auto-Submit: Gopher Robot <gobot@golang.org>
2023-10-10 16:31:03 +00:00
Damien Neil
24ae2d9272 [release-branch.go1.21] net/http: regenerate h2_bundle.go
Pull in a security fix from x/net/http2:
http2: limit maximum handler goroutines to MaxConcurrentStreamso

For #63417
Fixes #63427
Fixes CVE-2023-39325

Change-Id: I70626734e6d56edf508f27a5b055ddf96d806eeb
Reviewed-on: https://team-review.git.corp.google.com/c/golang/go-private/+/2047402
Reviewed-by: Tatiana Bradley <tatianabradley@google.com>
Run-TryBot: Damien Neil <dneil@google.com>
Reviewed-by: Ian Cottrell <iancottrell@google.com>
Reviewed-on: https://go-review.googlesource.com/c/go/+/534235
Auto-Submit: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Michael Pratt <mpratt@google.com>
Reviewed-by: Damien Neil <dneil@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2023-10-10 16:10:13 +00:00
Gopher Robot
26b5783b72 [release-branch.go1.21] go1.21.2
Change-Id: Ie06bc8d8e8e170f13ed938a33038931513eaf067
Reviewed-on: https://go-review.googlesource.com/c/go/+/533238
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: Dmitri Shuralyov <dmitshur@google.com>
2023-10-05 19:06:58 +00:00
Ian Lance Taylor
2ddfc04d12 [release-branch.go1.21] cmd/compile: use absolute file name in isCgo check
For #23672
Updates #63211
Fixes #63214
Fixes CVE-2023-39323

Change-Id: I4586a69e1b2560036afec29d53e53cf25e6c7352
Reviewed-on: https://team-review.git.corp.google.com/c/golang/go-private/+/2032884
Reviewed-by: Matthew Dempsky <mdempsky@google.com>
Reviewed-by: Roland Shoemaker <bracewell@google.com>
(cherry picked from commit 9b19e751918dd218035811b1ef83a8c2693b864a)
Reviewed-on: https://team-review.git.corp.google.com/c/golang/go-private/+/2037958
Reviewed-by: Damien Neil <dneil@google.com>
Reviewed-by: Tatiana Bradley <tatianabradley@google.com>
Run-TryBot: Roland Shoemaker <bracewell@google.com>
Reviewed-on: https://go-review.googlesource.com/c/go/+/533215
Reviewed-by: Than McIntosh <thanm@google.com>
Auto-Submit: Michael Pratt <mpratt@google.com>
Reviewed-by: Ian Lance Taylor <iant@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2023-10-05 18:07:27 +00:00
Keith Randall
a15ef1bb0f [release-branch.go1.21] cmd/compile: absorb InvertFlags into Noov comparisons
Unfortunately, there isn't a single op that provides the resulting
computation.
At least, I couldn't find one.

Fixes #62506

Change-Id: I236f3965b827aaeb3d70ef9fe89be66b116494f5
Reviewed-on: https://go-review.googlesource.com/c/go/+/526276
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
Reviewed-by: Keith Randall <khr@google.com>
(cherry picked from commit fb5bdb4cc9)
Reviewed-on: https://go-review.googlesource.com/c/go/+/526521
Reviewed-by: Than McIntosh <thanm@google.com>
2023-09-25 15:53:16 +00:00
Keith Randall
41d71a5afa [release-branch.go1.21] cmd/compile: reset memcombine correctly between basic blocks
Not sure why this bug didn't cause a complete failure, but it
certainly makes for doing a lot more work than is necessary.

Fixes #62668

Change-Id: If0be4acb6eafc3d7eeb42d2f4263c21b4e6e1c7d
Reviewed-on: https://go-review.googlesource.com/c/go/+/527699
Reviewed-by: David Chase <drchase@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Heschi Kreinick <heschi@google.com>
(cherry picked from commit 08cdfd06ed)
Reviewed-on: https://go-review.googlesource.com/c/go/+/528795
Reviewed-by: Keith Randall <khr@google.com>
2023-09-25 13:05:39 +00:00
Michael Anthony Knyszek
0b6b0a275a [release-branch.go1.21] runtime: always lock OS thread in debugcall
Right now debuggers like Delve rely on the new goroutine created to run
a debugcall function to run on the same thread it started on, up until
it hits itself with a SIGINT as part of the debugcall protocol.

That's all well and good, except debugCallWrap1 isn't particularly
careful about not growing the stack. For example, if the new goroutine
happens to have a stale preempt flag, then it's possible a stack growth
will cause a roundtrip into the scheduler, possibly causing the
goroutine to switch to another thread.

Previous attempts to just be more careful around debugCallWrap1 were
helpful, but insufficient. This change takes everything a step further
and always locks the debug call goroutine and the new goroutine it
creates to the OS thread.

For #61732.
Fixes #62509.

Change-Id: I038f3a4df30072833e27e6a5a1ec01806a32891f
Reviewed-on: https://go-review.googlesource.com/c/go/+/515637
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Alessandro Arzilli <alessandro.arzilli@gmail.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
(cherry picked from commit d9a4b24a17)
Reviewed-on: https://go-review.googlesource.com/c/go/+/526576
2023-09-25 13:03:10 +00:00
Cherry Mui
cd671a1180 [release-branch.go1.21] runtime: increase g0 stack size in non-cgo case
Currently, for non-cgo programs, the g0 stack size is 8 KiB on
most platforms. With PGO which could cause aggressive inlining in
the runtime, the runtime stack frames are larger and could
overflow the 8 KiB g0 stack. Increase it to 16 KiB. This is only
one per OS thread, so it shouldn't increase memory use much.

Updates #62120.
Updates #62489.
Fixes #62537.

Change-Id: I565b154517021f1fd849424dafc3f0f26a755cac
Reviewed-on: https://go-review.googlesource.com/c/go/+/526995
Reviewed-by: Michael Pratt <mpratt@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
(cherry picked from commit c6d550a668)
Reviewed-on: https://go-review.googlesource.com/c/go/+/527055
2023-09-22 18:58:01 +00:00
Cherry Mui
fc57cc31a0 [release-branch.go1.21] cmd/link: suppress -bind_at_load deprecation warning for ld-prime
ld-prime emits a deprecation warning for -bind_at_load. The flag
is needed for plugins to not deadlock (#38824) when linking with
older darwin linker. It is supposedly not needed with newer linker
when chained fixups are used. For now, we always pass it, and
suppress the warning.

Updates #61229.
For #62598.

Change-Id: I4b8a6f864a460c40dc38adbb533f664f7fd5343c
Reviewed-on: https://go-review.googlesource.com/c/go/+/508696
Reviewed-by: Than McIntosh <thanm@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Run-TryBot: Cherry Mui <cherryyz@google.com>
(cherry picked from commit 040dbf9c18)
Reviewed-on: https://go-review.googlesource.com/c/go/+/527817
2023-09-21 22:22:44 +00:00
Cherry Mui
9bec49cf52 [release-branch.go1.21] cmd/link: disable DWARF by default in c-shared mode on darwin
[This is a (manual) backport of CL 527415 to Go 1.21.]

Currently, linking a Go c-shared object with C code using Apple's
new linker, it fails with

% cc a.c go.so
ld: segment '__DWARF' filesize exceeds vmsize in 'go.so'

Apple's new linker has more checks for unmapped segments. It is
very hard to make it accept a Mach-O shared object with an
additional DWARF segment.

We may want to stop combinding DWARF into the shared object (see
also #62577). For now, disable DWARF by default in c-shared mode
on darwin.

Updates #61229.
For #62598.

Change-Id: I525987b7fe1a4e64571327cb4696f98cc7b419a1
Reviewed-on: https://go-review.googlesource.com/c/go/+/527816
Reviewed-by: Than McIntosh <thanm@google.com>
Run-TryBot: Cherry Mui <cherryyz@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
2023-09-21 22:21:24 +00:00
Cherry Mui
3ef4f939c3 [release-branch.go1.21] cmd/link: force old Apple linker in plugin mode
There are some bugs in Apple's new linker that causes plugins to
be built incorrectly. And the bugs probably will not be fixed when
Xcode 15 is released (some time soon). Force old Apple linker to
work around.

Updates #61229.
For #62598.

Change-Id: I01ba5caadec6dc14f8c85dd02f78c1ed2e8b7d4d
Reviewed-on: https://go-review.googlesource.com/c/go/+/527815
Run-TryBot: Cherry Mui <cherryyz@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Than McIntosh <thanm@google.com>
2023-09-21 22:21:10 +00:00
Than McIntosh
556e9c36ba [release-branch.go1.21] cmd/link: avoid deadcode of global map vars for programs using plugins
If a program imports the plugin package, the mechanisms in place for
detecting and deleting unused global map variables are no longer safe,
since it's possibly for a given global map var to be unreferenced in
the main program but referenced by a plugin. This patch changes the
linker to test for plugin use and to avoid removing any unused global
map variables if the main program could possibly load up a plugin.

Fixes #62505.
Updates #62430.

Change-Id: Ie00b18b681cb0d259e3c859ac947ade5778cd6c8
(cherry picked from commit 660620dd45)
Reviewed-on: https://go-review.googlesource.com/c/go/+/526575
Reviewed-by: Cherry Mui <cherryyz@google.com>
Run-TryBot: Than McIntosh <thanm@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
2023-09-20 16:24:52 +00:00
Bryan C. Mills
b64dc5f499 [release-branch.go1.21] cmd/go: in TestScript/gotoolchain_path, remove the user's PATH
This test checks a behavior of GOTOOLCHAIN when an appropriate
toolchain is found in PATH. That requires it to exclude any suitable
toolchain binaries from the user's $PATH, which may otherwise
interfere.

Fixes #62711.
Updates #62709.

Change-Id: Ie9161e52d33a65be0b5265cb49e9f2bc8473e057
Reviewed-on: https://go-review.googlesource.com/c/go/+/529217
Auto-Submit: Bryan Mills <bcmills@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
(cherry picked from commit 30886b1b1e)
Reviewed-on: https://go-review.googlesource.com/c/go/+/529435
Run-TryBot: Bryan Mills <bcmills@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Auto-Submit: Dmitri Shuralyov <dmitshur@google.com>
2023-09-19 16:21:36 +00:00
Nayef Ghattas
cd66ca0636 [release-branch.go1.21] runtime/metrics: fix /gc/scan/* metrics
In the existing implementation, all /gc/scan/* metrics are
always equal to 0 due to the dependency on gcStatDep not being
set. This leads to gcStatAggregate always containing zeros, and
always reporting 0 for those metrics.

Also, add a test to ensure that /gc/scan/* metrics are not empty.

For #62477.
Fixes #62478.

Change-Id: I67497347d50ed5c3ce1719a18714c062ec938cab
Reviewed-on: https://go-review.googlesource.com/c/go/+/526116
Reviewed-by: Michael Pratt <mpratt@google.com>
Auto-Submit: Heschi Kreinick <heschi@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2023-09-11 20:06:42 +00:00
Austin Clements
d7a0626806 [release-branch.go1.21] runtime: ignore SPWrite on innermost traceback frame
Prior to CL 458218, gentraceback ignored the SPWrite function flag on
the innermost frame when doing a precise traceback on the assumption
that precise tracebacks could only be started from the morestack
prologue, and that meant that the innermost function could not have
modified SP yet.

CL 458218 rearranged this logic a bit and unintentionally lost this
particular case. As a result, if traceback starts in an assembly
function that modifies SP (either as a result of stack growth or stack
scanning during a GC preemption), traceback stop at the SPWrite
function and then crash with "traceback did not unwind completely".

Fix this by restoring the earlier special case for when the innermost
frame is SPWrite.

This is a fairly minimal change that should be easy to backport. I
think a more robust change would be to encode this per-PC in the
spdelta table, so it would be clear that we're unwinding from the
morestack prologue and wouldn't rely on a complicated and potentially
fragile set of conditions.

Fixes #62464.

Change-Id: I34f38157631890d33a79d0bd32e32c0fcc2574e4
Reviewed-on: https://go-review.googlesource.com/c/go/+/526100
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Michael Pratt <mpratt@google.com>
Auto-Submit: Heschi Kreinick <heschi@google.com>
2023-09-11 20:06:38 +00:00
Gopher Robot
2c1e5b05fe [release-branch.go1.21] go1.21.1
Change-Id: I1c208f9cd77af66e98a4d159c2e6c3b6072ea7ec
Reviewed-on: https://go-review.googlesource.com/c/go/+/526039
Run-TryBot: Cherry Mui <cherryyz@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Joedian Reid <joedian@golang.org>
Auto-Submit: Gopher Robot <gobot@golang.org>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Cherry Mui <cherryyz@google.com>
2023-09-06 15:31:51 +00:00
Roland Shoemaker
bbd043ff0d [release-branch.go1.21] html/template: properly handle special tags within the script context
The HTML specification has incredibly complex rules for how to handle
"<!--", "<script", and "</script" when they appear within literals in
the script context. Rather than attempting to apply these restrictions
(which require a significantly more complex state machine) we apply
the workaround suggested in section 4.12.1.3 of the HTML specification [1].

More precisely, when "<!--", "<script", and "</script" appear within
literals (strings and regular expressions, ignoring comments since we
already elide their content) we replace the "<" with "\x3C". This avoids
the unintuitive behavior that using these tags within literals can cause,
by simply preventing the rendered content from triggering it. This may
break some correct usages of these tags, but on balance is more likely
to prevent XSS attacks where users are unknowingly either closing or not
closing the script blocks where they think they are.

Thanks to Takeshi Kaneko (GMO Cybersecurity by Ierae, Inc.) for
reporting this issue.

Fixes #62197
Fixes #62398
Fixes CVE-2023-39319

[1] https://html.spec.whatwg.org/#restrictions-for-contents-of-script-elements

Change-Id: Iab57b0532694827e3eddf57a7497ba1fab1746dc
Reviewed-on: https://team-review.git.corp.google.com/c/golang/go-private/+/1976594
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Tatiana Bradley <tatianabradley@google.com>
Reviewed-by: Damien Neil <dneil@google.com>
Run-TryBot: Roland Shoemaker <bracewell@google.com>
Reviewed-on: https://team-review.git.corp.google.com/c/golang/go-private/+/2014619
Reviewed-on: https://go-review.googlesource.com/c/go/+/526097
Run-TryBot: Cherry Mui <cherryyz@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
2023-09-06 14:20:20 +00:00
Roland Shoemaker
b0e1d3ea26 [release-branch.go1.21] html/template: support HTML-like comments in script contexts
Per Appendix B.1.1 of the ECMAScript specification, support HTML-like
comments in script contexts. Also per section 12.5, support hashbang
comments. This brings our parsing in-line with how browsers treat these
comment types.

Thanks to Takeshi Kaneko (GMO Cybersecurity by Ierae, Inc.) for
reporting this issue.

Fixes #62196
Fixes #62396
Fixes CVE-2023-39318

Change-Id: Id512702c5de3ae46cf648e268cb10e1eb392a181
Reviewed-on: https://team-review.git.corp.google.com/c/golang/go-private/+/1976593
Run-TryBot: Roland Shoemaker <bracewell@google.com>
Reviewed-by: Tatiana Bradley <tatianabradley@google.com>
Reviewed-by: Damien Neil <dneil@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-on: https://team-review.git.corp.google.com/c/golang/go-private/+/2014618
Reviewed-on: https://go-review.googlesource.com/c/go/+/526096
TryBot-Result: Gopher Robot <gobot@golang.org>
Run-TryBot: Cherry Mui <cherryyz@google.com>
2023-09-06 14:20:08 +00:00
Bryan C. Mills
d25a935574 [release-branch.go1.21] cmd/go: reject toolchain directives containing path separators
If GOTOOLCHAIN="path" or "auto", the go command uses exec.LookPath to
search for it in order to allow toolchains to refer to local-only
toolchain variants (such as toolchains built from enterprise- or
distro-patched source). However, those toolchains should only be
resolved from $PATH, not relative to the working directory of the
command.

Thanks to Juho Nurminen of Mattermost for reporting this issue.

Fixes #62198.
Fixes #62394.
Fixes CVE-2023-39320.

Change-Id: I247c7acea95d737362dd0475e9fc8515430d0fcc
Reviewed-on: https://team-review.git.corp.google.com/c/golang/go-private/+/1996318
Run-TryBot: Roland Shoemaker <bracewell@google.com>
Reviewed-by: Damien Neil <dneil@google.com>
Reviewed-by: Roland Shoemaker <bracewell@google.com>
(cherry picked from commit e41c0a55d45e9a9acbc5d7c1143ea4fff8fb9283)
Reviewed-on: https://team-review.git.corp.google.com/c/golang/go-private/+/2014013
Reviewed-by: Bryan Mills <bcmills@google.com>
Reviewed-by: Tatiana Bradley <tatianabradley@google.com>
Reviewed-on: https://go-review.googlesource.com/c/go/+/526095
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Run-TryBot: Cherry Mui <cherryyz@google.com>
2023-09-06 14:19:53 +00:00
haruyama480
e3ba569c78 [release-branch.go1.21] net/http: revert "support streaming POST content in wasm"
CL 458395 added support for streaming POST content in Wasm.
Unfortunately, this breaks requests to servers that only support HTTP/1.1.
Revert the change until a suitable fallback or opt-in strategy can be decided.

For #61889.
Fixes #62328.

Change-Id: If53a77e1890132063b39abde867d34515d4ac2af
Reviewed-on: https://go-review.googlesource.com/c/go/+/522955
Run-TryBot: Johan Brandhorst-Satzkorn <johan.brandhorst@gmail.com>
Reviewed-by: Damien Neil <dneil@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Bryan Mills <bcmills@google.com>
Reviewed-by: Johan Brandhorst-Satzkorn <johan.brandhorst@gmail.com>
Reviewed-on: https://go-review.googlesource.com/c/go/+/524855
Run-TryBot: Dmitri Shuralyov <dmitshur@golang.org>
Commit-Queue: Dmitri Shuralyov <dmitshur@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Auto-Submit: Dmitri Shuralyov <dmitshur@google.com>
2023-08-31 16:40:31 +00:00
Nick Ripley
8dc6ad1c61 [release-branch.go1.21] runtime: restore caller's frame pointer when recovering from panic
When recovering from a panic, restore the caller's frame pointer before
returning control to the caller. Otherwise, if the function proceeds to
run more deferred calls before returning, the deferred functions will
get invalid frame pointers pointing to an address lower in the stack.
This can cause frame pointer unwinding to crash, such as if an execution
trace event is recorded during the deferred call on architectures which
support frame pointer unwinding.

Original CL by Nick Ripley, includes fix from CL 523697, and includes a
test update from CL 524315.

This CL also deviates from the original fix by doing some extra
computation to figure out the fp from the sp, since we don't have the fp
immediately available to us in `recovery` on the Go 1.21 branch, and it
would probably be complicated to plumb that through its caller.

For #61766
Fixes #62046

Change-Id: I5a99ca4f909f6b6e209a330d595d1c99987d4359
Reviewed-on: https://go-review.googlesource.com/c/go/+/523698
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
2023-08-30 22:33:03 +00:00
Michael Anthony Knyszek
06df3292a8 [release-branch.go1.21] runtime: avoid MADV_HUGEPAGE for heap memory
Currently the runtime marks all new memory as MADV_HUGEPAGE on Linux and
manages its hugepage eligibility status. Unfortunately, the default
THP behavior on most Linux distros is that MADV_HUGEPAGE blocks while
the kernel eagerly reclaims and compacts memory to allocate a hugepage.

This direct reclaim and compaction is unbounded, and may result in
significant application thread stalls. In really bad cases, this can
exceed 100s of ms or even seconds.

Really all we want is to undo MADV_NOHUGEPAGE marks and let the default
Linux paging behavior take over, but the only way to unmark a region as
MADV_NOHUGEPAGE is to also mark it MADV_HUGEPAGE.

The overall strategy of trying to keep hugepages for the heap unbroken
however is sound. So instead let's use the new shiny MADV_COLLAPSE if it
exists.

MADV_COLLAPSE makes a best-effort synchronous attempt at collapsing the
physical memory backing a memory region into a hugepage. We'll use
MADV_COLLAPSE where we would've used MADV_HUGEPAGE, and stop using
MADV_NOHUGEPAGE altogether.

Because MADV_COLLAPSE is synchronous, it's also important to not
re-collapse huge pages if the huge pages are likely part of some large
allocation. Although in many cases it's advantageous to back these
allocations with hugepages because they're contiguous, eagerly
collapsing every hugepage means having to page in at least part of the
large allocation.

However, because we won't use MADV_NOHUGEPAGE anymore, we'll no longer
handle the fact that khugepaged might come in and back some memory we
returned to the OS with a hugepage. I've come to the conclusion that
this is basically unavoidable without a new madvise flag and that it's
just not a good default. If this change lands, advice about Linux huge
page settings will be added to the GC guide.

Verified that this change doesn't regress Sweet, at least not on my
machine with:

/sys/kernel/mm/transparent_hugepage/enabled [always or madvise]
/sys/kernel/mm/transparent_hugepage/defrag [madvise]
/sys/kernel/mm/transparent_hugepage/khugepaged/max_ptes_none [0 or 511]

Unfortunately, this workaround means that we only get forced hugepages
on Linux 6.1+.

For #61718.
Fixes #62329.

Change-Id: I7f4a7ba397847de29f800a99f9cb66cb2720a533
Reviewed-on: https://go-review.googlesource.com/c/go/+/516795
Reviewed-by: Austin Clements <austin@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Run-TryBot: Michael Knyszek <mknyszek@google.com>
Auto-Submit: Michael Knyszek <mknyszek@google.com>
(cherry picked from commit 9f9bb26880)
Reviewed-on: https://go-review.googlesource.com/c/go/+/523655
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Dmitri Shuralyov <dmitshur@google.com>
2023-08-30 21:59:35 +00:00
Robert Griesemer
b120517ffd [release-branch.go1.21] go/types, types2: remove order dependency in inference involving channels
In inexact unification, when a named type matches against an inferred
unnamed type, we change the previously inferred type to the named type.
This preserves the type name and assignability.

We have to do the same thing when encountering a directional channel:
a bidirectional channel can always be assigned to a directional channel
but not the other way around. Thus, if we see a directional channel, we
must choose the directional channel.

This CL extends the previously existing logic for named types to
directional channels and also makes the code conditional on inexact
unification. The latter is an optimization - if unification is exact,
type differences don't exist and updating an already inferred type has
no effect.

Fixes #62205.

Change-Id: I807e3b9f9ab363f9ed848bdb18b2577b1d680ea7
Reviewed-on: https://go-review.googlesource.com/c/go/+/524256
Run-TryBot: Robert Griesemer <gri@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Auto-Submit: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Robert Griesemer <gri@google.com>
Reviewed-by: Robert Findley <rfindley@google.com>
2023-08-30 21:35:21 +00:00
Bryan C. Mills
0a9582163c [release-branch.go1.21] cmd/go: retry ETXTBSY errors when running test binaries
An ETXTBSY error when starting a test binary is almost certainly
caused by the race reported in #22315. That race will resolve quickly
on its own, so we should just retry the command instead of reporting a
spurious failure.

Fixes #62222.
Updates #62221.

Change-Id: I408f3eaa7ab5d7efbc7a2b1c8bea3dbc459fc794
Reviewed-on: https://go-review.googlesource.com/c/go/+/522015
TryBot-Result: Gopher Robot <gobot@golang.org>
Run-TryBot: Bryan Mills <bcmills@google.com>
Auto-Submit: Bryan Mills <bcmills@google.com>
Reviewed-by: Ian Lance Taylor <iant@google.com>
(cherry picked from commit 4dc2564933)
Reviewed-on: https://go-review.googlesource.com/c/go/+/522176
Auto-Submit: Dmitri Shuralyov <dmitshur@google.com>
2023-08-30 21:32:23 +00:00
Damien Neil
91a4e74b98 [release-branch.go1.21] crypto/tls: QUIC: fix panics when processing post-handshake messages
The check for fragmentary post-handshake messages in QUICConn.HandleData
was reversed, resulting in a potential panic when HandleData receives
a partial message.

In addition, HandleData wasn't checking the size of buffered
post-handshake messages. Produce an error when a post-handshake
message is larger than maxHandshake.

TestQUICConnectionState was using an onHandleCryptoData hook
in runTestQUICConnection that was never being called.
(I think it was inadvertently removed at some point while
the CL was in review.) Fix this test while making the hook
more general.

For #62266
Fixes #62290

Change-Id: I210b70634e50beb456ab3977eb11272b8724c241
Reviewed-on: https://go-review.googlesource.com/c/go/+/522595
Run-TryBot: Damien Neil <dneil@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Marten Seemann <martenseemann@gmail.com>
Reviewed-by: Roland Shoemaker <roland@golang.org>
(cherry picked from commit e92c0f846c)
Reviewed-on: https://go-review.googlesource.com/c/go/+/523039
Auto-Submit: Dmitri Shuralyov <dmitshur@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2023-08-30 21:27:45 +00:00
Bryan C. Mills
6385a6fb18 [release-branch.go1.21] cmd/go: find GOROOT using os.Executable when installed to GOROOT/bin/GOOS_GOARCH
When running make.bash in a cross-compiled configuration
(for example, GOARCH different from GOHOSTARCH), cmd/go
is installed to GOROOT/bin/GOOS_GOARCH instead of GOROOT/bin.

That means that we need to look for GOROOT in both ../.. and ../../..,
not just the former.

Fixes #62144.
Updates #62119.
Updates #18678.

Change-Id: I283c6a10c46df573ff44da826f870417359226a7
Reviewed-on: https://go-review.googlesource.com/c/go/+/521015
Reviewed-by: Michael Matloob <matloob@golang.org>
Auto-Submit: Bryan Mills <bcmills@google.com>
Run-TryBot: Bryan Mills <bcmills@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
(cherry picked from commit 9e9556d328)
Reviewed-on: https://go-review.googlesource.com/c/go/+/521695
Auto-Submit: Dmitri Shuralyov <dmitshur@google.com>
2023-08-30 21:25:08 +00:00
xuri
2d07bb86f0 [release-branch.go1.21] encoding/xml: overriding by empty namespace when no new name declaration
The unmarshal and marshal XML text should be consistent if not modified deserialize variable.

For #61881
Fixes #62051

Change-Id: I475f7b05211b618685597d3ff20b97e3bbeaf8f8
GitHub-Last-Rev: 6831c770c3
GitHub-Pull-Request: golang/go#58401
Reviewed-on: https://go-review.googlesource.com/c/go/+/522316
Run-TryBot: Ian Lance Taylor <iant@golang.org>
Reviewed-by: Russ Cox <rsc@golang.org>
Auto-Submit: Ian Lance Taylor <iant@google.com>
Commit-Queue: Ian Lance Taylor <iant@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Ian Lance Taylor <iant@google.com>
2023-08-30 20:17:11 +00:00
Andy Pan
745b81b6e6 [release-branch.go1.21] encoding/gob: prevent panic from index out of range in Decoder.typeString
I believe this bug is introduced by CL 460543 which optimizes the allocations
by changing the type of `idToType` from map to slice, but didn't update the
access code in `Decoder.typeString` that is safe for map but not for slice.

For #62117
Fixes #62154

Change-Id: I0f2e4cc2f34c54dada1f83458ba512a6fde6dcbe
Reviewed-on: https://go-review.googlesource.com/c/go/+/520757
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Ian Lance Taylor <iant@google.com>
Auto-Submit: Ian Lance Taylor <iant@google.com>
Run-TryBot: Andy Pan <panjf2000@gmail.com>
Auto-Submit: Ian Lance Taylor <iant@golang.org>
Reviewed-by: Daniel Martí <mvdan@mvdan.cc>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Run-TryBot: Ian Lance Taylor <iant@google.com>
(cherry picked from commit ba626ac327)
Reviewed-on: https://go-review.googlesource.com/c/go/+/521156
Run-TryBot: Ian Lance Taylor <iant@golang.org>
Reviewed-by: Bryan Mills <bcmills@google.com>
2023-08-25 20:52:06 +00:00
Keith Randall
13339c75b8 [release-branch.go1.21] runtime: fix maps.Clone bug when cloning a map mid-grow
Fixes #62204

Change-Id: I0459d3f481b0cd20102f6d9fd3ea84335a7739a8
Reviewed-on: https://go-review.googlesource.com/c/go/+/522317
Reviewed-by: Cuong Manh Le <cuong.manhle.vn@gmail.com>
Reviewed-by: Keith Randall <khr@google.com>
Reviewed-by: Bryan Mills <bcmills@google.com>
Run-TryBot: Keith Randall <khr@golang.org>
TryBot-Result: Gopher Robot <gobot@golang.org>
(cherry picked from commit b303fb4855)
Reviewed-on: https://go-review.googlesource.com/c/go/+/522936
Reviewed-by: Carlos Amedee <carlos@golang.org>
2023-08-25 16:37:04 +00:00
Bryan C. Mills
2977709875 [release-branch.go1.21] context: fix synchronization in ExampleAfterFunc_cond
Condition variables are subtle and error-prone, and this example
demonstrates exactly the sorts of problems that they introduce.
Unfortunately, we're stuck with them for the foreseeable future.

As previously implemented, this example was racy: since the callback
passed to context.AfterFunc did not lock the mutex before calling
Broadcast, it was possible for the Broadcast to occur before the
goroutine was parked in the call to Wait, causing in a missed wakeup
resulting in deadlock.

The example also had a more insidious problem: it was not safe for
multiple goroutines to call waitOnCond concurrently, but the whole
point of using a sync.Cond is generally to synchronize concurrent
goroutines. waitOnCond must use Broadcast to ensure that it wakes up
the target goroutine, but the use of Broadcast in this way would
produce spurious wakeups for all of the other goroutines waiting on
the same condition variable. Since waitOnCond did not recheck the
condition in a loop, those spurious wakeups would cause waitOnCond
to spuriously return even if its own ctx was not yet done.

Fixing the aforementioned bugs exposes a final problem, inherent to
the use of condition variables in this way. This one is a performance
problem: for N concurrent calls to waitOnCond, the resulting CPU cost
is at least O(N²). This problem cannot be addressed without either
reintroducing one of the above bugs or abandoning sync.Cond in the
example entirely. Given that this example was already published in Go
1.21, I worry that Go users may think that it is appropriate to use a
sync.Cond in conjunction with context.AfterFunc, so I have chosen to
retain the Cond-based example and document its pitfalls instead of
removing or replacing it entirely.

I described this class of bugs and performance issues — and suggested
some channel-based alternatives — in my GopherCon 2018 talk,
“Rethinking Classical Concurrency Patterns”. The section on condition
variables starts on slide 37. (https://youtu.be/5zXAHh5tJqQ?t=679)

Fixes #62189.
Updates #62180.
For #20491.

Change-Id: If987cd9d112997c56171a7ef4fccadb360bb79bc
Reviewed-on: https://go-review.googlesource.com/c/go/+/521596
Reviewed-by: Cuong Manh Le <cuong.manhle.vn@gmail.com>
Auto-Submit: Bryan Mills <bcmills@google.com>
Reviewed-by: Matthew Dempsky <mdempsky@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Run-TryBot: Bryan Mills <bcmills@google.com>
(cherry picked from commit 1081f8c058)
Reviewed-on: https://go-review.googlesource.com/c/go/+/521598
2023-08-24 21:13:14 +00:00
Robert Griesemer
2d4746f37b [release-branch.go1.21] go/types, types2: disable interface inference for versions before Go 1.21
Change the internal constant enableInterfaceInference to a unifier
field that can be controlled dynamically and set it for Go 1.21
or later.

This restores Go 1.20 unification behavior for interfaces.

Fixes #61930.

Change-Id: Iefd6c0899811f8208a8be9cef2650a07787ae177
Reviewed-on: https://go-review.googlesource.com/c/go/+/519855
Reviewed-by: Robert Findley <rfindley@google.com>
Auto-Submit: Robert Griesemer <gri@google.com>
Reviewed-by: Robert Griesemer <gri@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Run-TryBot: Robert Griesemer <gri@google.com>
Reviewed-on: https://go-review.googlesource.com/c/go/+/520601
2023-08-24 21:12:30 +00:00
David Chase
2b8026f025 [release-branch.go1.21] cmd/compile: in expandCalls, move all arg marshalling into call block
For aggregate-typed arguments passed to a call, expandCalls
decomposed them into parts in the same block where the value
was created.  This is not necessarily the call block, and in
the case where stores are involved, can change the memory
leaving that block, and getting that right is problematic.

Instead, do all the expanding in the same block as the call,
which avoids the problems of (1) not being able to reorder
loads/stores across a block boundary to conform to memory
order and (2) (incorrectly, not) exposing the new memory to
consumers in other blocks.  Putting it all in the same block
as the call allows reordering, and the call creates its own
new memory (which is already dealt with correctly).

Fixes #62057.
Updates #61992.

Change-Id: Icc7918f0d2dd3c480cc7f496cdcd78edeca7f297
Reviewed-on: https://go-review.googlesource.com/c/go/+/519276
Reviewed-by: Keith Randall <khr@google.com>
Run-TryBot: David Chase <drchase@google.com>
Reviewed-by: Keith Randall <khr@golang.org>
TryBot-Result: Gopher Robot <gobot@golang.org>
(cherry picked from commit e72ecc6a6b)
Reviewed-on: https://go-review.googlesource.com/c/go/+/520058
2023-08-24 21:10:25 +00:00
Bryan Mills
7c97cc7d97 [release-branch.go1.21] Revert "os: use handle based APIs to read directories on windows"
This reverts CL 452995.

Reason for revert: caused os.File.ReadDir to fail on
filesystems that do not support FILE_ID_BOTH_DIR_INFO.

This is an alternative to a fix-forward change in CL 518196.
Since the original change was mostly a performance improvement,
reverting to the previous implementation seems less risky than
backporting a larger fix.

Fixes #61910
Fixes #61964

Change-Id: I60f1602b9eb6ea353e7eb23429f19f1ffa16b394
Reviewed-on: https://go-review.googlesource.com/c/go/+/520156
Run-TryBot: Bryan Mills <bcmills@google.com>
Reviewed-by: Austin Clements <austin@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Quim Muntal <quimmuntal@gmail.com>
2023-08-23 19:57:00 +00:00
Keith Randall
cb6ea94996 [release-branch.go1.21] Revert "cmd/compile: omit redundant sign/unsign extension on arm64"
This reverts CL 427454.

Reason for revert: causes incorrect generated code in some rare cases

We'll fix-forward at tip, so the revert just needs to be done for 1.21.

Fixes #62143

Change-Id: Id242230481ff4d4ba5f58236c6d8237729fc3b80
Reviewed-on: https://go-review.googlesource.com/c/go/+/520976
Run-TryBot: Keith Randall <khr@golang.org>
Reviewed-by: Ruinan Sun <Ruinan.Sun@arm.com>
Reviewed-by: Keith Randall <khr@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Cherry Mui <cherryyz@google.com>
2023-08-23 17:57:50 +00:00
Damien Neil
45b98bfb79 [release-branch.go1.21] path/filepath: don't drop .. elements when cleaning invalid Windows paths
Fix a bug where Clean could improperly drop .. elements from a
path on Windows, when the path contains elements containing a ':'.

For example, Clean("a/../b:/../../c") now correctly returns "..\c"
rather than "c".

For #61866.
Fixes #61868.

Change-Id: I97b0238953c183b2ce19ca89c14f26700008ea72
Reviewed-on: https://go-review.googlesource.com/c/go/+/517216
Run-TryBot: Damien Neil <dneil@google.com>
Reviewed-by: Bryan Mills <bcmills@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Quim Muntal <quimmuntal@gmail.com>
(cherry picked from commit 6e43407931)
Reviewed-on: https://go-review.googlesource.com/c/go/+/519655
Reviewed-by: Damien Neil <dneil@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Run-TryBot: Dmitri Shuralyov <dmitshur@golang.org>
2023-08-23 17:53:26 +00:00
Cherry Mui
bac083a584 [release-branch.go1.21] cmd/link: don't mangle string symbol names
String symbol names could contain weird characters as we put the
string literal into the symbol name. So it may appear to need
mangling. However, as string symbols are grouped into a single
"go:string.*" symbol, the individual symbol names actually don't
matter. So don't mangle them.

Also make the mangling code more defensive in case of weird
symbol names.

Updates #62098.
Fixes #62140.

Change-Id: I533012567a9fffab69debda934f426421c7abb04
Reviewed-on: https://go-review.googlesource.com/c/go/+/520856
Reviewed-by: Than McIntosh <thanm@google.com>
Run-TryBot: Cherry Mui <cherryyz@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
(cherry picked from commit b65e34f038)
Reviewed-on: https://go-review.googlesource.com/c/go/+/520857
2023-08-23 17:35:53 +00:00
Chris O'Hara
70aa116c4a [release-branch.go1.21] runtime/internal/wasitest: skip racy TCP echo test
The wasip1 TCP echo test introduced in CL 493358 has a race
condition with port selection. The test runner probes for a free
port and then asks the WASM runtime to listen on the port, which
may be taken by another process in the interim.

Due to limitations with WASI preview 1, the guest is unable to
query the port it's listening on. The test cannot ask the WASM
runtime to listen on port 0 (choose a free port) since there's
currently no way for the test to query the selected port and
connect to it.

Given the race condition is unavoidable, this test is now disabled
by default and requires opt-in via an environment variable.

This commit also eliminates the hard-coded connection timeout.

Updates #61820.
Fixes #61821.

Change-Id: I375145c1a1d03ad45c44f528da3347397e6dcb01
Reviewed-on: https://go-review.googlesource.com/c/go/+/519895
Run-TryBot: Johan Brandhorst-Satzkorn <johan.brandhorst@gmail.com>
Reviewed-by: Johan Brandhorst-Satzkorn <johan.brandhorst@gmail.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Bryan Mills <bcmills@google.com>
(cherry picked from commit 795e779610)
Reviewed-on: https://go-review.googlesource.com/c/go/+/520955
Run-TryBot: Bryan Mills <bcmills@google.com>
Auto-Submit: Dmitri Shuralyov <dmitshur@google.com>
2023-08-18 18:00:35 +00:00
Mauri de Souza Meneguzzo
31c5a236bc [release-branch.go1.21] runtime: mark traceEnabled and traceShuttingDown as no:split
This fixes a regression from CL 494181.
The traceEnabled function splits the stack and is being
called by reentersyscall that shouldn't call anything
that splits the stack. Same with traceShuttingDown.

For #61975
Fixes #61987

Change-Id: I5eca0ba74cfa6acb0259e8400b03c2093cd59dd1
GitHub-Last-Rev: 9e55ae9d7c
GitHub-Pull-Request: golang/go#61981
Reviewed-on: https://go-review.googlesource.com/c/go/+/519055
Reviewed-by: Michael Knyszek <mknyszek@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Run-TryBot: Dmitri Shuralyov <dmitshur@google.com>
(cherry picked from commit aa5d483f25)
Reviewed-on: https://go-review.googlesource.com/c/go/+/519495
Reviewed-by: Dmitri Shuralyov <dmitshur@golang.org>
Auto-Submit: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Austin Clements <austin@google.com>
Run-TryBot: Michael Knyszek <mknyszek@google.com>
2023-08-17 21:19:23 +00:00
Keith Randall
25ec110e51 [release-branch.go1.21] cmd/compile: ensure empty blocks in write barriers are marked unpreemptible
Fixes #61958

Change-Id: I242ab77ad2f1ea1dad2d14ef756fa92f9378429f
Reviewed-on: https://go-review.googlesource.com/c/go/+/518755
Reviewed-by: Keith Randall <khr@google.com>
Auto-Submit: Dmitri Shuralyov <dmitshur@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Run-TryBot: Keith Randall <khr@golang.org>
Reviewed-by: David Chase <drchase@google.com>
2023-08-17 21:19:19 +00:00
David Chase
6634ce2f41 [release-branch.go1.21] runtime: profiling on Darwin cannot use blocking reads
On Darwin (and assume also on iOS but not sure), notetsleepg
cannot be called in a signal-handling context.  Avoid this
by disabling block reads on Darwin.

An alternate approach was to add "sigNote" with a pipe-based
implementation on Darwin, but that ultimately would have required
at least one more linkname between runtime and syscall to avoid
racing with fork and opening the pipe, so, not.

Fixes #62019.
Updates #61768.

Change-Id: I0e8dd4abf9a606a3ff73fc37c3bd75f55924e07e
Reviewed-on: https://go-review.googlesource.com/c/go/+/518836
Run-TryBot: David Chase <drchase@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Michael Knyszek <mknyszek@google.com>
(cherry picked from commit c6ee8e31e3)
Reviewed-on: https://go-review.googlesource.com/c/go/+/519375
Reviewed-by: Austin Clements <austin@google.com>
Auto-Submit: Dmitri Shuralyov <dmitshur@google.com>
2023-08-17 21:10:08 +00:00
Cuong Manh Le
25c6dce188 [release-branch.go1.21] cmd/compile: make backingArrayPtrLen to return typecheck-ed nodes
Fixes #61909

Change-Id: Ief8e3a6c42c0644c9f71ebef5f28a294cd7c153f
Reviewed-on: https://go-review.googlesource.com/c/go/+/517936
Run-TryBot: Cuong Manh Le <cuong.manhle.vn@gmail.com>
Auto-Submit: Cuong Manh Le <cuong.manhle.vn@gmail.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Matthew Dempsky <mdempsky@google.com>
Reviewed-by: Michael Knyszek <mknyszek@google.com>
Reviewed-on: https://go-review.googlesource.com/c/go/+/518115
Auto-Submit: Dmitri Shuralyov <dmitshur@google.com>
2023-08-17 21:07:51 +00:00
Robert Findley
4e34f2e81d [release-branch.go1.21] go/types, types2: don't panic during interface completion
It should be possible for the importer to construct an invalid
interface, as would have been produced by type checking.

Updates #61737
Fixes #61743

Change-Id: I72e063f4f1a6205d273a623acce2ec08c34c3cc2
Reviewed-on: https://go-review.googlesource.com/c/go/+/515555
Reviewed-by: Robert Griesemer <gri@google.com>
Auto-Submit: Robert Findley <rfindley@google.com>
Reviewed-by: Olif Oftimis <oftimisolif@gmail.com>
Run-TryBot: Robert Findley <rfindley@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
(cherry picked from commit d2ee7821d3)
Reviewed-on: https://go-review.googlesource.com/c/go/+/515636
Run-TryBot: Dmitri Shuralyov <dmitshur@golang.org>
Auto-Submit: Dmitri Shuralyov <dmitshur@google.com>
2023-08-17 21:05:37 +00:00
Robert Griesemer
d91843ff67 [release-branch.go1.21] go/types, types2: use correct parameter list when checking argument passing
The existing code was simply wrong: we cannot ever use the result
signature parameter list (rsig.params) if sigParams was adjusted
for variadic functions. If it was adjusted, we always must either
use sigParams or its separately instantiated version.

In the condition "n > 0 && adjusted", the "n > 0" should have
been in either of the respective "if statement" branches.

Simplified the code by merging with the result signature parameter
update.

Fixes #61932.

Change-Id: I5d39bc8bbc4dd85c7c985055d29532b4b176955e
Reviewed-on: https://go-review.googlesource.com/c/go/+/519456
Auto-Submit: Robert Griesemer <gri@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Run-TryBot: Robert Griesemer <gri@google.com>
Reviewed-by: Robert Griesemer <gri@google.com>
Reviewed-by: Robert Findley <rfindley@google.com>
Reviewed-on: https://go-review.googlesource.com/c/go/+/519417
Auto-Submit: Dmitri Shuralyov <dmitshur@google.com>
2023-08-17 21:05:04 +00:00
Robert Griesemer
7437db1085 [release-branch.go1.21] go/types, types2: use exact unification when comparing interface methods
Irrespective of whether unification is exact or inexact, method
signatures of interfaces must always match exactly: a type never
satisfies/implements an interface if relevant method signatures
are different (i.e., not identical, possibly after substitution).

Fixes #61959.

Change-Id: I20c0aa28ac86e2edec615b40f2269938e4a96938
Reviewed-on: https://go-review.googlesource.com/c/go/+/519435
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Robert Griesemer <gri@google.com>
Run-TryBot: Robert Griesemer <gri@google.com>
Reviewed-by: Robert Findley <rfindley@google.com>
Auto-Submit: Robert Griesemer <gri@google.com>
Reviewed-on: https://go-review.googlesource.com/c/go/+/519416
Auto-Submit: Dmitri Shuralyov <dmitshur@google.com>
2023-08-17 21:05:01 +00:00
Russ Cox
ed527ecfb2 [release-branch.go1.21] cmd/api: rename api.go to main_test.go
This makes cmd/api no longer an importable package.
In CL 453258 I forgot that there was no direct prohibition
on importing packages from cmd - we just rely on the
fact that cmd/* is all package main and everything else
is cmd/internal.

Fixes #62069.
Fixes #62071.

Change-Id: Ifed738d333b40663f85eca8f83025fcea5df89a9
Reviewed-on: https://go-review.googlesource.com/c/go/+/520038
Reviewed-by: Bryan Mills <bcmills@google.com>
Run-TryBot: Russ Cox <rsc@golang.org>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-on: https://go-review.googlesource.com/c/go/+/520061
2023-08-17 01:32:58 +00:00
Roland Shoemaker
b78e8cc145 [release-branch.go1.21] crypto/tls: add GODEBUG to control max RSA key size
Add a new GODEBUG setting, tlsmaxrsasize, which allows controlling the
maximum RSA key size we will accept during TLS handshakes.

Fixes #61967

Change-Id: I52f060be132014d219f4cd438f59990011a35c96
Reviewed-on: https://go-review.googlesource.com/c/go/+/517495
Auto-Submit: Roland Shoemaker <roland@golang.org>
Reviewed-by: Russ Cox <rsc@golang.org>
Run-TryBot: Roland Shoemaker <roland@golang.org>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-on: https://go-review.googlesource.com/c/go/+/518535
Auto-Submit: Dmitri Shuralyov <dmitshur@google.com>
2023-08-16 17:16:32 +00:00
Michael Matloob
3475e6af4c [release-branch.go1.21] cmd/go: fix missing case checking for empty slice
When we were comparing the first element of import stacks when sorting
depserrors we checked if the first stack was non empty, but not the
second one. Do the check for both stacks.

Fixes #61818
Updates #61816
For #59905

Change-Id: Id5c11c2b1104eec93196a08c53372ee2ba97c701
Reviewed-on: https://go-review.googlesource.com/c/go/+/516739
Reviewed-by: Bryan Mills <bcmills@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Run-TryBot: Michael Matloob <matloob@golang.org>
(cherry picked from commit 58447d757c)
Reviewed-on: https://go-review.googlesource.com/c/go/+/519658
Reviewed-by: Michael Matloob <matloob@golang.org>
Run-TryBot: Bryan Mills <bcmills@google.com>
Auto-Submit: Dmitri Shuralyov <dmitshur@google.com>
2023-08-15 19:04:26 +00:00
Damien Neil
179821c9e1 [release-branch.go1.21] net/http: permit requests with invalid Host headers
Historically, the Transport has silently truncated invalid
Host headers at the first '/' or ' ' character. CL 506996 changed
this behavior to reject invalid Host headers entirely.
Unfortunately, Docker appears to rely on the previous behavior.

When sending a HTTP/1 request with an invalid Host, send an empty
Host header. This is safer than truncation: If you care about the
Host, then you should get the one you set; if you don't care,
then an empty Host should be fine.

Continue to fully validate Host headers sent to a proxy,
since proxies generally can't productively forward requests
without a Host.

For #60374
Fixes #61431
Fixes #61904

Change-Id: If170c7dd860aa20eb58fe32990fc93af832742b6
Reviewed-on: https://go-review.googlesource.com/c/go/+/511155
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Roland Shoemaker <roland@golang.org>
Run-TryBot: Damien Neil <dneil@google.com>
(cherry picked from commit b9153f6ef3)
Reviewed-on: https://go-review.googlesource.com/c/go/+/518856
Auto-Submit: Dmitri Shuralyov <dmitshur@google.com>
Run-TryBot: Roland Shoemaker <roland@golang.org>
Reviewed-by: Russ Cox <rsc@golang.org>
2023-08-14 21:55:15 +00:00
Russ Cox
9398951479 [release-branch.go1.21] cmd/distpack: include directory entries in tar files
Various tools expect tar files to contain entries for directories.
I dropped them when writing cmd/distpack because they're not
strictly necessary and omitting them saves space, but it also
turns out to break some things, so add them back.

We will backport this to release-branch.go1.21 so that Go 1.21.1
will include the directory entries. We can't do anything about
Go 1.21.0 retroactively.

% tar tzvf go1.22rsc1.src.tar.gz | sed 10q
drwxr-xr-x  0 0      0           0 Aug 10 10:07 go/
-rw-r--r--  0 0      0        1337 Aug 10 10:07 go/CONTRIBUTING.md
-rw-r--r--  0 0      0        1479 Aug 10 10:07 go/LICENSE
-rw-r--r--  0 0      0        1303 Aug 10 10:07 go/PATENTS
-rw-r--r--  0 0      0        1455 Aug 10 10:07 go/README.md
-rw-r--r--  0 0      0         419 Aug 10 10:07 go/SECURITY.md
-rw-r--r--  0 0      0          42 Aug 10 10:07 go/VERSION
drwxr-xr-x  0 0      0           0 Aug 10 10:07 go/api/
-rw-r--r--  0 0      0        1142 Aug 10 10:07 go/api/README
-rw-r--r--  0 0      0       35424 Aug 10 10:07 go/api/except.txt
% tar tzvf go1.22rsc1.darwin-amd64.tar.gz | sed 10q
drwxr-xr-x  0 0      0           0 Aug 10 10:07 go/
-rw-r--r--  0 0      0        1337 Aug 10 10:07 go/CONTRIBUTING.md
-rw-r--r--  0 0      0        1479 Aug 10 10:07 go/LICENSE
-rw-r--r--  0 0      0        1303 Aug 10 10:07 go/PATENTS
-rw-r--r--  0 0      0        1455 Aug 10 10:07 go/README.md
-rw-r--r--  0 0      0         419 Aug 10 10:07 go/SECURITY.md
-rw-r--r--  0 0      0          42 Aug 10 10:07 go/VERSION
drwxr-xr-x  0 0      0           0 Aug 10 10:07 go/api/
-rw-r--r--  0 0      0        1142 Aug 10 10:07 go/api/README
-rw-r--r--  0 0      0       35424 Aug 10 10:07 go/api/except.txt
%

Fixes #61862.
Fixes #61927.

Change-Id: Iecd9ba893015295e88715b031b79a104236b9ced
Reviewed-on: https://go-review.googlesource.com/c/go/+/518335
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Heschi Kreinick <heschi@google.com>
Run-TryBot: Russ Cox <rsc@golang.org>
Reviewed-on: https://go-review.googlesource.com/c/go/+/518835
Auto-Submit: Russ Cox <rsc@golang.org>
2023-08-11 17:56:21 +00:00
Bryan C. Mills
75d8be5fb4 [release-branch.go1.21] cmd/go/internal/web: release the net token when an HTTP request fails due to CheckRedirect
Updates #61877.
Fixes #61905.

Change-Id: I38c63565aaf9dc9b0c8085974521daccfbcbc790
Reviewed-on: https://go-review.googlesource.com/c/go/+/518015
Reviewed-by: Michael Matloob <matloob@golang.org>
Run-TryBot: Bryan Mills <bcmills@google.com>
Auto-Submit: Bryan Mills <bcmills@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
(cherry picked from commit 8cb5c55118)
Reviewed-on: https://go-review.googlesource.com/c/go/+/518395
2023-08-11 14:53:49 +00:00
Cuong Manh Le
1755d14559 [release-branch.go1.21] cmd/compile: fix missing init nodes for len(string([]byte)) optimization
CL 497276 added optimization for len(string([]byte)) by avoiding call to
slicebytetostring. However, the bytes to string expression may contain
init nodes, which need to be preserved. Otherwise, it would make the
liveness analysis confusing about the lifetime of temporary variables
created by init nodes.

Fixes #61781

Change-Id: I6d1280a7d61bcc75f11132af41bda086f084ab54
Reviewed-on: https://go-review.googlesource.com/c/go/+/516375
Run-TryBot: Cuong Manh Le <cuong.manhle.vn@gmail.com>
Reviewed-by: Keith Randall <khr@golang.org>
Reviewed-by: Keith Randall <khr@google.com>
Auto-Submit: Cuong Manh Le <cuong.manhle.vn@gmail.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Matthew Dempsky <mdempsky@google.com>
Reviewed-on: https://go-review.googlesource.com/c/go/+/516535
2023-08-11 14:53:01 +00:00
Gopher Robot
c19c4c566c [release-branch.go1.21] go1.21.0
Change-Id: Iffac2ce43cd3a48ba420594adc3eab5aa9bcf113
Reviewed-on: https://go-review.googlesource.com/c/go/+/517055
Auto-Submit: Gopher Robot <gobot@golang.org>
Reviewed-by: David Chase <drchase@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Michael Knyszek <mknyszek@google.com>
Run-TryBot: Gopher Robot <gobot@golang.org>
Run-TryBot: Michael Knyszek <mknyszek@google.com>
Auto-Submit: Michael Knyszek <mknyszek@google.com>
2023-08-08 15:00:52 +00:00
Damien Neil
e973d24261 [release-branch.go1.21] Revert "net/http: use Copy in ServeContent if CopyN not needed"
This reverts CL 446276.

Reason for revert: Causing surprising performance regression.

Fixes #61530

Change-Id: Ic970f2e05d875b606ce274ea621f7e4c8c337481
Reviewed-on: https://go-review.googlesource.com/c/go/+/512615
Run-TryBot: Damien Neil <dneil@google.com>
Reviewed-by: Bryan Mills <bcmills@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
(cherry picked from commit df0a129789)
Reviewed-on: https://go-review.googlesource.com/c/go/+/515795
Run-TryBot: Ian Lance Taylor <iant@golang.org>
Reviewed-by: David Chase <drchase@google.com>
Reviewed-by: Damien Neil <dneil@google.com>
2023-08-04 16:24:02 +00:00
Robert Griesemer
2e6276df34 [release-branch.go1.21] spec: remove unnecessary sentence
Change-Id: I06345199ff16c80be83c345d734caef1714ec089
Reviewed-on: https://go-review.googlesource.com/c/go/+/515338
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>
Reviewed-on: https://go-review.googlesource.com/c/go/+/515715
2023-08-03 23:35:21 +00:00
Johan Brandhorst-Satzkorn
aeef93cd64 [release-branch.go1.21] runtime/internal: switch GOWASIRUNTIME default
CL 513235 switched the default wasip1 runtime in the misc/wasm
executable script, but it missed this use of the GOWASIRUNTIME
environment variable. Update this instance to make the default runtime
choice consistent.

Change-Id: Iff7f96231422747a38d65d13a940f6e9d04d835d
Reviewed-on: https://go-review.googlesource.com/c/go/+/515116
Reviewed-by: David Chase <drchase@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Auto-Submit: Johan Brandhorst-Satzkorn <johan.brandhorst@gmail.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@golang.org>
Run-TryBot: Johan Brandhorst-Satzkorn <johan.brandhorst@gmail.com>
2023-08-03 22:16:40 +00:00
Damien Neil
35de5f2b0e [release-branch.go1.21] crypto/tls: change SendSessionTicket to take an options struct
To allow for future evolution of the API, make
QUICConn.SendSessionTicket take a QUICSessionTicketOptions
rather than a single bool.

For #60107

Change-Id: I798fd0feec5c7581e3c3574e2de99611c81df47f
Reviewed-on: https://go-review.googlesource.com/c/go/+/514997
Reviewed-by: Roland Shoemaker <roland@golang.org>
Run-TryBot: Damien Neil <dneil@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Marten Seemann <martenseemann@gmail.com>
(cherry picked from commit a915b999c9)
Reviewed-on: https://go-review.googlesource.com/c/go/+/515335
Auto-Submit: Damien Neil <dneil@google.com>
2023-08-02 17:43:27 +00:00
Cherry Mui
a3b092d65e [release-branch.go1.21] cmd/link: use symbol-targeted relocation for initializers on Mach-O
Apple's new linker, ld-prime from Xcode 15 beta, when handling
initializers in __mod_init_func, drops the offset in the data,
resolving the relocation to the beginning of the section. The
latest version of ld-prime rejects non-zero addend. We need to use
symbol-targeted "external" relocations, so that it doesn't need
an addend and can be resolved correctly. This also works fine with
ld64.

Fixes #60694.
For #61229.

Change-Id: Ida2be6aa4c91bfcd142b755e2ec63aabfbbd77a6
Reviewed-on: https://go-review.googlesource.com/c/go/+/502616
Run-TryBot: Cherry Mui <cherryyz@google.com>
Reviewed-by: Than McIntosh <thanm@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
(cherry picked from commit bad9ca8a61)
Reviewed-on: https://go-review.googlesource.com/c/go/+/514535
2023-08-02 17:38:41 +00:00
Mauri de Souza Meneguzzo
07c72a0915 [release-branch.go1.21] cmd/go: missing name in failed command error
Fixed the error reporting for an unknown command to
preserve the name when displaying the error message.

Fixes #61604

Change-Id: I13defb84e61265ab48ab514e9d4f1626a4a3f758
GitHub-Last-Rev: 5d2889c60c
GitHub-Pull-Request: golang/go#61607
Reviewed-on: https://go-review.googlesource.com/c/go/+/513555
Run-TryBot: Russ Cox <rsc@golang.org>
Reviewed-by: David Chase <drchase@google.com>
Auto-Submit: Russ Cox <rsc@golang.org>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Russ Cox <rsc@golang.org>
Reviewed-on: https://go-review.googlesource.com/c/go/+/515278
Auto-Submit: David Chase <drchase@google.com>
2023-08-02 15:53:43 +00:00
Gopher Robot
041dd5ce05 [release-branch.go1.21] go1.21rc4
Change-Id: I4a166f3d04747703f2c0b3c3f245d9cde44f3068
Reviewed-on: https://go-review.googlesource.com/c/go/+/514777
Reviewed-by: David Chase <drchase@google.com>
Run-TryBot: Gopher Robot <gobot@golang.org>
Auto-Submit: Gopher Robot <gobot@golang.org>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Russ Cox <rsc@golang.org>
2023-08-02 13:51:49 +00:00
Roland Shoemaker
a51957fb0b [release-branch.go1.21] crypto/tls: restrict RSA keys in certificates to <= 8192 bits
Extremely large RSA keys in certificate chains can cause a client/server
to expend significant CPU time verifying signatures. Limit this by
restricting the size of RSA keys transmitted during handshakes to <=
8192 bits.

Based on a survey of publicly trusted RSA keys, there are currently only
three certificates in circulation with keys larger than this, and all
three appear to be test certificates that are not actively deployed. It
is possible there are larger keys in use in private PKIs, but we target
the web PKI, so causing breakage here in the interests of increasing the
default safety of users of crypto/tls seems reasonable.

Thanks to Mateusz Poliwczak for reporting this issue.

Updates #61460
Fixes CVE-2023-29409

Change-Id: Ie35038515a649199a36a12fc2c5df3af855dca6c
Reviewed-on: https://team-review.git.corp.google.com/c/golang/go-private/+/1912161
Reviewed-by: Damien Neil <dneil@google.com>
Reviewed-by: Tatiana Bradley <tatianabradley@google.com>
Run-TryBot: Roland Shoemaker <bracewell@google.com>
(cherry picked from commit d865c715d92887361e4bd5596e19e513f27781b7)
Reviewed-on: https://go-review.googlesource.com/c/go/+/515056
Run-TryBot: David Chase <drchase@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
2023-08-01 21:58:27 +00:00
Russ Cox
363f2594aa [release-branch.go1.21] cmd/go: make go list -m -u all not complain about missing checksums
This is a band-aid of a fix for Go 1.21, to create space to work on
a real fix for Go 1.22, if in fact the real fix is different. It simply
disables the go.sum update check during go list -m -u.
I don't have a self-contained test for the breakage. See #61605.
All existing tests continue to pass.

For #61605.
After merging into the Go 1.21 branch we can move #61605 to the Go 1.22 milestone.

Change-Id: Ib155710092003f08d2a6ce0aefa8e0270cad5a5c
Reviewed-on: https://go-review.googlesource.com/c/go/+/514899
Reviewed-by: Michael Matloob <matloob@golang.org>
Run-TryBot: Russ Cox <rsc@golang.org>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
2023-08-01 18:40:48 +00:00
Johan Brandhorst-Satzkorn
9b53b9b585 [release-branch.go1.21] misc/wasm: switch default WASI runtime
The default WASI runtime was originally set to Wazero, because it was
the first runtime used to test the Go implementation and because we
could easily find and fix issues in our implementation and theirs.

In CL 498675 we switched the default wasip1 runner to Wasmtime as it
runs faster and is a more established and mature runtime. We should
switch the default runtime to Wasmtime to consistently promote
Wasmtime as the primary tested and approved runtime.

Change-Id: Ic6c064142321af90f015e02b7fe0e71444d8842c
Reviewed-on: https://go-review.googlesource.com/c/go/+/513235
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Eli Bendersky <eliben@google.com>
Run-TryBot: Johan Brandhorst-Satzkorn <johan.brandhorst@gmail.com>
Auto-Submit: Johan Brandhorst-Satzkorn <johan.brandhorst@gmail.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@golang.org>
(cherry picked from commit 4918490962)
Reviewed-on: https://go-review.googlesource.com/c/go/+/514155
Auto-Submit: Dmitri Shuralyov <dmitshur@golang.org>
Reviewed-by: David Chase <drchase@google.com>
2023-07-31 18:16:13 +00:00
Robert Griesemer
4a14d9c9af [release-branch.go1.21] spec: update spec to version at tip
This updates the spec by copying over several recent CLs
describing the new type inference mechanisms.

Fixes #61659.

Change-Id: I750c901e73e0404f782a3632f5cd936e3775ae13
Reviewed-on: https://go-review.googlesource.com/c/go/+/514435
Reviewed-by: Robert Griesemer <gri@google.com>
Auto-Submit: Robert Griesemer <gri@google.com>
TryBot-Bypass: Robert Griesemer <gri@google.com>
Reviewed-by: Ian Lance Taylor <iant@google.com>
2023-07-31 17:13:23 +00:00
Cherry Mui
9786164333 [release-branch.go1.21 cmd/cgo/internal/test: don't pass -lm on darwin
On darwin, -lm is not necessary as the math functions are included
in libSystem. Passing -lm multiple times results in linker
warnings. Don't pass it on darwin.

For #61229.

Change-Id: I72d8dab1f0eead68cbeb176ac97b8ed1a0cfddab
Reviewed-on: https://go-review.googlesource.com/c/go/+/508697
Run-TryBot: Cherry Mui <cherryyz@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Than McIntosh <thanm@google.com>
(cherry picked from commit 333c80694c)
Reviewed-on: https://go-review.googlesource.com/c/go/+/513758
2023-07-31 16:12:29 +00:00
Dmitri Shuralyov
6df6e61cbb [release-branch.go1.21] cmd/dist: handle -json flag in runPending (minimal)
The -json flag is new to Go 1.21, but missed skips in runPending.
This CL adds minimal code to fix that. CL 512115 cleans up a bit.

For #37486.
Fixes #61557.

Change-Id: I53e426c9a5585b2703f0ff6661a0470e1993f960
Reviewed-on: https://go-review.googlesource.com/c/go/+/513761
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Austin Clements <austin@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Run-TryBot: Dmitri Shuralyov <dmitshur@golang.org>
Auto-Submit: Dmitri Shuralyov <dmitshur@golang.org>
2023-07-28 17:57:22 +00:00
Ian Lance Taylor
b25266c58d [release-branch.go1.21] maps: remove Keys and Values
Preserve the names in case we want them to return an iterator.
Keep the efficient runtime implementations for now,
as we will probably want them under some name, perhaps KeysSlice
and ValuesSlice.

Fixes #61538

Change-Id: I6b03010bf071fb4531cb2f967dad46425962fcb8
Reviewed-on: https://go-review.googlesource.com/c/go/+/513476
Run-TryBot: Ian Lance Taylor <iant@golang.org>
Auto-Submit: Ian Lance Taylor <iant@google.com>
Reviewed-by: Ian Lance Taylor <iant@google.com>
Run-TryBot: Ian Lance Taylor <iant@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Russ Cox <rsc@golang.org>
Reviewed-on: https://go-review.googlesource.com/c/go/+/513715
Run-TryBot: Russ Cox <rsc@golang.org>
2023-07-27 22:20:27 +00:00
Cherry Mui
1ea8d38517 [release-branch.go1.21] cmd/link: don't generate DYSYMTAB when external linking on Mach-O
When external linking, the external linker will generate it.

Updates #60694.
For #61229.

Change-Id: I086a7628dd9baa84b46315641746fc3640473f2b
Reviewed-on: https://go-review.googlesource.com/c/go/+/502617
Reviewed-by: Than McIntosh <thanm@google.com>
Run-TryBot: Cherry Mui <cherryyz@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
(cherry picked from commit f55e7e104b)
Reviewed-on: https://go-review.googlesource.com/c/go/+/513757
2023-07-27 20:07:01 +00:00
zikaeroh
b2ffc23a82 [release-branch.go1.21] log/slog: fix comment above log levels
This extra newline causes pkg.go.dev and gopls to only show the bottom
half of this comment; I'm pretty sure this entire thing is meant to be
in the docs.

Change-Id: I5bbf081fb2072d9d773d5a995bc3693dc44f65ff
Reviewed-on: https://go-review.googlesource.com/c/go/+/511855
Run-TryBot: Jonathan Amsterdam <jba@google.com>
Reviewed-by: Jonathan Amsterdam <jba@google.com>
Reviewed-by: Carlos Amedee <carlos@golang.org>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-on: https://go-review.googlesource.com/c/go/+/512199
Reviewed-by: Dmitri Shuralyov <dmitshur@golang.org>
Run-TryBot: Dmitri Shuralyov <dmitshur@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Auto-Submit: Dmitri Shuralyov <dmitshur@golang.org>
2023-07-24 17:02:06 +00:00
Rob Findley
8472fcb62d [release-branch.go1.21] go/types, types2: update documentation for GoVersion
Update the documentation for Config.GoVersion to reflect the changes
made for #61175.

Change-Id: I9f3fbcf8ee88e52d6a5e7cf80dad3d2fb5313893
Reviewed-on: https://go-review.googlesource.com/c/go/+/511096
TryBot-Result: Gopher Robot <gobot@golang.org>
Run-TryBot: Robert Findley <rfindley@google.com>
Reviewed-by: Robert Griesemer <gri@google.com>
(cherry picked from commit 12f3d6858e)
Reviewed-on: https://go-review.googlesource.com/c/go/+/511699
Run-TryBot: Dmitri Shuralyov <dmitshur@golang.org>
2023-07-24 02:02:15 +00:00
Dmitri Shuralyov
b36e5555dd [release-branch.go1.21] cmd/dist: apply timeout scale even if timeout isn't overridden
The timeout field is documented as being available so that it's possible
to override timeout by setting a non-zero value. If it's left at zero,
we don't need to override the default go test timeout, but we still need
to apply the timeout scale whenever it's something other than 1.

Fixes #61468.

Change-Id: I63634e9b3ef8c4ec7f334b5a6b4bf3cad121355c
Reviewed-on: https://go-review.googlesource.com/c/go/+/511976
Reviewed-by: Bryan Mills <bcmills@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Auto-Submit: Dmitri Shuralyov <dmitshur@golang.org>
Run-TryBot: Dmitri Shuralyov <dmitshur@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
2023-07-21 14:59:06 +00:00
Meng Zhuo
ed977e2f47 [release-branch.go1.21] cmd/asm, cmd/internal/obj: generate proper atomic ops for riscv64
Go's memory model closely follows the approach C++ concurrency memory
model (https://go.dev/ref/mem) and Go atomic "has the same semantics as C++'s
sequentially consistent atomics".

Meanwhile according to RISCV manual A.6 "Mappings from C/C++ primitives to RISC-V primitives".
C/C++ atomic operations (memory_order_acq_rel) should be map to "amo<op>.{w|d}.aqrl"
LR/SC (memory_order_acq_rel) should map to "lr.{w|d}.aq; <op>; sc.{w|d}.rl"

goos: linux
goarch: riscv64
pkg: runtime/internal/atomic
                │ atomic.old.bench │          atomic.new.bench           │
                │      sec/op      │   sec/op     vs base                │
AtomicLoad64-4         4.216n ± 1%   4.202n ± 0%        ~ (p=0.127 n=10)
AtomicStore64-4        5.040n ± 0%   6.718n ± 0%  +33.30% (p=0.000 n=10)
AtomicLoad-4           4.217n ± 0%   4.213n ± 0%        ~ (p=0.145 n=10)
AtomicStore-4          5.040n ± 0%   6.718n ± 0%  +33.30% (p=0.000 n=10)
And8-4                 9.237n ± 0%   9.240n ± 0%        ~ (p=0.582 n=10)
And-4                  5.878n ± 0%   6.719n ± 0%  +14.31% (p=0.000 n=10)
And8Parallel-4         28.44n ± 0%   28.46n ± 0%   +0.07% (p=0.000 n=10)
AndParallel-4          28.40n ± 0%   28.43n ± 0%   +0.11% (p=0.000 n=10)
Or8-4                  8.399n ± 0%   8.398n ± 0%        ~ (p=0.357 n=10)
Or-4                   5.879n ± 0%   6.718n ± 0%  +14.27% (p=0.000 n=10)
Or8Parallel-4          28.43n ± 0%   28.45n ± 0%   +0.09% (p=0.000 n=10)
OrParallel-4           28.40n ± 0%   28.43n ± 0%   +0.11% (p=0.000 n=10)
Xadd-4                 30.05n ± 0%   30.10n ± 0%   +0.18% (p=0.000 n=10)
Xadd64-4               30.05n ± 0%   30.09n ± 0%   +0.12% (p=0.000 n=10)
Cas-4                  60.48n ± 0%   61.13n ± 0%   +1.08% (p=0.000 n=10)
Cas64-4                62.28n ± 0%   62.34n ± 0%        ~ (p=0.810 n=10)
Xchg-4                 30.05n ± 0%   30.09n ± 0%   +0.15% (p=0.000 n=10)
Xchg64-4               30.05n ± 0%   30.09n ± 0%   +0.13% (p=0.000 n=10)
geomean                15.42n        16.17n        +4.89%

Fixes #61295

Change-Id: I97b5325db50467eeec36fb079bded7b09a32330f
Reviewed-on: https://go-review.googlesource.com/c/go/+/508715
Reviewed-by: Austin Clements <austin@google.com>
Reviewed-by: Joel Sing <joel@sing.id.au>
Run-TryBot: M Zhuo <mzh@golangcn.org>
Reviewed-by: Cherry Mui <cherryyz@google.com>
Reviewed-by: Bryan Mills <bcmills@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
(cherry picked from commit 890b96f7ab)
Reviewed-on: https://go-review.googlesource.com/c/go/+/511856
Auto-Submit: M Zhuo <mzh@golangcn.org>
Reviewed-by: Heschi Kreinick <heschi@google.com>
Reviewed-by: M Zhuo <mzh@golangcn.org>
2023-07-21 14:45:34 +00:00
Robert Griesemer
2fabb143d7 [release-branch.go1.21] go/types, types2: a min/max value argument must not be untyped
Fizes #61492.

Change-Id: I5770e238e44b724816894d914b3ea5dc78bc3ced
Reviewed-on: https://go-review.googlesource.com/c/go/+/511835
Reviewed-by: Robert Griesemer <gri@google.com>
Auto-Submit: Robert Griesemer <gri@google.com>
Run-TryBot: Robert Griesemer <gri@google.com>
Reviewed-by: Matthew Dempsky <mdempsky@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-on: https://go-review.googlesource.com/c/go/+/511857
Reviewed-by: Cherry Mui <cherryyz@google.com>
2023-07-21 03:06:31 +00:00
Cherry Mui
c9f01f0ec7 [release-branch.go1.21 cmd/go: attach PGO profile for test dependencies
When running "go test" including a main package which has a PGO
profile, we currently build the package being tested and its
dependencies with PGO, but we failed to attach the profile to
test-only dependencies. If a package is (transitively) imported
by both the package being tested and the test, the PGO version
and the non-PGO version of the package are both linked into the
binary, causing link-time error.

This CL fixes this by attaching the PGO profile to dependencies of
the test.

Fixes #61376.

Change-Id: I2559db9843c4cdab596b31e2025d8475ffbf58ec
Reviewed-on: https://go-review.googlesource.com/c/go/+/510835
Run-TryBot: Cherry Mui <cherryyz@google.com>
Reviewed-by: Bryan Mills <bcmills@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
(cherry picked from commit af0609b080)
Reviewed-on: https://go-review.googlesource.com/c/go/+/511698
2023-07-20 20:44:54 +00:00
Dmitri Shuralyov
252f20b2c1 [release-branch.go1.21] doc: delete go1.21.html copy
When the final Go 1.21.0 release is made, the release notes will lose
the draft status and begin to be visible at https://go.dev/doc/go1.21.
The source go1.21.html file will then move from the main Go repository
to x/website as part of it becoming a finished and eventually frozen
historical release notes page.

The https://tip.golang.org/doc/go1.21 page that currently serves the
current draft always uses the main repository's main branch, so this
copy on the release branch is not used by anything. Its existence on
this branch may attract backports, which are harmless but also not
very useful. Avoid that temptation by deleting it here sooner.

(Since the first RC comes with a mostly complete release notes draft,
maybe in the future we can consider moving this file to x/website
right before a release branch is cut, making the draft available at
https://go.dev/doc/go1.21 sooner so fewer links will need updating.)

For #58645.

Change-Id: I92c0200b748a5f255f9b8113b4952c122631c6d6
Reviewed-on: https://go-review.googlesource.com/c/go/+/511317
Auto-Submit: Dmitri Shuralyov <dmitshur@golang.org>
Reviewed-by: Heschi Kreinick <heschi@google.com>
TryBot-Bypass: Dmitri Shuralyov <dmitshur@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
2023-07-20 19:16:29 +00:00
qmuntal
7ee7a21ef2 [release-branch.go1.21] runtime: ensure stack is aligned in _rt0_amd64_windows_lib
The Windows DLL loader may call a DLL entry point, in our case
_rt0_amd64_windows_lib, with a stack that is
not 16-byte aligned. In theory, it shouldn't, but under some
circumstances, it does (see below how to reproduce it).

Having an unaligned stack can, and probably will, cause problems
down the line, for example if a movaps instruction tries to store
a value in an unaligned address it throws an Access Violation exception
(code 0xc0000005).

I managed to consistently reproduce this issue by loading a Go DLL into
a C program that has the Page Heap Verification diagnostic enabled [1].

Updates #54187 (and potentially fixes)

[1] https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/example-12---using-page-heap-verification-to-find-a-bug

Change-Id: Id0fea7f407e024c9b8cdce10ce4802d7535e7542
Reviewed-on: https://go-review.googlesource.com/c/go/+/510755
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Cherry Mui <cherryyz@google.com>
Reviewed-by: Than McIntosh <thanm@google.com>
Run-TryBot: Quim Muntal <quimmuntal@gmail.com>
(cherry picked from commit 5fe3f0a265)
Reviewed-on: https://go-review.googlesource.com/c/go/+/511135
Run-TryBot: Dmitri Shuralyov <dmitshur@golang.org>
Reviewed-by: Quim Muntal <quimmuntal@gmail.com>
2023-07-20 18:24:32 +00:00
Heschi Kreinick
06a9034b60 [release-branch.go1.21] net: tolerate permission errors in interface tests
On our linux-arm64 builders, we're getting permission errors despite
running as root. Detect those errors and skip the test.

Fixes #61414.

Change-Id: I5d7c45789337bee3860b19335bbb9eb884c48986
Reviewed-on: https://go-review.googlesource.com/c/go/+/510737
Auto-Submit: Heschi Kreinick <heschi@google.com>
Run-TryBot: Heschi Kreinick <heschi@google.com>
Reviewed-by: Ian Lance Taylor <iant@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
(cherry picked from commit 8e1ec1cb93)
Reviewed-on: https://go-review.googlesource.com/c/go/+/511136
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
TryBot-Bypass: Dmitri Shuralyov <dmitshur@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@golang.org>
2023-07-20 15:04:53 +00:00
Guoqi Chen
03c7e96be9 [release-branch.go1.21] doc/go1.21: add release notes for linux/loong64
Fixes #53301

Change-Id: Id447d57d43b12c3748267295928d45a089549340
Reviewed-on: https://go-review.googlesource.com/c/go/+/507815
Reviewed-by: Ian Lance Taylor <iant@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
TryBot-Bypass: Ian Lance Taylor <iant@golang.org>
Reviewed-by: Meidan Li <limeidan@loongson.cn>
TryBot-Bypass: Ian Lance Taylor <iant@google.com>
Auto-Submit: Ian Lance Taylor <iant@golang.org>
Auto-Submit: Ian Lance Taylor <iant@google.com>
Reviewed-by: Ian Lance Taylor <iant@google.com>
(cherry picked from commit 700727151f)
Reviewed-on: https://go-review.googlesource.com/c/go/+/510916
Reviewed-by: Heschi Kreinick <heschi@google.com>
2023-07-19 21:06:47 +00:00
Heschi Kreinick
c2de6836c1 [release-branch.go1.21] all: merge master (2639a17) into release-branch.go1.21
Change-Id: I316578aec6c2b618c840d43a65ef87b8d2168ac0
2023-07-18 13:25:02 -04:00
Gopher Robot
4aeac326b5 [release-branch.go1.21] go1.21rc3
Change-Id: Ibab6e2a998d5b57fcae923fa0627037846af1492
Reviewed-on: https://go-review.googlesource.com/c/go/+/509775
Reviewed-by: Eli Bendersky <eliben@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Cherry Mui <cherryyz@google.com>
Run-TryBot: Gopher Robot <gobot@golang.org>
Auto-Submit: Gopher Robot <gobot@golang.org>
2023-07-14 15:07:26 +00:00
Cherry Mui
9480b4adf9 [release-branch.go1.21] all: merge master (b88bd91) into release-branch.go1.21
Merge List:

+ 2023-07-13 b88bd917b8 cmd/go/internal/modfetch: always allow Stat for the current toolchain to succeed
+ 2023-07-13 d4f0d896a6 net/http: revert stray edit to h2_bundle.go from CL 508996
+ 2023-07-13 4a0f51696e all: remove duplicate word and fix comment
+ 2023-07-12 49d42128fd all: fix typos and remove repeated words

Change-Id: Ie4f17f633483d5cd1d244b6e7cde6422dc246d9e
2023-07-13 12:46:26 -04:00
Cherry Mui
cc0cb3020d [release-branch.go1.21] all: merge master (6244b19) into release-branch.go1.21
Merge List:

+ 2023-07-12 6244b1946b all: update vendored dependencies
+ 2023-07-12 b4872ea187 cmd/go: fix go get go@badversion
+ 2023-07-12 87350393e6 cmd/go: fix GOTOOLCHAIN parsing for +auto
+ 2023-07-12 230e549142 doc/go1.21: add a release note for CL 463177
+ 2023-07-12 5e4000ad7f cmd/compile: on PPC64, fix sign/zero extension when masking
+ 2023-07-11 af8f94e3c5 src/README.vendor: s/latest/master/
+ 2023-07-11 3eaee3d5dd testing/slogtest: check for no group with empty record
+ 2023-07-11 167c8b73bf net/http/fcgi: eliminate goroutine leaks in tests
+ 2023-07-11 cb7a091d72 os/exec: ignore context.Canceled errors in TestConcurrentExec
+ 2023-07-11 651869716a log/slog: replace nil contexts with context.Background()
+ 2023-07-11 3f8b04bfb5 log/slog: change XXXCtx functions to XXXContext
+ 2023-07-11 4c58d6bf52 time: increase arbitrary upper bound in TestReset to 10s
+ 2023-07-11 6a063b01b0 net: mptcp: force using MPTCP with GODEBUG
+ 2023-07-10 07ede7a543 syscall: serialize locks on ForkLock on platforms where forkExecPipe is not atomic
+ 2023-07-10 7dc62f3bda test: add test cases for index value with range array clear
+ 2023-07-10 0b65b02ba5 cmd/compile: fix clear on slice with zero size elem
+ 2023-07-10 c4db811e44 cmd/compile: don't ICE on unaligned offsets for pointer writes
+ 2023-07-07 5c15498609 os: support reading empty root directories on Windows
+ 2023-07-07 894d24d617 src/database/sql: run gofmt
+ 2023-07-07 ac9137f8d3 go/types, types2: do not mutate arguments in NewChecker
+ 2023-07-07 158d11196f math: add test that covers riscv64 fnm{add,sub} codegen
+ 2023-07-07 d3d78b4bcc log/slog: handle recursively empty groups
+ 2023-07-06 39c5070712 os: do not skip directory entries with zero inodes on wasip1
+ 2023-07-06 e6ec2a34dc runtime: print output on failure in TestMemPprof
+ 2023-07-06 449ef3795d net: only build cgo_stub.go on unix or wasip1
+ 2023-07-06 6305d7fdd3 cmd/go: pass GoVersion in vet config
+ 2023-07-06 b490bdc27d go/types: record Config.GoVersion for reporting in Package.GoVersion method
+ 2023-07-06 36ea4f9680 log/slog: fix faulty test
+ 2023-07-05 3fce111535 cmd/compile: fix FMA negative commutativity of riscv64
+ 2023-07-05 c8dad424bf math: fix portable FMA when x*y < 0 and x*y == -z
+ 2023-07-05 cd6676126b database/sql: prevent internal context error from being returned from Rows.Err()
+ 2023-07-05 b2215e49c7 runtime,runtime/metrics: clarify OS stack metrics
+ 2023-07-04 e126572f8a runtime: have ReadMemStats do a nil check before switching stacks
+ 2023-07-04 e4ed92a355 os, syscall: update unreachable link about =C: envs
+ 2023-07-04 5c1a15df41 test/codegen: enable Mul2 DivPow2 test for riscv64
+ 2023-06-30 5b72f45dd1 runtime: check GOFLAGS not GCFLAGS
+ 2023-06-29 18e17e2cb1 net: enable pure Go resolver for wasip1
+ 2023-06-29 1e97c51536 syscall: stub Getrlimit on wasip1
+ 2023-06-29 683f51d307 cmd/asm/internal/lex: fix comment, remove the first "has"
+ 2023-06-29 2db31efdba cmd/compile/internal/types2: make TestIssue43124 match the go/types version
+ 2023-06-29 499458f7ca net/http: validate Host header before sending
+ 2023-06-29 fe73c186eb cmd/{go,compile}: run gofmt
+ 2023-06-29 da5d8fdd0c runtime: run wasip1 tests with wazero
+ 2023-06-29 411c99671a slices, maps: add examples; doc comment fixes
+ 2023-06-29 03cd8a7b0e internal/bytealg: fix alignment code in equal_riscv64.s
+ 2023-06-28 8b5fe5980c cmd/compile: handle min/max correctly in mayCall
+ 2023-06-28 79d4defa75 cmd/compile/internal/ssagen: fix min/max codegen, again
+ 2023-06-28 a3093eca64 cmd/go: enable slog vet check during 'go test'
+ 2023-06-27 6691f438c3 cmd/dist, internal/abi: support bootstrapping with gccgo
+ 2023-06-27 942c1c12d8 runtime: fix trace.Stop deadlock when built with faketime
+ 2023-06-27 4ad4128d3c cmd/compile: fix bad order of evaluation for min/max builtin
+ 2023-06-27 4f36f7e4dd encoding: document that base32 and base64 do not use UTF-8
+ 2023-06-27 8008c0840f syscall: clarify which handles are affected by SysProcAttr.NoInheritHandles
+ 2023-06-27 13529cc5f4 syscall: try non-blocking stdio on wasip1
+ 2023-06-26 1dbbafc70f go/types, types2: replace TODO with clarifying comment
+ 2023-06-26 7cc0740596 slices: add godoc links
+ 2023-06-26 d49017a7c3 go/types, types2: fix interface unification
+ 2023-06-26 b3ca8d2b3c types2, go/types: record final type for min/max arguments
+ 2023-06-26 ee361ce66c go/types, types2: more readable inference trace
+ 2023-06-26 9f6e87ff74 doc/go1.21: document changes in crypto/x509
+ 2023-06-26 f5015b5164 doc/go1.21: context.Background and TODO may now appear equal
+ 2023-06-24 a031f4ef83 cmd/compile: fix min/max builtin code generation
+ 2023-06-24 ea927e560d slices: clarify MinFunc/MaxFunc result for equal elements
+ 2023-06-23 3619255777 crypto/x509: rename duplicated test
+ 2023-06-23 48dbb6227a runtime: set raceignore to zero when starting a new goroutine
+ 2023-06-23 3adcce5ae7 crypto: document non-determinism of GenerateKey
+ 2023-06-23 6dce882b3a cmd/compile: scanning closures body when visiting wrapper function
+ 2023-06-23 164aceea08 log/slog: fix broken link to AnyValue in comment
+ 2023-06-23 82e17c4d11 log/slog: fix broken link to Record.Clone in package docs
+ 2023-06-22 25e46693a1 cmd/go: impersonate 'go tool dist list' if 'go tool dist' is not present
+ 2023-06-22 f8616b8484 internal/platform,cmd/dist: export the list of supported platforms
+ 2023-06-22 51885c1fa2 cmd/{go,cover}: enable response file args for cmd/cover
+ 2023-06-22 3479e1e543 internal/fuzz: fix typo in comment
+ 2023-06-22 20313660f5 crypto/x509: tolerate multiple matching chains in testVerify
+ 2023-06-21 78c3aba470 net/mail: permit more characters in mail headers
+ 2023-06-21 633b742ae0 test: add test that caused a gofrontend crash
+ 2023-06-21 ad2c517708 doc/go1.21: correct GOOS to GOARCH (another location)
+ 2023-06-21 b23cae8095 doc/go1.21: correct GOOS to GOARCH
+ 2023-06-21 b1f1fb2950 go/types, types2: avoid spurious "declared and not used" error
+ 2023-06-21 e45202f215 runtime: relate GODEBUG=gctrace output to runtime/metrics
+ 2023-06-21 36edde9d9f cmd/go: shorten longest 5 tests
+ 2023-06-21 413e6c0499 cmd/compile/internal/ir: typo
+ 2023-06-20 f3bf18117b log/slog: fix HandlerOptions.ReplaceAttr doc
+ 2023-06-20 e122ebabb6 encoding/binary: on invalid type return -1 from Size
+ 2023-06-20 8484f2fe02 cmd/go: add comment for intentional misspelling

Change-Id: Ie91c398dde7ca2a210b286c7865d3e7a905d6ea9
2023-07-12 17:23:13 -04:00
Gopher Robot
d8117459c5 [release-branch.go1.21] go1.21rc2
Change-Id: I4a2c753f3edf22290e0e71a90df6d380fc009202
Reviewed-on: https://go-review.googlesource.com/c/go/+/504876
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Auto-Submit: Gopher Robot <gobot@golang.org>
Run-TryBot: Gopher Robot <gobot@golang.org>
TryBot-Bypass: Dmitri Shuralyov <dmitshur@golang.org>
Reviewed-by: Michael Pratt <mpratt@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@golang.org>
2023-06-21 15:40:05 +00:00
Dmitri Shuralyov
ebbff91f59 [release-branch.go1.21] all: merge master (a7b1793) into release-branch.go1.21
Merge List:

+ 2023-06-20 a7b1793701 cmd/go: do not index std as a module in modcache
+ 2023-06-20 3d279283a4 cmd/go: restore go.mod files during toolchain selection
+ 2023-06-20 3b4b7b84de cmd/distpack: rename go.mod to _go.mod in toolchain modules
+ 2023-06-20 6459494014 cmd/go: disable sumdb less often for toolchain downloads
+ 2023-06-20 02789816c4 internal/bisect: add 'q' hash option for quiet hash behavior switching
+ 2023-06-20 98617fd23f runtime/trace: add godoc links
+ 2023-06-19 bc21d6a4fc cmd/go/internal/modfetch: fix retractions slice initial length not zero
+ 2023-06-17 261e267618 os/exec: document a method to check if a process is alive
+ 2023-06-16 dbf9bf2c39 cmd/internal/moddeps: allow the "misc" module to be missing from GOROOT
+ 2023-06-16 0183c1aa02 cmd/compile/internal/syntax: skip GOROOT/misc in TestStdLib if it doesn't exist
+ 2023-06-16 199fbd4b59 cmd/internal/testdir: skip Test if GOROOT/test does not exist
+ 2023-06-16 a48f9c26d5 go/types: skip tests that require GOROOT/test if it is not present
+ 2023-06-16 3891ecbd35 go/internal/gcimporter: skip TestImportTypeparamTests if GOROOT/test is missing
+ 2023-06-16 60876717b4 cmd/go/internal/test: don't wait for previous test actions when interrupted
+ 2023-06-16 c1bc44642d path/filepath: avoid assuming that GOROOT/test is present
+ 2023-06-16 9ece9a7ac9 cmd/cgo/internal/testshared: disable gccgo tests on PPC64
+ 2023-06-16 23c5e48c4a cmd/cgo/internal/testshared: strip newline from gccgo -dumpversion
+ 2023-06-16 cf7ae4f136 compress/bzip2: fix typo
+ 2023-06-16 3c8b7a9551 net/http: check RemoteAddr isn't nil before dereferencing
+ 2023-06-16 548790e64a net/http: close req.Body only when it's non-nil on js
+ 2023-06-16 6dc2d2aa6b testing/fstest: fix the Glob test when dir entries are out of order
+ 2023-06-16 2b0ff4b629 reflect: fix ArenaNew to match documentation
+ 2023-06-16 4eceefa338 cmd/distpack: make go_$GOOS_$GOARCH_exec programs executable
+ 2023-06-16 1a7709d6af runtime: use 1-byte load for address checking in racecallatomic
+ 2023-06-15 3e7ec13166 cmd/go: fix build config for 'go list -cover'
+ 2023-06-15 30b17f4f97 net/http: only disable Fetch API in tests
+ 2023-06-15 65db95d0ed math: document that Min/Max differ from min/max
+ 2023-06-15 60e6afb689 cmd/compile: do not report division by error during typecheck
+ 2023-06-15 f6e0dcc474 slices: add sort benchmark for sorted strings

Change-Id: If342a000b719335fbbb421f027a8b253b07c1cab
2023-06-20 13:19:35 -04:00
Gopher Robot
1c1c82432a [release-branch.go1.21] go1.21rc1
time 2023-06-15T19:02:18Z

Change-Id: If39aa20f4858a5a794f30e3564b0165e6d096b70
Reviewed-on: https://go-review.googlesource.com/c/go/+/504015
Auto-Submit: Gopher Robot <gobot@golang.org>
Reviewed-by: Michael Pratt <mpratt@google.com>
TryBot-Bypass: Michael Pratt <mpratt@google.com>
Run-TryBot: Gopher Robot <gobot@golang.org>
Auto-Submit: Michael Pratt <mpratt@google.com>
Reviewed-by: David Chase <drchase@google.com>
2023-06-16 14:21:46 +00:00
Michael Pratt
b4a0665266 [release-branch.go1.21] all: merge master (b7e7467) into release-branch.go1.21
Merge List:

+ 2023-06-15 b7e7467865 test/codegen: add fsqrt test for riscv64
+ 2023-06-15 befec5ddbb text/template: set variables correctly in range assignment
+ 2023-06-15 c5463218a2 cmd/api: skip TestIssue29837 when -short is set
+ 2023-06-15 9fc84363d1 cmd/asm: fix encoding errors for FMOVD and FMOVS instructions on arm64
+ 2023-06-14 da94586aa3 cmd/go: check for errors reading gccgo package list
+ 2023-06-14 b01cd41b46 cmd/go: use gover.Local for $goversion in TestScript
+ 2023-06-14 3aea422e2c crypto/x509: use synthetic root for platform testing

Change-Id: Icec55130749c52eef75c0e0325d889ff18b067f6
2023-06-15 11:36:34 -04:00
Michael Pratt
577e7b9bb9 [release-branch.go1.21] update codereview.cfg for release-branch.go1.21
Change-Id: Ib853d63f300b75ae399529dadd9baa03693b6f60
Reviewed-on: https://go-review.googlesource.com/c/go/+/503435
Auto-Submit: Michael Pratt <mpratt@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@golang.org>
Reviewed-by: Heschi Kreinick <heschi@google.com>
Run-TryBot: Michael Pratt <mpratt@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
2023-06-14 20:26:29 +00:00
279 changed files with 5853 additions and 3574 deletions

2
VERSION Normal file
View File

@@ -0,0 +1,2 @@
go1.21.10
time 2024-05-01T19:49:47Z

View File

@@ -60,7 +60,9 @@ pkg crypto/tls, method (*QUICConn) Close() error #44886
pkg crypto/tls, method (*QUICConn) ConnectionState() ConnectionState #44886
pkg crypto/tls, method (*QUICConn) HandleData(QUICEncryptionLevel, []uint8) error #44886
pkg crypto/tls, method (*QUICConn) NextEvent() QUICEvent #44886
pkg crypto/tls, method (*QUICConn) SendSessionTicket(bool) error #60107
pkg crypto/tls, method (*QUICConn) SendSessionTicket(QUICSessionTicketOptions) error #60107
pkg crypto/tls, type QUICSessionTicketOptions struct #60107
pkg crypto/tls, type QUICSessionTicketOptions struct, EarlyData bool #60107
pkg crypto/tls, method (*QUICConn) SetTransportParameters([]uint8) #44886
pkg crypto/tls, method (*QUICConn) Start(context.Context) error #44886
pkg crypto/tls, method (QUICEncryptionLevel) String() string #44886
@@ -344,8 +346,6 @@ pkg maps, func Copy[$0 interface{ ~map[$2]$3 }, $1 interface{ ~map[$2]$3 }, $2 c
pkg maps, func DeleteFunc[$0 interface{ ~map[$1]$2 }, $1 comparable, $2 interface{}]($0, func($1, $2) bool) #57436
pkg maps, func Equal[$0 interface{ ~map[$2]$3 }, $1 interface{ ~map[$2]$3 }, $2 comparable, $3 comparable]($0, $1) bool #57436
pkg maps, func EqualFunc[$0 interface{ ~map[$2]$3 }, $1 interface{ ~map[$2]$4 }, $2 comparable, $3 interface{}, $4 interface{}]($0, $1, func($3, $4) bool) bool #57436
pkg maps, func Keys[$0 interface{ ~map[$1]$2 }, $1 comparable, $2 interface{}]($0) []$1 #57436
pkg maps, func Values[$0 interface{ ~map[$1]$2 }, $1 comparable, $2 interface{}]($0) []$2 #57436
pkg math/big, method (*Int) Float64() (float64, Accuracy) #56984
pkg net/http, method (*ProtocolError) Is(error) bool #41198
pkg net/http, method (*ResponseController) EnableFullDuplex() error #57786

View File

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

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
<!--{
"Title": "The Go Programming Language Specification",
"Subtitle": "Version of June 14, 2023",
"Subtitle": "Version of Aug 2, 2023",
"Path": "/ref/spec"
}-->
@@ -2511,7 +2511,7 @@ type (
<p>
A type definition creates a new, distinct type with the same
<a href="#Types">underlying type</a> and operations as the given type
<a href="#Underlying_types">underlying type</a> and operations as the given type
and binds an identifier, the <i>type name</i>, to it.
</p>
@@ -4343,7 +4343,7 @@ type parameter list type arguments after substitution
When using a generic function, type arguments may be provided explicitly,
or they may be partially or completely <a href="#Type_inference">inferred</a>
from the context in which the function is used.
Provided that they can be inferred, type arguments may be omitted entirely if the function is:
Provided that they can be inferred, type argument lists may be omitted entirely if the function is:
</p>
<ul>
@@ -4351,7 +4351,7 @@ Provided that they can be inferred, type arguments may be omitted entirely if th
<a href="#Calls">called</a> with ordinary arguments,
</li>
<li>
<a href="#Assignment_statements">assigned</a> to a variable with an explicitly declared type,
<a href="#Assignment_statements">assigned</a> to a variable with a known type
</li>
<li>
<a href="#Calls">passed as an argument</a> to another function, or
@@ -4371,7 +4371,7 @@ must be inferrable from the context in which the function is used.
// sum returns the sum (concatenation, for strings) of its arguments.
func sum[T ~int | ~float64 | ~string](x... T) T { … }
x := sum // illegal: sum must have a type argument (x is a variable without a declared type)
x := sum // illegal: the type of x is unknown
intSum := sum[int] // intSum has type func(x... int) int
a := intSum(2, 3) // a has value 5 of type int
b := sum[float64](2.0, 3) // b has value 5.0 of type float64
@@ -4406,402 +4406,323 @@ For a generic type, all type arguments must always be provided explicitly.
<h3 id="Type_inference">Type inference</h3>
<p>
<em>NOTE: This section is not yet up-to-date for Go 1.21.</em>
A use of a generic function may omit some or all type arguments if they can be
<i>inferred</i> from the context within which the function is used, including
the constraints of the function's type parameters.
Type inference succeeds if it can infer the missing type arguments
and <a href="#Instantiations">instantiation</a> succeeds with the
inferred type arguments.
Otherwise, type inference fails and the program is invalid.
</p>
<p>
Missing function type arguments may be <i>inferred</i> by a series of steps, described below.
Each step attempts to use known information to infer additional type arguments.
Type inference stops as soon as all type arguments are known.
After type inference is complete, it is still necessary to substitute all type arguments
for type parameters and verify that each type argument
<a href="#Implementing_an_interface">implements</a> the relevant constraint;
it is possible for an inferred type argument to fail to implement a constraint, in which
case instantiation fails.
Type inference uses the type relationships between pairs of types for inference:
For instance, a function argument must be <a href="#Assignability">assignable</a>
to its respective function parameter; this establishes a relationship between the
type of the argument and the type of the parameter.
If either of these two types contains type parameters, type inference looks for the
type arguments to substitute the type parameters with such that the assignability
relationship is satisfied.
Similarly, type inference uses the fact that a type argument must
<a href="#Satisfying_a_type_constraint">satisfy</a> the constraint of its respective
type parameter.
</p>
<p>
Type inference is based on
Each such pair of matched types corresponds to a <i>type equation</i> containing
one or multiple type parameters, from one or possibly multiple generic functions.
Inferring the missing type arguments means solving the resulting set of type
equations for the respective type parameters.
</p>
<p>
For example, given
</p>
<pre>
// dedup returns a copy of the argument slice with any duplicate entries removed.
func dedup[S ~[]E, E comparable](S) S { … }
type Slice []int
var s Slice
s = dedup(s) // same as s = dedup[Slice, int](s)
</pre>
<p>
the variable <code>s</code> of type <code>Slice</code> must be assignable to
the function parameter type <code>S</code> for the program to be valid.
To reduce complexity, type inference ignores the directionality of assignments,
so the type relationship between <code>Slice</code> and <code>S</code> can be
expressed via the (symmetric) type equation <code>Slice ≡<sub>A</sub> S</code>
(or <code>S ≡<sub>A</sub> Slice</code> for that matter),
where the <code><sub>A</sub></code> in <code><sub>A</sub></code>
indicates that the LHS and RHS types must match per assignability rules
(see the section on <a href="#Type_unification">type unification</a> for
details).
Similarly, the type parameter <code>S</code> must satisfy its constraint
<code>~[]E</code>. This can be expressed as <code>S ≡<sub>C</sub> ~[]E</code>
where <code>X ≡<sub>C</sub> Y</code> stands for
"<code>X</code> satisfies constraint <code>Y</code>".
These observations lead to a set of two equations
</p>
<pre>
Slice ≡<sub>A</sub> S (1)
S ≡<sub>C</sub> ~[]E (2)
</pre>
<p>
which now can be solved for the type parameters <code>S</code> and <code>E</code>.
From (1) a compiler can infer that the type argument for <code>S</code> is <code>Slice</code>.
Similarly, because the underlying type of <code>Slice</code> is <code>[]int</code>
and <code>[]int</code> must match <code>[]E</code> of the constraint,
a compiler can infer that <code>E</code> must be <code>int</code>.
Thus, for these two equations, type inference infers
</p>
<pre>
S ➞ Slice
E ➞ int
</pre>
<p>
Given a set of type equations, the type parameters to solve for are
the type parameters of the functions that need to be instantiated
and for which no explicit type arguments is provided.
These type parameters are called <i>bound</i> type parameters.
For instance, in the <code>dedup</code> example above, the type parameters
<code>P</code> and <code>E</code> are bound to <code>dedup</code>.
An argument to a generic function call may be a generic function itself.
The type parameters of that function are included in the set of bound
type parameters.
The types of function arguments may contain type parameters from other
functions (such as a generic function enclosing a function call).
Those type parameters may also appear in type equations but they are
not bound in that context.
Type equations are always solved for the bound type parameters only.
</p>
<p>
Type inference supports calls of generic functions and assignments
of generic functions to (explicitly function-typed) variables.
This includes passing generic functions as arguments to other
(possibly also generic) functions, and returning generic functions
as results.
Type inference operates on a set of equations specific to each of
these cases.
The equations are as follows (type argument lists are omitted for clarity):
</p>
<ul>
<li>
a <a href="#Type_parameter_declarations">type parameter list</a>
<p>
For a function call <code>f(a<sub>0</sub>, a<sub>1</sub>, …)</code> where
<code>f</code> or a function argument <code>a<sub>i</sub></code> is
a generic function:
<br>
Each pair <code>(a<sub>i</sub>, p<sub>i</sub>)</code> of corresponding
function arguments and parameters where <code>a<sub>i</sub></code> is not an
<a href="#Constants">untyped constant</a> yields an equation
<code>typeof(p<sub>i</sub>) ≡<sub>A</sub> typeof(a<sub>i</sub>)</code>.
<br>
If <code>a<sub>i</sub></code> is an untyped constant <code>c<sub>j</sub></code>,
and <code>typeof(p<sub>i</sub>)</code> is a bound type parameter <code>P<sub>k</sub></code>,
the pair <code>(c<sub>j</sub>, P<sub>k</sub>)</code> is collected separately from
the type equations.
</p>
</li>
<li>
a substitution map <i>M</i> initialized with the known type arguments, if any
<p>
For an assignment <code>v = f</code> of a generic function <code>f</code> to a
(non-generic) variable <code>v</code> of function type:
<br>
<code>typeof(v) ≡<sub>A</sub> typeof(f)</code>.
</p>
</li>
<li>
a (possibly empty) list of ordinary function arguments (in case of a function call only)
<p>
For a return statement <code>return …, f, … </code> where <code>f</code> is a
generic function returned as a result to a (non-generic) result variable
<code>r</code> of function type:
<br>
<code>typeof(r) ≡<sub>A</sub> typeof(f)</code>.
</p>
</li>
</ul>
<p>
and then proceeds with the following steps:
Additionally, each type parameter <code>P<sub>k</sub></code> and corresponding type constraint
<code>C<sub>k</sub></code> yields the type equation
<code>P<sub>k</sub><sub>C</sub> C<sub>k</sub></code>.
</p>
<p>
Type inference gives precedence to type information obtained from typed operands
before considering untyped constants.
Therefore, inference proceeds in two phases:
</p>
<ol>
<li>
apply <a href="#Function_argument_type_inference"><i>function argument type inference</i></a>
to all <i>typed</i> ordinary function arguments
<p>
The type equations are solved for the bound
type parameters using <a href="#Type_unification">type unification</a>.
If unification fails, type inference fails.
</p>
</li>
<li>
apply <a href="#Constraint_type_inference"><i>constraint type inference</i></a>
</li>
<li>
apply function argument type inference to all <i>untyped</i> ordinary function arguments
using the default type for each of the untyped function arguments
</li>
<li>
apply constraint type inference
<p>
For each bound type parameter <code>P<sub>k</sub></code> for which no type argument
has been inferred yet and for which one or more pairs
<code>(c<sub>j</sub>, P<sub>k</sub>)</code> with that same type parameter
were collected, determine the <a href="#Constant_expressions">constant kind</a>
of the constants <code>c<sub>j</sub></code> in all those pairs the same way as for
<a href="#Constant_expressions">constant expressions</a>.
The type argument for <code>P<sub>k</sub></code> is the
<a href="#Constants">default type</a> for the determined constant kind.
If a constant kind cannot be determined due to conflicting constant kinds,
type inference fails.
</p>
</li>
</ol>
<p>
If there are no ordinary or untyped function arguments, the respective steps are skipped.
Constraint type inference is skipped if the previous step didn't infer any new type arguments,
but it is run at least once if there are missing type arguments.
If not all type arguments have been found after these two phases, type inference fails.
</p>
<p>
The substitution map <i>M</i> is carried through all steps, and each step may add entries to <i>M</i>.
The process stops as soon as <i>M</i> has a type argument for each type parameter or if an inference step fails.
If an inference step fails, or if <i>M</i> is still missing type arguments after the last step, type inference fails.
If the two phases are successful, type inference determined a type argument for each
bound type parameter:
</p>
<pre>
P<sub>k</sub> ➞ A<sub>k</sub>
</pre>
<p>
A type argument <code>A<sub>k</sub></code> may be a composite type,
containing other bound type parameters <code>P<sub>k</sub></code> as element types
(or even be just another bound type parameter).
In a process of repeated simplification, the bound type parameters in each type
argument are substituted with the respective type arguments for those type
parameters until each type argument is free of bound type parameters.
</p>
<p>
If type arguments contain cyclic references to themselves
through bound type parameters, simplification and thus type
inference fails.
Otherwise, type inference succeeds.
</p>
<h4 id="Type_unification">Type unification</h4>
<p>
Type inference is based on <i>type unification</i>. A single unification step
applies to a <a href="#Type_inference">substitution map</a> and two types, either
or both of which may be or contain type parameters. The substitution map tracks
the known (explicitly provided or already inferred) type arguments: the map
contains an entry <code>P</code> &RightArrow; <code>A</code> for each type
parameter <code>P</code> and corresponding known type argument <code>A</code>.
During unification, known type arguments take the place of their corresponding type
parameters when comparing types. Unification is the process of finding substitution
map entries that make the two types equivalent.
Type inference solves type equations through <i>type unification</i>.
Type unification recursively compares the LHS and RHS types of an
equation, where either or both types may be or contain bound type parameters,
and looks for type arguments for those type parameters such that the LHS
and RHS match (become identical or assignment-compatible, depending on
context).
To that effect, type inference maintains a map of bound type parameters
to inferred type arguments; this map is consulted and updated during type unification.
Initially, the bound type parameters are known but the map is empty.
During type unification, if a new type argument <code>A</code> is inferred,
the respective mapping <code>P ➞ A</code> from type parameter to argument
is added to the map.
Conversely, when comparing types, a known type argument
(a type argument for which a map entry already exists)
takes the place of its corresponding type parameter.
As type inference progresses, the map is populated more and more
until all equations have been considered, or until unification fails.
Type inference succeeds if no unification step fails and the map has
an entry for each type parameter.
</p>
<p>
For unification, two types that don't contain any type parameters from the current type
parameter list are <i>equivalent</i>
if they are identical, or if they are channel types that are identical ignoring channel
direction, or if their underlying types are equivalent.
</p>
<p>
Unification works by comparing the structure of pairs of types: their structure
disregarding type parameters must be identical, and types other than type parameters
must be equivalent.
A type parameter in one type may match any complete subtype in the other type;
each successful match causes an entry to be added to the substitution map.
If the structure differs, or types other than type parameters are not equivalent,
unification fails.
</p>
<!--
TODO(gri) Somewhere we need to describe the process of adding an entry to the
substitution map: if the entry is already present, the type argument
values are themselves unified.
-->
<p>
For example, if <code>T1</code> and <code>T2</code> are type parameters,
<code>[]map[int]bool</code> can be unified with any of the following:
</pre>
For example, given the type equation with the bound type parameter
<code>P</code>
</p>
<pre>
[]map[int]bool // types are identical
T1 // adds T1 &RightArrow; []map[int]bool to substitution map
[]T1 // adds T1 &RightArrow; map[int]bool to substitution map
[]map[T1]T2 // adds T1 &RightArrow; int and T2 &RightArrow; bool to substitution map
[10]struct{ elem P, list []P } ≡<sub>A</sub> [10]struct{ elem string; list []string }
</pre>
<p>
On the other hand, <code>[]map[int]bool</code> cannot be unified with any of
</p>
<pre>
int // int is not a slice
struct{} // a struct is not a slice
[]struct{} // a struct is not a map
[]map[T1]string // map element types don't match
</pre>
<p>
As an exception to this general rule, because a <a href="#Type_definitions">defined type</a>
<code>D</code> and a type literal <code>L</code> are never equivalent,
unification compares the underlying type of <code>D</code> with <code>L</code> instead.
For example, given the defined type
</p>
<pre>
type Vector []float64
</pre>
<p>
and the type literal <code>[]E</code>, unification compares <code>[]float64</code> with
<code>[]E</code> and adds an entry <code>E</code> &RightArrow; <code>float64</code> to
the substitution map.
</p>
<h4 id="Function_argument_type_inference">Function argument type inference</h4>
<!-- In this section and the section on constraint type inference we start with examples
rather than have the examples follow the rules as is customary elsewhere in spec.
Hopefully this helps building an intuition and makes the rules easier to follow. -->
<p>
Function argument type inference infers type arguments from function arguments:
if a function parameter is declared with a type <code>T</code> that uses
type parameters,
<a href="#Type_unification">unifying</a> the type of the corresponding
function argument with <code>T</code> may infer type arguments for the type
parameters used by <code>T</code>.
type inference starts with an empty map.
Unification first compares the top-level structure of the LHS and RHS
types.
Both are arrays of the same length; they unify if the element types unify.
Both element types are structs; they unify if they have
the same number of fields with the same names and if the
field types unify.
The type argument for <code>P</code> is not known yet (there is no map entry),
so unifying <code>P</code> with <code>string</code> adds
the mapping <code>P ➞ string</code> to the map.
Unifying the types of the <code>list</code> field requires
unifying <code>[]P</code> and <code>[]string</code> and
thus <code>P</code> and <code>string</code>.
Since the type argument for <code>P</code> is known at this point
(there is a map entry for <code>P</code>), its type argument
<code>string</code> takes the place of <code>P</code>.
And since <code>string</code> is identical to <code>string</code>,
this unification step succeeds as well.
Unification of the LHS and RHS of the equation is now finished.
Type inference succeeds because there is only one type equation,
no unification step failed, and the map is fully populated.
</p>
<p>
For instance, given the generic function
</p>
<pre>
func scale[Number ~int64|~float64|~complex128](v []Number, s Number) []Number
</pre>
<p>
and the call
</p>
<pre>
var vector []float64
scaledVector := scale(vector, 42)
</pre>
<p>
the type argument for <code>Number</code> can be inferred from the function argument
<code>vector</code> by unifying the type of <code>vector</code> with the corresponding
parameter type: <code>[]float64</code> and <code>[]Number</code>
match in structure and <code>float64</code> matches with <code>Number</code>.
This adds the entry <code>Number</code> &RightArrow; <code>float64</code> to the
<a href="#Type_unification">substitution map</a>.
Untyped arguments, such as the second function argument <code>42</code> here, are ignored
in the first round of function argument type inference and only considered if there are
unresolved type parameters left.
Unification uses a combination of <i>exact</i> and <i>loose</i>
unification depending on whether two types have to be
<a href="#Type_identity">identical</a>,
<a href="#Assignability">assignment-compatible</a>, or
only structurally equal.
The respective <a href="#Type_unification_rules">type unification rules</a>
are spelled out in detail in the <a href="#Appendix">Appendix</a>.
</p>
<p>
Inference happens in two separate phases; each phase operates on a specific list of
(parameter, argument) pairs:
For an equation of the form <code>X ≡<sub>A</sub> Y</code>,
where <code>X</code> and <code>Y</code> are types involved
in an assignment (including parameter passing and return statements),
the top-level type structures may unify loosely but element types
must unify exactly, matching the rules for assignments.
</p>
<ol>
<p>
For an equation of the form <code>P ≡<sub>C</sub> C</code>,
where <code>P</code> is a type parameter and <code>C</code>
its corresponding constraint, the unification rules are bit
more complicated:
</p>
<ul>
<li>
The list <i>Lt</i> contains all (parameter, argument) pairs where the parameter
type uses type parameters and where the function argument is <i>typed</i>.
If <code>C</code> has a <a href="#Core_types">core type</a>
<code>core(C)</code>
and <code>P</code> has a known type argument <code>A</code>,
<code>core(C)</code> and <code>A</code> must unify loosely.
If <code>P</code> does not have a known type argument
and <code>C</code> contains exactly one type term <code>T</code>
that is not an underlying (tilde) type, unification adds the
mapping <code>P ➞ T</code> to the map.
</li>
<li>
The list <i>Lu</i> contains all remaining pairs where the parameter type is a single
type parameter. In this list, the respective function arguments are untyped.
If <code>C</code> does not have a core type
and <code>P</code> has a known type argument <code>A</code>,
<code>A</code> must have all methods of <code>C</code>, if any,
and corresponding method types must unify exactly.
</li>
</ol>
</ul>
<p>
Any other (parameter, argument) pair is ignored.
</p>
<p>
By construction, the arguments of the pairs in <i>Lu</i> are <i>untyped</i> constants
(or the untyped boolean result of a comparison). And because <a href="#Constants">default types</a>
of untyped values are always predeclared non-composite types, they can never match against
a composite type, so it is sufficient to only consider parameter types that are single type
parameters.
</p>
<p>
Each list is processed in a separate phase:
</p>
<ol>
<li>
In the first phase, the parameter and argument types of each pair in <i>Lt</i>
are unified. If unification succeeds for a pair, it may yield new entries that
are added to the substitution map <i>M</i>. If unification fails, type inference
fails.
</li>
<li>
The second phase considers the entries of list <i>Lu</i>. Type parameters for
which the type argument has already been determined are ignored in this phase.
For each remaining pair, the parameter type (which is a single type parameter) and
the <a href="#Constants">default type</a> of the corresponding untyped argument is
unified. If unification fails, type inference fails.
</li>
</ol>
<p>
While unification is successful, processing of each list continues until all list elements
are considered, even if all type arguments are inferred before the last list element has
been processed.
</p>
<p>
Example:
</p>
<pre>
func min[T ~int|~float64](x, y T) T
var x int
min(x, 2.0) // T is int, inferred from typed argument x; 2.0 is assignable to int
min(1.0, 2.0) // T is float64, inferred from default type for 1.0 and matches default type for 2.0
min(1.0, 2) // illegal: default type float64 (for 1.0) doesn't match default type int (for 2)
</pre>
<p>
In the example <code>min(1.0, 2)</code>, processing the function argument <code>1.0</code>
yields the substitution map entry <code>T</code> &RightArrow; <code>float64</code>. Because
processing continues until all untyped arguments are considered, an error is reported. This
ensures that type inference does not depend on the order of the untyped arguments.
</p>
<h4 id="Constraint_type_inference">Constraint type inference</h4>
<p>
Constraint type inference infers type arguments by considering type constraints.
If a type parameter <code>P</code> has a constraint with a
<a href="#Core_types">core type</a> <code>C</code>,
<a href="#Type_unification">unifying</a> <code>P</code> with <code>C</code>
may infer additional type arguments, either the type argument for <code>P</code>,
or if that is already known, possibly the type arguments for type parameters
used in <code>C</code>.
</p>
<p>
For instance, consider the type parameter list with type parameters <code>List</code> and
<code>Elem</code>:
</p>
<pre>
[List ~[]Elem, Elem any]
</pre>
<p>
Constraint type inference can deduce the type of <code>Elem</code> from the type argument
for <code>List</code> because <code>Elem</code> is a type parameter in the core type
<code>[]Elem</code> of <code>List</code>.
If the type argument is <code>Bytes</code>:
</p>
<pre>
type Bytes []byte
</pre>
<p>
unifying the underlying type of <code>Bytes</code> with the core type means
unifying <code>[]byte</code> with <code>[]Elem</code>. That unification succeeds and yields
the <a href="#Type_unification">substitution map</a> entry
<code>Elem</code> &RightArrow; <code>byte</code>.
Thus, in this example, constraint type inference can infer the second type argument from the
first one.
</p>
<p>
Using the core type of a constraint may lose some information: In the (unlikely) case that
the constraint's type set contains a single <a href="#Type_definitions">defined type</a>
<code>N</code>, the corresponding core type is <code>N</code>'s underlying type rather than
<code>N</code> itself. In this case, constraint type inference may succeed but instantiation
will fail because the inferred type is not in the type set of the constraint.
Thus, constraint type inference uses the <i>adjusted core type</i> of
a constraint: if the type set contains a single type, use that type; otherwise use the
constraint's core type.
</p>
<p>
Generally, constraint type inference proceeds in two phases: Starting with a given
substitution map <i>M</i>
</p>
<ol>
<li>
For all type parameters with an adjusted core type, unify the type parameter with that
type. If any unification fails, constraint type inference fails.
</li>
<li>
At this point, some entries in <i>M</i> may map type parameters to other
type parameters or to types containing type parameters. For each entry
<code>P</code> &RightArrow; <code>A</code> in <i>M</i> where <code>A</code> is or
contains type parameters <code>Q</code> for which there exist entries
<code>Q</code> &RightArrow; <code>B</code> in <i>M</i>, substitute those
<code>Q</code> with the respective <code>B</code> in <code>A</code>.
Stop when no further substitution is possible.
</li>
</ol>
<p>
The result of constraint type inference is the final substitution map <i>M</i> from type
parameters <code>P</code> to type arguments <code>A</code> where no type parameter <code>P</code>
appears in any of the <code>A</code>.
</p>
<p>
For instance, given the type parameter list
</p>
<pre>
[A any, B []C, C *A]
</pre>
<p>
and the single provided type argument <code>int</code> for type parameter <code>A</code>,
the initial substitution map <i>M</i> contains the entry <code>A</code> &RightArrow; <code>int</code>.
</p>
<p>
In the first phase, the type parameters <code>B</code> and <code>C</code> are unified
with the core type of their respective constraints. This adds the entries
<code>B</code> &RightArrow; <code>[]C</code> and <code>C</code> &RightArrow; <code>*A</code>
to <i>M</i>.
<p>
At this point there are two entries in <i>M</i> where the right-hand side
is or contains type parameters for which there exists other entries in <i>M</i>:
<code>[]C</code> and <code>*A</code>.
In the second phase, these type parameters are replaced with their respective
types. It doesn't matter in which order this happens. Starting with the state
of <i>M</i> after the first phase:
</p>
<p>
<code>A</code> &RightArrow; <code>int</code>,
<code>B</code> &RightArrow; <code>[]C</code>,
<code>C</code> &RightArrow; <code>*A</code>
</p>
<p>
Replace <code>A</code> on the right-hand side of &RightArrow; with <code>int</code>:
</p>
<p>
<code>A</code> &RightArrow; <code>int</code>,
<code>B</code> &RightArrow; <code>[]C</code>,
<code>C</code> &RightArrow; <code>*int</code>
</p>
<p>
Replace <code>C</code> on the right-hand side of &RightArrow; with <code>*int</code>:
</p>
<p>
<code>A</code> &RightArrow; <code>int</code>,
<code>B</code> &RightArrow; <code>[]*int</code>,
<code>C</code> &RightArrow; <code>*int</code>
</p>
<p>
At this point no further substitution is possible and the map is full.
Therefore, <code>M</code> represents the final map of type parameters
to type arguments for the given type parameter list.
When solving type equations from type constraints,
solving one equation may infer additional type arguments,
which in turn may enable solving other equations that depend
on those type arguments.
Type inference repeats type unification as long as new type
arguments are inferred.
</p>
<h3 id="Operators">Operators</h3>
@@ -5479,7 +5400,7 @@ in any of these cases:
ignoring struct tags (see below),
<code>x</code>'s type and <code>T</code> are not
<a href="#Type_parameter_declarations">type parameters</a> but have
<a href="#Type_identity">identical</a> <a href="#Types">underlying types</a>.
<a href="#Type_identity">identical</a> <a href="#Underlying_types">underlying types</a>.
</li>
<li>
ignoring struct tags (see below),
@@ -7324,7 +7245,8 @@ clear(t) type parameter see below
</pre>
<p>
If the argument type is a <a href="#Type_parameter_declarations">type parameter</a>,
If the type of the argument to <code>clear</code> is a
<a href="#Type_parameter_declarations">type parameter</a>,
all types in its type set must be maps or slices, and <code>clear</code>
performs the operation corresponding to the actual type argument.
</p>
@@ -8290,7 +8212,7 @@ of if the general conversion rules take care of this.
<p>
A <code>Pointer</code> is a <a href="#Pointer_types">pointer type</a> but a <code>Pointer</code>
value may not be <a href="#Address_operators">dereferenced</a>.
Any pointer or value of <a href="#Types">underlying type</a> <code>uintptr</code> can be
Any pointer or value of <a href="#Underlying_types">underlying type</a> <code>uintptr</code> can be
<a href="#Conversions">converted</a> to a type of underlying type <code>Pointer</code> and vice versa.
The effect of converting between <code>Pointer</code> and <code>uintptr</code> is implementation-defined.
</p>
@@ -8438,3 +8360,145 @@ The following minimal alignment properties are guaranteed:
<p>
A struct or array type has size zero if it contains no fields (or elements, respectively) that have a size greater than zero. Two distinct zero-size variables may have the same address in memory.
</p>
<h2 id="Appendix">Appendix</h2>
<h3 id="Type_unification_rules">Type unification rules</h3>
<p>
The type unification rules describe if and how two types unify.
The precise details are relevant for Go implementations,
affect the specifics of error messages (such as whether
a compiler reports a type inference or other error),
and may explain why type inference fails in unusual code situations.
But by and large these rules can be ignored when writing Go code:
type inference is designed to mostly "work as expected",
and the unification rules are fine-tuned accordingly.
</p>
<p>
Type unification is controlled by a <i>matching mode</i>, which may
be <i>exact</i> or <i>loose</i>.
As unification recursively descends a composite type structure,
the matching mode used for elements of the type, the <i>element matching mode</i>,
remains the same as the matching mode except when two types are unified for
<a href="#Assignability">assignability</a> (<code><sub>A</sub></code>):
in this case, the matching mode is <i>loose</i> at the top level but
then changes to <i>exact</i> for element types, reflecting the fact
that types don't have to be identical to be assignable.
</p>
<p>
Two types that are not bound type parameters unify exactly if any of
following conditions is true:
</p>
<ul>
<li>
Both types are <a href="#Type_identity">identical</a>.
</li>
<li>
Both types have identical structure and their element types
unify exactly.
</li>
<li>
Exactly one type is an <a href="#Type_inference">unbound</a>
type parameter with a <a href="#Core_types">core type</a>,
and that core type unifies with the other type per the
unification rules for <code><sub>A</sub></code>
(loose unification at the top level and exact unification
for element types).
</li>
</ul>
<p>
If both types are bound type parameters, they unify per the given
matching modes if:
</p>
<ul>
<li>
Both type parameters are identical.
</li>
<li>
At most one of the type parameters has a known type argument.
In this case, the type parameters are <i>joined</i>:
they both stand for the same type argument.
If neither type parameter has a known type argument yet,
a future type argument inferred for one the type parameters
is simultaneously inferred for both of them.
</li>
<li>
Both type parameters have a known type argument
and the type arguments unify per the given matching modes.
</li>
</ul>
<p>
A single bound type parameter <code>P</code> and another type <code>T</code> unify
per the given matching modes if:
</p>
<ul>
<li>
<code>P</code> doesn't have a known type argument.
In this case, <code>T</code> is inferred as the type argument for <code>P</code>.
</li>
<li>
<code>P</code> does have a known type argument <code>A</code>,
<code>A</code> and <code>T</code> unify per the given matching modes,
and one of the following conditions is true:
<ul>
<li>
Both <code>A</code> and <code>T</code> are interface types:
In this case, if both <code>A</code> and <code>T</code> are
also <a href="#Type_definitions">defined</a> types,
they must be <a href="#Type_identity">identical</a>.
Otherwise, if neither of them is a defined type, they must
have the same number of methods
(unification of <code>A</code> and <code>T</code> already
established that the methods match).
</li>
<li>
Neither <code>A</code> nor <code>T</code> are interface types:
In this case, if <code>T</code> is a defined type, <code>T</code>
replaces <code>A</code> as the inferred type argument for <code>P</code>.
</li>
</ul>
</li>
</ul>
<p>
Finally, two types that are not bound type parameters unify loosely
(and per the element matching mode) if:
</p>
<ul>
<li>
Both types unify exactly.
</li>
<li>
One type is a <a href="#Type_definitions">defined type</a>,
the other type is a type literal, but not an interface,
and their underlying types unify per the element matching mode.
</li>
<li>
Both types are interfaces (but not type parameters) with
identical <a href="#Interface_types">type terms</a>,
both or neither embed the predeclared type
<a href="#Predeclared_identifiers">comparable</a>,
corresponding method types unify per the element matching mode,
and the method set of one of the interfaces is a subset of
the method set of the other interface.
</li>
<li>
Only one type is an interface (but not a type parameter),
corresponding methods of the two types unify per the element matching mode,
and the method set of the interface is a subset of
the method set of the other type.
</li>
<li>
Both types have the same structure and their element types
unify per the element matching mode.
</li>
</ul>

View File

@@ -126,6 +126,27 @@ for example,
see the [runtime documentation](/pkg/runtime#hdr-Environment_Variables)
and the [go command documentation](/cmd/go#hdr-Build_and_test_caching).
### Go 1.22
Go 1.22 adds a configurable limit to control the maximum acceptable RSA key size
that can be used in TLS handshakes, controlled by the [`tlsmaxrsasize`setting](/pkg/crypto/tls#Conn.Handshake).
The default is tlsmaxrsasize=8192, limiting RSA to 8192-bit keys. To avoid
denial of service attacks, this setting and default was backported to Go
1.19.13, Go 1.20.8, and Go 1.21.1.
Go 1.22 changed how the runtime interacts with transparent huge pages on Linux.
In particular, a common default Linux kernel configuration can result in
significant memory overheads, and Go 1.22 no longer works around this default.
To work around this issue without adjusting kernel settings, transparent huge
pages can be disabled for Go memory with the
[`disablethp` setting](/pkg/runtime#hdr-Environment_Variable).
This behavior was backported to Go 1.21.1, but the setting is only available
starting with Go 1.21.6.
This setting may be removed in a future release, and users impacted by this issue
should adjust their Linux configuration according to the recommendations in the
[GC guide](/doc/gc-guide#Linux_transparent_huge_pages), or switch to a Linux
distribution that disables transparent huge pages altogether.
### Go 1.21
Go 1.21 made it a run-time error to call `panic` with a nil interface value,

View File

@@ -10,12 +10,12 @@ case "$GOWASIRUNTIME" in
"wasmer")
exec wasmer run --dir=/ --env PWD="$PWD" --env PATH="$PATH" ${GOWASIRUNTIMEARGS:-} "$1" -- "${@:2}"
;;
"wasmtime")
exec wasmtime run --dir=/ --env PWD="$PWD" --env PATH="$PATH" --max-wasm-stack 1048576 ${GOWASIRUNTIMEARGS:-} "$1" -- "${@:2}"
;;
"wazero" | "")
"wazero")
exec wazero run -mount /:/ -env-inherit -cachedir "${TMPDIR:-/tmp}"/wazero ${GOWASIRUNTIMEARGS:-} "$1" "${@:2}"
;;
"wasmtime" | "")
exec wasmtime run --dir=/ --env PWD="$PWD" --env PATH="$PATH" --max-wasm-stack 1048576 ${GOWASIRUNTIMEARGS:-} "$1" -- "${@:2}"
;;
*)
echo "Unknown Go WASI runtime specified: $GOWASIRUNTIME"
exit 1

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 api
package main
import (
"flag"

View File

@@ -4,7 +4,7 @@
//go:build boringcrypto
package api
package main
import (
"fmt"

View File

@@ -2,9 +2,10 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package api computes the exported API of a set of Go packages.
// This package computes the exported API of a set of Go packages.
// It is only a test, not a command, nor a usefully importable package.
package api
package main
import (
"bufio"

View File

@@ -183,28 +183,28 @@ start:
// 8.2: Load-Reserved/Store-Conditional
LRW (X5), X6 // 2fa30214
LRD (X5), X6 // 2fb30214
SCW X5, (X6), X7 // af23531c
SCD X5, (X6), X7 // af33531c
SCW X5, (X6), X7 // af23531a
SCD X5, (X6), X7 // af33531a
// 8.3: Atomic Memory Operations
AMOSWAPW X5, (X6), X7 // af23530c
AMOSWAPD X5, (X6), X7 // af33530c
AMOADDW X5, (X6), X7 // af235304
AMOADDD X5, (X6), X7 // af335304
AMOANDW X5, (X6), X7 // af235364
AMOANDD X5, (X6), X7 // af335364
AMOORW X5, (X6), X7 // af235344
AMOORD X5, (X6), X7 // af335344
AMOXORW X5, (X6), X7 // af235324
AMOXORD X5, (X6), X7 // af335324
AMOMAXW X5, (X6), X7 // af2353a4
AMOMAXD X5, (X6), X7 // af3353a4
AMOMAXUW X5, (X6), X7 // af2353e4
AMOMAXUD X5, (X6), X7 // af3353e4
AMOMINW X5, (X6), X7 // af235384
AMOMIND X5, (X6), X7 // af335384
AMOMINUW X5, (X6), X7 // af2353c4
AMOMINUD X5, (X6), X7 // af3353c4
AMOSWAPW X5, (X6), X7 // af23530e
AMOSWAPD X5, (X6), X7 // af33530e
AMOADDW X5, (X6), X7 // af235306
AMOADDD X5, (X6), X7 // af335306
AMOANDW X5, (X6), X7 // af235366
AMOANDD X5, (X6), X7 // af335366
AMOORW X5, (X6), X7 // af235346
AMOORD X5, (X6), X7 // af335346
AMOXORW X5, (X6), X7 // af235326
AMOXORD X5, (X6), X7 // af335326
AMOMAXW X5, (X6), X7 // af2353a6
AMOMAXD X5, (X6), X7 // af3353a6
AMOMAXUW X5, (X6), X7 // af2353e6
AMOMAXUD X5, (X6), X7 // af3353e6
AMOMINW X5, (X6), X7 // af235386
AMOMIND X5, (X6), X7 // af335386
AMOMINUW X5, (X6), X7 // af2353c6
AMOMINUD X5, (X6), X7 // af3353c6
// 10.1: Base Counters and Timers
RDCYCLE X5 // f32200c0

View File

@@ -1,7 +1,7 @@
package cgotest
/*
#cgo LDFLAGS: -lm
#cgo !darwin LDFLAGS: -lm
#include <math.h>
*/
import "C"

View File

@@ -1,7 +1,7 @@
package issue8756
/*
#cgo LDFLAGS: -lm
#cgo !darwin LDFLAGS: -lm
#include <math.h>
*/
import "C"

View File

@@ -23,7 +23,7 @@ package cgotest
#include <unistd.h>
#include <sys/stat.h>
#include <errno.h>
#cgo LDFLAGS: -lm
#cgo !darwin LDFLAGS: -lm
#ifndef WIN32
#include <pthread.h>

View File

@@ -1365,3 +1365,35 @@ func TestDeepStack(t *testing.T) {
t.Error(err)
}
}
func TestSharedObject(t *testing.T) {
// Test that we can put a Go c-archive into a C shared object.
globalSkip(t)
testenv.MustHaveGoBuild(t)
testenv.MustHaveCGO(t)
testenv.MustHaveBuildMode(t, "c-archive")
t.Parallel()
if !testWork {
defer func() {
os.Remove("libgo_s.a")
os.Remove("libgo_s.h")
os.Remove("libgo_s.so")
}()
}
cmd := exec.Command("go", "build", "-buildmode=c-archive", "-o", "libgo_s.a", "./libgo")
out, err := cmd.CombinedOutput()
t.Logf("%v\n%s", cmd.Args, out)
if err != nil {
t.Fatal(err)
}
ccArgs := append(cc, "-shared", "-o", "libgo_s.so", "libgo_s.a")
out, err = exec.Command(ccArgs[0], ccArgs[1:]...).CombinedOutput()
t.Logf("%v\n%s", ccArgs, out)
if err != nil {
t.Fatal(err)
}
}

View File

@@ -111,6 +111,7 @@ func TestReportsTypeErrors(t *testing.T) {
for _, file := range []string{
"err1.go",
"err2.go",
"err5.go",
"issue11097a.go",
"issue11097b.go",
"issue18452.go",

View File

@@ -0,0 +1,10 @@
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
//line /tmp/_cgo_.go:1
//go:cgo_dynamic_linker "/elf/interp" // ERROR HERE: only allowed in cgo-generated code
func main() {}

View File

@@ -389,9 +389,18 @@ func TestForkExec(t *testing.T) {
}
}
func TestGeneric(t *testing.T) {
func TestSymbolNameMangle(t *testing.T) {
// Issue 58800: generic function name may contain weird characters
// that confuse the external linker.
// Issue 62098: the name mangling code doesn't handle some string
// symbols correctly.
globalSkip(t)
goCmd(t, "build", "-buildmode=plugin", "-o", "generic.so", "./generic/plugin.go")
goCmd(t, "build", "-buildmode=plugin", "-o", "mangle.so", "./mangle/plugin.go")
}
func TestIssue62430(t *testing.T) {
globalSkip(t)
goCmd(t, "build", "-buildmode=plugin", "-o", "issue62430.so", "./issue62430/plugin.go")
goCmd(t, "build", "-o", "issue62430.exe", "./issue62430/main.go")
run(t, "./issue62430.exe")
}

View File

@@ -0,0 +1,35 @@
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Issue 62430: a program that uses plugins may appear
// to have no references to an initialized global map variable defined
// in some stdlib package (ex: unicode), however there
// may be references to that map var from a plugin that
// gets loaded.
package main
import (
"fmt"
"plugin"
"unicode"
)
func main() {
p, err := plugin.Open("issue62430.so")
if err != nil {
panic(err)
}
s, err := p.Lookup("F")
if err != nil {
panic(err)
}
f := s.(func(string) *unicode.RangeTable)
if f("C") == nil {
panic("unicode.Categories not properly initialized")
} else {
fmt.Println("unicode.Categories properly initialized")
}
}

View File

@@ -0,0 +1,11 @@
package main
import (
"unicode"
)
func F(s string) *unicode.RangeTable {
return unicode.Categories[s]
}
func main() {}

View File

@@ -2,21 +2,37 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Instantiated function name may contain weird characters
// that confuse the external linker, so it needs to be
// mangled.
// Test cases for symbol name mangling.
package main
//go:noinline
func F[T any]() {}
import (
"fmt"
"strings"
)
// Issue 58800:
// Instantiated function name may contain weird characters
// that confuse the external linker, so it needs to be
// mangled.
type S struct {
X int `parser:"|@@)"`
}
//go:noinline
func F[T any]() {}
func P() {
F[S]()
}
// Issue 62098: the name mangling code doesn't handle some string
// symbols correctly.
func G(id string) error {
if strings.ContainsAny(id, "&$@;/:+,?\\{^}%`]\">[~<#|") {
return fmt.Errorf("invalid")
}
return nil
}
func main() {}

View File

@@ -16,8 +16,10 @@ import (
"encoding/json"
"errors"
"fmt"
"internal/testenv"
"os"
"os/exec"
"os/user"
"path/filepath"
"regexp"
"strconv"
@@ -266,12 +268,28 @@ func compilerSupportsLocation() bool {
case "gcc":
return compiler.major >= 10
case "clang":
// TODO(65606): The clang toolchain on the LUCI builders is not built against
// zlib, the ASAN runtime can't actually symbolize its own stack trace. Once
// this is resolved, one way or another, switch this back to 'true'. We still
// have coverage from the 'gcc' case above.
if inLUCIBuild() {
return false
}
return true
default:
return false
}
}
// inLUCIBuild returns true if we're currently executing in a LUCI build.
func inLUCIBuild() bool {
u, err := user.Current()
if err != nil {
return false
}
return testenv.Builder() != "" && u.Username == "swarming"
}
// compilerRequiredTsanVersion reports whether the compiler is the version required by Tsan.
// Only restrictions for ppc64le are known; otherwise return true.
func compilerRequiredTsanVersion(goos, goarch string) bool {

View File

@@ -186,7 +186,7 @@ func (e *escape) callCommon(ks []hole, call ir.Node, init *ir.Nodes, wrapper *ir
argument(e.discardHole(), &call.X)
argument(e.discardHole(), &call.Y)
case ir.ODELETE, ir.OMAX, ir.OMIN, ir.OPRINT, ir.OPRINTN, ir.ORECOVER:
case ir.ODELETE, ir.OPRINT, ir.OPRINTN, ir.ORECOVER:
call := call.(*ir.CallExpr)
fixRecoverCall(call)
for i := range call.Args {
@@ -194,6 +194,14 @@ func (e *escape) callCommon(ks []hole, call ir.Node, init *ir.Nodes, wrapper *ir
}
argumentRType(&call.RType)
case ir.OMIN, ir.OMAX:
call := call.(*ir.CallExpr)
fixRecoverCall(call)
for i := range call.Args {
argument(ks[0], &call.Args[i])
}
argumentRType(&call.RType)
case ir.OLEN, ir.OCAP, ir.OREAL, ir.OIMAG, ir.OCLOSE, ir.OCLEAR:
call := call.(*ir.UnaryExpr)
argument(e.discardHole(), &call.X)

View File

@@ -333,8 +333,14 @@ func (p *noder) pragma(pos syntax.Pos, blankLine bool, text string, old syntax.P
// contain cgo directives, and for security reasons
// (primarily misuse of linker flags), other files are not.
// See golang.org/issue/23672.
// Note that cmd/go ignores files whose names start with underscore,
// so the only _cgo_ files we will see from cmd/go are generated by cgo.
// It's easy to bypass this check by calling the compiler directly;
// we only protect against uses by cmd/go.
func isCgoGeneratedFile(pos syntax.Pos) bool {
return strings.HasPrefix(filepath.Base(trimFilename(pos.Base())), "_cgo_")
// We need the absolute file, independent of //line directives,
// so we call pos.Base().Pos().
return strings.HasPrefix(filepath.Base(trimFilename(pos.Base().Pos().Base())), "_cgo_")
}
// safeArg reports whether arg is a "safe" command-line argument,

View File

@@ -1552,33 +1552,27 @@
(GreaterEqualU (FlagConstant [fc])) => (MOVDconst [b2i(fc.uge())])
// absorb InvertFlags into boolean values
(Equal (InvertFlags x)) => (Equal x)
(NotEqual (InvertFlags x)) => (NotEqual x)
(LessThan (InvertFlags x)) => (GreaterThan x)
(LessThanU (InvertFlags x)) => (GreaterThanU x)
(GreaterThan (InvertFlags x)) => (LessThan x)
(GreaterThanU (InvertFlags x)) => (LessThanU x)
(LessEqual (InvertFlags x)) => (GreaterEqual x)
(LessEqualU (InvertFlags x)) => (GreaterEqualU x)
(GreaterEqual (InvertFlags x)) => (LessEqual x)
(GreaterEqualU (InvertFlags x)) => (LessEqualU x)
(LessThanF (InvertFlags x)) => (GreaterThanF x)
(LessEqualF (InvertFlags x)) => (GreaterEqualF x)
(GreaterThanF (InvertFlags x)) => (LessThanF x)
(GreaterEqualF (InvertFlags x)) => (LessEqualF x)
(Equal (InvertFlags x)) => (Equal x)
(NotEqual (InvertFlags x)) => (NotEqual x)
(LessThan (InvertFlags x)) => (GreaterThan x)
(LessThanU (InvertFlags x)) => (GreaterThanU x)
(GreaterThan (InvertFlags x)) => (LessThan x)
(GreaterThanU (InvertFlags x)) => (LessThanU x)
(LessEqual (InvertFlags x)) => (GreaterEqual x)
(LessEqualU (InvertFlags x)) => (GreaterEqualU x)
(GreaterEqual (InvertFlags x)) => (LessEqual x)
(GreaterEqualU (InvertFlags x)) => (LessEqualU x)
(LessThanF (InvertFlags x)) => (GreaterThanF x)
(LessEqualF (InvertFlags x)) => (GreaterEqualF x)
(GreaterThanF (InvertFlags x)) => (LessThanF x)
(GreaterEqualF (InvertFlags x)) => (LessEqualF x)
(LessThanNoov (InvertFlags x)) => (BIC (GreaterEqualNoov <typ.Bool> x) (Equal <typ.Bool> x))
(GreaterEqualNoov (InvertFlags x)) => (OR (LessThanNoov <typ.Bool> x) (Equal <typ.Bool> x))
// Boolean-generating instructions (NOTE: NOT all boolean Values) always
// zero upper bit of the register; no need to zero-extend
(MOVBUreg x:((Equal|NotEqual|LessThan|LessThanU|LessThanF|LessEqual|LessEqualU|LessEqualF|GreaterThan|GreaterThanU|GreaterThanF|GreaterEqual|GreaterEqualU|GreaterEqualF) _)) => (MOVDreg x)
// omit unsign extension
(MOVWUreg x) && zeroUpper32Bits(x, 3) => x
// omit sign extension
(MOVWreg <t> (ANDconst x [c])) && uint64(c) & uint64(0xffffffff80000000) == 0 => (ANDconst <t> x [c])
(MOVHreg <t> (ANDconst x [c])) && uint64(c) & uint64(0xffffffffffff8000) == 0 => (ANDconst <t> x [c])
(MOVBreg <t> (ANDconst x [c])) && uint64(c) & uint64(0xffffffffffffff80) == 0 => (ANDconst <t> x [c])
// absorb flag constants into conditional instructions
(CSEL [cc] x _ flag) && ccARM64Eval(cc, flag) > 0 => x
(CSEL [cc] _ y flag) && ccARM64Eval(cc, flag) < 0 => y

View File

@@ -13,7 +13,6 @@ import "strings"
// - *const instructions may use a constant larger than the instruction can encode.
// In this case the assembler expands to multiple instructions and uses tmp
// register (R27).
// - All 32-bit Ops will zero the upper 32 bits of the destination register.
// Suffixes encode the bit width of various instructions.
// D (double word) = 64 bit

View File

@@ -981,7 +981,7 @@
(ConstNil <typ.Uintptr>)
(ConstNil <typ.BytePtr>))
(NilCheck (GetG mem) mem) => mem
(NilCheck ptr:(GetG mem) mem) => ptr
(If (Not cond) yes no) => (If cond no yes)
(If (ConstBool [c]) yes no) && c => (First yes no)
@@ -2055,19 +2055,19 @@
&& isSameCall(call.Aux, "runtime.newobject")
=> mem
(NilCheck (SelectN [0] call:(StaticLECall _ _)) _)
(NilCheck ptr:(SelectN [0] call:(StaticLECall _ _)) _)
&& isSameCall(call.Aux, "runtime.newobject")
&& warnRule(fe.Debug_checknil(), v, "removed nil check")
=> (Invalid)
=> ptr
(NilCheck (OffPtr (SelectN [0] call:(StaticLECall _ _))) _)
(NilCheck ptr:(OffPtr (SelectN [0] call:(StaticLECall _ _))) _)
&& isSameCall(call.Aux, "runtime.newobject")
&& warnRule(fe.Debug_checknil(), v, "removed nil check")
=> (Invalid)
=> ptr
// Addresses of globals are always non-nil.
(NilCheck (Addr {_} (SB)) _) => (Invalid)
(NilCheck (Convert (Addr {_} (SB)) _) _) => (Invalid)
(NilCheck ptr:(Addr {_} (SB)) _) => ptr
(NilCheck ptr:(Convert (Addr {_} (SB)) _) _) => ptr
// for late-expanded calls, recognize memequal applied to a single constant byte
// Support is limited by 1, 2, 4, 8 byte sizes

View File

@@ -471,7 +471,7 @@ var genericOps = []opData{
{name: "IsNonNil", argLength: 1, typ: "Bool"}, // arg0 != nil
{name: "IsInBounds", argLength: 2, typ: "Bool"}, // 0 <= arg0 < arg1. arg1 is guaranteed >= 0.
{name: "IsSliceInBounds", argLength: 2, typ: "Bool"}, // 0 <= arg0 <= arg1. arg1 is guaranteed >= 0.
{name: "NilCheck", argLength: 2, typ: "Void"}, // arg0=ptr, arg1=mem. Panics if arg0 is nil. Returns void.
{name: "NilCheck", argLength: 2, nilCheck: true}, // arg0=ptr, arg1=mem. Panics if arg0 is nil. Returns the ptr unmodified.
// Pseudo-ops
{name: "GetG", argLength: 1, zeroWidth: true}, // runtime.getg() (read g pointer). arg0=mem

View File

@@ -317,7 +317,28 @@ func checkFunc(f *Func) {
if !v.Aux.(*ir.Name).Type().HasPointers() {
f.Fatalf("vardef must have pointer type %s", v.Aux.(*ir.Name).Type().String())
}
case OpNilCheck:
// nil checks have pointer type before scheduling, and
// void type after scheduling.
if f.scheduled {
if v.Uses != 0 {
f.Fatalf("nilcheck must have 0 uses %s", v.Uses)
}
if !v.Type.IsVoid() {
f.Fatalf("nilcheck must have void type %s", v.Type.String())
}
} else {
if !v.Type.IsPtrShaped() && !v.Type.IsUintptr() {
f.Fatalf("nilcheck must have pointer type %s", v.Type.String())
}
}
if !v.Args[0].Type.IsPtrShaped() && !v.Args[0].Type.IsUintptr() {
f.Fatalf("nilcheck must have argument of pointer type %s", v.Args[0].Type.String())
}
if !v.Args[1].Type.IsMemory() {
f.Fatalf("bad arg 1 type to %s: want mem, have %s",
v.Op, v.Args[1].Type.String())
}
}
// TODO: check for cycles in values

View File

@@ -110,16 +110,15 @@ func liveValues(f *Func, reachable []bool) (live []bool, liveOrderStmts []*Value
}
}
for _, v := range b.Values {
if (opcodeTable[v.Op].call || opcodeTable[v.Op].hasSideEffects) && !live[v.ID] {
if (opcodeTable[v.Op].call || opcodeTable[v.Op].hasSideEffects || opcodeTable[v.Op].nilCheck) && !live[v.ID] {
live[v.ID] = true
q = append(q, v)
if v.Pos.IsStmt() != src.PosNotStmt {
liveOrderStmts = append(liveOrderStmts, v)
}
}
if v.Type.IsVoid() && !live[v.ID] {
// The only Void ops are nil checks and inline marks. We must keep these.
if v.Op == OpInlMark && !liveInlIdx[int(v.AuxInt)] {
if v.Op == OpInlMark {
if !liveInlIdx[int(v.AuxInt)] {
// We don't need marks for bodies that
// have been completely optimized away.
// TODO: save marks only for bodies which

View File

@@ -73,9 +73,9 @@ func dse(f *Func) {
}
// Walk backwards looking for dead stores. Keep track of shadowed addresses.
// A "shadowed address" is a pointer and a size describing a memory region that
// is known to be written. We keep track of shadowed addresses in the shadowed
// map, mapping the ID of the address to the size of the shadowed region.
// A "shadowed address" is a pointer, offset, and size describing a memory region that
// is known to be written. We keep track of shadowed addresses in the shadowed map,
// mapping the ID of the address to a shadowRange where future writes will happen.
// Since we're walking backwards, writes to a shadowed region are useless,
// as they will be immediately overwritten.
shadowed.clear()
@@ -88,13 +88,20 @@ func dse(f *Func) {
shadowed.clear()
}
if v.Op == OpStore || v.Op == OpZero {
ptr := v.Args[0]
var off int64
for ptr.Op == OpOffPtr { // Walk to base pointer
off += ptr.AuxInt
ptr = ptr.Args[0]
}
var sz int64
if v.Op == OpStore {
sz = v.Aux.(*types.Type).Size()
} else { // OpZero
sz = v.AuxInt
}
if shadowedSize := int64(shadowed.get(v.Args[0].ID)); shadowedSize != -1 && shadowedSize >= sz {
sr := shadowRange(shadowed.get(ptr.ID))
if sr.contains(off, off+sz) {
// Modify the store/zero into a copy of the memory state,
// effectively eliding the store operation.
if v.Op == OpStore {
@@ -108,10 +115,8 @@ func dse(f *Func) {
v.AuxInt = 0
v.Op = OpCopy
} else {
if sz > 0x7fffffff { // work around sparseMap's int32 value type
sz = 0x7fffffff
}
shadowed.set(v.Args[0].ID, int32(sz))
// Extend shadowed region.
shadowed.set(ptr.ID, int32(sr.merge(off, off+sz)))
}
}
// walk to previous store
@@ -131,6 +136,49 @@ func dse(f *Func) {
}
}
// A shadowRange encodes a set of byte offsets [lo():hi()] from
// a given pointer that will be written to later in the block.
// A zero shadowRange encodes an empty shadowed range (and so
// does a -1 shadowRange, which is what sparsemap.get returns
// on a failed lookup).
type shadowRange int32
func (sr shadowRange) lo() int64 {
return int64(sr & 0xffff)
}
func (sr shadowRange) hi() int64 {
return int64((sr >> 16) & 0xffff)
}
// contains reports whether [lo:hi] is completely within sr.
func (sr shadowRange) contains(lo, hi int64) bool {
return lo >= sr.lo() && hi <= sr.hi()
}
// merge returns the union of sr and [lo:hi].
// merge is allowed to return something smaller than the union.
func (sr shadowRange) merge(lo, hi int64) shadowRange {
if lo < 0 || hi > 0xffff {
// Ignore offsets that are too large or small.
return sr
}
if sr.lo() == sr.hi() {
// Old range is empty - use new one.
return shadowRange(lo + hi<<16)
}
if hi < sr.lo() || lo > sr.hi() {
// The two regions don't overlap or abut, so we would
// have to keep track of multiple disjoint ranges.
// Because we can only keep one, keep the larger one.
if sr.hi()-sr.lo() >= hi-lo {
return sr
}
return shadowRange(lo + hi<<16)
}
// Regions overlap or abut - compute the union.
return shadowRange(min(lo, sr.lo()) + max(hi, sr.hi())<<16)
}
// elimDeadAutosGeneric deletes autos that are never accessed. To achieve this
// we track the operations that the address of each auto reaches and if it only
// reaches stores then we delete all the stores. The other operations will then
@@ -201,7 +249,7 @@ func elimDeadAutosGeneric(f *Func) {
}
if v.Uses == 0 && v.Op != OpNilCheck && !v.Op.IsCall() && !v.Op.HasSideEffects() || len(args) == 0 {
// Nil check has no use, but we need to keep it.
// We need to keep nil checks even if they have no use.
// Also keep calls and values that have side effects.
return
}

View File

@@ -855,7 +855,7 @@ func storeOneArg(x *expandState, pos src.XPos, b *Block, locs []*LocalSlot, suff
// storeOneLoad creates a decomposed (one step) load that is then stored.
func storeOneLoad(x *expandState, pos src.XPos, b *Block, source, mem *Value, t *types.Type, offArg, offStore int64, loadRegOffset Abi1RO, storeRc registerCursor) *Value {
from := x.offsetFrom(source.Block, source.Args[0], offArg, types.NewPtr(t))
w := source.Block.NewValue2(source.Pos, OpLoad, t, from, mem)
w := b.NewValue2(source.Pos, OpLoad, t, from, mem)
return x.storeArgOrLoad(pos, b, w, mem, t, offStore, loadRegOffset, storeRc)
}
@@ -962,7 +962,7 @@ func (x *expandState) storeArgOrLoad(pos src.XPos, b *Block, source, mem *Value,
eltRO := x.regWidth(elt)
source.Type = t
for i := int64(0); i < t.NumElem(); i++ {
sel := source.Block.NewValue1I(pos, OpArraySelect, elt, i, source)
sel := b.NewValue1I(pos, OpArraySelect, elt, i, source)
mem = x.storeArgOrLoad(pos, b, sel, mem, elt, storeOffset+i*elt.Size(), loadRegOffset, storeRc.at(t, 0))
loadRegOffset += eltRO
pos = pos.WithNotStmt()
@@ -997,7 +997,7 @@ func (x *expandState) storeArgOrLoad(pos src.XPos, b *Block, source, mem *Value,
source.Type = t
for i := 0; i < t.NumFields(); i++ {
fld := t.Field(i)
sel := source.Block.NewValue1I(pos, OpStructSelect, fld.Type, int64(i), source)
sel := b.NewValue1I(pos, OpStructSelect, fld.Type, int64(i), source)
mem = x.storeArgOrLoad(pos, b, sel, mem, fld.Type, storeOffset+fld.Offset, loadRegOffset, storeRc.next(fld.Type))
loadRegOffset += x.regWidth(fld.Type)
pos = pos.WithNotStmt()
@@ -1009,48 +1009,48 @@ func (x *expandState) storeArgOrLoad(pos src.XPos, b *Block, source, mem *Value,
break
}
tHi, tLo := x.intPairTypes(t.Kind())
sel := source.Block.NewValue1(pos, OpInt64Hi, tHi, source)
sel := b.NewValue1(pos, OpInt64Hi, tHi, source)
mem = x.storeArgOrLoad(pos, b, sel, mem, tHi, storeOffset+x.hiOffset, loadRegOffset+x.hiRo, storeRc.plus(x.hiRo))
pos = pos.WithNotStmt()
sel = source.Block.NewValue1(pos, OpInt64Lo, tLo, source)
sel = b.NewValue1(pos, OpInt64Lo, tLo, source)
return x.storeArgOrLoad(pos, b, sel, mem, tLo, storeOffset+x.lowOffset, loadRegOffset+x.loRo, storeRc.plus(x.hiRo))
case types.TINTER:
sel := source.Block.NewValue1(pos, OpITab, x.typs.BytePtr, source)
sel := b.NewValue1(pos, OpITab, x.typs.BytePtr, source)
mem = x.storeArgOrLoad(pos, b, sel, mem, x.typs.BytePtr, storeOffset, loadRegOffset, storeRc.next(x.typs.BytePtr))
pos = pos.WithNotStmt()
sel = source.Block.NewValue1(pos, OpIData, x.typs.BytePtr, source)
sel = b.NewValue1(pos, OpIData, x.typs.BytePtr, source)
return x.storeArgOrLoad(pos, b, sel, mem, x.typs.BytePtr, storeOffset+x.ptrSize, loadRegOffset+RO_iface_data, storeRc)
case types.TSTRING:
sel := source.Block.NewValue1(pos, OpStringPtr, x.typs.BytePtr, source)
sel := b.NewValue1(pos, OpStringPtr, x.typs.BytePtr, source)
mem = x.storeArgOrLoad(pos, b, sel, mem, x.typs.BytePtr, storeOffset, loadRegOffset, storeRc.next(x.typs.BytePtr))
pos = pos.WithNotStmt()
sel = source.Block.NewValue1(pos, OpStringLen, x.typs.Int, source)
sel = b.NewValue1(pos, OpStringLen, x.typs.Int, source)
return x.storeArgOrLoad(pos, b, sel, mem, x.typs.Int, storeOffset+x.ptrSize, loadRegOffset+RO_string_len, storeRc)
case types.TSLICE:
et := types.NewPtr(t.Elem())
sel := source.Block.NewValue1(pos, OpSlicePtr, et, source)
sel := b.NewValue1(pos, OpSlicePtr, et, source)
mem = x.storeArgOrLoad(pos, b, sel, mem, et, storeOffset, loadRegOffset, storeRc.next(et))
pos = pos.WithNotStmt()
sel = source.Block.NewValue1(pos, OpSliceLen, x.typs.Int, source)
sel = b.NewValue1(pos, OpSliceLen, x.typs.Int, source)
mem = x.storeArgOrLoad(pos, b, sel, mem, x.typs.Int, storeOffset+x.ptrSize, loadRegOffset+RO_slice_len, storeRc.next(x.typs.Int))
sel = source.Block.NewValue1(pos, OpSliceCap, x.typs.Int, source)
sel = b.NewValue1(pos, OpSliceCap, x.typs.Int, source)
return x.storeArgOrLoad(pos, b, sel, mem, x.typs.Int, storeOffset+2*x.ptrSize, loadRegOffset+RO_slice_cap, storeRc)
case types.TCOMPLEX64:
sel := source.Block.NewValue1(pos, OpComplexReal, x.typs.Float32, source)
sel := b.NewValue1(pos, OpComplexReal, x.typs.Float32, source)
mem = x.storeArgOrLoad(pos, b, sel, mem, x.typs.Float32, storeOffset, loadRegOffset, storeRc.next(x.typs.Float32))
pos = pos.WithNotStmt()
sel = source.Block.NewValue1(pos, OpComplexImag, x.typs.Float32, source)
sel = b.NewValue1(pos, OpComplexImag, x.typs.Float32, source)
return x.storeArgOrLoad(pos, b, sel, mem, x.typs.Float32, storeOffset+4, loadRegOffset+RO_complex_imag, storeRc)
case types.TCOMPLEX128:
sel := source.Block.NewValue1(pos, OpComplexReal, x.typs.Float64, source)
sel := b.NewValue1(pos, OpComplexReal, x.typs.Float64, source)
mem = x.storeArgOrLoad(pos, b, sel, mem, x.typs.Float64, storeOffset, loadRegOffset, storeRc.next(x.typs.Float64))
pos = pos.WithNotStmt()
sel = source.Block.NewValue1(pos, OpComplexImag, x.typs.Float64, source)
sel = b.NewValue1(pos, OpComplexImag, x.typs.Float64, source)
return x.storeArgOrLoad(pos, b, sel, mem, x.typs.Float64, storeOffset+8, loadRegOffset+RO_complex_imag, storeRc)
}
@@ -1113,6 +1113,9 @@ func (x *expandState) rewriteArgs(v *Value, firstArg int) {
}
}
}
if x.debug > 1 {
x.Printf("...storeArg %s, %v, %d\n", a.LongString(), aType, aOffset)
}
// "Dereference" of addressed (probably not-SSA-eligible) value becomes Move
// TODO(register args) this will be more complicated with registers in the picture.
mem = x.rewriteDereference(v.Block, sp, a, mem, aOffset, aux.SizeOfArg(auxI), aType, v.Pos)

View File

@@ -169,7 +169,7 @@ func fuseBlockIf(b *Block) bool {
// There may be false positives.
func isEmpty(b *Block) bool {
for _, v := range b.Values {
if v.Uses > 0 || v.Op.IsCall() || v.Op.HasSideEffects() || v.Type.IsVoid() {
if v.Uses > 0 || v.Op.IsCall() || v.Op.HasSideEffects() || v.Type.IsVoid() || opcodeTable[v.Op].nilCheck {
return false
}
}

View File

@@ -254,7 +254,7 @@ func TestFuseSideEffects(t *testing.T) {
Valu("p", OpArg, c.config.Types.IntPtr, 0, nil),
If("c1", "z0", "exit")),
Bloc("z0",
Valu("nilcheck", OpNilCheck, types.TypeVoid, 0, nil, "p", "mem"),
Valu("nilcheck", OpNilCheck, c.config.Types.IntPtr, 0, nil, "p", "mem"),
Goto("exit")),
Bloc("exit",
Exit("mem"),

View File

@@ -127,6 +127,13 @@ func findIndVar(f *Func) []indVar {
less = false
}
if ind.Block != b {
// TODO: Could be extended to include disjointed loop headers.
// I don't think this is causing missed optimizations in real world code often.
// See https://go.dev/issue/63955
continue
}
// Expect the increment to be a nonzero constant.
if !inc.isGenericIntConst() {
continue

View File

@@ -41,6 +41,7 @@ func memcombineLoads(f *Func) {
}
}
for _, b := range f.Blocks {
order = order[:0]
for _, v := range b.Values {
if v.Op != OpOr16 && v.Op != OpOr32 && v.Op != OpOr64 {
continue
@@ -312,8 +313,8 @@ func combineLoads(root *Value, n int64) bool {
if isLittleEndian && shift0 != 0 {
v = leftShift(loadBlock, pos, v, shift0)
}
if isBigEndian && shift0-(n-1)*8 != 0 {
v = leftShift(loadBlock, pos, v, shift0-(n-1)*8)
if isBigEndian && shift0-(n-1)*size*8 != 0 {
v = leftShift(loadBlock, pos, v, shift0-(n-1)*size*8)
}
// Install with (Copy v).
@@ -587,14 +588,14 @@ func combineStores(root *Value, n int64) bool {
isLittleEndian := true
shift0 := shift(a[0].store, shiftBase)
for i := int64(1); i < n; i++ {
if shift(a[i].store, shiftBase) != shift0+i*8 {
if shift(a[i].store, shiftBase) != shift0+i*size*8 {
isLittleEndian = false
break
}
}
isBigEndian := true
for i := int64(1); i < n; i++ {
if shift(a[i].store, shiftBase) != shift0-i*8 {
if shift(a[i].store, shiftBase) != shift0-i*size*8 {
isBigEndian = false
break
}
@@ -617,8 +618,8 @@ func combineStores(root *Value, n int64) bool {
if isLittleEndian && shift0 != 0 {
sv = rightShift(root.Block, root.Pos, sv, shift0)
}
if isBigEndian && shift0-(n-1)*8 != 0 {
sv = rightShift(root.Block, root.Pos, sv, shift0-(n-1)*8)
if isBigEndian && shift0-(n-1)*size*8 != 0 {
sv = rightShift(root.Block, root.Pos, sv, shift0-(n-1)*size*8)
}
if sv.Type.Size() > size*n {
sv = truncate(root.Block, root.Pos, sv, sv.Type.Size(), size*n)

View File

@@ -38,11 +38,14 @@ func nilcheckelim(f *Func) {
work := make([]bp, 0, 256)
work = append(work, bp{block: f.Entry})
// map from value ID to bool indicating if value is known to be non-nil
// in the current dominator path being walked. This slice is updated by
// map from value ID to known non-nil version of that value ID
// (in the current dominator path being walked). This slice is updated by
// walkStates to maintain the known non-nil values.
nonNilValues := f.Cache.allocBoolSlice(f.NumValues())
defer f.Cache.freeBoolSlice(nonNilValues)
// If there is extrinsic information about non-nil-ness, this map
// points a value to itself. If a value is known non-nil because we
// already did a nil check on it, it points to the nil check operation.
nonNilValues := f.Cache.allocValueSlice(f.NumValues())
defer f.Cache.freeValueSlice(nonNilValues)
// make an initial pass identifying any non-nil values
for _, b := range f.Blocks {
@@ -54,7 +57,7 @@ func nilcheckelim(f *Func) {
// We assume that SlicePtr is non-nil because we do a bounds check
// before the slice access (and all cap>0 slices have a non-nil ptr). See #30366.
if v.Op == OpAddr || v.Op == OpLocalAddr || v.Op == OpAddPtr || v.Op == OpOffPtr || v.Op == OpAdd32 || v.Op == OpAdd64 || v.Op == OpSub32 || v.Op == OpSub64 || v.Op == OpSlicePtr {
nonNilValues[v.ID] = true
nonNilValues[v.ID] = v
}
}
}
@@ -68,16 +71,16 @@ func nilcheckelim(f *Func) {
if v.Op == OpPhi {
argsNonNil := true
for _, a := range v.Args {
if !nonNilValues[a.ID] {
if nonNilValues[a.ID] == nil {
argsNonNil = false
break
}
}
if argsNonNil {
if !nonNilValues[v.ID] {
if nonNilValues[v.ID] == nil {
changed = true
}
nonNilValues[v.ID] = true
nonNilValues[v.ID] = v
}
}
}
@@ -103,8 +106,8 @@ func nilcheckelim(f *Func) {
if len(b.Preds) == 1 {
p := b.Preds[0].b
if p.Kind == BlockIf && p.Controls[0].Op == OpIsNonNil && p.Succs[0].b == b {
if ptr := p.Controls[0].Args[0]; !nonNilValues[ptr.ID] {
nonNilValues[ptr.ID] = true
if ptr := p.Controls[0].Args[0]; nonNilValues[ptr.ID] == nil {
nonNilValues[ptr.ID] = ptr
work = append(work, bp{op: ClearPtr, ptr: ptr})
}
}
@@ -117,14 +120,11 @@ func nilcheckelim(f *Func) {
pendingLines.clear()
// Next, process values in the block.
i := 0
for _, v := range b.Values {
b.Values[i] = v
i++
switch v.Op {
case OpIsNonNil:
ptr := v.Args[0]
if nonNilValues[ptr.ID] {
if nonNilValues[ptr.ID] != nil {
if v.Pos.IsStmt() == src.PosIsStmt { // Boolean true is a terrible statement boundary.
pendingLines.add(v.Pos)
v.Pos = v.Pos.WithNotStmt()
@@ -135,7 +135,7 @@ func nilcheckelim(f *Func) {
}
case OpNilCheck:
ptr := v.Args[0]
if nonNilValues[ptr.ID] {
if nilCheck := nonNilValues[ptr.ID]; nilCheck != nil {
// This is a redundant implicit nil check.
// Logging in the style of the former compiler -- and omit line 1,
// which is usually in generated code.
@@ -145,14 +145,13 @@ func nilcheckelim(f *Func) {
if v.Pos.IsStmt() == src.PosIsStmt { // About to lose a statement boundary
pendingLines.add(v.Pos)
}
v.reset(OpUnknown)
f.freeValue(v)
i--
v.Op = OpCopy
v.SetArgs1(nilCheck)
continue
}
// Record the fact that we know ptr is non nil, and remember to
// undo that information when this dominator subtree is done.
nonNilValues[ptr.ID] = true
nonNilValues[ptr.ID] = v
work = append(work, bp{op: ClearPtr, ptr: ptr})
fallthrough // a non-eliminated nil check might be a good place for a statement boundary.
default:
@@ -163,7 +162,7 @@ func nilcheckelim(f *Func) {
}
}
// This reduces the lost statement count in "go" by 5 (out of 500 total).
for j := 0; j < i; j++ { // is this an ordering problem?
for j := range b.Values { // is this an ordering problem?
v := b.Values[j]
if v.Pos.IsStmt() != src.PosNotStmt && !isPoorStatementOp(v.Op) && pendingLines.contains(v.Pos) {
v.Pos = v.Pos.WithIsStmt()
@@ -174,7 +173,6 @@ func nilcheckelim(f *Func) {
b.Pos = b.Pos.WithIsStmt()
pendingLines.remove(b.Pos)
}
b.truncateValues(i)
// Add all dominated blocks to the work list.
for w := sdom[node.block.ID].child; w != nil; w = sdom[w.ID].sibling {
@@ -182,7 +180,7 @@ func nilcheckelim(f *Func) {
}
case ClearPtr:
nonNilValues[node.ptr.ID] = false
nonNilValues[node.ptr.ID] = nil
continue
}
}

View File

@@ -39373,9 +39373,10 @@ var opcodeTable = [...]opInfo{
generic: true,
},
{
name: "NilCheck",
argLen: 2,
generic: true,
name: "NilCheck",
argLen: 2,
nilCheck: true,
generic: true,
},
{
name: "GetG",

View File

@@ -859,6 +859,9 @@ func disjoint(p1 *Value, n1 int64, p2 *Value, n2 int64) bool {
offset += base.AuxInt
base = base.Args[0]
}
if opcodeTable[base.Op].nilCheck {
base = base.Args[0]
}
return base, offset
}
p1, off1 := baseAndOffset(p1)
@@ -1183,6 +1186,12 @@ func min(x, y int64) int64 {
}
return y
}
func max(x, y int64) int64 {
if x > y {
return x
}
return y
}
func isConstZero(v *Value) bool {
switch v.Op {
@@ -1281,10 +1290,6 @@ func zeroUpper32Bits(x *Value, depth int) bool {
OpAMD64SHRL, OpAMD64SHRLconst, OpAMD64SARL, OpAMD64SARLconst,
OpAMD64SHLL, OpAMD64SHLLconst:
return true
case OpARM64REV16W, OpARM64REVW, OpARM64RBITW, OpARM64CLZW, OpARM64EXTRWconst,
OpARM64MULW, OpARM64MNEGW, OpARM64UDIVW, OpARM64DIVW, OpARM64UMODW,
OpARM64MADDW, OpARM64MSUBW, OpARM64RORW, OpARM64RORWconst:
return true
case OpArg:
return x.Type.Size() == 4
case OpPhi, OpSelect0, OpSelect1:

View File

@@ -154,6 +154,8 @@ func rewriteValueARM64(v *Value) bool {
return rewriteValueARM64_OpARM64GreaterEqual(v)
case OpARM64GreaterEqualF:
return rewriteValueARM64_OpARM64GreaterEqualF(v)
case OpARM64GreaterEqualNoov:
return rewriteValueARM64_OpARM64GreaterEqualNoov(v)
case OpARM64GreaterEqualU:
return rewriteValueARM64_OpARM64GreaterEqualU(v)
case OpARM64GreaterThan:
@@ -174,6 +176,8 @@ func rewriteValueARM64(v *Value) bool {
return rewriteValueARM64_OpARM64LessThan(v)
case OpARM64LessThanF:
return rewriteValueARM64_OpARM64LessThanF(v)
case OpARM64LessThanNoov:
return rewriteValueARM64_OpARM64LessThanNoov(v)
case OpARM64LessThanU:
return rewriteValueARM64_OpARM64LessThanU(v)
case OpARM64MADD:
@@ -5953,6 +5957,27 @@ func rewriteValueARM64_OpARM64GreaterEqualF(v *Value) bool {
}
return false
}
func rewriteValueARM64_OpARM64GreaterEqualNoov(v *Value) bool {
v_0 := v.Args[0]
b := v.Block
typ := &b.Func.Config.Types
// match: (GreaterEqualNoov (InvertFlags x))
// result: (OR (LessThanNoov <typ.Bool> x) (Equal <typ.Bool> x))
for {
if v_0.Op != OpARM64InvertFlags {
break
}
x := v_0.Args[0]
v.reset(OpARM64OR)
v0 := b.NewValue0(v.Pos, OpARM64LessThanNoov, typ.Bool)
v0.AddArg(x)
v1 := b.NewValue0(v.Pos, OpARM64Equal, typ.Bool)
v1.AddArg(x)
v.AddArg2(v0, v1)
return true
}
return false
}
func rewriteValueARM64_OpARM64GreaterEqualU(v *Value) bool {
v_0 := v.Args[0]
// match: (GreaterEqualU (FlagConstant [fc]))
@@ -6667,6 +6692,27 @@ func rewriteValueARM64_OpARM64LessThanF(v *Value) bool {
}
return false
}
func rewriteValueARM64_OpARM64LessThanNoov(v *Value) bool {
v_0 := v.Args[0]
b := v.Block
typ := &b.Func.Config.Types
// match: (LessThanNoov (InvertFlags x))
// result: (BIC (GreaterEqualNoov <typ.Bool> x) (Equal <typ.Bool> x))
for {
if v_0.Op != OpARM64InvertFlags {
break
}
x := v_0.Args[0]
v.reset(OpARM64BIC)
v0 := b.NewValue0(v.Pos, OpARM64GreaterEqualNoov, typ.Bool)
v0.AddArg(x)
v1 := b.NewValue0(v.Pos, OpARM64Equal, typ.Bool)
v1.AddArg(x)
v.AddArg2(v0, v1)
return true
}
return false
}
func rewriteValueARM64_OpARM64LessThanU(v *Value) bool {
v_0 := v.Args[0]
// match: (LessThanU (FlagConstant [fc]))
@@ -8668,25 +8714,6 @@ func rewriteValueARM64_OpARM64MOVBreg(v *Value) bool {
v.AuxInt = int64ToAuxInt(int64(int8(c)))
return true
}
// match: (MOVBreg <t> (ANDconst x [c]))
// cond: uint64(c) & uint64(0xffffffffffffff80) == 0
// result: (ANDconst <t> x [c])
for {
t := v.Type
if v_0.Op != OpARM64ANDconst {
break
}
c := auxIntToInt64(v_0.AuxInt)
x := v_0.Args[0]
if !(uint64(c)&uint64(0xffffffffffffff80) == 0) {
break
}
v.reset(OpARM64ANDconst)
v.Type = t
v.AuxInt = int64ToAuxInt(c)
v.AddArg(x)
return true
}
// match: (MOVBreg (SLLconst [lc] x))
// cond: lc < 8
// result: (SBFIZ [armBFAuxInt(lc, 8-lc)] x)
@@ -10765,25 +10792,6 @@ func rewriteValueARM64_OpARM64MOVHreg(v *Value) bool {
v.AuxInt = int64ToAuxInt(int64(int16(c)))
return true
}
// match: (MOVHreg <t> (ANDconst x [c]))
// cond: uint64(c) & uint64(0xffffffffffff8000) == 0
// result: (ANDconst <t> x [c])
for {
t := v.Type
if v_0.Op != OpARM64ANDconst {
break
}
c := auxIntToInt64(v_0.AuxInt)
x := v_0.Args[0]
if !(uint64(c)&uint64(0xffffffffffff8000) == 0) {
break
}
v.reset(OpARM64ANDconst)
v.Type = t
v.AuxInt = int64ToAuxInt(c)
v.AddArg(x)
return true
}
// match: (MOVHreg (SLLconst [lc] x))
// cond: lc < 16
// result: (SBFIZ [armBFAuxInt(lc, 16-lc)] x)
@@ -11943,17 +11951,6 @@ func rewriteValueARM64_OpARM64MOVWUreg(v *Value) bool {
v.AuxInt = int64ToAuxInt(int64(uint32(c)))
return true
}
// match: (MOVWUreg x)
// cond: zeroUpper32Bits(x, 3)
// result: x
for {
x := v_0
if !(zeroUpper32Bits(x, 3)) {
break
}
v.copyOf(x)
return true
}
// match: (MOVWUreg (SLLconst [lc] x))
// cond: lc >= 32
// result: (MOVDconst [0])
@@ -12458,25 +12455,6 @@ func rewriteValueARM64_OpARM64MOVWreg(v *Value) bool {
v.AuxInt = int64ToAuxInt(int64(int32(c)))
return true
}
// match: (MOVWreg <t> (ANDconst x [c]))
// cond: uint64(c) & uint64(0xffffffff80000000) == 0
// result: (ANDconst <t> x [c])
for {
t := v.Type
if v_0.Op != OpARM64ANDconst {
break
}
c := auxIntToInt64(v_0.AuxInt)
x := v_0.Args[0]
if !(uint64(c)&uint64(0xffffffff80000000) == 0) {
break
}
v.reset(OpARM64ANDconst)
v.Type = t
v.AuxInt = int64ToAuxInt(c)
v.AddArg(x)
return true
}
// match: (MOVWreg (SLLconst [lc] x))
// cond: lc < 32
// result: (SBFIZ [armBFAuxInt(lc, 32-lc)] x)

View File

@@ -18967,79 +18967,84 @@ func rewriteValuegeneric_OpNilCheck(v *Value) bool {
v_0 := v.Args[0]
b := v.Block
fe := b.Func.fe
// match: (NilCheck (GetG mem) mem)
// result: mem
// match: (NilCheck ptr:(GetG mem) mem)
// result: ptr
for {
if v_0.Op != OpGetG {
ptr := v_0
if ptr.Op != OpGetG {
break
}
mem := v_0.Args[0]
mem := ptr.Args[0]
if mem != v_1 {
break
}
v.copyOf(mem)
v.copyOf(ptr)
return true
}
// match: (NilCheck (SelectN [0] call:(StaticLECall _ _)) _)
// match: (NilCheck ptr:(SelectN [0] call:(StaticLECall _ _)) _)
// cond: isSameCall(call.Aux, "runtime.newobject") && warnRule(fe.Debug_checknil(), v, "removed nil check")
// result: (Invalid)
// result: ptr
for {
if v_0.Op != OpSelectN || auxIntToInt64(v_0.AuxInt) != 0 {
ptr := v_0
if ptr.Op != OpSelectN || auxIntToInt64(ptr.AuxInt) != 0 {
break
}
call := v_0.Args[0]
call := ptr.Args[0]
if call.Op != OpStaticLECall || len(call.Args) != 2 || !(isSameCall(call.Aux, "runtime.newobject") && warnRule(fe.Debug_checknil(), v, "removed nil check")) {
break
}
v.reset(OpInvalid)
v.copyOf(ptr)
return true
}
// match: (NilCheck (OffPtr (SelectN [0] call:(StaticLECall _ _))) _)
// match: (NilCheck ptr:(OffPtr (SelectN [0] call:(StaticLECall _ _))) _)
// cond: isSameCall(call.Aux, "runtime.newobject") && warnRule(fe.Debug_checknil(), v, "removed nil check")
// result: (Invalid)
// result: ptr
for {
if v_0.Op != OpOffPtr {
ptr := v_0
if ptr.Op != OpOffPtr {
break
}
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpSelectN || auxIntToInt64(v_0_0.AuxInt) != 0 {
ptr_0 := ptr.Args[0]
if ptr_0.Op != OpSelectN || auxIntToInt64(ptr_0.AuxInt) != 0 {
break
}
call := v_0_0.Args[0]
call := ptr_0.Args[0]
if call.Op != OpStaticLECall || len(call.Args) != 2 || !(isSameCall(call.Aux, "runtime.newobject") && warnRule(fe.Debug_checknil(), v, "removed nil check")) {
break
}
v.reset(OpInvalid)
v.copyOf(ptr)
return true
}
// match: (NilCheck (Addr {_} (SB)) _)
// result: (Invalid)
// match: (NilCheck ptr:(Addr {_} (SB)) _)
// result: ptr
for {
if v_0.Op != OpAddr {
ptr := v_0
if ptr.Op != OpAddr {
break
}
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpSB {
ptr_0 := ptr.Args[0]
if ptr_0.Op != OpSB {
break
}
v.reset(OpInvalid)
v.copyOf(ptr)
return true
}
// match: (NilCheck (Convert (Addr {_} (SB)) _) _)
// result: (Invalid)
// match: (NilCheck ptr:(Convert (Addr {_} (SB)) _) _)
// result: ptr
for {
if v_0.Op != OpConvert {
ptr := v_0
if ptr.Op != OpConvert {
break
}
v_0_0 := v_0.Args[0]
if v_0_0.Op != OpAddr {
ptr_0 := ptr.Args[0]
if ptr_0.Op != OpAddr {
break
}
v_0_0_0 := v_0_0.Args[0]
if v_0_0_0.Op != OpSB {
ptr_0_0 := ptr_0.Args[0]
if ptr_0_0.Op != OpSB {
break
}
v.reset(OpInvalid)
v.copyOf(ptr)
return true
}
return false

View File

@@ -312,14 +312,21 @@ func schedule(f *Func) {
}
// Remove SPanchored now that we've scheduled.
// Also unlink nil checks now that ordering is assured
// between the nil check and the uses of the nil-checked pointer.
for _, b := range f.Blocks {
for _, v := range b.Values {
for i, a := range v.Args {
if a.Op == OpSPanchored {
if a.Op == OpSPanchored || opcodeTable[a.Op].nilCheck {
v.SetArg(i, a.Args[0])
}
}
}
for i, c := range b.ControlValues() {
if c.Op == OpSPanchored || opcodeTable[c.Op].nilCheck {
b.ReplaceControl(i, c.Args[0])
}
}
}
for _, b := range f.Blocks {
i := 0
@@ -332,6 +339,15 @@ func schedule(f *Func) {
v.resetArgs()
f.freeValue(v)
} else {
if opcodeTable[v.Op].nilCheck {
if v.Uses != 0 {
base.Fatalf("nilcheck still has %d uses", v.Uses)
}
// We can't delete the nil check, but we mark
// it as having void type so regalloc won't
// try to allocate a register for it.
v.Type = types.TypeVoid
}
b.Values[i] = v
i++
}

View File

@@ -552,7 +552,11 @@ func (v *Value) LackingPos() bool {
// if its use count drops to 0.
func (v *Value) removeable() bool {
if v.Type.IsVoid() {
// Void ops, like nil pointer checks, must stay.
// Void ops (inline marks), must stay.
return false
}
if opcodeTable[v.Op].nilCheck {
// Nil pointer checks must stay.
return false
}
if v.Type.IsMemory() {

View File

@@ -1991,7 +1991,8 @@ func (s *state) stmt(n ir.Node) {
case ir.OCHECKNIL:
n := n.(*ir.UnaryExpr)
p := s.expr(n.X)
s.nilCheck(p)
_ = s.nilCheck(p)
// TODO: check that throwing away the nilcheck result is ok.
case ir.OINLMARK:
n := n.(*ir.InlineMarkStmt)
@@ -5621,18 +5622,20 @@ func (s *state) exprPtr(n ir.Node, bounded bool, lineno src.XPos) *ssa.Value {
}
return p
}
s.nilCheck(p)
p = s.nilCheck(p)
return p
}
// nilCheck generates nil pointer checking code.
// Used only for automatically inserted nil checks,
// not for user code like 'x != nil'.
func (s *state) nilCheck(ptr *ssa.Value) {
// Returns a "definitely not nil" copy of x to ensure proper ordering
// of the uses of the post-nilcheck pointer.
func (s *state) nilCheck(ptr *ssa.Value) *ssa.Value {
if base.Debug.DisableNil != 0 || s.curfn.NilCheckDisabled() {
return
return ptr
}
s.newValue2(ssa.OpNilCheck, types.TypeVoid, ptr, s.mem())
return s.newValue2(ssa.OpNilCheck, ptr.Type, ptr, s.mem())
}
// boundsCheck generates bounds checking code. Checks if 0 <= idx <[=] len, branches to exit if not.
@@ -5984,8 +5987,8 @@ func (s *state) slice(v, i, j, k *ssa.Value, bounded bool) (p, l, c *ssa.Value)
if !t.Elem().IsArray() {
s.Fatalf("bad ptr to array in slice %v\n", t)
}
s.nilCheck(v)
ptr = s.newValue1(ssa.OpCopy, types.NewPtr(t.Elem().Elem()), v)
nv := s.nilCheck(v)
ptr = s.newValue1(ssa.OpCopy, types.NewPtr(t.Elem().Elem()), nv)
len = s.constInt(types.Types[types.TINT], t.Elem().NumElem())
cap = len
default:
@@ -7083,8 +7086,21 @@ func genssa(f *ssa.Func, pp *objw.Progs) {
// for an empty block this will be used for its control
// instruction. We won't use the actual liveness map on a
// control instruction. Just mark it something that is
// preemptible, unless this function is "all unsafe".
s.pp.NextLive = objw.LivenessIndex{StackMapIndex: -1, IsUnsafePoint: liveness.IsUnsafe(f)}
// preemptible, unless this function is "all unsafe", or
// the empty block is in a write barrier.
unsafe := liveness.IsUnsafe(f)
if b.Kind == ssa.BlockPlain {
// Empty blocks that are part of write barriers need
// to have their control instructions marked unsafe.
c := b.Succs[0].Block()
for _, v := range c.Values {
if v.Op == ssa.OpWBend {
unsafe = true
break
}
}
}
s.pp.NextLive = objw.LivenessIndex{StackMapIndex: -1, IsUnsafePoint: unsafe}
if idx, ok := argLiveBlockMap[b.ID]; ok && idx != argLiveIdx {
argLiveIdx = idx

View File

@@ -71,3 +71,129 @@ func readUint32be(b []byte) uint64 {
//go:noinline
func nop() {
}
type T32 struct {
a, b uint32
}
//go:noinline
func (t *T32) bigEndianLoad() uint64 {
return uint64(t.a)<<32 | uint64(t.b)
}
//go:noinline
func (t *T32) littleEndianLoad() uint64 {
return uint64(t.a) | (uint64(t.b) << 32)
}
//go:noinline
func (t *T32) bigEndianStore(x uint64) {
t.a = uint32(x >> 32)
t.b = uint32(x)
}
//go:noinline
func (t *T32) littleEndianStore(x uint64) {
t.a = uint32(x)
t.b = uint32(x >> 32)
}
type T16 struct {
a, b uint16
}
//go:noinline
func (t *T16) bigEndianLoad() uint32 {
return uint32(t.a)<<16 | uint32(t.b)
}
//go:noinline
func (t *T16) littleEndianLoad() uint32 {
return uint32(t.a) | (uint32(t.b) << 16)
}
//go:noinline
func (t *T16) bigEndianStore(x uint32) {
t.a = uint16(x >> 16)
t.b = uint16(x)
}
//go:noinline
func (t *T16) littleEndianStore(x uint32) {
t.a = uint16(x)
t.b = uint16(x >> 16)
}
type T8 struct {
a, b uint8
}
//go:noinline
func (t *T8) bigEndianLoad() uint16 {
return uint16(t.a)<<8 | uint16(t.b)
}
//go:noinline
func (t *T8) littleEndianLoad() uint16 {
return uint16(t.a) | (uint16(t.b) << 8)
}
//go:noinline
func (t *T8) bigEndianStore(x uint16) {
t.a = uint8(x >> 8)
t.b = uint8(x)
}
//go:noinline
func (t *T8) littleEndianStore(x uint16) {
t.a = uint8(x)
t.b = uint8(x >> 8)
}
func TestIssue64468(t *testing.T) {
t32 := T32{1, 2}
if got, want := t32.bigEndianLoad(), uint64(1<<32+2); got != want {
t.Errorf("T32.bigEndianLoad got %x want %x\n", got, want)
}
if got, want := t32.littleEndianLoad(), uint64(1+2<<32); got != want {
t.Errorf("T32.littleEndianLoad got %x want %x\n", got, want)
}
t16 := T16{1, 2}
if got, want := t16.bigEndianLoad(), uint32(1<<16+2); got != want {
t.Errorf("T16.bigEndianLoad got %x want %x\n", got, want)
}
if got, want := t16.littleEndianLoad(), uint32(1+2<<16); got != want {
t.Errorf("T16.littleEndianLoad got %x want %x\n", got, want)
}
t8 := T8{1, 2}
if got, want := t8.bigEndianLoad(), uint16(1<<8+2); got != want {
t.Errorf("T8.bigEndianLoad got %x want %x\n", got, want)
}
if got, want := t8.littleEndianLoad(), uint16(1+2<<8); got != want {
t.Errorf("T8.littleEndianLoad got %x want %x\n", got, want)
}
t32.bigEndianStore(1<<32 + 2)
if got, want := t32, (T32{1, 2}); got != want {
t.Errorf("T32.bigEndianStore got %x want %x\n", got, want)
}
t32.littleEndianStore(1<<32 + 2)
if got, want := t32, (T32{2, 1}); got != want {
t.Errorf("T32.littleEndianStore got %x want %x\n", got, want)
}
t16.bigEndianStore(1<<16 + 2)
if got, want := t16, (T16{1, 2}); got != want {
t.Errorf("T16.bigEndianStore got %x want %x\n", got, want)
}
t16.littleEndianStore(1<<16 + 2)
if got, want := t16, (T16{2, 1}); got != want {
t.Errorf("T16.littleEndianStore got %x want %x\n", got, want)
}
t8.bigEndianStore(1<<8 + 2)
if got, want := t8, (T8{1, 2}); got != want {
t.Errorf("T8.bigEndianStore got %x want %x\n", got, want)
}
t8.littleEndianStore(1<<8 + 2)
if got, want := t8, (T8{2, 1}); got != want {
t.Errorf("T8.littleEndianStore got %x want %x\n", got, want)
}
}

View File

@@ -94,40 +94,24 @@ func ClosureType(clo *ir.ClosureExpr) *types.Type {
// and has one float64 argument and no results,
// the generated code looks like:
//
// clos = &struct{.F uintptr; i *int; s *string}{func.1, &i, &s}
// clos = &struct{F uintptr; X0 *int; X1 *string}{func.1, &i, &s}
//
// The use of the struct provides type information to the garbage
// collector so that it can walk the closure. We could use (in this case)
// [3]unsafe.Pointer instead, but that would leave the gc in the dark.
// The information appears in the binary in the form of type descriptors;
// the struct is unnamed so that closures in multiple packages with the
// same struct type can share the descriptor.
// collector so that it can walk the closure. We could use (in this
// case) [3]unsafe.Pointer instead, but that would leave the gc in
// the dark. The information appears in the binary in the form of
// type descriptors; the struct is unnamed and uses exported field
// names so that closures in multiple packages with the same struct
// type can share the descriptor.
// Make sure the .F field is in the same package as the rest of the
// fields. This deals with closures in instantiated functions, which are
// compiled as if from the source package of the generic function.
var pkg *types.Pkg
if len(clo.Func.ClosureVars) == 0 {
pkg = types.LocalPkg
} else {
for _, v := range clo.Func.ClosureVars {
if pkg == nil {
pkg = v.Sym().Pkg
} else if pkg != v.Sym().Pkg {
base.Fatalf("Closure variables from multiple packages: %+v", clo)
}
}
}
fields := []*types.Field{
types.NewField(base.Pos, pkg.Lookup(".F"), types.Types[types.TUINTPTR]),
}
for _, v := range clo.Func.ClosureVars {
fields := make([]*types.Field, 1+len(clo.Func.ClosureVars))
fields[0] = types.NewField(base.AutogeneratedPos, types.LocalPkg.Lookup("F"), types.Types[types.TUINTPTR])
for i, v := range clo.Func.ClosureVars {
typ := v.Type()
if !v.Byval() {
typ = types.NewPtr(typ)
}
fields = append(fields, types.NewField(base.Pos, v.Sym(), typ))
fields[1+i] = types.NewField(base.AutogeneratedPos, types.LocalPkg.LookupNum("X", i), typ)
}
typ := types.NewStruct(fields)
typ.SetNoalg(true)

View File

@@ -642,9 +642,6 @@ func fldconv(b *bytes.Buffer, f *Field, verb rune, mode fmtMode, visited map[*Ty
name = fmt.Sprint(f.Nname)
} else if verb == 'L' {
name = s.Name
if name == ".F" {
name = "F" // Hack for toolstash -cmp.
}
if !IsExported(name) && mode != fmtTypeIDName {
name = sconv(s, 0, mode) // qualify non-exported names (used on structs, not on funarg)
}

View File

@@ -110,11 +110,11 @@ type Config struct {
// type checker will initialize this field with a newly created context.
Context *Context
// GoVersion describes the accepted Go language version. The string
// must follow the format "go%d.%d" (e.g. "go1.12") or ist must be
// empty; an empty string disables Go language version checks.
// If the format is invalid, invoking the type checker will cause a
// panic.
// GoVersion describes the accepted Go language version. The string must
// start with a prefix of the form "go%d.%d" (e.g. "go1.20", "go1.21rc1", or
// "go1.21.0") or it must be empty; an empty string disables Go language
// version checks. If the format is invalid, invoking the type checker will
// result in an error.
GoVersion string
// If IgnoreFuncBodies is set, function bodies are not

View File

@@ -2070,6 +2070,29 @@ func TestIdenticalUnions(t *testing.T) {
}
}
func TestIssue61737(t *testing.T) {
// This test verifies that it is possible to construct invalid interfaces
// containing duplicate methods using the go/types API.
//
// It must be possible for importers to construct such invalid interfaces.
// Previously, this panicked.
sig1 := NewSignatureType(nil, nil, nil, NewTuple(NewParam(nopos, nil, "", Typ[Int])), nil, false)
sig2 := NewSignatureType(nil, nil, nil, NewTuple(NewParam(nopos, nil, "", Typ[String])), nil, false)
methods := []*Func{
NewFunc(nopos, nil, "M", sig1),
NewFunc(nopos, nil, "M", sig2),
}
embeddedMethods := []*Func{
NewFunc(nopos, nil, "M", sig2),
}
embedded := NewInterfaceType(embeddedMethods, nil)
iface := NewInterfaceType(methods, []Type{embedded})
iface.NumMethods() // unlike go/types, there is no Complete() method, so we complete implicitly
}
func TestIssue15305(t *testing.T) {
const src = "package p; func f() int16; var _ = f(undef)"
f := mustParse(src)

View File

@@ -576,6 +576,11 @@ func (check *Checker) builtin(x *operand, call *syntax.CallExpr, id builtinId) (
// If nargs == 1, make sure x.mode is either a value or a constant.
if x.mode != constant_ {
x.mode = value
// A value must not be untyped.
check.assignment(x, &emptyInterface, "argument to "+bin.name)
if x.mode == invalid {
return
}
}
// Use the final type computed above for all arguments.

View File

@@ -569,6 +569,14 @@ func (check *Checker) arguments(call *syntax.CallExpr, sig *Signature, targs []T
for i, arg := range args {
// generic arguments cannot have a defined (*Named) type - no need for underlying type below
if asig, _ := arg.typ.(*Signature); asig != nil && asig.TypeParams().Len() > 0 {
// The argument type is a generic function signature. This type is
// pointer-identical with (it's copied from) the type of the generic
// function argument and thus the function object.
// Before we change the type (type parameter renaming, below), make
// a clone of it as otherwise we implicitly modify the object's type
// (go.dev/issues/63260).
clone := *asig
asig = &clone
// Rename type parameters for cases like f(g, g); this gives each
// generic function argument a unique type identity (go.dev/issues/59956).
// TODO(gri) Consider only doing this if a function argument appears
@@ -610,20 +618,17 @@ func (check *Checker) arguments(call *syntax.CallExpr, sig *Signature, targs []T
return // error already reported
}
// compute result signature: instantiate if needed
rsig = sig
// update result signature: instantiate if needed
if n > 0 {
rsig = check.instantiateSignature(call.Pos(), call.Fun, sig, targs[:n], xlist)
}
// Optimization: Only if the callee's parameter list was adjusted do we need to
// compute it from the adjusted list; otherwise we can simply use the result
// signature's parameter list. We only need the n type parameters and arguments
// of the callee.
if n > 0 && adjusted {
sigParams = check.subst(call.Pos(), sigParams, makeSubstMap(tparams[:n], targs[:n]), nil, check.context()).(*Tuple)
} else {
sigParams = rsig.params
// If the callee's parameter list was adjusted we need to update (instantiate)
// it separately. Otherwise we can simply use the result signature's parameter
// list.
if adjusted {
sigParams = check.subst(call.Pos(), sigParams, makeSubstMap(tparams[:n], targs[:n]), nil, check.context()).(*Tuple)
} else {
sigParams = rsig.params
}
}
// compute argument signatures: instantiate if needed

View File

@@ -96,7 +96,7 @@ func (check *Checker) infer(pos syntax.Pos, tparams []*TypeParam, targs []Type,
// Unify parameter and argument types for generic parameters with typed arguments
// and collect the indices of generic parameters with untyped arguments.
// Terminology: generic parameter = function parameter with a type-parameterized type
u := newUnifier(tparams, targs)
u := newUnifier(tparams, targs, check.allowVersion(check.pkg, pos, go1_21))
errorf := func(kind string, tpar, targ Type, arg *operand) {
// provide a better error message if we can

View File

@@ -900,3 +900,84 @@ func _cgoCheckResult(interface{})
*boolFieldAddr(cfg, "go115UsesCgo") = true
})
}
func TestIssue61931(t *testing.T) {
const src = `
package p
func A(func(any), ...any) {}
func B[T any](T) {}
func _() {
A(B, nil // syntax error: missing ',' before newline in argument list
}
`
f, err := syntax.Parse(syntax.NewFileBase(pkgName(src)), strings.NewReader(src), func(error) {}, nil, 0)
if err == nil {
t.Fatal("expected syntax error")
}
var conf Config
conf.Check(f.PkgName.Value, []*syntax.File{f}, nil) // must not panic
}
func TestIssue63260(t *testing.T) {
const src = `
package p
func _() {
use(f[*string])
}
func use(func()) {}
func f[I *T, T any]() {
var v T
_ = v
}`
info := Info{
Defs: make(map[*syntax.Name]Object),
}
pkg := mustTypecheck(src, nil, &info)
// get type parameter T in signature of f
T := pkg.Scope().Lookup("f").Type().(*Signature).TypeParams().At(1)
if T.Obj().Name() != "T" {
t.Fatalf("got type parameter %s, want T", T)
}
// get type of variable v in body of f
var v Object
for name, obj := range info.Defs {
if name.Value == "v" {
v = obj
break
}
}
if v == nil {
t.Fatal("variable v not found")
}
// type of v and T must be pointer-identical
if v.Type() != T {
t.Fatalf("types of v and T are not pointer-identical: %p != %p", v.Type().(*TypeParam), T)
}
}
func TestIssue64759(t *testing.T) {
const src = `
//go:build go1.18
package p
func f[S ~[]E, E any](S) {}
func _() {
f([]string{})
}
`
// Per the go:build directive, the source must typecheck
// even though the (module) Go version is set to go1.17.
conf := Config{GoVersion: "go1.17"}
mustTypecheck(src, &conf, nil)
}

View File

@@ -169,6 +169,7 @@ func (subst *subster) typ(typ Type) Type {
if mcopied || ecopied {
iface := subst.check.newInterface()
iface.embeddeds = embeddeds
iface.embedPos = t.embedPos
iface.implicit = t.implicit
iface.complete = t.complete
// If we've changed the interface type, we may need to replace its

View File

@@ -6,7 +6,6 @@ package types2
import (
"cmd/compile/internal/syntax"
"fmt"
. "internal/types/errors"
"sort"
"strings"
@@ -212,7 +211,6 @@ func computeInterfaceTypeSet(check *Checker, pos syntax.Pos, ityp *Interface) *_
// we can get rid of the mpos map below and simply use the cloned method's
// position.
var todo []*Func
var seen objset
var allMethods []*Func
mpos := make(map[*Func]syntax.Pos) // method specification or method embedding position, for good error messages
@@ -222,36 +220,30 @@ func computeInterfaceTypeSet(check *Checker, pos syntax.Pos, ityp *Interface) *_
allMethods = append(allMethods, m)
mpos[m] = pos
case explicit:
if check == nil {
panic(fmt.Sprintf("%s: duplicate method %s", m.pos, m.name))
if check != nil {
var err error_
err.code = DuplicateDecl
err.errorf(pos, "duplicate method %s", m.name)
err.errorf(mpos[other.(*Func)], "other declaration of %s", m.name)
check.report(&err)
}
// check != nil
var err error_
err.code = DuplicateDecl
err.errorf(pos, "duplicate method %s", m.name)
err.errorf(mpos[other.(*Func)], "other declaration of %s", m.name)
check.report(&err)
default:
// We have a duplicate method name in an embedded (not explicitly declared) method.
// Check method signatures after all types are computed (go.dev/issue/33656).
// If we're pre-go1.14 (overlapping embeddings are not permitted), report that
// error here as well (even though we could do it eagerly) because it's the same
// error message.
if check == nil {
// check method signatures after all locally embedded interfaces are computed
todo = append(todo, m, other.(*Func))
break
if check != nil {
check.later(func() {
if !check.allowVersion(m.pkg, pos, go1_14) || !Identical(m.typ, other.Type()) {
var err error_
err.code = DuplicateDecl
err.errorf(pos, "duplicate method %s", m.name)
err.errorf(mpos[other.(*Func)], "other declaration of %s", m.name)
check.report(&err)
}
}).describef(pos, "duplicate method check for %s", m.name)
}
// check != nil
check.later(func() {
if !check.allowVersion(m.pkg, pos, go1_14) || !Identical(m.typ, other.Type()) {
var err error_
err.code = DuplicateDecl
err.errorf(pos, "duplicate method %s", m.name)
err.errorf(mpos[other.(*Func)], "other declaration of %s", m.name)
check.report(&err)
}
}).describef(pos, "duplicate method check for %s", m.name)
}
}
@@ -263,9 +255,8 @@ func computeInterfaceTypeSet(check *Checker, pos syntax.Pos, ityp *Interface) *_
allTerms := allTermlist
allComparable := false
for i, typ := range ityp.embeddeds {
// The embedding position is nil for imported interfaces
// and also for interface copies after substitution (but
// in that case we don't need to report errors again).
// The embedding position is nil for imported interfaces.
// We don't need to do version checks in those cases.
var pos syntax.Pos // embedding position
if ityp.embedPos != nil {
pos = (*ityp.embedPos)[i]
@@ -278,7 +269,7 @@ func computeInterfaceTypeSet(check *Checker, pos syntax.Pos, ityp *Interface) *_
assert(!isTypeParam(typ))
tset := computeInterfaceTypeSet(check, pos, u)
// If typ is local, an error was already reported where typ is specified/defined.
if check != nil && check.isImportedConstraint(typ) && !check.verifyVersionf(pos, go1_18, "embedding constraint interface %s", typ) {
if pos.IsKnown() && check != nil && check.isImportedConstraint(typ) && !check.verifyVersionf(pos, go1_18, "embedding constraint interface %s", typ) {
continue
}
comparable = tset.comparable
@@ -287,7 +278,7 @@ func computeInterfaceTypeSet(check *Checker, pos syntax.Pos, ityp *Interface) *_
}
terms = tset.terms
case *Union:
if check != nil && !check.verifyVersionf(pos, go1_18, "embedding interface element %s", u) {
if pos.IsKnown() && check != nil && !check.verifyVersionf(pos, go1_18, "embedding interface element %s", u) {
continue
}
tset := computeUnionTypeSet(check, unionSets, pos, u)
@@ -301,7 +292,7 @@ func computeInterfaceTypeSet(check *Checker, pos syntax.Pos, ityp *Interface) *_
if u == Typ[Invalid] {
continue
}
if check != nil && !check.verifyVersionf(pos, go1_18, "embedding non-interface type %s", typ) {
if pos.IsKnown() && check != nil && !check.verifyVersionf(pos, go1_18, "embedding non-interface type %s", typ) {
continue
}
terms = termlist{{false, typ}}
@@ -312,16 +303,6 @@ func computeInterfaceTypeSet(check *Checker, pos syntax.Pos, ityp *Interface) *_
// separately. Here we only need to intersect the term lists and comparable bits.
allTerms, allComparable = intersectTermLists(allTerms, allComparable, terms, comparable)
}
ityp.embedPos = nil // not needed anymore (errors have been reported)
// process todo's (this only happens if check == nil)
for i := 0; i < len(todo); i += 2 {
m := todo[i]
other := todo[i+1]
if !Identical(m.typ, other.typ) {
panic(fmt.Sprintf("%s: duplicate method %s", m.pos, m.name))
}
}
ityp.tset.comparable = allComparable
if len(allMethods) != 0 {

View File

@@ -53,11 +53,6 @@ const (
// the core types, if any, of non-local (unbound) type parameters.
enableCoreTypeUnification = true
// If enableInterfaceInference is set, type inference uses
// shared methods for improved type inference involving
// interfaces.
enableInterfaceInference = true
// If traceInference is set, unification will print a trace of its operation.
// Interpretation of trace:
// x ≡ y attempt to unify types x and y
@@ -81,15 +76,16 @@ type unifier struct {
// that inferring the type for a given type parameter P will
// automatically infer the same type for all other parameters
// unified (joined) with P.
handles map[*TypeParam]*Type
depth int // recursion depth during unification
handles map[*TypeParam]*Type
depth int // recursion depth during unification
enableInterfaceInference bool // use shared methods for better inference
}
// newUnifier returns a new unifier initialized with the given type parameter
// and corresponding type argument lists. The type argument list may be shorter
// than the type parameter list, and it may contain nil types. Matching type
// parameters and arguments must have the same index.
func newUnifier(tparams []*TypeParam, targs []Type) *unifier {
func newUnifier(tparams []*TypeParam, targs []Type, enableInterfaceInference bool) *unifier {
assert(len(tparams) >= len(targs))
handles := make(map[*TypeParam]*Type, len(tparams))
// Allocate all handles up-front: in a correct program, all type parameters
@@ -103,7 +99,7 @@ func newUnifier(tparams []*TypeParam, targs []Type) *unifier {
}
handles[x] = &t
}
return &unifier{handles, 0}
return &unifier{handles, 0, enableInterfaceInference}
}
// unifyMode controls the behavior of the unifier.
@@ -339,7 +335,7 @@ func (u *unifier) nify(x, y Type, mode unifyMode, p *ifacePair) (result bool) {
// we will fail at function instantiation or argument assignment time.
//
// If we have at least one defined type, there is one in y.
if ny, _ := y.(*Named); mode&exact == 0 && ny != nil && isTypeLit(x) && !(enableInterfaceInference && IsInterface(x)) {
if ny, _ := y.(*Named); mode&exact == 0 && ny != nil && isTypeLit(x) && !(u.enableInterfaceInference && IsInterface(x)) {
if traceInference {
u.tracef("%s ≡ under %s", x, ny)
}
@@ -405,18 +401,40 @@ func (u *unifier) nify(x, y Type, mode unifyMode, p *ifacePair) (result bool) {
// Therefore, we must fail unification (go.dev/issue/60933).
return false
}
// If y is a defined type, make sure we record that type
// for type parameter x, which may have until now only
// recorded an underlying type (go.dev/issue/43056).
// Either both types are interfaces, or neither type is.
// If both are interfaces, they have the same methods.
// If we have inexact unification and one of x or y is a defined type, select the
// defined type. This ensures that in a series of types, all matching against the
// same type parameter, we infer a defined type if there is one, independent of
// order. Type inference or assignment may fail, which is ok.
// Selecting a defined type, if any, ensures that we don't lose the type name;
// and since we have inexact unification, a value of equally named or matching
// undefined type remains assignable (go.dev/issue/43056).
//
// Note: Changing the recorded type for a type parameter to
// a defined type is only ok when unification is inexact.
// But in exact unification, if we have a match, x and y must
// be identical, so changing the recorded type for x is a no-op.
if yn {
u.set(px, y)
// Similarly, if we have inexact unification and there are no defined types but
// channel types, select a directed channel, if any. This ensures that in a series
// of unnamed types, all matching against the same type parameter, we infer the
// directed channel if there is one, independent of order.
// Selecting a directional channel, if any, ensures that a value of another
// inexactly unifying channel type remains assignable (go.dev/issue/62157).
//
// If we have multiple defined channel types, they are either identical or we
// have assignment conflicts, so we can ignore directionality in this case.
//
// If we have defined and literal channel types, a defined type wins to avoid
// order dependencies.
if mode&exact == 0 {
switch {
case xn:
// x is a defined type: nothing to do.
case yn:
// x is not a defined type and y is a defined type: select y.
u.set(px, y)
default:
// Neither x nor y are defined types.
if yc, _ := under(y).(*Chan); yc != nil && yc.dir != SendRecv {
// y is a directed channel type: select y.
u.set(px, y)
}
}
}
return true
}
@@ -437,12 +455,12 @@ func (u *unifier) nify(x, y Type, mode unifyMode, p *ifacePair) (result bool) {
emode |= exact
}
// If EnableInterfaceInference is set and we don't require exact unification,
// If u.EnableInterfaceInference is set and we don't require exact unification,
// if both types are interfaces, one interface must have a subset of the
// methods of the other and corresponding method signatures must unify.
// If only one type is an interface, all its methods must be present in the
// other type and corresponding method signatures must unify.
if enableInterfaceInference && mode&exact == 0 {
if u.enableInterfaceInference && mode&exact == 0 {
// One or both interfaces may be defined types.
// Look under the name, but not under type parameters (go.dev/issue/60564).
xi := asInterface(x)
@@ -505,7 +523,7 @@ func (u *unifier) nify(x, y Type, mode unifyMode, p *ifacePair) (result bool) {
}
// All xmethods must exist in ymethods and corresponding signatures must unify.
for _, xm := range xmethods {
if ym := ymap[xm.Id()]; ym == nil || !u.nify(xm.typ, ym.typ, emode, p) {
if ym := ymap[xm.Id()]; ym == nil || !u.nify(xm.typ, ym.typ, exact, p) {
return false
}
}
@@ -526,7 +544,7 @@ func (u *unifier) nify(x, y Type, mode unifyMode, p *ifacePair) (result bool) {
xmethods := xi.typeSet().methods
for _, xm := range xmethods {
obj, _, _ := LookupFieldOrMethod(y, false, xm.pkg, xm.name)
if ym, _ := obj.(*Func); ym == nil || !u.nify(xm.typ, ym.typ, emode, p) {
if ym, _ := obj.(*Func); ym == nil || !u.nify(xm.typ, ym.typ, exact, p) {
return false
}
}
@@ -632,7 +650,7 @@ func (u *unifier) nify(x, y Type, mode unifyMode, p *ifacePair) (result bool) {
}
case *Interface:
assert(!enableInterfaceInference || mode&exact != 0) // handled before this switch
assert(!u.enableInterfaceInference || mode&exact != 0) // handled before this switch
// Two interface types unify if they have the same set of methods with
// the same names, and corresponding function types unify.
@@ -685,7 +703,7 @@ func (u *unifier) nify(x, y Type, mode unifyMode, p *ifacePair) (result bool) {
}
for i, f := range a {
g := b[i]
if f.Id() != g.Id() || !u.nify(f.typ, g.typ, emode, q) {
if f.Id() != g.Id() || !u.nify(f.typ, g.typ, exact, q) {
return false
}
}

View File

@@ -255,7 +255,10 @@ func walkLenCap(n *ir.UnaryExpr, init *ir.Nodes) ir.Node {
return mkcall("countrunes", n.Type(), init, typecheck.Conv(n.X.(*ir.ConvExpr).X, types.Types[types.TSTRING]))
}
if isByteCount(n) {
_, len := backingArrayPtrLen(cheapExpr(n.X.(*ir.ConvExpr).X, init))
conv := n.X.(*ir.ConvExpr)
walkStmtList(conv.Init())
init.Append(ir.TakeInit(conv)...)
_, len := backingArrayPtrLen(cheapExpr(conv.X, init))
return len
}

View File

@@ -278,8 +278,10 @@ func backingArrayPtrLen(n ir.Node) (ptr, length ir.Node) {
} else {
ptr.SetType(n.Type().Elem().PtrTo())
}
ptr.SetTypecheck(1)
length = ir.NewUnaryExpr(base.Pos, ir.OLEN, n)
length.SetType(types.Types[types.TINT])
length.SetTypecheck(1)
return ptr, length
}

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

@@ -91,6 +91,29 @@ type work struct {
end chan bool
}
// printSkip prints a skip message for all of work.
func (w *work) printSkip(t *tester, msg string) {
if t.json {
type event struct {
Time time.Time
Action string
Package string
Output string `json:",omitempty"`
}
enc := json.NewEncoder(&w.out)
ev := event{Time: time.Now(), Package: w.dt.name, Action: "start"}
enc.Encode(ev)
ev.Action = "output"
ev.Output = msg
enc.Encode(ev)
ev.Action = "skip"
ev.Output = ""
enc.Encode(ev)
return
}
fmt.Fprintln(&w.out, msg)
}
// A distTest is a test run by dist test.
// Each test has a unique name and belongs to a group (heading)
type distTest struct {
@@ -405,6 +428,9 @@ func (opts *goTest) buildArgs(t *tester) (build, run, pkgs, testFlags []string,
if opts.timeout != 0 {
d := opts.timeout * time.Duration(t.timeoutScale)
run = append(run, "-timeout="+d.String())
} else if t.timeoutScale != 1 {
const goTestDefaultTimeout = 10 * time.Minute // Default value of go test -timeout flag.
run = append(run, "-timeout="+(goTestDefaultTimeout*time.Duration(t.timeoutScale)).String())
}
if opts.short || t.short {
run = append(run, "-short")
@@ -1235,7 +1261,7 @@ func (t *tester) runPending(nextTest *distTest) {
go func(w *work) {
if !<-w.start {
timelog("skip", w.dt.name)
w.out.WriteString("skipped due to earlier error\n")
w.printSkip(t, "skipped due to earlier error")
} else {
timelog("start", w.dt.name)
w.err = w.cmd.Run()
@@ -1246,7 +1272,7 @@ func (t *tester) runPending(nextTest *distTest) {
if isUnsupportedVMASize(w) {
timelog("skip", w.dt.name)
w.out.Reset()
w.out.WriteString("skipped due to unsupported VMA\n")
w.printSkip(t, "skipped due to unsupported VMA")
w.err = nil
}
}

View File

@@ -44,7 +44,7 @@ type fileInfo struct {
func (i fileInfo) Name() string { return path.Base(i.f.Name) }
func (i fileInfo) ModTime() time.Time { return i.f.Time }
func (i fileInfo) Mode() fs.FileMode { return i.f.Mode }
func (i fileInfo) IsDir() bool { return false }
func (i fileInfo) IsDir() bool { return i.f.Mode&fs.ModeDir != 0 }
func (i fileInfo) Size() int64 { return i.f.Size }
func (i fileInfo) Sys() any { return nil }

View File

@@ -329,8 +329,47 @@ func writeTgz(name string, a *Archive) {
zw := check(gzip.NewWriterLevel(out, gzip.BestCompression))
tw := tar.NewWriter(zw)
// Find the mode and mtime to use for directory entries,
// based on the mode and mtime of the first file we see.
// We know that modes and mtimes are uniform across the archive.
var dirMode fs.FileMode
var mtime time.Time
for _, f := range a.Files {
dirMode = fs.ModeDir | f.Mode | (f.Mode&0444)>>2 // copy r bits down to x bits
mtime = f.Time
break
}
// mkdirAll ensures that the tar file contains directory
// entries for dir and all its parents. Some programs reading
// these tar files expect that. See go.dev/issue/61862.
haveDir := map[string]bool{".": true}
var mkdirAll func(string)
mkdirAll = func(dir string) {
if dir == "/" {
panic("mkdirAll /")
}
if haveDir[dir] {
return
}
haveDir[dir] = true
mkdirAll(path.Dir(dir))
df := &File{
Name: dir + "/",
Time: mtime,
Mode: dirMode,
}
h := check(tar.FileInfoHeader(df.Info(), ""))
h.Name = dir + "/"
if err := tw.WriteHeader(h); err != nil {
panic(err)
}
}
for _, f = range a.Files {
h := check(tar.FileInfoHeader(f.Info(), ""))
mkdirAll(path.Dir(f.Name))
h.Name = f.Name
if err := tw.WriteHeader(h); err != nil {
panic(err)

View File

@@ -490,25 +490,43 @@ func findGOROOT(env string) string {
// depend on the executable's location.
return def
}
// canonical returns a directory path that represents
// the same directory as dir,
// preferring the spelling in def if the two are the same.
canonical := func(dir string) string {
if isSameDir(def, dir) {
return def
}
return dir
}
exe, err := os.Executable()
if err == nil {
exe, err = filepath.Abs(exe)
if err == nil {
// cmd/go may be installed in GOROOT/bin or GOROOT/bin/GOOS_GOARCH,
// depending on whether it was cross-compiled with a different
// GOHOSTOS (see https://go.dev/issue/62119). Try both.
if dir := filepath.Join(exe, "../.."); isGOROOT(dir) {
// If def (runtime.GOROOT()) and dir are the same
// directory, prefer the spelling used in def.
if isSameDir(def, dir) {
return def
}
return dir
return canonical(dir)
}
if dir := filepath.Join(exe, "../../.."); isGOROOT(dir) {
return canonical(dir)
}
// Depending on what was passed on the command line, it is possible
// that os.Executable is a symlink (like /usr/local/bin/go) referring
// to a binary installed in a real GOROOT elsewhere
// (like /usr/lib/go/bin/go).
// Try to find that GOROOT by resolving the symlinks.
exe, err = filepath.EvalSymlinks(exe)
if err == nil {
if dir := filepath.Join(exe, "../.."); isGOROOT(dir) {
if isSameDir(def, dir) {
return def
}
return dir
return canonical(dir)
}
if dir := filepath.Join(exe, "../../.."); isGOROOT(dir) {
return canonical(dir)
}
}
}

View File

@@ -181,6 +181,8 @@ func init() {
}
func runGenerate(ctx context.Context, cmd *base.Command, args []string) {
modload.InitWorkfile()
if generateRunFlag != "" {
var err error
generateRunRE, err = regexp.Compile(generateRunFlag)

View File

@@ -22,6 +22,13 @@ import (
// FromToolchain("go1.2.3-bigcorp") == "1.2.3"
// FromToolchain("invalid") == ""
func FromToolchain(name string) string {
if strings.ContainsAny(name, "\\/") {
// The suffix must not include a path separator, since that would cause
// exec.LookPath to resolve it from a relative directory instead of from
// $PATH.
return ""
}
var v string
if strings.HasPrefix(name, "go") {
v = name[2:]

View File

@@ -959,7 +959,10 @@ func collectDepsErrors(p *load.Package) {
if len(stkj) != 0 {
return true
}
return p.DepsErrors[i].Err.Error() < p.DepsErrors[j].Err.Error()
} else if len(stkj) == 0 {
return false
}
pathi, pathj := stki[len(stki)-1], stkj[len(stkj)-1]
return pathi < pathj

View File

@@ -473,6 +473,7 @@ func recompileForTest(pmain, preal, ptest, pxtest *Package) *PackageError {
p.Target = ""
p.Internal.BuildInfo = nil
p.Internal.ForceLibrary = true
p.Internal.PGOProfile = preal.Internal.PGOProfile
}
// Update p.Internal.Imports to use test copies.
@@ -496,6 +497,11 @@ func recompileForTest(pmain, preal, ptest, pxtest *Package) *PackageError {
if p.Name == "main" && p != pmain && p != ptest {
split()
}
// Split and attach PGO information to test dependencies if preal
// is built with PGO.
if preal.Internal.PGOProfile != "" && p.Internal.PGOProfile == "" {
split()
}
}
// Do search to find cycle.

View File

@@ -10,6 +10,7 @@ import (
"errors"
"os"
"runtime"
"sync"
"cmd/go/internal/base"
"cmd/go/internal/cfg"
@@ -17,6 +18,7 @@ import (
"cmd/go/internal/modfetch"
"cmd/go/internal/modfetch/codehost"
"cmd/go/internal/modload"
"cmd/go/internal/toolchain"
"golang.org/x/mod/module"
)
@@ -153,7 +155,10 @@ func runDownload(ctx context.Context, cmd *base.Command, args []string) {
// 'go mod graph', and similar commands.
_, err := modload.LoadModGraph(ctx, "")
if err != nil {
base.Fatal(err)
// TODO(#64008): call base.Fatalf instead of toolchain.SwitchOrFatal
// here, since we can only reach this point with an outdated toolchain
// if the go.mod file is inconsistent.
toolchain.SwitchOrFatal(ctx, err)
}
for _, m := range modFile.Require {
@@ -194,8 +199,26 @@ func runDownload(ctx context.Context, cmd *base.Command, args []string) {
// from the resulting TooNewError), all before we try the actual full download
// of each module.
//
// For now, we just let it fail: the user can explicitly set GOTOOLCHAIN
// and retry if they want to.
// For now, we go ahead and try all the downloads and collect the errors, and
// if any download failed due to a TooNewError, we switch toolchains and try
// again. Any downloads that already succeeded will still be in cache.
// That won't give optimal concurrency (we'll do two batches of concurrent
// downloads instead of all in one batch), and it might add a little overhead
// to look up the downloads from the first batch in the module cache when
// we see them again in the second batch. On the other hand, it's way simpler
// to implement, and not really any more expensive if the user is requesting
// no explicit arguments (their go.mod file should already list an appropriate
// toolchain version) or only one module (as is used by the Go Module Proxy).
if infosErr != nil {
var sw toolchain.Switcher
sw.Error(infosErr)
if sw.NeedSwitch() {
sw.Switch(ctx)
}
// Otherwise, wait to report infosErr after we have downloaded
// when we can.
}
if !haveExplicitArgs && modload.WorkFilePath() == "" {
// 'go mod download' is sometimes run without arguments to pre-populate the
@@ -205,7 +228,7 @@ func runDownload(ctx context.Context, cmd *base.Command, args []string) {
// (golang.org/issue/45332). We do still fix inconsistencies in go.mod
// though.
//
// TODO(#45551): In the future, report an error if go.mod or go.sum need to
// TODO(#64008): In the future, report an error if go.mod or go.sum need to
// be updated after loading the build list. This may require setting
// the mode to "mod" or "readonly" depending on haveExplicitArgs.
if err := modload.WriteGoMod(ctx, modload.WriteOpts{}); err != nil {
@@ -213,6 +236,7 @@ func runDownload(ctx context.Context, cmd *base.Command, args []string) {
}
}
var downloadErrs sync.Map
for _, info := range infos {
if info.Replace != nil {
info = info.Replace
@@ -239,7 +263,11 @@ func runDownload(ctx context.Context, cmd *base.Command, args []string) {
}
sem <- token{}
go func() {
DownloadModule(ctx, m)
err := DownloadModule(ctx, m)
if err != nil {
downloadErrs.Store(m, err)
m.Error = err.Error()
}
<-sem
}()
}
@@ -249,6 +277,39 @@ func runDownload(ctx context.Context, cmd *base.Command, args []string) {
sem <- token{}
}
// If there were explicit arguments
// (like 'go mod download golang.org/x/tools@latest'),
// check whether we need to upgrade the toolchain in order to download them.
//
// (If invoked without arguments, we expect the module graph to already
// be tidy and the go.mod file to declare a 'go' version that satisfies
// transitive requirements. If that invariant holds, then we should have
// already upgraded when we loaded the module graph, and should not need
// an additional check here. See https://go.dev/issue/45551.)
//
// We also allow upgrades if in a workspace because in workspace mode
// with no arguments we download the module pattern "all",
// which may include dependencies that are normally pruned out
// of the individual modules in the workspace.
if haveExplicitArgs || modload.WorkFilePath() != "" {
var sw toolchain.Switcher
// Add errors to the Switcher in deterministic order so that they will be
// logged deterministically.
for _, m := range mods {
if erri, ok := downloadErrs.Load(m); ok {
sw.Error(erri.(error))
}
}
// Only call sw.Switch if it will actually switch.
// Otherwise, we may want to write the errors as JSON
// (instead of using base.Error as sw.Switch would),
// and we may also have other errors to report from the
// initial infos returned by ListModules.
if sw.NeedSwitch() {
sw.Switch(ctx)
}
}
if *downloadJSON {
for _, m := range mods {
b, err := json.MarshalIndent(m, "", "\t")
@@ -302,34 +363,27 @@ func runDownload(ctx context.Context, cmd *base.Command, args []string) {
// DownloadModule runs 'go mod download' for m.Path@m.Version,
// leaving the results (including any error) in m itself.
func DownloadModule(ctx context.Context, m *ModuleJSON) {
func DownloadModule(ctx context.Context, m *ModuleJSON) error {
var err error
_, file, err := modfetch.InfoFile(ctx, m.Path, m.Version)
if err != nil {
m.Error = err.Error()
return
return err
}
m.Info = file
m.GoMod, err = modfetch.GoModFile(ctx, m.Path, m.Version)
if err != nil {
m.Error = err.Error()
return
return err
}
m.GoModSum, err = modfetch.GoModSum(ctx, m.Path, m.Version)
if err != nil {
m.Error = err.Error()
return
return err
}
mod := module.Version{Path: m.Path, Version: m.Version}
m.Zip, err = modfetch.DownloadZip(ctx, mod)
if err != nil {
m.Error = err.Error()
return
return err
}
m.Sum = modfetch.Sum(ctx, mod)
m.Dir, err = modfetch.Download(ctx, mod)
if err != nil {
m.Error = err.Error()
return
}
return err
}

View File

@@ -61,7 +61,7 @@ func runVerify(ctx context.Context, cmd *base.Command, args []string) {
if err != nil {
base.Fatal(err)
}
mods := mg.BuildList()[modload.MainModules.Len():]
mods := mg.BuildList()
// Use a slice of result channels, so that the output is deterministic.
errsChans := make([]<-chan []error, len(mods))
@@ -94,6 +94,9 @@ func verifyMod(ctx context.Context, mod module.Version) []error {
// "go" and "toolchain" have no disk footprint; nothing to verify.
return nil
}
if modload.MainModules.Contains(mod.Path) {
return nil
}
var errs []error
zip, zipErr := modfetch.CachePath(ctx, mod, "zip")
if zipErr == nil {

View File

@@ -110,7 +110,13 @@ func ListModules(ctx context.Context, args []string, mode ListMode, reuseFile st
if err == nil {
requirements = rs
if !ExplicitWriteGoMod {
// TODO(#61605): The extra ListU clause fixes a problem with Go 1.21rc3
// where "go mod tidy" and "go list -m -u all" fight over whether the go.sum
// should be considered up-to-date. The fix for now is to always treat the
// go.sum as up-to-date during list -m -u. Probably the right fix is more targeted,
// but in general list -u is looking up other checksums in the checksum database
// that won't be necessary later, so it makes sense not to write the go.sum back out.
if !ExplicitWriteGoMod && mode&ListU == 0 {
err = commitRequirements(ctx, WriteOpts{})
}
}

View File

@@ -1363,65 +1363,87 @@ func (r *runTestActor) Act(b *work.Builder, ctx context.Context, a *work.Action)
ctx, cancel := context.WithTimeout(ctx, testKillTimeout)
defer cancel()
cmd := exec.CommandContext(ctx, args[0], args[1:]...)
cmd.Dir = a.Package.Dir
env := slices.Clip(cfg.OrigEnv)
env = base.AppendPATH(env)
env = base.AppendPWD(env, cmd.Dir)
cmd.Env = env
if addToEnv != "" {
cmd.Env = append(cmd.Env, addToEnv)
}
cmd.Stdout = stdout
cmd.Stderr = stdout
// If there are any local SWIG dependencies, we want to load
// the shared library from the build directory.
if a.Package.UsesSwig() {
env := cmd.Env
found := false
prefix := "LD_LIBRARY_PATH="
for i, v := range env {
if strings.HasPrefix(v, prefix) {
env[i] = v + ":."
found = true
break
}
}
if !found {
env = append(env, "LD_LIBRARY_PATH=.")
}
cmd.Env = env
}
// Now we're ready to actually run the command.
//
// If the -o flag is set, or if at some point we change cmd/go to start
// copying test executables into the build cache, we may run into spurious
// ETXTBSY errors on Unix platforms (see https://go.dev/issue/22315).
//
// Since we know what causes those, and we know that they should resolve
// quickly (the ETXTBSY error will resolve as soon as the subprocess
// holding the descriptor open reaches its 'exec' call), we retry them
// in a loop.
var (
cmd *exec.Cmd
t0 time.Time
cancelKilled = false
cancelSignaled = false
)
cmd.Cancel = func() error {
if base.SignalTrace == nil {
err := cmd.Process.Kill()
for {
cmd = exec.CommandContext(ctx, args[0], args[1:]...)
cmd.Dir = a.Package.Dir
env := slices.Clip(cfg.OrigEnv)
env = base.AppendPATH(env)
env = base.AppendPWD(env, cmd.Dir)
cmd.Env = env
if addToEnv != "" {
cmd.Env = append(cmd.Env, addToEnv)
}
cmd.Stdout = stdout
cmd.Stderr = stdout
// If there are any local SWIG dependencies, we want to load
// the shared library from the build directory.
if a.Package.UsesSwig() {
env := cmd.Env
found := false
prefix := "LD_LIBRARY_PATH="
for i, v := range env {
if strings.HasPrefix(v, prefix) {
env[i] = v + ":."
found = true
break
}
}
if !found {
env = append(env, "LD_LIBRARY_PATH=.")
}
cmd.Env = env
}
cmd.Cancel = func() error {
if base.SignalTrace == nil {
err := cmd.Process.Kill()
if err == nil {
cancelKilled = true
}
return err
}
// Send a quit signal in the hope that the program will print
// a stack trace and exit.
err := cmd.Process.Signal(base.SignalTrace)
if err == nil {
cancelKilled = true
cancelSignaled = true
}
return err
}
cmd.WaitDelay = testWaitDelay
// Send a quit signal in the hope that the program will print
// a stack trace and exit.
err := cmd.Process.Signal(base.SignalTrace)
if err == nil {
cancelSignaled = true
base.StartSigHandlers()
t0 = time.Now()
err = cmd.Run()
if !isETXTBSY(err) {
// We didn't hit the race in #22315, so there is no reason to retry the
// command.
break
}
return err
}
cmd.WaitDelay = testWaitDelay
base.StartSigHandlers()
t0 := time.Now()
err = cmd.Run()
out := buf.Bytes()
a.TestOutput = &buf
t := fmt.Sprintf("%.3fs", time.Since(t0).Seconds())

View File

@@ -0,0 +1,12 @@
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build !unix
package test
func isETXTBSY(err error) bool {
// syscall.ETXTBSY is only meaningful on Unix platforms.
return false
}

View File

@@ -0,0 +1,16 @@
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build unix
package test
import (
"errors"
"syscall"
)
func isETXTBSY(err error) bool {
return errors.Is(err, syscall.ETXTBSY)
}

View File

@@ -61,7 +61,7 @@ func init() {
cf.String("run", "", "")
cf.Bool("short", false, "")
cf.String("skip", "", "")
cf.DurationVar(&testTimeout, "timeout", 10*time.Minute, "")
cf.DurationVar(&testTimeout, "timeout", 10*time.Minute, "") // known to cmd/dist
cf.String("fuzztime", "", "")
cf.String("fuzzminimizetime", "", "")
cf.StringVar(&testTrace, "trace", "", "")

View File

@@ -8,6 +8,7 @@ package toolchain
import (
"context"
"errors"
"flag"
"fmt"
"go/build"
"io/fs"
@@ -25,6 +26,7 @@ import (
"cmd/go/internal/modfetch"
"cmd/go/internal/modload"
"cmd/go/internal/run"
"cmd/go/internal/work"
"golang.org/x/mod/module"
)
@@ -485,74 +487,132 @@ func goInstallVersion() 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.
if len(os.Args) < 3 || (os.Args[1] != "install" && os.Args[1] != "run") {
if len(os.Args) < 3 {
return false
}
// Check for pkg@version.
var arg string
var cmdFlags *flag.FlagSet
switch os.Args[1] {
default:
// Command doesn't support a pkg@version as the main module.
return false
case "install":
// We would like to let 'go install -newflag pkg@version' work even
// across a toolchain switch. To make that work, assume the pkg@version
// is the last argument and skip the flag parsing.
arg = os.Args[len(os.Args)-1]
cmdFlags = &work.CmdInstall.Flag
case "run":
// For run, the pkg@version can be anywhere on the command line,
// because it is preceded by run flags and followed by arguments to the
// program being run. To handle that precisely, we have to interpret the
// flags a little bit, to know whether each flag takes an optional argument.
// We can still allow unknown flags as long as they have an explicit =value.
args := os.Args[2:]
for i := 0; i < len(args); i++ {
a := args[i]
if !strings.HasPrefix(a, "-") {
arg = a
break
}
if a == "-" {
// non-flag but also non-pkg@version
cmdFlags = &run.CmdRun.Flag
}
// The modcachrw flag is unique, in that it affects how we fetch the
// requested module to even figure out what toolchain it needs.
// We need to actually set it before we check the toolchain version.
// (See https://go.dev/issue/64282.)
modcacherwFlag := cmdFlags.Lookup("modcacherw")
if modcacherwFlag == nil {
base.Fatalf("internal error: modcacherw flag not registered for command")
}
modcacherwVal, ok := modcacherwFlag.Value.(interface {
IsBoolFlag() bool
flag.Value
})
if !ok || !modcacherwVal.IsBoolFlag() {
base.Fatalf("internal error: modcacherw is not a boolean flag")
}
// Make a best effort to parse the command's args to find the pkg@version
// argument and the -modcacherw flag.
var (
pkgArg string
modcacherwSeen bool
)
for args := os.Args[2:]; len(args) > 0; {
a := args[0]
args = args[1:]
if a == "--" {
if len(args) == 0 {
return false
}
if a == "--" {
if i+1 >= len(args) {
return false
pkgArg = args[0]
break
}
a, ok := strings.CutPrefix(a, "-")
if !ok {
// Not a flag argument. Must be a package.
pkgArg = a
break
}
a = strings.TrimPrefix(a, "-") // Treat --flag as -flag.
name, val, hasEq := strings.Cut(a, "=")
if name == "modcacherw" {
if !hasEq {
val = "true"
}
if err := modcacherwVal.Set(val); err != nil {
return false
}
modcacherwSeen = true
continue
}
if hasEq {
// Already has a value; don't bother parsing it.
continue
}
f := run.CmdRun.Flag.Lookup(a)
if f == nil {
// We don't know whether this flag is a boolean.
if os.Args[1] == "run" {
// We don't know where to find the pkg@version argument.
// For run, the pkg@version can be anywhere on the command line,
// because it is preceded by run flags and followed by arguments to the
// program being run. Since we don't know whether this flag takes
// an argument, we can't reliably identify the end of the run flags.
// Just give up and let the user clarify using the "=" form..
return false
}
// We would like to let 'go install -newflag pkg@version' work even
// across a toolchain switch. To make that work, assume by default that
// the pkg@version is the last argument and skip the remaining args unless
// we spot a plausible "-modcacherw" flag.
for len(args) > 0 {
a := args[0]
name, _, _ := strings.Cut(a, "=")
if name == "-modcacherw" || name == "--modcacherw" {
break
}
arg = args[i+1]
break
if len(args) == 1 && !strings.HasPrefix(a, "-") {
pkgArg = a
}
args = args[1:]
}
a = strings.TrimPrefix(a, "-")
a = strings.TrimPrefix(a, "-")
if strings.HasPrefix(a, "-") {
// non-flag but also non-pkg@version
return false
}
if strings.Contains(a, "=") {
// already has value
continue
}
f := run.CmdRun.Flag.Lookup(a)
if f == nil {
// Unknown flag. Give up. The command is going to fail in flag parsing.
return false
}
if bf, ok := f.Value.(interface{ IsBoolFlag() bool }); ok && bf.IsBoolFlag() {
// Does not take value.
continue
}
i++ // Does take a value; skip it.
continue
}
if bf, ok := f.Value.(interface{ IsBoolFlag() bool }); !ok || !bf.IsBoolFlag() {
// The next arg is the value for this flag. Skip it.
args = args[1:]
continue
}
}
if !strings.Contains(arg, "@") || build.IsLocalImport(arg) || filepath.IsAbs(arg) {
if !strings.Contains(pkgArg, "@") || build.IsLocalImport(pkgArg) || filepath.IsAbs(pkgArg) {
return false
}
path, version, _ := strings.Cut(arg, "@")
path, version, _ := strings.Cut(pkgArg, "@")
if path == "" || version == "" || gover.IsToolchain(path) {
return false
}
if !modcacherwSeen && base.InGOFLAGS("-modcacherw") {
fs := flag.NewFlagSet("goInstallVersion", flag.ExitOnError)
fs.Var(modcacherwVal, "modcacherw", modcacherwFlag.Usage)
base.SetFromGOFLAGS(fs)
}
// It would be correct to simply return true here, bypassing use
// of the current go.mod or go.work, and let "go run" or "go install"
// do the rest, including a toolchain switch.

View File

@@ -1204,18 +1204,31 @@ func repoRootFromVCSPaths(importPath string, security web.SecurityMode, vcsPaths
var ok bool
repoURL, ok = interceptVCSTest(repo, vcs, security)
if !ok {
scheme := vcs.Scheme[0] // default to first scheme
if vcs.PingCmd != "" {
// If we know how to test schemes, scan to find one.
scheme, err := func() (string, error) {
for _, s := range vcs.Scheme {
if security == web.SecureOnly && !vcs.isSecureScheme(s) {
continue
}
if vcs.Ping(s, repo) == nil {
scheme = s
break
// If we know how to ping URL schemes for this VCS,
// check that this repo works.
// Otherwise, default to the first scheme
// that meets the requested security level.
if vcs.PingCmd == "" {
return s, nil
}
if err := vcs.Ping(s, repo); err == nil {
return s, nil
}
}
securityFrag := ""
if security == web.SecureOnly {
securityFrag = "secure "
}
return "", fmt.Errorf("no %sprotocol found for repository", securityFrag)
}()
if err != nil {
return nil, err
}
repoURL = scheme + "://" + repo
}

View File

@@ -212,16 +212,22 @@ func get(security SecurityMode, url *urlpkg.URL) (*Response, error) {
}
}
if res == nil || res.Body == nil {
if err != nil {
// Per the docs for [net/http.Client.Do], “On error, any Response can be
// ignored. A non-nil Response with a non-nil error only occurs when
// CheckRedirect fails, and even then the returned Response.Body is
// already closed.”
release()
} else {
body := res.Body
res.Body = hookCloser{
ReadCloser: body,
afterClose: release,
}
return nil, nil, err
}
// “If the returned error is nil, the Response will contain a non-nil Body
// which the user is expected to close.”
body := res.Body
res.Body = hookCloser{
ReadCloser: body,
afterClose: release,
}
return url, res, err
}

View File

@@ -141,6 +141,12 @@ var validCompilerFlagsWithNextArg = []string{
"-x",
}
var invalidLinkerFlags = []*lazyregexp.Regexp{
// On macOS this means the linker loads and executes the next argument.
// Have to exclude separately because -lfoo is allowed in general.
re(`-lto_library`),
}
var validLinkerFlags = []*lazyregexp.Regexp{
re(`-F([^@\-].*)`),
re(`-l([^@\-].*)`),
@@ -231,12 +237,12 @@ var validLinkerFlagsWithNextArg = []string{
func checkCompilerFlags(name, source string, list []string) error {
checkOverrides := true
return checkFlags(name, source, list, validCompilerFlags, validCompilerFlagsWithNextArg, checkOverrides)
return checkFlags(name, source, list, nil, validCompilerFlags, validCompilerFlagsWithNextArg, checkOverrides)
}
func checkLinkerFlags(name, source string, list []string) error {
checkOverrides := true
return checkFlags(name, source, list, validLinkerFlags, validLinkerFlagsWithNextArg, checkOverrides)
return checkFlags(name, source, list, invalidLinkerFlags, validLinkerFlags, validLinkerFlagsWithNextArg, checkOverrides)
}
// checkCompilerFlagsForInternalLink returns an error if 'list'
@@ -245,7 +251,7 @@ func checkLinkerFlags(name, source string, list []string) error {
// external linker).
func checkCompilerFlagsForInternalLink(name, source string, list []string) error {
checkOverrides := false
if err := checkFlags(name, source, list, validCompilerFlags, validCompilerFlagsWithNextArg, checkOverrides); err != nil {
if err := checkFlags(name, source, list, nil, validCompilerFlags, validCompilerFlagsWithNextArg, checkOverrides); err != nil {
return err
}
// Currently the only flag on the allow list that causes problems
@@ -258,7 +264,7 @@ func checkCompilerFlagsForInternalLink(name, source string, list []string) error
return nil
}
func checkFlags(name, source string, list []string, valid []*lazyregexp.Regexp, validNext []string, checkOverrides bool) error {
func checkFlags(name, source string, list []string, invalid, valid []*lazyregexp.Regexp, validNext []string, checkOverrides bool) error {
// Let users override rules with $CGO_CFLAGS_ALLOW, $CGO_CFLAGS_DISALLOW, etc.
var (
allow *regexp.Regexp
@@ -290,6 +296,11 @@ Args:
if allow != nil && allow.FindString(arg) == arg {
continue Args
}
for _, re := range invalid {
if re.FindString(arg) == arg { // must be complete match
goto Bad
}
}
for _, re := range valid {
if re.FindString(arg) == arg { // must be complete match
continue Args

View File

@@ -175,7 +175,11 @@ func main() {
if used > 0 {
helpArg += " " + strings.Join(args[:used], " ")
}
fmt.Fprintf(os.Stderr, "go %s: unknown command\nRun 'go help%s' for usage.\n", cfg.CmdName, helpArg)
cmdName := cfg.CmdName
if cmdName == "" {
cmdName = args[0]
}
fmt.Fprintf(os.Stderr, "go %s: unknown command\nRun 'go help%s' for usage.\n", cmdName, helpArg)
base.SetExitStatus(2)
base.Exit()
}

View File

@@ -45,6 +45,12 @@ stderr 'compile.*-pgoprofile=.*b(/|\\\\)default\.pgo.*b(/|\\\\)b_test\.go'
stderr 'compile.*-pgoprofile=.*b(/|\\\\)default\.pgo.*dep(/|\\\\)dep\.go'
! stderr 'compile.*-pgoprofile=.*nopgo(/|\\\\)nopgo_test\.go'
# test-only dependencies also have profiles attached
stderr 'compile.*-pgoprofile=.*a(/|\\\\)default\.pgo.*testdep(/|\\\\)testdep\.go'
stderr 'compile.*-pgoprofile=.*b(/|\\\\)default\.pgo.*testdep(/|\\\\)testdep\.go'
stderr 'compile.*-pgoprofile=.*a(/|\\\\)default\.pgo.*testdep2(/|\\\\)testdep2\.go'
stderr 'compile.*-pgoprofile=.*b(/|\\\\)default\.pgo.*testdep2(/|\\\\)testdep2\.go'
# go list -deps prints packages built multiple times.
go list -pgo=auto -deps ./a ./b ./nopgo
stdout 'test/dep \[test/a\]'
@@ -66,6 +72,7 @@ func main() {}
-- a/a_test.go --
package main
import "testing"
import _ "test/testdep"
func TestA(*testing.T) {}
-- a/default.pgo --
-- b/b.go --
@@ -76,6 +83,7 @@ func main() {}
-- b/b_test.go --
package main
import "testing"
import _ "test/testdep"
func TestB(*testing.T) {}
-- b/default.pgo --
-- nopgo/nopgo.go --
@@ -94,3 +102,8 @@ import _ "test/dep3"
package dep2
-- dep3/dep3.go --
package dep3
-- testdep/testdep.go --
package testdep
import _ "test/testdep2"
-- testdep2/testdep2.go --
package testdep2

View File

@@ -0,0 +1,17 @@
[!GOOS:darwin] skip
[!cgo] skip
! go build
stderr 'invalid flag in #cgo LDFLAGS: -lto_library'
-- go.mod --
module ldflag
-- main.go --
package main
// #cgo CFLAGS: -flto
// #cgo LDFLAGS: -lto_library bad.dylib
import "C"
func main() {}

View File

@@ -0,0 +1,27 @@
# This is a regression test for Issue #56098: Go generate
# wasn't initializing workspace mode
[short] skip
go generate ./mod
cmp ./mod/got.txt want.txt
-- go.work --
go 1.21
use ./mod
-- mod/go.mod --
module example.com/mod
-- mod/gen.go --
//go:generate go run gen.go got.txt
package main
import "os"
func main() {
outfile := os.Args[1]
os.WriteFile(outfile, []byte("Hello World!\n"), 0644)
}
-- want.txt --
Hello World!

View File

@@ -0,0 +1,2 @@
! go asdf
stderr '^go asdf: unknown command'

View File

@@ -1,4 +1,5 @@
[compiler:gccgo] skip
[short] skip 'builds and links another cmd/go'
mkdir $WORK/new/bin
@@ -9,15 +10,18 @@ mkdir $WORK/new/bin
# new cmd/go is built.
env GOROOT_FINAL=
# $GOROOT/bin/go is whatever the user has already installed
# (using make.bash or similar). We can't make assumptions about what
# options it may have been built with, such as -trimpath or GOROOT_FINAL.
# Instead, we build a fresh copy of the binary with known settings.
go build -o $WORK/new/bin/go$GOEXE cmd/go &
go build -o $WORK/bin/check$GOEXE check.go &
go build -trimpath -o $WORK/bin/check$GOEXE check.go &
wait
env TESTGOROOT=$GOROOT
env GOROOT=
# Relocated Executable
# cp $TESTGOROOT/bin/go$GOEXE $WORK/new/bin/go$GOEXE
exec $WORK/bin/check$GOEXE $WORK/new/bin/go$GOEXE $TESTGOROOT
# Relocated Tree:

View File

@@ -0,0 +1,91 @@
# Regression test for https://go.dev/issue/62119:
# A 'go' command cross-compiled with a different GOHOSTOS
# should be able to locate its GOROOT using os.Executable.
#
# (This also tests a 'go' command built with -trimpath
# that is not cross-compiled, since we need to build that
# configuration for the test anyway.)
[short] skip 'builds and links another cmd/go'
mkdir $WORK/new/bin
mkdir $WORK/new/bin/${GOOS}_${GOARCH}
# In this test, we are specifically checking the logic for deriving
# the value of GOROOT from os.Executable when runtime.GOROOT is
# trimmed away.
# GOROOT_FINAL changes the default behavior of runtime.GOROOT,
# so we explicitly clear it to remove it as a confounding variable.
env GOROOT_FINAL=
# $GOROOT/bin/go is whatever the user has already installed
# (using make.bash or similar). We can't make assumptions about what
# options it may have been built with, such as -trimpath or GOROOT_FINAL.
# Instead, we build a fresh copy of the binary with known settings.
go build -trimpath -o $WORK/new/bin/go$GOEXE cmd/go &
go build -trimpath -o $WORK/bin/check$GOEXE check.go &
wait
env TESTGOROOT=$GOROOT
env GOROOT=
# Relocated Executable
# Since we built with -trimpath and the binary isn't installed in a
# normal-looking GOROOT, this command should fail.
! exec $WORK/new/bin/go$GOEXE env GOROOT
stderr '^go: cannot find GOROOT directory: ''go'' binary is trimmed and GOROOT is not set$'
# Cross-compiled binaries in cmd are installed to a ${GOOS}_${GOARCH} subdirectory,
# so we also want to try a copy there.
# (Note that the script engine's 'exec' engine already works around
# https://go.dev/issue/22315, so we don't have to do that explicitly in the
# 'check' program we use later.)
cp $WORK/new/bin/go$GOEXE $WORK/new/bin/${GOOS}_${GOARCH}/go$GOEXE
! exec $WORK/new/bin/${GOOS}_${GOARCH}/go$GOEXE env GOROOT
stderr '^go: cannot find GOROOT directory: ''go'' binary is trimmed and GOROOT is not set$'
# Relocated Tree:
# If the binary is sitting in a bin dir next to ../pkg/tool, that counts as a GOROOT,
# so it should find the new tree.
mkdir $WORK/new/pkg/tool
exec $WORK/bin/check$GOEXE $WORK/new/bin/go$GOEXE $WORK/new
exec $WORK/bin/check$GOEXE $WORK/new/bin/${GOOS}_${GOARCH}/go$GOEXE $WORK/new
-- check.go --
package main
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
)
func main() {
exe := os.Args[1]
want := os.Args[2]
cmd := exec.Command(exe, "env", "GOROOT")
out, err := cmd.CombinedOutput()
if err != nil {
fmt.Fprintf(os.Stderr, "%s env GOROOT: %v, %s\n", exe, err, out)
os.Exit(1)
}
goroot, err := filepath.EvalSymlinks(strings.TrimSpace(string(out)))
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
want, err = filepath.EvalSymlinks(want)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
if !strings.EqualFold(goroot, want) {
fmt.Fprintf(os.Stderr, "go env GOROOT:\nhave %s\nwant %s\n", goroot, want)
os.Exit(1)
}
fmt.Fprintf(os.Stderr, "go env GOROOT: %s\n", goroot)
}

View File

@@ -3,25 +3,18 @@ env TESTGO_VERSION_SWITCH=switch
# If the main module's go.mod file lists a version lower than the version
# required by its dependencies, the commands that fetch and diagnose the module
# graph (such as 'go mod download' and 'go mod graph') should fail explicitly:
# graph (such as 'go mod graph' and 'go mod verify') should fail explicitly:
# they can't interpret the graph themselves, and they aren't allowed to update
# the go.mod file to record a specific, stable toolchain version that can.
! go mod download rsc.io/future@v1.0.0
stderr '^go: rsc.io/future@v1.0.0 requires go >= 1.999 \(running go 1.21.0\)'
! go mod download rsc.io/future
stderr '^go: rsc.io/future@v1.0.0 requires go >= 1.999 \(running go 1.21.0\)'
! go mod download
stderr '^go: rsc.io/future@v1.0.0: module rsc.io/future@v1.0.0 requires go >= 1.999 \(running go 1.21.0\)'
! go mod verify
stderr '^go: rsc.io/future@v1.0.0: module rsc.io/future@v1.0.0 requires go >= 1.999 \(running go 1.21.0\)'
! go mod graph
stderr '^go: rsc.io/future@v1.0.0: module rsc.io/future@v1.0.0 requires go >= 1.999 \(running go 1.21.0\)'
# TODO(#64008): 'go mod download' without arguments should fail too.
# 'go get' should update the main module's go.mod file to a version compatible with the
# go version required for rsc.io/future, not fail.
@@ -33,8 +26,6 @@ stderr '^go: added toolchain go1.999testmod$'
# Now, the various 'go mod' subcommands should succeed.
go mod download rsc.io/future@v1.0.0
go mod download rsc.io/future
go mod download
go mod verify

View File

@@ -8,11 +8,12 @@ env TESTGO_VERSION=go1.21pre3
# Compile a fake toolchain to put in the path under various names.
env GOTOOLCHAIN=
mkdir $WORK/bin
[!GOOS:plan9] env PATH=$WORK/bin${:}$PATH
[GOOS:plan9] env path=$WORK/bin${:}$path
go build -o $WORK/bin/ ./fakego.go # adds .exe extension implicitly on Windows
cp $WORK/bin/fakego$GOEXE $WORK/bin/go1.50.0$GOEXE
[!GOOS:plan9] env PATH=$WORK/bin
[GOOS:plan9] env path=$WORK/bin
go version
stdout go1.21pre3

View File

@@ -0,0 +1,45 @@
# Regression test for https://go.dev/issue/64282.
#
# 'go install' and 'go run' with pkg@version arguments should make
# a best effort to parse flags relevant to downloading modules
# (currently only -modcacherw) before actually downloading the module
# to identify which toolchain version to use.
#
# However, the best-effort flag parsing should not interfere with
# actual flag parsing if we don't switch toolchains. In particular,
# unrecognized flags should still be diagnosed after the module for
# the requested package has been downloaded and checked for toolchain
# upgrades.
! go install -cake=delicious -modcacherw example.com/printversion@v0.1.0
stderr '^flag provided but not defined: -cake$'
# Because the -modcacherw flag was set, we should be able to modify the contents
# of a directory within the module cache.
cp $WORK/extraneous.txt $GOPATH/pkg/mod/example.com/printversion@v0.1.0/extraneous_file.go
go clean -modcache
! go install -unknownflag -tags -modcacherw example.com/printversion@v0.1.0
stderr '^flag provided but not defined: -unknownflag$'
cp $WORK/extraneous.txt $GOPATH/pkg/mod/example.com/printversion@v0.1.0/extraneous_file.go
go clean -modcache
# Also try it with a 'go install' that succeeds.
# (But skip in short mode, because linking a binary is expensive.)
[!short] go install -modcacherw example.com/printversion@v0.1.0
[!short] cp $WORK/extraneous.txt $GOPATH/pkg/mod/example.com/printversion@v0.1.0/extraneous_file.go
[!short] go clean -modcache
# The flag should also be applied if given in GOFLAGS
# instead of on the command line.
env GOFLAGS=-modcacherw
! go install -cake=delicious example.com/printversion@v0.1.0
stderr '^flag provided but not defined: -cake$'
cp $WORK/extraneous.txt $GOPATH/pkg/mod/example.com/printversion@v0.1.0/extraneous_file.go
-- $WORK/extraneous.txt --
This is not a Go source file.

View File

@@ -1,8 +1,13 @@
# Expect no panic
go list -f '{{if .DepsErrors}}{{.DepsErrors}}{{end}}' -export -e -deps
cmpenv stdout wanterr
cmpenv stdout wanterr_59905
-- wanterr --
# Expect no panic (Issue 61816)
cp level1b_61816.txt level1b/pkg.go
go list -f '{{if .DepsErrors}}{{.DepsErrors}}{{end}}' -export -e -deps
cmpenv stdout wanterr_61816
-- wanterr_59905 --
[# test/main/level1a
level1a${/}pkg.go:5:2: level2x redeclared in this block
level1a${/}pkg.go:4:2: other declaration of level2x
@@ -14,6 +19,23 @@ level1b${/}pkg.go:5:2: level2x redeclared in this block
level1b${/}pkg.go:5:2: "test/main/level1b/level2y" imported as level2x and not used
level1b${/}pkg.go:8:39: undefined: level2y
]
-- wanterr_61816 --
[level1b${/}pkg.go:4:2: package foo is not in std ($GOROOT${/}src${/}foo)]
[# test/main/level1a
level1a${/}pkg.go:5:2: level2x redeclared in this block
level1a${/}pkg.go:4:2: other declaration of level2x
level1a${/}pkg.go:5:2: "test/main/level1a/level2y" imported as level2x and not used
level1a${/}pkg.go:8:39: undefined: level2y
level1b${/}pkg.go:4:2: package foo is not in std ($GOROOT${/}src${/}foo)]
-- level1b_61816.txt --
package level1b
import (
"foo"
)
func Print() { println(level2x.Value, level2y.Value) }
-- go.mod --
module test/main

View File

@@ -0,0 +1,107 @@
env TESTGO_VERSION=go1.21
env TESTGO_VERSION_SWITCH=switch
# First, test 'go mod download' outside of a module.
#
# There is no go.mod file into which we can record the selected toolchain,
# so unfortunately these version switches won't be as reproducible as other
# go commands, but that's still preferable to failing entirely or downloading
# a module zip that we don't understand.
# GOTOOLCHAIN=auto should run the newer toolchain
env GOTOOLCHAIN=auto
go mod download rsc.io/needgo121@latest rsc.io/needgo122@latest rsc.io/needgo123@latest rsc.io/needall@latest
stderr '^go: rsc.io/needall@v0.0.1 requires go >= 1.23; switching to go1.23.9$'
! stderr '\(running'
# GOTOOLCHAIN=min+auto should run the newer toolchain
env GOTOOLCHAIN=go1.21+auto
go mod download rsc.io/needgo121@latest rsc.io/needgo122@latest rsc.io/needgo123@latest rsc.io/needall@latest
stderr '^go: rsc.io/needall@v0.0.1 requires go >= 1.23; switching to go1.23.9$'
! stderr '\(running'
# GOTOOLCHAIN=go1.21 should NOT run the newer toolchain
env GOTOOLCHAIN=go1.21
! go mod download rsc.io/needgo121@latest rsc.io/needgo122@latest rsc.io/needgo123@latest rsc.io/needall@latest
! stderr switching
stderr 'rsc.io/needgo122@v0.0.1 requires go >= 1.22'
stderr 'rsc.io/needgo123@v0.0.1 requires go >= 1.23'
stderr 'rsc.io/needall@v0.0.1 requires go >= 1.23'
stderr 'requires go >= 1.23'
! stderr 'requires go >= 1.21' # that's us!
# JSON output should be emitted exactly once,
# and non-JSON output should go to stderr instead of stdout.
env GOTOOLCHAIN=auto
go mod download -json rsc.io/needgo121@latest rsc.io/needgo122@latest rsc.io/needgo123@latest rsc.io/needall@latest
stderr '^go: rsc.io/needall@v0.0.1 requires go >= 1.23; switching to go1.23.9$'
! stderr '\(running'
stdout -count=1 '"Path": "rsc.io/needgo121",'
stdout -count=1 '"Path": "rsc.io/needgo122",'
stdout -count=1 '"Path": "rsc.io/needgo123",'
stdout -count=1 '"Path": "rsc.io/needall",'
# GOTOOLCHAIN=go1.21 should write the errors in the JSON Error fields, not to stderr.
env GOTOOLCHAIN=go1.21
! go mod download -json rsc.io/needgo121@latest rsc.io/needgo122@latest rsc.io/needgo123@latest rsc.io/needall@latest
! stderr switching
stdout -count=1 '"Error": "rsc.io/needgo122@v0.0.1 requires go .*= 1.22 \(running go 1.21; GOTOOLCHAIN=go1.21\)"'
stdout -count=1 '"Error": "rsc.io/needgo123@v0.0.1 requires go .*= 1.23 \(running go 1.21; GOTOOLCHAIN=go1.21\)"'
stdout -count=1 '"Error": "rsc.io/needall@v0.0.1 requires go .*= 1.23 \(running go 1.21; GOTOOLCHAIN=go1.21\)"'
! stdout '"Error": "rsc.io/needgo121' # We can handle this one.
! stderr .
# Within a module, 'go mod download' of explicit versions should upgrade if
# needed to perform the download, but should not change the main module's
# toolchain version (because the downloaded modules are still not required by
# the main module).
cd example
cp go.mod go.mod.orig
env GOTOOLCHAIN=auto
go mod download rsc.io/needgo121@latest rsc.io/needgo122@latest rsc.io/needgo123@latest rsc.io/needall@latest
stderr '^go: rsc.io/needall@v0.0.1 requires go >= 1.23; switching to go1.23.9$'
! stderr '\(running'
cmp go.mod go.mod.orig
# However, 'go mod download' without arguments should fix up the
# 'go' and 'toolchain' lines to be consistent with the existing
# requirements in the module graph.
go mod edit -require=rsc.io/needall@v0.0.1
cp go.mod go.mod.121
# If an upgrade is needed, GOTOOLCHAIN=go1.21 should cause
# the command to fail without changing go.mod.
env GOTOOLCHAIN=go1.21
! go mod download
stderr 'rsc.io/needall@v0.0.1 requires go >= 1.23'
! stderr switching
cmp go.mod go.mod.121
# If an upgrade is needed, GOTOOLCHAIN=auto should perform
# the upgrade and record the resulting toolchain version.
env GOTOOLCHAIN=auto
go mod download
stderr '^go: module rsc.io/needall@v0.0.1 requires go >= 1.23; switching to go1.23.9$'
cmp go.mod go.mod.final
-- example/go.mod --
module example
go 1.21
-- example/go.mod.final --
module example
go 1.23
toolchain go1.23.9
require rsc.io/needall v0.0.1

View File

@@ -1,6 +1,7 @@
env TESTGO_VERSION=go1.21
env GOTOOLCHAIN=local
! go mod download rsc.io/future@v1.0.0
stderr '^go: rsc.io/future@v1.0.0 requires go >= 1.999 \(running go 1.21\)$'
stderr '^go: rsc.io/future@v1.0.0 requires go >= 1.999 \(running go 1.21; GOTOOLCHAIN=local\)$'
-- go.mod --
module m

View File

@@ -0,0 +1,19 @@
# golang.org/issue/29591: 'go get' was following plain-HTTP redirects even without -insecure (now replaced by GOINSECURE).
# golang.org/issue/61877: 'go get' would panic in case of an insecure redirect in module mode
[!git] skip
env GOPRIVATE=vcs-test.golang.org
! go get -d vcs-test.golang.org/insecure/go/insecure
stderr 'redirected .* to insecure URL'
[short] stop 'builds a git repo'
env GOINSECURE=vcs-test.golang.org/insecure/go/insecure
go get -d vcs-test.golang.org/insecure/go/insecure
-- go.mod --
module example
go 1.21

View File

@@ -0,0 +1,28 @@
# Regression test for https://go.dev/issue/63845:
# If 'git ls-remote' fails for all secure protocols,
# we should fail instead of falling back to an arbitrary protocol.
#
# Note that this test does not use the local vcweb test server
# (vcs-test.golang.org), because the hook for redirecting to that
# server bypasses the "ping to determine protocol" logic
# in cmd/go/internal/vcs.
[!net:golang.org] skip
[!git] skip
[short] skip 'tries to access a nonexistent external Git repo'
env GOPRIVATE=golang.org
env CURLOPT_TIMEOUT_MS=100
env GIT_SSH_COMMAND=false
! go get -x golang.org/nonexist.git@latest
stderr '^git ls-remote https://golang.org/nonexist$'
stderr '^git ls-remote git\+ssh://golang.org/nonexist'
stderr '^git ls-remote ssh://golang.org/nonexist$'
! stderr 'git://'
stderr '^go: golang.org/nonexist.git@latest: no secure protocol found for repository$'
-- go.mod --
module example
go 1.19

View File

@@ -0,0 +1,32 @@
[!exec:/bin/sh] skip
chmod 0777 go1.999999-/run.sh
chmod 0777 run.sh
! go list all
! stdout 'RAN SCRIPT'
cd subdir
! go list all
! stdout 'RAN SCRIPT'
-- go.mod --
module exploit
go 1.21
toolchain go1.999999-/run.sh
-- go1.999999-/run.sh --
#!/bin/sh
printf 'RAN SCRIPT\n'
exit 1
-- run.sh --
#!/bin/sh
printf 'RAN SCRIPT\n'
exit 1
-- subdir/go.mod --
module exploit
go 1.21
toolchain go1.999999-/../../run.sh
-- subdir/go1.999999-/README.txt --
heh heh heh

View File

@@ -0,0 +1,24 @@
# Regression test for Issue #62663: we would filter out the toolchain and
# main modules from the build list incorrectly, leading to the workspace
# modules being checked for correct sums. Specifically this would happen when
# the module name sorted after the virtual 'go' version module name because
# it could not get chopped off when we removed the MainModules.Len() modules
# at the beginning of the build list and we would remove the go module instead.
go mod verify
-- go.work --
go 1.21
use (
./a
./b
)
-- a/go.mod --
module hexample.com/a // important for test that module name sorts after 'go'
go 1.21
-- b/go.mod --
module hexample.com/b // important for test that module name sorts after 'go'
go 1.21

View File

@@ -2,6 +2,10 @@
# Verify test -c can output multiple executables to a directory.
# This test also serves as a regression test for https://go.dev/issue/62221:
# prior to the fix for that issue, it occasionally failed with ETXTBSY when
# run on Unix platforms.
go test -c -o $WORK/some/nonexisting/directory/ ./pkg/...
exists -exec $WORK/some/nonexisting/directory/pkg1.test$GOEXE
exists -exec $WORK/some/nonexisting/directory/pkg2.test$GOEXE
@@ -43,4 +47,4 @@ package pkg1
package pkg2
-- anotherpkg/pkg1/pkg1_test.go --
package pkg1
package pkg1

View File

@@ -14,6 +14,10 @@ go build -ldflags='-linkmode=internal'
exec ./abitest
stdout success
go build -buildmode=pie -o abitest.pie -ldflags='-linkmode=internal'
exec ./abitest.pie
stdout success
-- go.mod --
module abitest

View File

@@ -826,21 +826,24 @@ func preprocess(ctxt *obj.Link, cursym *obj.LSym, newprog obj.ProgAlloc) {
p.To = obj.Addr{}
if c.cursym.Func().Text.Mark&LEAF != 0 {
if c.autosize != 0 {
// Restore frame pointer.
// ADD $framesize-8, RSP, R29
p.As = AADD
p.From.Type = obj.TYPE_CONST
p.From.Offset = int64(c.autosize) - 8
p.Reg = REGSP
p.To.Type = obj.TYPE_REG
p.To.Reg = REGFP
// Pop stack frame.
// ADD $framesize, RSP, RSP
p = obj.Appendp(p, c.newprog)
p.As = AADD
p.From.Type = obj.TYPE_CONST
p.From.Offset = int64(c.autosize)
p.To.Type = obj.TYPE_REG
p.To.Reg = REGSP
p.Spadj = -c.autosize
// Frame pointer.
p = obj.Appendp(p, c.newprog)
p.As = ASUB
p.From.Type = obj.TYPE_CONST
p.From.Offset = 8
p.Reg = REGSP
p.To.Type = obj.TYPE_REG
p.To.Reg = REGFP
}
} else {
aoffset := c.autosize

View File

@@ -36,8 +36,25 @@ import (
"cmd/internal/sys"
"internal/abi"
"log"
"strings"
)
// Is this a symbol which should never have a TOC prologue generated?
// These are special functions which should not have a TOC regeneration
// prologue.
func isNOTOCfunc(name string) bool {
switch {
case name == "runtime.duffzero":
return true
case name == "runtime.duffcopy":
return true
case strings.HasPrefix(name, "runtime.elf_"):
return true
default:
return false
}
}
func progedit(ctxt *obj.Link, p *obj.Prog, newprog obj.ProgAlloc) {
p.From.Class = 0
p.To.Class = 0
@@ -643,7 +660,7 @@ func preprocess(ctxt *obj.Link, cursym *obj.LSym, newprog obj.ProgAlloc) {
q = p
if NeedTOCpointer(c.ctxt) && c.cursym.Name != "runtime.duffzero" && c.cursym.Name != "runtime.duffcopy" {
if NeedTOCpointer(c.ctxt) && !isNOTOCfunc(c.cursym.Name) {
// When compiling Go into PIC, without PCrel support, all functions must start
// with instructions to load the TOC pointer into r2:
//

View File

@@ -2067,17 +2067,22 @@ func instructionsForProg(p *obj.Prog) []*instruction {
return instructionsForStore(p, ins.as, p.To.Reg)
case ALRW, ALRD:
// Set aq to use acquire access ordering, which matches Go's memory requirements.
// Set aq to use acquire access ordering
ins.funct7 = 2
ins.rs1, ins.rs2 = uint32(p.From.Reg), REG_ZERO
case AADDI, AANDI, AORI, AXORI:
inss = instructionsForOpImmediate(p, ins.as, p.Reg)
case ASCW, ASCD, AAMOSWAPW, AAMOSWAPD, AAMOADDW, AAMOADDD, AAMOANDW, AAMOANDD, AAMOORW, AAMOORD,
case ASCW, ASCD:
// Set release access ordering
ins.funct7 = 1
ins.rd, ins.rs1, ins.rs2 = uint32(p.RegTo2), uint32(p.To.Reg), uint32(p.From.Reg)
case AAMOSWAPW, AAMOSWAPD, AAMOADDW, AAMOADDD, AAMOANDW, AAMOANDD, AAMOORW, AAMOORD,
AAMOXORW, AAMOXORD, AAMOMINW, AAMOMIND, AAMOMINUW, AAMOMINUD, AAMOMAXW, AAMOMAXD, AAMOMAXUW, AAMOMAXUD:
// Set aq to use acquire access ordering, which matches Go's memory requirements.
ins.funct7 = 2
// Set aqrl to use acquire & release access ordering
ins.funct7 = 3
ins.rd, ins.rs1, ins.rs2 = uint32(p.RegTo2), uint32(p.To.Reg), uint32(p.From.Reg)
case AECALL, AEBREAK, ARDCYCLE, ARDTIME, ARDINSTRET:

View File

@@ -446,7 +446,7 @@ func machoreloc1(arch *sys.Arch, out *ld.OutBuf, ldr *loader.Loader, s loader.Sy
rs := r.Xsym
rt := r.Type
if ldr.SymType(rs) == sym.SHOSTOBJ || rt == objabi.R_PCREL || rt == objabi.R_GOTPCREL || rt == objabi.R_CALL {
if rt == objabi.R_PCREL || rt == objabi.R_GOTPCREL || rt == objabi.R_CALL || ldr.SymType(rs) == sym.SHOSTOBJ || ldr.SymType(s) == sym.SINITARR {
if ldr.SymDynid(rs) < 0 {
ldr.Errorf(s, "reloc %d (%s) to non-macho symbol %s type=%d (%s)", rt, sym.RelocName(arch, rt), ldr.SymName(rs), ldr.SymType(rs), ldr.SymType(rs))
return false

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