diff --git a/hack/tools/go.mod b/hack/tools/go.mod index 77fc52133225..9687273ed2e8 100644 --- a/hack/tools/go.mod +++ b/hack/tools/go.mod @@ -5,7 +5,7 @@ go 1.25.3 require ( github.com/ahmetb/gen-crd-api-reference-docs v0.3.0 github.com/gobwas/glob v0.2.3 - github.com/golangci/golangci-lint/v2 v2.11.1 + github.com/golangci/golangci-lint/v2 v2.11.4 github.com/google/cel-go v0.26.1 github.com/openshift/api/tools v0.0.0-20250915151906-94481d71bb6f go.uber.org/mock v0.6.0 @@ -90,7 +90,7 @@ require ( github.com/emicklei/go-restful/v3 v3.12.2 // indirect github.com/emirpasic/gods v1.18.1 // indirect github.com/ettle/strcase v0.2.0 // indirect - github.com/fatih/color v1.18.0 // indirect + github.com/fatih/color v1.19.0 // indirect github.com/fatih/structtag v1.2.0 // indirect github.com/felixge/httpsnoop v1.0.4 // indirect github.com/firefart/nonamedreturns v1.0.6 // indirect @@ -217,19 +217,19 @@ require ( github.com/russross/blackfriday v2.0.0+incompatible // indirect github.com/russross/blackfriday/v2 v2.1.0 // indirect github.com/ryancurrah/gomodguard v1.4.1 // indirect - github.com/ryanrolds/sqlclosecheck v0.5.1 // indirect + github.com/ryanrolds/sqlclosecheck v0.6.0 // indirect github.com/sagikazarmark/locafero v0.7.0 // indirect github.com/sanposhiho/wastedassign/v2 v2.1.0 // indirect github.com/santhosh-tekuri/jsonschema/v6 v6.0.2 // indirect github.com/sashamelentyev/interfacebloat v1.1.0 // indirect github.com/sashamelentyev/usestdlibvars v1.29.0 // indirect - github.com/securego/gosec/v2 v2.24.7 // indirect + github.com/securego/gosec/v2 v2.24.8-0.20260309165252-619ce2117e08 // indirect github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3 // indirect github.com/shurcooL/sanitized_anchor_name v1.0.0 // indirect github.com/sirupsen/logrus v1.9.4 // indirect github.com/sivchari/containedctx v1.0.3 // indirect github.com/skeema/knownhosts v1.3.1 // indirect - github.com/sonatard/noctx v0.5.0 // indirect + github.com/sonatard/noctx v0.5.1 // indirect github.com/sourcegraph/conc v0.3.0 // indirect github.com/sourcegraph/go-diff v0.7.0 // indirect github.com/spf13/afero v1.15.0 // indirect @@ -282,18 +282,18 @@ require ( go.uber.org/zap v1.27.1 // indirect go.yaml.in/yaml/v2 v2.4.3 // indirect go.yaml.in/yaml/v3 v3.0.4 // indirect - golang.org/x/crypto v0.48.0 // indirect + golang.org/x/crypto v0.49.0 // indirect golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b // indirect golang.org/x/exp/typeparams v0.0.0-20260209203927-2842357ff358 // indirect - golang.org/x/mod v0.33.0 // indirect - golang.org/x/net v0.51.0 // indirect + golang.org/x/mod v0.34.0 // indirect + golang.org/x/net v0.52.0 // indirect golang.org/x/oauth2 v0.35.0 // indirect - golang.org/x/sync v0.19.0 // indirect - golang.org/x/sys v0.41.0 // indirect - golang.org/x/term v0.40.0 // indirect - golang.org/x/text v0.34.0 // indirect + golang.org/x/sync v0.20.0 // indirect + golang.org/x/sys v0.42.0 // indirect + golang.org/x/term v0.41.0 // indirect + golang.org/x/text v0.35.0 // indirect golang.org/x/time v0.14.0 // indirect - golang.org/x/tools v0.42.0 // indirect + golang.org/x/tools v0.43.0 // indirect google.golang.org/genproto/googleapis/api v0.0.0-20260128011058-8636f8732409 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20260217215200-42d3e9bedb6d // indirect google.golang.org/grpc v1.79.2 // indirect diff --git a/hack/tools/go.sum b/hack/tools/go.sum index b5a69aef0d77..756388ab0e48 100644 --- a/hack/tools/go.sum +++ b/hack/tools/go.sum @@ -162,8 +162,8 @@ github.com/emirpasic/gods v1.18.1 h1:FXtiHYKDGKCW2KzwZKx0iC0PQmdlorYgdFG9jPXJ1Bc github.com/emirpasic/gods v1.18.1/go.mod h1:8tpGGwCnJ5H4r6BWwaV6OrWmMoPhUl5jm/FMNAnJvWQ= github.com/ettle/strcase v0.2.0 h1:fGNiVF21fHXpX1niBgk0aROov1LagYsOwV/xqKDKR/Q= github.com/ettle/strcase v0.2.0/go.mod h1:DajmHElDSaX76ITe3/VHVyMin4LWSJN5Z909Wp+ED1A= -github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM= -github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU= +github.com/fatih/color v1.19.0 h1:Zp3PiM21/9Ld6FzSKyL5c/BULoe/ONr9KlbYVOfG8+w= +github.com/fatih/color v1.19.0/go.mod h1:zNk67I0ZUT1bEGsSGyCZYZNrHuTkJJB+r6Q9VuMi0LE= github.com/fatih/structtag v1.2.0 h1:/OdNE99OxoI/PqaW/SuSK9uxxT3f/tcSZgon/ssNSx4= github.com/fatih/structtag v1.2.0/go.mod h1:mBJUNpUnHmRKrKlQQlmCrh5PuhftFbNv8Ys4/aAZl94= github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg= @@ -260,8 +260,8 @@ github.com/golangci/go-printf-func-name v0.1.1 h1:hIYTFJqAGp1iwoIfsNTpoq1xZAarog github.com/golangci/go-printf-func-name v0.1.1/go.mod h1:Es64MpWEZbh0UBtTAICOZiB+miW53w/K9Or/4QogJss= github.com/golangci/gofmt v0.0.0-20250106114630-d62b90e6713d h1:viFft9sS/dxoYY0aiOTsLKO2aZQAPT4nlQCsimGcSGE= github.com/golangci/gofmt v0.0.0-20250106114630-d62b90e6713d/go.mod h1:ivJ9QDg0XucIkmwhzCDsqcnxxlDStoTl89jDMIoNxKY= -github.com/golangci/golangci-lint/v2 v2.11.1 h1:aGbjflzzKNIdOoq/NawrhFjYpkNY4WzPSeIp2zBbzG8= -github.com/golangci/golangci-lint/v2 v2.11.1/go.mod h1:wexdFBIQNhHNhDe1oqzlGFE5dYUqlfccWJKWjoWF1GI= +github.com/golangci/golangci-lint/v2 v2.11.4 h1:GK+UlZBN5y7rh2PBnHA93XLSX6RaF7uhzJQ3JwU1wuA= +github.com/golangci/golangci-lint/v2 v2.11.4/go.mod h1:ODQDCASMA3VqfZYIbbQLpTRTzV7O/vjmIRF6u8NyFwI= github.com/golangci/golines v0.15.0 h1:Qnph25g8Y1c5fdo1X7GaRDGgnMHgnxh4Gk4VfPTtRx0= github.com/golangci/golines v0.15.0/go.mod h1:AZjXd23tbHMpowhtnGlj9KCNsysj72aeZVVHnVcZx10= github.com/golangci/misspell v0.8.0 h1:qvxQhiE2/5z+BVRo1kwYA8yGz+lOlu5Jfvtx2b04Jbg= @@ -504,8 +504,8 @@ github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/ryancurrah/gomodguard v1.4.1 h1:eWC8eUMNZ/wM/PWuZBv7JxxqT5fiIKSIyTvjb7Elr+g= github.com/ryancurrah/gomodguard v1.4.1/go.mod h1:qnMJwV1hX9m+YJseXEBhd2s90+1Xn6x9dLz11ualI1I= -github.com/ryanrolds/sqlclosecheck v0.5.1 h1:dibWW826u0P8jNLsLN+En7+RqWWTYrjCB9fJfSfdyCU= -github.com/ryanrolds/sqlclosecheck v0.5.1/go.mod h1:2g3dUjoS6AL4huFdv6wn55WpLIDjY7ZgUR4J8HOO/XQ= +github.com/ryanrolds/sqlclosecheck v0.6.0 h1:pEyL9okISdg1F1SEpJNlrEotkTGerv5BMk7U4AG0eVg= +github.com/ryanrolds/sqlclosecheck v0.6.0/go.mod h1:xyX16hsDaCMXHrMJ3JMzGf5OpDfHTOTTQrT7HOFUmeU= github.com/sagikazarmark/locafero v0.7.0 h1:5MqpDsTGNDhY8sGp0Aowyf0qKsPrhewaLSsFaodPcyo= github.com/sagikazarmark/locafero v0.7.0/go.mod h1:2za3Cg5rMaTMoG/2Ulr9AwtFaIppKXTRYnozin4aB5k= github.com/sanposhiho/wastedassign/v2 v2.1.0 h1:crurBF7fJKIORrV85u9UUpePDYGWnwvv3+A96WvwXT0= @@ -516,8 +516,8 @@ github.com/sashamelentyev/interfacebloat v1.1.0 h1:xdRdJp0irL086OyW1H/RTZTr1h/tM github.com/sashamelentyev/interfacebloat v1.1.0/go.mod h1:+Y9yU5YdTkrNvoX0xHc84dxiN1iBi9+G8zZIhPVoNjQ= github.com/sashamelentyev/usestdlibvars v1.29.0 h1:8J0MoRrw4/NAXtjQqTHrbW9NN+3iMf7Knkq057v4XOQ= github.com/sashamelentyev/usestdlibvars v1.29.0/go.mod h1:8PpnjHMk5VdeWlVb4wCdrB8PNbLqZ3wBZTZWkrpZZL8= -github.com/securego/gosec/v2 v2.24.7 h1:3k5yJnrhT1TTdsG0ZsnenlfCcT+7Y/+zeCPHbL7QAn8= -github.com/securego/gosec/v2 v2.24.7/go.mod h1:AdDJbjcG/XxFgVv7pW19vMNYlFM6+Q6Qy3t6lWAUcEY= +github.com/securego/gosec/v2 v2.24.8-0.20260309165252-619ce2117e08 h1:AoLtJX4WUtZkhhUUMFy3GgecAALp/Mb4S1iyQOA2s0U= +github.com/securego/gosec/v2 v2.24.8-0.20260309165252-619ce2117e08/go.mod h1:+XLCJiRE95ga77XInNELh2M6zQP+PdqiT9Zpm0D9Wpk= github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3 h1:n661drycOFuPLCN3Uc8sB6B/s6Z4t2xvBgU1htSHuq8= github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4= github.com/shurcooL/go v0.0.0-20180423040247-9e1955d9fb6e/go.mod h1:TDJrrUr11Vxrven61rcy3hJMUqaf/CLWYhHNPmT14Lk= @@ -531,8 +531,8 @@ github.com/sivchari/containedctx v1.0.3 h1:x+etemjbsh2fB5ewm5FeLNi5bUjK0V8n0RB+W github.com/sivchari/containedctx v1.0.3/go.mod h1:c1RDvCbnJLtH4lLcYD/GqwiBSSf4F5Qk0xld2rBqzJ4= github.com/skeema/knownhosts v1.3.1 h1:X2osQ+RAjK76shCbvhHHHVl3ZlgDm8apHEHFqRjnBY8= github.com/skeema/knownhosts v1.3.1/go.mod h1:r7KTdC8l4uxWRyK2TpQZ/1o5HaSzh06ePQNxPwTcfiY= -github.com/sonatard/noctx v0.5.0 h1:e/jdaqAsuWVOKQ0P6NWiIdDNHmHT5SwuuSfojFjzwrw= -github.com/sonatard/noctx v0.5.0/go.mod h1:64XdbzFb18XL4LporKXp8poqZtPKbCrqQ402CV+kJas= +github.com/sonatard/noctx v0.5.1 h1:wklWg9c9ZYugOAk7qG4yP4PBrlQsmSLPTvW1K4PRQMs= +github.com/sonatard/noctx v0.5.1/go.mod h1:64XdbzFb18XL4LporKXp8poqZtPKbCrqQ402CV+kJas= github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo= github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0= github.com/sourcegraph/go-diff v0.7.0 h1:9uLlrd5T46OXs5qpp8L/MTltk0zikUGi0sNNyCpA8G0= @@ -677,8 +677,8 @@ golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5y golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc= golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4= -golang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts= -golang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos= +golang.org/x/crypto v0.49.0 h1:+Ng2ULVvLHnJ/ZFEq4KdcDd/cfjrrjjNSXNzxg0Y4U4= +golang.org/x/crypto v0.49.0/go.mod h1:ErX4dUh2UM+CFYiXZRTcMpEcN8b/1gxEuv3nODoYtCA= golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b h1:M2rDM6z3Fhozi9O7NWsxAkg/yqS/lQJ6PmkyIV3YP+o= golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b/go.mod h1:3//PLf8L/X+8b4vuAfHzxeRUl04Adcb341+IGKfnqS8= golang.org/x/exp/typeparams v0.0.0-20220428152302-39d4317da171/go.mod h1:AbB0pIl9nAr9wVwH+Z2ZpaocVmF5I4GyWCDIsVjR0bk= @@ -694,8 +694,8 @@ golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91 golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/mod v0.13.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= -golang.org/x/mod v0.33.0 h1:tHFzIWbBifEmbwtGz65eaWyGiGZatSrT9prnU8DbVL8= -golang.org/x/mod v0.33.0/go.mod h1:swjeQEj+6r7fODbD2cqrnje9PnziFuw4bmLbBZFrQ5w= +golang.org/x/mod v0.34.0 h1:xIHgNUUnW6sYkcM5Jleh05DvLOtwc6RitGHbDk4akRI= +golang.org/x/mod v0.34.0/go.mod h1:ykgH52iCZe79kzLLMhyCUzhMci+nQj+0XkbXpNYtVjY= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= @@ -710,8 +710,8 @@ golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk= golang.org/x/net v0.16.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE= -golang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo= -golang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y= +golang.org/x/net v0.52.0 h1:He/TN1l0e4mmR3QqHMT2Xab3Aj3L9qjbhRm78/6jrW0= +golang.org/x/net v0.52.0/go.mod h1:R1MAz7uMZxVMualyPXb+VaqGSa3LIaUqk0eEt3w36Sw= golang.org/x/oauth2 v0.35.0 h1:Mv2mzuHuZuY2+bkyWXIHMfhNdJAdwW3FuWeCPYN5GVQ= golang.org/x/oauth2 v0.35.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -723,8 +723,8 @@ golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y= golang.org/x/sync v0.4.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y= -golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4= -golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= +golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4= +golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -746,16 +746,16 @@ golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k= -golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= +golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo= +golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU= golang.org/x/term v0.13.0/go.mod h1:LTmsnFJwVN6bCy1rVCoS+qHT1HhALEFxKncY3WNNh4U= -golang.org/x/term v0.40.0 h1:36e4zGLqU4yhjlmxEaagx2KuYbJq3EwY8K943ZsHcvg= -golang.org/x/term v0.40.0/go.mod h1:w2P8uVp06p2iyKKuvXIm7N/y0UCRt3UfJTfZ7oOpglM= +golang.org/x/term v0.41.0 h1:QCgPso/Q3RTJx2Th4bDLqML4W6iJiaXFq2/ftQF13YU= +golang.org/x/term v0.41.0/go.mod h1:3pfBgksrReYfZ5lvYM0kSO0LIkAl4Yl2bXOkKP7Ec2A= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= @@ -764,8 +764,8 @@ golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= -golang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk= -golang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA= +golang.org/x/text v0.35.0 h1:JOVx6vVDFokkpaq1AEptVzLTpDe9KGpj5tR4/X+ybL8= +golang.org/x/text v0.35.0/go.mod h1:khi/HExzZJ2pGnjenulevKNX1W67CUy0AsXcNubPGCA= golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI= golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= @@ -783,8 +783,8 @@ golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58= golang.org/x/tools v0.14.0/go.mod h1:uYBEerGOWcJyEORxN+Ek8+TT266gXkNlHdJBwexUsBg= -golang.org/x/tools v0.42.0 h1:uNgphsn75Tdz5Ji2q36v/nsFSfR/9BRFvqhGBaJGd5k= -golang.org/x/tools v0.42.0/go.mod h1:Ma6lCIwGZvHK6XtgbswSoWroEkhugApmsXyrUmBhfr0= +golang.org/x/tools v0.43.0 h1:12BdW9CeB3Z+J/I/wj34VMl8X+fEXBxVR90JeMX5E7s= +golang.org/x/tools v0.43.0/go.mod h1:uHkMso649BX2cZK6+RpuIPXS3ho2hZo4FVwfoy1vIk0= golang.org/x/tools/go/expect v0.1.1-deprecated h1:jpBZDwmgPhXsKZC6WhL20P4b/wmnpsEAGHaNy0n/rJM= golang.org/x/tools/go/expect v0.1.1-deprecated/go.mod h1:eihoPOH+FgIqa3FpoTwguz/bVUSGBlGQU67vpBeOrBY= golang.org/x/tools/go/packages/packagestest v0.1.1-deprecated h1:1h2MnaIAIXISqTFKdENegdpAgUXz6NrPEsbIeWaBRvM= diff --git a/hack/tools/vendor/github.com/fatih/color/color.go b/hack/tools/vendor/github.com/fatih/color/color.go index ee39b408e95f..d3906bfbd5ac 100644 --- a/hack/tools/vendor/github.com/fatih/color/color.go +++ b/hack/tools/vendor/github.com/fatih/color/color.go @@ -19,15 +19,15 @@ var ( // set (regardless of its value). This is a global option and affects all // colors. For more control over each color block use the methods // DisableColor() individually. - NoColor = noColorIsSet() || os.Getenv("TERM") == "dumb" || - (!isatty.IsTerminal(os.Stdout.Fd()) && !isatty.IsCygwinTerminal(os.Stdout.Fd())) + NoColor = noColorIsSet() || os.Getenv("TERM") == "dumb" || !stdoutIsTerminal() // Output defines the standard output of the print functions. By default, - // os.Stdout is used. - Output = colorable.NewColorableStdout() + // stdOut() is used. + Output = stdOut() - // Error defines a color supporting writer for os.Stderr. - Error = colorable.NewColorableStderr() + // Error defines the standard error of the print functions. By default, + // stdErr() is used. + Error = stdErr() // colorsCache is used to reduce the count of created Color objects and // allows to reuse already created objects with required Attribute. @@ -40,6 +40,33 @@ func noColorIsSet() bool { return os.Getenv("NO_COLOR") != "" } +// stdoutIsTerminal returns true if os.Stdout is a terminal. +// Returns false if os.Stdout is nil (e.g., when running as a Windows service). +func stdoutIsTerminal() bool { + if os.Stdout == nil { + return false + } + return isatty.IsTerminal(os.Stdout.Fd()) || isatty.IsCygwinTerminal(os.Stdout.Fd()) +} + +// stdOut returns a writer for color output. +// Returns io.Discard if os.Stdout is nil (e.g., when running as a Windows service). +func stdOut() io.Writer { + if os.Stdout == nil { + return io.Discard + } + return colorable.NewColorableStdout() +} + +// stdErr returns a writer for color error output. +// Returns io.Discard if os.Stderr is nil (e.g., when running as a Windows service). +func stdErr() io.Writer { + if os.Stderr == nil { + return io.Discard + } + return colorable.NewColorableStderr() +} + // Color defines a custom color object which is defined by SGR parameters. type Color struct { params []Attribute @@ -220,26 +247,30 @@ func (c *Color) unset() { // a low-level function, and users should use the higher-level functions, such // as color.Fprint, color.Print, etc. func (c *Color) SetWriter(w io.Writer) *Color { + _, _ = c.setWriter(w) + return c +} + +func (c *Color) setWriter(w io.Writer) (int, error) { if c.isNoColorSet() { - return c + return 0, nil } - fmt.Fprint(w, c.format()) - return c + return fmt.Fprint(w, c.format()) } // UnsetWriter resets all escape attributes and clears the output with the give // io.Writer. Usually should be called after SetWriter(). func (c *Color) UnsetWriter(w io.Writer) { - if c.isNoColorSet() { - return - } + _, _ = c.unsetWriter(w) +} - if NoColor { - return +func (c *Color) unsetWriter(w io.Writer) (int, error) { + if c.isNoColorSet() { + return 0, nil } - fmt.Fprintf(w, "%s[%dm", escape, Reset) + return fmt.Fprintf(w, "%s[%dm", escape, Reset) } // Add is used to chain SGR parameters. Use as many as parameters to combine @@ -255,10 +286,20 @@ func (c *Color) Add(value ...Attribute) *Color { // On Windows, users should wrap w with colorable.NewColorable() if w is of // type *os.File. func (c *Color) Fprint(w io.Writer, a ...interface{}) (n int, err error) { - c.SetWriter(w) - defer c.UnsetWriter(w) + n, err = c.setWriter(w) + if err != nil { + return n, err + } + + nn, err := fmt.Fprint(w, a...) + n += nn + if err != nil { + return + } - return fmt.Fprint(w, a...) + nn, err = c.unsetWriter(w) + n += nn + return n, err } // Print formats using the default formats for its operands and writes to @@ -278,10 +319,20 @@ func (c *Color) Print(a ...interface{}) (n int, err error) { // On Windows, users should wrap w with colorable.NewColorable() if w is of // type *os.File. func (c *Color) Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) { - c.SetWriter(w) - defer c.UnsetWriter(w) + n, err = c.setWriter(w) + if err != nil { + return n, err + } + + nn, err := fmt.Fprintf(w, format, a...) + n += nn + if err != nil { + return + } - return fmt.Fprintf(w, format, a...) + nn, err = c.unsetWriter(w) + n += nn + return n, err } // Printf formats according to a format specifier and writes to standard output. @@ -475,27 +526,24 @@ func (c *Color) Equals(c2 *Color) bool { if c == nil || c2 == nil { return false } + if len(c.params) != len(c2.params) { return false } + counts := make(map[Attribute]int, len(c.params)) for _, attr := range c.params { - if !c2.attrExists(attr) { - return false - } + counts[attr]++ } - return true -} - -func (c *Color) attrExists(a Attribute) bool { - for _, attr := range c.params { - if attr == a { - return true + for _, attr := range c2.params { + if counts[attr] == 0 { + return false } + counts[attr]-- } - return false + return true } func boolPtr(v bool) *bool { diff --git a/hack/tools/vendor/github.com/fatih/color/color_windows.go b/hack/tools/vendor/github.com/fatih/color/color_windows.go index be01c558e506..97e5a765a5e2 100644 --- a/hack/tools/vendor/github.com/fatih/color/color_windows.go +++ b/hack/tools/vendor/github.com/fatih/color/color_windows.go @@ -9,6 +9,9 @@ import ( func init() { // Opt-in for ansi color support for current process. // https://learn.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences#output-sequences + if os.Stdout == nil { + return + } var outMode uint32 out := windows.Handle(os.Stdout.Fd()) if err := windows.GetConsoleMode(out, &outMode); err != nil { diff --git a/hack/tools/vendor/github.com/golangci/golangci-lint/v2/internal/x/tools/analysisflags/readme.md b/hack/tools/vendor/github.com/golangci/golangci-lint/v2/internal/x/tools/analysisflags/readme.md deleted file mode 100644 index 6035c2226568..000000000000 --- a/hack/tools/vendor/github.com/golangci/golangci-lint/v2/internal/x/tools/analysisflags/readme.md +++ /dev/null @@ -1,11 +0,0 @@ -# analysisflags - -Extracted from `/go/analysis/internal/analysisflags` (related to `checker`). -This is just a copy of the code without any changes. - -## History - -- https://github.com/golangci/golangci-lint/pull/6076 - - sync with https://github.com/golang/tools/blob/v0.37.0/go/analysis/internal/analysisflags -- https://github.com/golangci/golangci-lint/pull/5576 - - sync with https://github.com/golang/tools/blob/v0.28.0/go/analysis/internal/analysisflags diff --git a/hack/tools/vendor/github.com/golangci/golangci-lint/v2/internal/x/tools/analysisinternal/readme.md b/hack/tools/vendor/github.com/golangci/golangci-lint/v2/internal/x/tools/analysisinternal/readme.md deleted file mode 100644 index 6c54592d9e26..000000000000 --- a/hack/tools/vendor/github.com/golangci/golangci-lint/v2/internal/x/tools/analysisinternal/readme.md +++ /dev/null @@ -1,11 +0,0 @@ -# analysisinternal - -Extracted from `/internal/analysisinternal/` (related to `checker`). -This is just a copy of the code without any changes. - -## History - -- https://github.com/golangci/golangci-lint/pull/6076 - - sync with https://github.com/golang/tools/blob/v0.37.0/internal/analysisinternal/ -- https://github.com/golangci/golangci-lint/pull/5576 - - sync with https://github.com/golang/tools/blob/v0.28.0/internal/analysisinternal/ diff --git a/hack/tools/vendor/github.com/golangci/golangci-lint/v2/internal/x/tools/analysisinternal/analysis.go b/hack/tools/vendor/github.com/golangci/golangci-lint/v2/internal/x/tools/driverutil/readfile.go similarity index 88% rename from hack/tools/vendor/github.com/golangci/golangci-lint/v2/internal/x/tools/analysisinternal/analysis.go rename to hack/tools/vendor/github.com/golangci/golangci-lint/v2/internal/x/tools/driverutil/readfile.go index b613d167348a..dc1d54dd8bd3 100644 --- a/hack/tools/vendor/github.com/golangci/golangci-lint/v2/internal/x/tools/analysisinternal/analysis.go +++ b/hack/tools/vendor/github.com/golangci/golangci-lint/v2/internal/x/tools/driverutil/readfile.go @@ -2,9 +2,9 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -// Package analysisinternal provides gopls' internal analyses with a -// number of helper functions that operate on typed syntax trees. -package analysisinternal +package driverutil + +// This file defines helpers for implementing [analysis.Pass.ReadFile]. import ( "fmt" diff --git a/hack/tools/vendor/github.com/golangci/golangci-lint/v2/internal/x/tools/driverutil/readme.md b/hack/tools/vendor/github.com/golangci/golangci-lint/v2/internal/x/tools/driverutil/readme.md new file mode 100644 index 000000000000..8720fb6ffd9d --- /dev/null +++ b/hack/tools/vendor/github.com/golangci/golangci-lint/v2/internal/x/tools/driverutil/readme.md @@ -0,0 +1,25 @@ +# driverutil + +Extracted from `/internal/analysis/driverutil/` (related to `checker`). +This is just a copy of `readfile.go` and `url.go` without any changes. + +Previously, it was `analysisinternal` and `analysisflags` packages. + +## History + +- https://github.com/golangci/golangci-lint/pull/6434 + - sync with https://github.com/golang/tools/blob/v0.43.0/internal/analysis/driverutil/readfile.go + +## analysisinternal History + +- https://github.com/golangci/golangci-lint/pull/6076 + - sync with https://github.com/golang/tools/blob/v0.37.0/internal/analysisinternal/ +- https://github.com/golangci/golangci-lint/pull/5576 + - sync with https://github.com/golang/tools/blob/v0.28.0/internal/analysisinternal/ + +## analysisflags History + +- https://github.com/golangci/golangci-lint/pull/6076 + - sync with https://github.com/golang/tools/blob/v0.37.0/go/analysis/internal/analysisflags +- https://github.com/golangci/golangci-lint/pull/5576 + - sync with https://github.com/golang/tools/blob/v0.28.0/go/analysis/internal/analysisflags diff --git a/hack/tools/vendor/github.com/golangci/golangci-lint/v2/internal/x/tools/analysisflags/url.go b/hack/tools/vendor/github.com/golangci/golangci-lint/v2/internal/x/tools/driverutil/url.go similarity index 97% rename from hack/tools/vendor/github.com/golangci/golangci-lint/v2/internal/x/tools/analysisflags/url.go rename to hack/tools/vendor/github.com/golangci/golangci-lint/v2/internal/x/tools/driverutil/url.go index 26a917a9919c..93b3ecfd4917 100644 --- a/hack/tools/vendor/github.com/golangci/golangci-lint/v2/internal/x/tools/analysisflags/url.go +++ b/hack/tools/vendor/github.com/golangci/golangci-lint/v2/internal/x/tools/driverutil/url.go @@ -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 analysisflags +package driverutil import ( "fmt" diff --git a/hack/tools/vendor/github.com/golangci/golangci-lint/v2/pkg/goanalysis/runner_checker.go b/hack/tools/vendor/github.com/golangci/golangci-lint/v2/pkg/goanalysis/runner_checker.go index 0d3fcdb9e3ef..284aed2e6b58 100644 --- a/hack/tools/vendor/github.com/golangci/golangci-lint/v2/pkg/goanalysis/runner_checker.go +++ b/hack/tools/vendor/github.com/golangci/golangci-lint/v2/pkg/goanalysis/runner_checker.go @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // -// Altered copy of https://github.com/golang/tools/blob/v0.28.0/go/analysis/internal/checker/checker.go +// Altered copy of https://github.com/golang/tools/blob/v0.43.0/go/analysis/checker/checker.go package goanalysis @@ -19,8 +19,7 @@ import ( "golang.org/x/tools/go/analysis" "golang.org/x/tools/go/packages" - "github.com/golangci/golangci-lint/v2/internal/x/tools/analysisflags" - "github.com/golangci/golangci-lint/v2/internal/x/tools/analysisinternal" + "github.com/golangci/golangci-lint/v2/internal/x/tools/driverutil" "github.com/golangci/golangci-lint/v2/pkg/goanalysis/pkgerrors" ) @@ -134,9 +133,7 @@ func (act *action) analyze() { module := &analysis.Module{} // possibly empty (non nil) in go/analysis drivers. if mod := act.Package.Module; mod != nil { - module.Path = mod.Path - module.Version = mod.Version - module.GoVersion = mod.GoVersion + module = analysisModuleFromPackagesModule(mod) } // Run the analysis. @@ -161,7 +158,7 @@ func (act *action) analyze() { AllObjectFacts: act.AllObjectFacts, AllPackageFacts: act.AllPackageFacts, } - pass.ReadFile = analysisinternal.CheckedReadFile(pass, os.ReadFile) + pass.ReadFile = driverutil.CheckedReadFile(pass, os.ReadFile) act.pass = pass act.runner.passToPkgGuard.Lock() @@ -199,7 +196,7 @@ func (act *action) analyze() { // resolve diagnostic URLs for i := range act.Diagnostics { - url, err := analysisflags.ResolveURL(act.Analyzer, act.Diagnostics[i]) + url, err := driverutil.ResolveURL(act.Analyzer, act.Diagnostics[i]) if err != nil { return nil, err } @@ -324,7 +321,7 @@ func exportedFrom(obj types.Object, pkg *types.Package) bool { switch obj := obj.(type) { case *types.Func: return obj.Exported() && obj.Pkg() == pkg || - obj.Type().(*types.Signature).Recv() != nil + obj.Signature().Recv() != nil case *types.Var: if obj.IsField() { return true @@ -387,8 +384,8 @@ func (act *action) exportObjectFact(obj types.Object, fact analysis.Fact) { // See documentation at AllObjectFacts field of [analysis.Pass]. func (act *action) AllObjectFacts() []analysis.ObjectFact { facts := make([]analysis.ObjectFact, 0, len(act.objectFacts)) - for k := range act.objectFacts { - facts = append(facts, analysis.ObjectFact{Object: k.obj, Fact: act.objectFacts[k]}) + for k, fact := range act.objectFacts { + facts = append(facts, analysis.ObjectFact{Object: k.obj, Fact: fact}) } return facts } @@ -445,3 +442,30 @@ func (act *action) AllPackageFacts() []analysis.PackageFact { } return facts } + +// NOTE(ldez) no alteration. +func analysisModuleFromPackagesModule(mod *packages.Module) *analysis.Module { + if mod == nil { + return nil + } + + var modErr *analysis.ModuleError + if mod.Error != nil { + modErr = &analysis.ModuleError{ + Err: mod.Error.Err, + } + } + + return &analysis.Module{ + Path: mod.Path, + Version: mod.Version, + Replace: analysisModuleFromPackagesModule(mod.Replace), + Time: mod.Time, + Main: mod.Main, + Indirect: mod.Indirect, + Dir: mod.Dir, + GoMod: mod.GoMod, + GoVersion: mod.GoVersion, + Error: modErr, + } +} diff --git a/hack/tools/vendor/github.com/golangci/golangci-lint/v2/pkg/goformat/runner.go b/hack/tools/vendor/github.com/golangci/golangci-lint/v2/pkg/goformat/runner.go index f15fd0a1a62a..ac70dc70a19e 100644 --- a/hack/tools/vendor/github.com/golangci/golangci-lint/v2/pkg/goformat/runner.go +++ b/hack/tools/vendor/github.com/golangci/golangci-lint/v2/pkg/goformat/runner.go @@ -79,11 +79,6 @@ func (c *Runner) Run(paths []string) error { } func (c *Runner) walk(root string, stdout *os.File) error { - r, err := os.OpenRoot(root) - if err != nil { - return err - } - return filepath.Walk(root, func(path string, f fs.FileInfo, err error) error { if err != nil { return err @@ -102,7 +97,10 @@ func (c *Runner) walk(root string, stdout *os.File) error { return err } - in, err := r.Open(path) + //nolint:gosec // See explanation below. + // `path` contains the `root` but when using `r, err := os.OpenRoot(root)`, this part is not inside the file tree of `r`. + // `filepath.Rel()` can be used but it seems overkill in the context and doesn't work well with a file. + in, err := os.Open(path) if err != nil { return err } diff --git a/hack/tools/vendor/github.com/golangci/golangci-lint/v2/pkg/golinters/sqlclosecheck/sqlclosecheck.go b/hack/tools/vendor/github.com/golangci/golangci-lint/v2/pkg/golinters/sqlclosecheck/sqlclosecheck.go index 4c970cc5295d..69872733e359 100644 --- a/hack/tools/vendor/github.com/golangci/golangci-lint/v2/pkg/golinters/sqlclosecheck/sqlclosecheck.go +++ b/hack/tools/vendor/github.com/golangci/golangci-lint/v2/pkg/golinters/sqlclosecheck/sqlclosecheck.go @@ -8,6 +8,6 @@ import ( func New() *goanalysis.Linter { return goanalysis. - NewLinterFromAnalyzer(analyzer.NewAnalyzer()). + NewLinterFromAnalyzer(analyzer.NewDeferOnlyAnalyzer()). WithLoadMode(goanalysis.LoadModeTypesInfo) } diff --git a/hack/tools/vendor/github.com/golangci/golangci-lint/v2/pkg/lint/lintersdb/builder_linter.go b/hack/tools/vendor/github.com/golangci/golangci-lint/v2/pkg/lint/lintersdb/builder_linter.go index 2581bb74e201..44eadecc56d6 100644 --- a/hack/tools/vendor/github.com/golangci/golangci-lint/v2/pkg/lint/lintersdb/builder_linter.go +++ b/hack/tools/vendor/github.com/golangci/golangci-lint/v2/pkg/lint/lintersdb/builder_linter.go @@ -132,7 +132,7 @@ func NewLinterBuilder() *LinterBuilder { } // Build loads all the "internal" linters. -// The configuration is use for the linter settings. +// The configuration is used for the linter settings. func (LinterBuilder) Build(cfg *config.Config) ([]*linter.Config, error) { if cfg == nil { return nil, nil diff --git a/hack/tools/vendor/github.com/ryanrolds/sqlclosecheck/pkg/analyzer/analyzer.go b/hack/tools/vendor/github.com/ryanrolds/sqlclosecheck/pkg/analyzer/analyzer.go index 55e931a898ce..8dd836255434 100644 --- a/hack/tools/vendor/github.com/ryanrolds/sqlclosecheck/pkg/analyzer/analyzer.go +++ b/hack/tools/vendor/github.com/ryanrolds/sqlclosecheck/pkg/analyzer/analyzer.go @@ -1,405 +1,35 @@ package analyzer import ( - "go/types" + "flag" "golang.org/x/tools/go/analysis" "golang.org/x/tools/go/analysis/passes/buildssa" - "golang.org/x/tools/go/ssa" ) -const ( - rowsName = "Rows" - stmtName = "Stmt" - namedStmtName = "NamedStmt" - closeMethod = "Close" -) - -type action uint8 - -const ( - actionUnhandled action = iota - actionHandled - actionReturned - actionPassed - actionClosed - actionUnvaluedCall - actionUnvaluedDefer - actionNoOp -) +// NewAnalyzer returns a non-configurable analyzer that defaults to the defer-only mode. +// Deprecated, this will be removed in v1.0.0. +func NewAnalyzer() *analysis.Analyzer { + flags := flag.NewFlagSet("analyzer", flag.ExitOnError) + return newAnalyzer(run, flags) +} -var ( - sqlPackages = []string{ - "database/sql", - "github.com/jmoiron/sqlx", - "github.com/jackc/pgx/v5", - "github.com/jackc/pgx/v5/pgxpool", - } -) +func run(pass *analysis.Pass) (interface{}, error) { + opinionatedAnalyzer := &deferOnlyAnalyzer{} + return opinionatedAnalyzer.Run(pass) +} -func NewAnalyzer() *analysis.Analyzer { +// newAnalyzer returns a new analyzer with the given run function, should be used by all analyzers. +func newAnalyzer( + r func(pass *analysis.Pass) (interface{}, error), + flags *flag.FlagSet, +) *analysis.Analyzer { return &analysis.Analyzer{ Name: "sqlclosecheck", Doc: "Checks that sql.Rows, sql.Stmt, sqlx.NamedStmt, pgx.Query are closed.", - Run: run, + Run: r, Requires: []*analysis.Analyzer{ buildssa.Analyzer, }, } } - -func run(pass *analysis.Pass) (interface{}, error) { - pssa, ok := pass.ResultOf[buildssa.Analyzer].(*buildssa.SSA) - if !ok { - return nil, nil - } - - // Build list of types we are looking for - targetTypes := getTargetTypes(pssa, sqlPackages) - - // If non of the types are found, skip - if len(targetTypes) == 0 { - return nil, nil - } - - funcs := pssa.SrcFuncs - for _, f := range funcs { - for _, b := range f.Blocks { - for i := range b.Instrs { - // Check if instruction is call that returns a target pointer type - targetValues := getTargetTypesValues(b, i, targetTypes) - if len(targetValues) == 0 { - continue - } - - // For each found target check if they are closed and deferred - for _, targetValue := range targetValues { - refs := (*targetValue.value).Referrers() - isClosed := checkClosed(refs, targetTypes) - if !isClosed { - pass.Reportf((targetValue.instr).Pos(), "Rows/Stmt/NamedStmt was not closed") - } - - checkDeferred(pass, refs, targetTypes, false) - } - } - } - } - - return nil, nil -} - -func getTargetTypes(pssa *buildssa.SSA, targetPackages []string) []any { - targets := []any{} - - for _, sqlPkg := range targetPackages { - pkg := pssa.Pkg.Prog.ImportedPackage(sqlPkg) - if pkg == nil { - // the SQL package being checked isn't imported - continue - } - - rowsPtrType := getTypePointerFromName(pkg, rowsName) - if rowsPtrType != nil { - targets = append(targets, rowsPtrType) - } - - rowsType := getTypeFromName(pkg, rowsName) - if rowsType != nil { - targets = append(targets, rowsType) - } - - stmtType := getTypePointerFromName(pkg, stmtName) - if stmtType != nil { - targets = append(targets, stmtType) - } - - namedStmtType := getTypePointerFromName(pkg, namedStmtName) - if namedStmtType != nil { - targets = append(targets, namedStmtType) - } - } - - return targets -} - -func getTypePointerFromName(pkg *ssa.Package, name string) *types.Pointer { - pkgType := pkg.Type(name) - if pkgType == nil { - // this package does not use Rows/Stmt/NamedStmt - return nil - } - - obj := pkgType.Object() - named, ok := obj.Type().(*types.Named) - if !ok { - return nil - } - - return types.NewPointer(named) -} - -func getTypeFromName(pkg *ssa.Package, name string) *types.Named { - pkgType := pkg.Type(name) - if pkgType == nil { - // this package does not use Rows/Stmt - return nil - } - - obj := pkgType.Object() - named, ok := obj.Type().(*types.Named) - if !ok { - return nil - } - - return named -} - -type targetValue struct { - value *ssa.Value - instr ssa.Instruction -} - -func getTargetTypesValues(b *ssa.BasicBlock, i int, targetTypes []any) []targetValue { - targetValues := []targetValue{} - - instr := b.Instrs[i] - call, ok := instr.(*ssa.Call) - if !ok { - return targetValues - } - - signature := call.Call.Signature() - results := signature.Results() - for i := 0; i < results.Len(); i++ { - v := results.At(i) - varType := v.Type() - - for _, targetType := range targetTypes { - var tt types.Type - - switch t := targetType.(type) { - case *types.Pointer: - tt = t - case *types.Named: - tt = t - default: - continue - } - - if !types.Identical(varType, tt) { - continue - } - - for _, cRef := range *call.Referrers() { - switch instr := cRef.(type) { - case *ssa.Call: - if len(instr.Call.Args) >= 1 && types.Identical(instr.Call.Args[0].Type(), tt) { - targetValues = append(targetValues, targetValue{ - value: &instr.Call.Args[0], - instr: call, - }) - } - case ssa.Value: - if types.Identical(instr.Type(), tt) { - targetValues = append(targetValues, targetValue{ - value: &instr, - instr: call, - }) - } - } - } - } - } - - return targetValues -} - -func checkClosed(refs *[]ssa.Instruction, targetTypes []any) bool { - numInstrs := len(*refs) - for idx, ref := range *refs { - action := getAction(ref, targetTypes) - switch action { - case actionClosed, actionReturned, actionHandled: - return true - case actionPassed: - // Passed and not used after - if numInstrs == idx+1 { - return true - } - } - } - - return false -} - -func getAction(instr ssa.Instruction, targetTypes []any) action { - switch instr := instr.(type) { - case *ssa.Defer: - if instr.Call.Value != nil { - name := instr.Call.Value.Name() - if name == closeMethod { - return actionClosed - } - } - - if instr.Call.Method != nil { - name := instr.Call.Method.Name() - if name == closeMethod { - return actionClosed - } - } - - return actionUnvaluedDefer - case *ssa.Call: - if instr.Call.Value == nil { - return actionUnvaluedCall - } - - isTarget := false - staticCallee := instr.Call.StaticCallee() - if staticCallee != nil { - receiver := instr.Call.StaticCallee().Signature.Recv() - if receiver != nil { - isTarget = isTargetType(receiver.Type(), targetTypes) - } - } - - name := instr.Call.Value.Name() - if isTarget && name == closeMethod { - return actionClosed - } - - if !isTarget { - return actionPassed - } - case *ssa.Phi: - return actionPassed - case *ssa.MakeInterface: - return actionPassed - case *ssa.Store: - // A Row/Stmt is stored in a struct, which may be closed later - // by a different flow. - if _, ok := instr.Addr.(*ssa.FieldAddr); ok { - return actionReturned - } - - if len(*instr.Addr.Referrers()) == 0 { - return actionNoOp - } - - for _, aRef := range *instr.Addr.Referrers() { - if c, ok := aRef.(*ssa.MakeClosure); ok { - if f, ok := c.Fn.(*ssa.Function); ok { - for _, b := range f.Blocks { - if checkClosed(&b.Instrs, targetTypes) { - return actionHandled - } - } - } - } - } - case *ssa.UnOp: - instrType := instr.Type() - for _, targetType := range targetTypes { - var tt types.Type - - switch t := targetType.(type) { - case *types.Pointer: - tt = t - case *types.Named: - tt = t - default: - continue - } - - if types.Identical(instrType, tt) { - if checkClosed(instr.Referrers(), targetTypes) { - return actionHandled - } - } - } - case *ssa.FieldAddr: - if checkClosed(instr.Referrers(), targetTypes) { - return actionHandled - } - case *ssa.Return: - return actionReturned - } - - return actionUnhandled -} - -func checkDeferred(pass *analysis.Pass, instrs *[]ssa.Instruction, targetTypes []any, inDefer bool) { - for _, instr := range *instrs { - switch instr := instr.(type) { - case *ssa.Defer: - if instr.Call.Value != nil && instr.Call.Value.Name() == closeMethod { - return - } - - if instr.Call.Method != nil && instr.Call.Method.Name() == closeMethod { - return - } - case *ssa.Call: - if instr.Call.Value != nil && instr.Call.Value.Name() == closeMethod { - if !inDefer { - pass.Reportf(instr.Pos(), "Close should use defer") - } - - return - } - case *ssa.Store: - if len(*instr.Addr.Referrers()) == 0 { - return - } - - for _, aRef := range *instr.Addr.Referrers() { - if c, ok := aRef.(*ssa.MakeClosure); ok { - if f, ok := c.Fn.(*ssa.Function); ok { - for _, b := range f.Blocks { - checkDeferred(pass, &b.Instrs, targetTypes, true) - } - } - } - } - case *ssa.UnOp: - instrType := instr.Type() - for _, targetType := range targetTypes { - var tt types.Type - - switch t := targetType.(type) { - case *types.Pointer: - tt = t - case *types.Named: - tt = t - default: - continue - } - - if types.Identical(instrType, tt) { - checkDeferred(pass, instr.Referrers(), targetTypes, inDefer) - } - } - case *ssa.FieldAddr: - checkDeferred(pass, instr.Referrers(), targetTypes, inDefer) - } - } -} - -func isTargetType(t types.Type, targetTypes []any) bool { - for _, targetType := range targetTypes { - switch tt := targetType.(type) { - case *types.Pointer: - if types.Identical(t, tt) { - return true - } - case *types.Named: - if types.Identical(t, tt) { - return true - } - } - } - - return false -} diff --git a/hack/tools/vendor/github.com/ryanrolds/sqlclosecheck/pkg/analyzer/closed.go b/hack/tools/vendor/github.com/ryanrolds/sqlclosecheck/pkg/analyzer/closed.go new file mode 100644 index 000000000000..72fdbdf9c751 --- /dev/null +++ b/hack/tools/vendor/github.com/ryanrolds/sqlclosecheck/pkg/analyzer/closed.go @@ -0,0 +1,25 @@ +package analyzer + +import ( + "flag" + + "golang.org/x/tools/go/analysis" +) + +type closedAnalyzer struct{} + +func NewClosedAnalyzer() *analysis.Analyzer { + analyzer := &closedAnalyzer{} + flags := flag.NewFlagSet("closedAnalyzer", flag.ExitOnError) + return newAnalyzer(analyzer.Run, flags) +} + +// Run implements the main analysis pass +func (a *closedAnalyzer) Run(pass *analysis.Pass) (interface{}, error) { + // pssa, ok := pass.ResultOf[buildssa.Analyzer].(*buildssa.SSA) + // if !ok { + // return nil, nil + // } + + return nil, nil +} diff --git a/hack/tools/vendor/github.com/ryanrolds/sqlclosecheck/pkg/analyzer/configurable.go b/hack/tools/vendor/github.com/ryanrolds/sqlclosecheck/pkg/analyzer/configurable.go new file mode 100644 index 000000000000..d7e96ff125cd --- /dev/null +++ b/hack/tools/vendor/github.com/ryanrolds/sqlclosecheck/pkg/analyzer/configurable.go @@ -0,0 +1,40 @@ +package analyzer + +import ( + "flag" + "fmt" + + "golang.org/x/tools/go/analysis" +) + +type ConfigurableModeType string + +const ( + ConfigurableAnalyzerDeferOnly ConfigurableModeType = "defer-only" + ConfigurableAnalyzerClosed ConfigurableModeType = "closed" +) + +type ConifgurableAnalyzer struct { + Mode string +} + +func NewConfigurableAnalyzer(mode ConfigurableModeType) *analysis.Analyzer { + cfgAnalyzer := &ConifgurableAnalyzer{} + flags := flag.NewFlagSet("cfgAnalyzer", flag.ExitOnError) + flags.StringVar(&cfgAnalyzer.Mode, "mode", string(mode), + "Mode to run the analyzer in. (defer-only, closed)") + return newAnalyzer(cfgAnalyzer.run, flags) +} + +func (c *ConifgurableAnalyzer) run(pass *analysis.Pass) (interface{}, error) { + switch c.Mode { + case string(ConfigurableAnalyzerDeferOnly): + analyzer := &deferOnlyAnalyzer{} + return analyzer.Run(pass) + case string(ConfigurableAnalyzerClosed): + analyzer := &closedAnalyzer{} + return analyzer.Run(pass) + default: + return nil, fmt.Errorf("invalid mode: %s", c.Mode) + } +} diff --git a/hack/tools/vendor/github.com/ryanrolds/sqlclosecheck/pkg/analyzer/defer_only.go b/hack/tools/vendor/github.com/ryanrolds/sqlclosecheck/pkg/analyzer/defer_only.go new file mode 100644 index 000000000000..701c7c6f615f --- /dev/null +++ b/hack/tools/vendor/github.com/ryanrolds/sqlclosecheck/pkg/analyzer/defer_only.go @@ -0,0 +1,441 @@ +package analyzer + +import ( + "flag" + "go/types" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/buildssa" + "golang.org/x/tools/go/ssa" +) + +const ( + rowsName = "Rows" + stmtName = "Stmt" + namedStmtName = "NamedStmt" + closeMethod = "Close" +) + +type action uint8 + +const ( + actionUnhandled action = iota + actionHandled + actionReturned + actionPassed + actionClosed + actionUnvaluedCall + actionUnvaluedDefer + actionNoOp +) + +var ( + sqlPackages = []string{ + "database/sql", + "github.com/jmoiron/sqlx", + "github.com/jackc/pgx/v5", + "github.com/jackc/pgx/v5/pgxpool", + } +) + +type deferOnlyAnalyzer struct{} + +func NewDeferOnlyAnalyzer() *analysis.Analyzer { + analyzer := &deferOnlyAnalyzer{} + flags := flag.NewFlagSet("deferOnlyAnalyzer", flag.ExitOnError) + return newAnalyzer(analyzer.Run, flags) +} + +// Run implements the main analysis pass +func (a *deferOnlyAnalyzer) Run(pass *analysis.Pass) (interface{}, error) { + pssa, ok := pass.ResultOf[buildssa.Analyzer].(*buildssa.SSA) + if !ok { + return nil, nil + } + + // Build list of types we are looking for + targetTypes := getTargetTypes(pssa, sqlPackages) + + // If non of the types are found, skip + if len(targetTypes) == 0 { + return nil, nil + } + + funcs := pssa.SrcFuncs + for _, f := range funcs { + for _, b := range f.Blocks { + for i := range b.Instrs { + // Check if instruction is call that returns a target pointer type + targetValues := getTargetTypesValues(b, i, targetTypes) + if len(targetValues) == 0 { + continue + } + + // For each found target check if they are closed and deferred + for _, targetValue := range targetValues { + refs := (*targetValue.value).Referrers() + isClosed := checkClosed(refs, targetTypes) + if !isClosed { + pass.Reportf((targetValue.instr).Pos(), "Rows/Stmt/NamedStmt was not closed") + } + + checkDeferred(pass, refs, targetTypes, false) + } + } + } + } + + return nil, nil +} + +func getTargetTypes(pssa *buildssa.SSA, targetPackages []string) []any { + targets := []any{} + + for _, sqlPkg := range targetPackages { + pkg := pssa.Pkg.Prog.ImportedPackage(sqlPkg) + if pkg == nil { + // the SQL package being checked isn't imported + continue + } + + rowsPtrType := getTypePointerFromName(pkg, rowsName) + if rowsPtrType != nil { + targets = append(targets, rowsPtrType) + } + + rowsType := getTypeFromName(pkg, rowsName) + if rowsType != nil { + targets = append(targets, rowsType) + } + + stmtType := getTypePointerFromName(pkg, stmtName) + if stmtType != nil { + targets = append(targets, stmtType) + } + + namedStmtType := getTypePointerFromName(pkg, namedStmtName) + if namedStmtType != nil { + targets = append(targets, namedStmtType) + } + } + + return targets +} + +func getTypePointerFromName(pkg *ssa.Package, name string) *types.Pointer { + pkgType := pkg.Type(name) + if pkgType == nil { + // this package does not use Rows/Stmt/NamedStmt + return nil + } + + obj := pkgType.Object() + named, ok := obj.Type().(*types.Named) + if !ok { + return nil + } + + return types.NewPointer(named) +} + +func getTypeFromName(pkg *ssa.Package, name string) *types.Named { + pkgType := pkg.Type(name) + if pkgType == nil { + // this package does not use Rows/Stmt + return nil + } + + obj := pkgType.Object() + named, ok := obj.Type().(*types.Named) + if !ok { + return nil + } + + return named +} + +type targetValue struct { + value *ssa.Value + instr ssa.Instruction +} + +func getTargetTypesValues(b *ssa.BasicBlock, i int, targetTypes []any) []targetValue { + targetValues := []targetValue{} + + instr := b.Instrs[i] + call, ok := instr.(*ssa.Call) + if !ok { + return targetValues + } + + signature := call.Call.Signature() + results := signature.Results() + for i := 0; i < results.Len(); i++ { + v := results.At(i) + varType := v.Type() + + for _, targetType := range targetTypes { + var tt types.Type + + switch t := targetType.(type) { + case *types.Pointer: + tt = t + case *types.Named: + tt = t + default: + continue + } + + if !types.Identical(varType, tt) { + continue + } + + for _, cRef := range *call.Referrers() { + switch instr := cRef.(type) { + case *ssa.Call: + if len(instr.Call.Args) >= 1 && types.Identical(instr.Call.Args[0].Type(), tt) { + targetValues = append(targetValues, targetValue{ + value: &instr.Call.Args[0], + instr: call, + }) + } + case ssa.Value: + if types.Identical(instr.Type(), tt) { + targetValues = append(targetValues, targetValue{ + value: &instr, + instr: call, + }) + } + } + } + } + } + + return targetValues +} + +func checkClosed(refs *[]ssa.Instruction, targetTypes []any) bool { + numInstrs := len(*refs) + for idx, ref := range *refs { + action := getAction(ref, targetTypes) + switch action { + case actionClosed, actionReturned, actionHandled: + return true + case actionPassed: + // Passed and not used after + if numInstrs == idx+1 { + return true + } + } + } + + return false +} + +func getAction(instr ssa.Instruction, targetTypes []any) action { + switch instr := instr.(type) { + case *ssa.Defer: + if instr.Call.Value != nil { + name := instr.Call.Value.Name() + if name == closeMethod { + return actionClosed + } + } + + if instr.Call.Method != nil { + name := instr.Call.Method.Name() + if name == closeMethod { + return actionClosed + } + } else if instr.Call.Value != nil { + // If it is a deferred function, go further down the call chain + if f, ok := instr.Call.Value.(*ssa.Function); ok { + for _, b := range f.Blocks { + if checkClosed(&b.Instrs, targetTypes) { + return actionHandled + } + } + } + } + + return actionUnvaluedDefer + case *ssa.Call: + if instr.Call.Value == nil { + return actionUnvaluedCall + } + + isTarget := false + staticCallee := instr.Call.StaticCallee() + if staticCallee != nil { + receiver := instr.Call.StaticCallee().Signature.Recv() + if receiver != nil { + isTarget = isTargetType(receiver.Type(), targetTypes) + } + } + + name := instr.Call.Value.Name() + if isTarget && name == closeMethod { + return actionClosed + } + + if !isTarget { + return actionPassed + } + case *ssa.Phi: + return actionPassed + case *ssa.MakeInterface: + return actionPassed + case *ssa.Store: + // A Row/Stmt is stored in a struct, which may be closed later + // by a different flow. + if _, ok := instr.Addr.(*ssa.FieldAddr); ok { + return actionReturned + } + + if instr.Addr.Referrers() == nil { + return actionNoOp + } + + if len(*instr.Addr.Referrers()) == 0 { + return actionNoOp + } + + for _, aRef := range *instr.Addr.Referrers() { + if c, ok := aRef.(*ssa.MakeClosure); ok { + if f, ok := c.Fn.(*ssa.Function); ok { + for _, b := range f.Blocks { + if checkClosed(&b.Instrs, targetTypes) { + return actionHandled + } + } + } + } + } + case *ssa.UnOp: + instrType := instr.Type() + for _, targetType := range targetTypes { + var tt types.Type + + switch t := targetType.(type) { + case *types.Pointer: + tt = t + case *types.Named: + tt = t + default: + continue + } + + if types.Identical(instrType, tt) { + if checkClosed(instr.Referrers(), targetTypes) { + return actionHandled + } + } + } + case *ssa.FieldAddr: + if checkClosed(instr.Referrers(), targetTypes) { + return actionHandled + } + case *ssa.Return: + if len(instr.Results) != 0 { + for _, result := range instr.Results { + resultType := result.Type() + for _, targetType := range targetTypes { + var tt types.Type + + switch t := targetType.(type) { + case *types.Pointer: + tt = t + case *types.Named: + tt = t + default: + continue + } + + if types.Identical(resultType, tt) { + return actionReturned + } + } + } + } + } + + return actionUnhandled +} + +func checkDeferred(pass *analysis.Pass, instrs *[]ssa.Instruction, targetTypes []any, inDefer bool) { + for _, instr := range *instrs { + switch instr := instr.(type) { + case *ssa.Defer: + if instr.Call.Value != nil && instr.Call.Value.Name() == closeMethod { + return + } + + if instr.Call.Method != nil && instr.Call.Method.Name() == closeMethod { + return + } + case *ssa.Call: + if instr.Call.Value != nil && instr.Call.Value.Name() == closeMethod { + if !inDefer { + pass.Reportf(instr.Pos(), "Close should use defer") + } + + return + } + case *ssa.Store: + if instr.Addr.Referrers() == nil { + return + } + + if len(*instr.Addr.Referrers()) == 0 { + return + } + + for _, aRef := range *instr.Addr.Referrers() { + if c, ok := aRef.(*ssa.MakeClosure); ok { + if f, ok := c.Fn.(*ssa.Function); ok { + for _, b := range f.Blocks { + checkDeferred(pass, &b.Instrs, targetTypes, true) + } + } + } + } + case *ssa.UnOp: + instrType := instr.Type() + for _, targetType := range targetTypes { + var tt types.Type + + switch t := targetType.(type) { + case *types.Pointer: + tt = t + case *types.Named: + tt = t + default: + continue + } + + if types.Identical(instrType, tt) { + checkDeferred(pass, instr.Referrers(), targetTypes, inDefer) + } + } + case *ssa.FieldAddr: + checkDeferred(pass, instr.Referrers(), targetTypes, inDefer) + } + } +} + +func isTargetType(t types.Type, targetTypes []any) bool { + for _, targetType := range targetTypes { + switch tt := targetType.(type) { + case *types.Pointer: + if types.Identical(t, tt) { + return true + } + case *types.Named: + if types.Identical(t, tt) { + return true + } + } + } + + return false +} diff --git a/hack/tools/vendor/github.com/securego/gosec/v2/README.md b/hack/tools/vendor/github.com/securego/gosec/v2/README.md index 89c268a9432a..6f6d27d12051 100644 --- a/hack/tools/vendor/github.com/securego/gosec/v2/README.md +++ b/hack/tools/vendor/github.com/securego/gosec/v2/README.md @@ -3,9 +3,6 @@ Inspects source code for security problems by scanning the Go AST and SSA code representation. -> ⚠️ Container image migration notice: `gosec` images have been migrated from Docker Hub to `ghcr.io/securego/gosec`. -> Starting with the next release, Docker Hub images will no longer be published. - ## Quick links @@ -17,6 +14,9 @@ Inspects source code for security problems by scanning the Go AST and SSA code r - [Selecting rules](#selecting-rules) - [Output formats](#output-formats) +> ⚠️ Container image migration notice: `gosec` images was migrated from Docker Hub to `ghcr.io/securego/gosec`. +> Starting with release `v2.24.7` the image is no longer published in Docker Hub. + ## Features - **Pattern-based rules** for detecting common security issues in Go code @@ -48,7 +48,7 @@ You may obtain a copy of the License [here](http://www.apache.org/licenses/LICEN You can run `gosec` as a GitHub action as follows: -Use a versioned tag (for example `@v2`) instead of `@master` for stable behavior. +Use the versioned tag with `@master` which is pinned to the latest stable release. This will provide a stable behavior. ```yaml name: Run Gosec @@ -68,7 +68,7 @@ jobs: - name: Checkout Source uses: actions/checkout@v3 - name: Run Gosec Security Scanner - uses: securego/gosec@v2 + uses: securego/gosec@master with: args: ./... ``` diff --git a/hack/tools/vendor/github.com/securego/gosec/v2/action.yml b/hack/tools/vendor/github.com/securego/gosec/v2/action.yml index 58bd5edc87f1..dce5779453e3 100644 --- a/hack/tools/vendor/github.com/securego/gosec/v2/action.yml +++ b/hack/tools/vendor/github.com/securego/gosec/v2/action.yml @@ -10,7 +10,7 @@ inputs: runs: using: "docker" - image: "docker://ghcr.io/securego/gosec:2.24.6" + image: "docker://ghcr.io/securego/gosec:2.24.7" args: - ${{ inputs.args }} diff --git a/hack/tools/vendor/github.com/securego/gosec/v2/analyzer.go b/hack/tools/vendor/github.com/securego/gosec/v2/analyzer.go index c3c8876b480d..ed03efc69590 100644 --- a/hack/tools/vendor/github.com/securego/gosec/v2/analyzer.go +++ b/hack/tools/vendor/github.com/securego/gosec/v2/analyzer.go @@ -194,8 +194,18 @@ func (m *Metrics) Merge(other *Metrics) { // Analyzer object is the main object of gosec. It has methods to load and analyze // packages, traverse ASTs, and invoke the correct checking rules on each node as required. type Analyzer struct { - ignoreNosec bool - ruleset RuleSet + ignoreNosec bool + ruleset RuleSet + // ruleBuilders and ruleSuppressed store the original arguments passed to + // LoadRules so that checkRules can call buildPackageRuleset to produce a + // goroutine-local RuleSet for every concurrent package walk. Each walk + // therefore owns its own freshly allocated rule instances, which means + // rules are free to keep per-package mutable state (e.g. maps tracking + // cleaned or joined variables) without any synchronisation. The shared + // gosec.ruleset is kept for callers that use the public CheckRules API + // directly (backward-compatible path). + ruleBuilders map[string]RuleBuilder + ruleSuppressed map[string]bool context *Context config Config logger *log.Logger @@ -254,12 +264,32 @@ func (gosec *Analyzer) Config() Config { // LoadRules instantiates all the rules to be used when analyzing source // packages func (gosec *Analyzer) LoadRules(ruleDefinitions map[string]RuleBuilder, ruleSuppressed map[string]bool) { + // Persist the builders so checkRules can produce per-package rule + // instances via buildPackageRuleset, eliminating shared mutable state + // across concurrent goroutines without requiring locks inside rules. + gosec.ruleBuilders = ruleDefinitions + gosec.ruleSuppressed = ruleSuppressed + for id, def := range ruleDefinitions { r, nodes := def(id, gosec.config) gosec.ruleset.Register(r, ruleSuppressed[id], nodes...) } } +// buildPackageRuleset constructs a brand-new RuleSet by re-invoking every +// stored RuleBuilder. The returned ruleset is intended to be used for a single +// package walk: because each concurrent worker calls buildPackageRuleset +// independently, every goroutine gets its own rule instances with their own +// internal state (maps, caches, etc.), so rules require no synchronisation. +func (gosec *Analyzer) buildPackageRuleset() RuleSet { + rs := NewRuleSet() + for id, def := range gosec.ruleBuilders { + r, nodes := def(id, gosec.config) + rs.Register(r, gosec.ruleSuppressed[id], nodes...) + } + return rs +} + // LoadAnalyzers instantiates all the analyzers to be used when analyzing source // packages func (gosec *Analyzer) LoadAnalyzers(analyzerDefinitions map[string]analyzers.AnalyzerDefinition, analyzerSuppressed map[string]bool) { @@ -460,8 +490,20 @@ func (gosec *Analyzer) checkRules(pkg *packages.Package) ([]*issue.Issue, *Metri callCachePool.Put(callCache) }() + // Build a goroutine-local RuleSet so this package walk owns its own fresh + // rule instances. Rules with internal maps (e.g. readfile.cleanedVar, + // joinedVar) are therefore safe to use without any synchronisation: each + // concurrent worker has completely independent rule objects. Falls back to + // the shared ruleset when builders are unavailable (direct CheckRules path). + var pkgRuleset *RuleSet + if len(gosec.ruleBuilders) > 0 { + rs := gosec.buildPackageRuleset() + pkgRuleset = &rs + } + visitor := &astVisitor{ gosec: gosec, + ruleset: pkgRuleset, issues: make([]*issue.Issue, 0, 16), stats: stats, ignoreNosec: gosec.ignoreNosec, @@ -502,7 +544,7 @@ func (gosec *Analyzer) checkRules(pkg *packages.Package) ([]*issue.Issue, *Metri visitor.context = ctx visitor.updateIgnores() - if len(gosec.ruleset.Rules) > 0 { + if len(visitor.activeRuleset().Rules) > 0 { ast.Walk(visitor, file) } stats.NumFiles++ @@ -811,7 +853,12 @@ func findNoSecTag(text, tag string) (bool, string) { // astVisitor implements ast.Visitor for per-file rule checking and issue collection. type astVisitor struct { - gosec *Analyzer + gosec *Analyzer + // ruleset is a package-local RuleSet built fresh by buildPackageRuleset + // for each concurrent package walk. It is non-nil when invoked through + // the normal Process → checkRules path and nil when the public CheckRules + // API is called directly (falling back to the shared gosec.ruleset). + ruleset *RuleSet context *Context issues []*issue.Issue stats *Metrics @@ -820,13 +867,22 @@ type astVisitor struct { trackSuppressions bool } +// activeRuleset returns the package-local ruleset when available, falling back +// to the shared analyzer ruleset for direct CheckRules callers. +func (v *astVisitor) activeRuleset() *RuleSet { + if v.ruleset != nil { + return v.ruleset + } + return &v.gosec.ruleset +} + func (v *astVisitor) Visit(n ast.Node) ast.Visitor { switch i := n.(type) { case *ast.File: v.context.Imports.TrackFile(i) } - for _, rule := range v.gosec.ruleset.RegisteredFor(n) { + for _, rule := range v.activeRuleset().RegisteredFor(n) { issue, err := rule.Match(n, v.context) if err != nil { file, line := GetLocation(n, v.context) @@ -1012,5 +1068,7 @@ func (gosec *Analyzer) Reset() { gosec.issues = make([]*issue.Issue, 0, 16) gosec.stats = &Metrics{} gosec.ruleset = NewRuleSet() + gosec.ruleBuilders = nil + gosec.ruleSuppressed = nil gosec.analyzerSet = analyzers.NewAnalyzerSet() } diff --git a/hack/tools/vendor/github.com/securego/gosec/v2/analyzers/context_propagation.go b/hack/tools/vendor/github.com/securego/gosec/v2/analyzers/context_propagation.go index 4ece39e08a86..0136d660d4c5 100644 --- a/hack/tools/vendor/github.com/securego/gosec/v2/analyzers/context_propagation.go +++ b/hack/tools/vendor/github.com/securego/gosec/v2/analyzers/context_propagation.go @@ -705,6 +705,11 @@ func isCancelCalled(cancelValue ssa.Value, allFuncs []*ssa.Function) bool { if isCancelCalledViaStructField(fa, allFuncs) { return true } + // Check if the struct containing this field is returned, + // transferring cancel responsibility to the caller. + if isStructFieldReturnedFromFunc(fa) { + return true + } } queue = append(queue, r.Addr) case *ssa.UnOp: @@ -725,6 +730,52 @@ func isCancelCalled(cancelValue ssa.Value, allFuncs []*ssa.Function) bool { if r.X == current { queue = append(queue, r) } + case *ssa.MakeClosure: + // The cancel value is captured as a free variable in a closure. + // Find the corresponding FreeVar inside the closure body and + // follow it so that calls within the closure are detected. + if fn, ok := r.Fn.(*ssa.Function); ok { + for i, binding := range r.Bindings { + if binding == current && i < len(fn.FreeVars) { + queue = append(queue, fn.FreeVars[i]) + } + } + } + case *ssa.Return: + // Cancel function is returned to the caller — responsibility + // is transferred; treat as "called". + for _, result := range r.Results { + if result == current { + return true + } + } + } + } + } + + return false +} + +// isStructFieldReturnedFromFunc checks whether the struct that owns a FieldAddr +// is loaded and returned from the enclosing function. When a cancel is stored in +// a struct field and the struct is returned, responsibility for calling the +// cancel is transferred to the caller. +func isStructFieldReturnedFromFunc(fa *ssa.FieldAddr) bool { + structBase := fa.X + if structBase == nil { + return false + } + + // Follow referrers of the struct base pointer to find loads (*struct) + // that are then returned. + for _, ref := range safeReferrers(structBase) { + load, ok := ref.(*ssa.UnOp) + if !ok || load.Op != token.MUL { + continue + } + for _, loadRef := range safeReferrers(load) { + if _, ok := loadRef.(*ssa.Return); ok { + return true } } } diff --git a/hack/tools/vendor/github.com/securego/gosec/v2/analyzers/conversion_overflow.go b/hack/tools/vendor/github.com/securego/gosec/v2/analyzers/conversion_overflow.go index 0881d4904ef5..23a350b477ca 100644 --- a/hack/tools/vendor/github.com/securego/gosec/v2/analyzers/conversion_overflow.go +++ b/hack/tools/vendor/github.com/securego/gosec/v2/analyzers/conversion_overflow.go @@ -17,6 +17,7 @@ package analyzers import ( "fmt" "go/types" + "math" "golang.org/x/tools/go/analysis" "golang.org/x/tools/go/analysis/passes/buildssa" @@ -216,7 +217,11 @@ func (s *overflowState) validateRangeLimits(v ssa.Value, res *rangeResult, dstIn } minSafe := true if srcInt.Min < 0 { - minSafe = minValueSet && toInt64(minValue) >= 0 + minBound := int64(0) + if res.isRangeCheck && maxValueSet && toInt64(maxValue) > signedMaxForUnsignedSize(dstInt.Size) { + minBound = signedMinForUnsignedSize(dstInt.Size) + } + minSafe = minValueSet && toInt64(minValue) >= minBound } maxSafe := true if srcInt.Max > dstInt.Max { @@ -225,36 +230,81 @@ func (s *overflowState) validateRangeLimits(v ssa.Value, res *rangeResult, dstIn return minSafe && maxSafe } +func signedMinForUnsignedSize(size int) int64 { + if size >= 64 { + return math.MinInt64 + } + return -(int64(1) << (size - 1)) +} + +func signedMaxForUnsignedSize(size int) int64 { + if size >= 64 { + return math.MaxInt64 + } + return (int64(1) << (size - 1)) - 1 +} + func (s *overflowState) isSafeFromPredecessor(v ssa.Value, dstInt IntTypeInfo, pred *ssa.BasicBlock, targetBlock *ssa.BasicBlock) bool { - if vIf, ok := pred.Instrs[len(pred.Instrs)-1].(*ssa.If); ok { - isSrcUnsigned := isUint(v) - for i, succ := range pred.Succs { - if succ == targetBlock { - // We took this specific edge. - result := s.Analyzer.getResultRangeForIfEdge(vIf, i == 0, v) - defer s.Analyzer.releaseResult(result) - - if result.isRangeCheck { - var safe bool - if dstInt.Signed { - if isSrcUnsigned { - safe = result.maxValueSet && result.maxValue <= dstInt.Max - } else { - safe = (result.minValueSet && toInt64(result.minValue) >= dstInt.Min) && (result.maxValueSet && toInt64(result.maxValue) <= toInt64(dstInt.Max)) - } - } else { - if isSrcUnsigned { - safe = result.maxValueSet && result.maxValue <= dstInt.Max - } else { - safe = (result.minValueSet && toInt64(result.minValue) >= 0) && (result.maxValueSet && result.maxValue <= dstInt.Max) - } - } - if safe { + edgeValue := v + if phi, ok := v.(*ssa.Phi); ok && phi.Block() == targetBlock { + for i, p := range targetBlock.Preds { + if p == pred && i < len(phi.Edges) { + edgeValue = phi.Edges[i] + break + } + } + } + + if len(pred.Instrs) > 0 { + if vIf, ok := pred.Instrs[len(pred.Instrs)-1].(*ssa.If); ok { + for i, succ := range pred.Succs { + if succ == targetBlock { + result := s.Analyzer.getResultRangeForIfEdge(vIf, i == 0, edgeValue) + defer s.Analyzer.releaseResult(result) + if s.isSafeIfEdgeResult(edgeValue, dstInt, result) { return true } } } } } + + if len(pred.Preds) == 1 { + parent := pred.Preds[0] + if len(parent.Instrs) > 0 { + if vIf, ok := parent.Instrs[len(parent.Instrs)-1].(*ssa.If); ok { + for i, succ := range parent.Succs { + if succ == pred { + result := s.Analyzer.getResultRangeForIfEdge(vIf, i == 0, edgeValue) + defer s.Analyzer.releaseResult(result) + if s.isSafeIfEdgeResult(edgeValue, dstInt, result) { + return true + } + } + } + } + } + } + return false } + +func (s *overflowState) isSafeIfEdgeResult(v ssa.Value, dstInt IntTypeInfo, result *rangeResult) bool { + if !result.isRangeCheck { + return false + } + + isSrcUnsigned := isUint(v) + if dstInt.Signed { + if isSrcUnsigned { + return result.maxValueSet && result.maxValue <= dstInt.Max + } + return (result.minValueSet && toInt64(result.minValue) >= dstInt.Min) && (result.maxValueSet && toInt64(result.maxValue) <= toInt64(dstInt.Max)) + } + + if isSrcUnsigned { + return result.maxValueSet && result.maxValue <= dstInt.Max + } + + return (result.minValueSet && toInt64(result.minValue) >= 0) && (result.maxValueSet && result.maxValue <= dstInt.Max) +} diff --git a/hack/tools/vendor/github.com/securego/gosec/v2/taint/taint.go b/hack/tools/vendor/github.com/securego/gosec/v2/taint/taint.go index d0b669a1bb98..d53b14f2fa2d 100644 --- a/hack/tools/vendor/github.com/securego/gosec/v2/taint/taint.go +++ b/hack/tools/vendor/github.com/securego/gosec/v2/taint/taint.go @@ -1073,6 +1073,12 @@ func (a *Analyzer) isFieldTaintedViaCall(call *ssa.Call, fieldIdx int, callee *s return false } + // Prevent re-analyzing the same call site + if visited[call] { + return false + } + visited[call] = true + // If we don't have SSA blocks (external function or no body), use fallback logic: // Assume the field is tainted if any argument to the constructor is tainted. if callee.Blocks == nil { @@ -1114,6 +1120,11 @@ func (a *Analyzer) isFieldOfAllocTaintedInCallee(alloc *ssa.Alloc, fieldIdx int, if alloc.Referrers() == nil || depth > maxTaintDepth { return false } + + if visited[alloc] { + return false + } + visited[alloc] = true for _, ref := range *alloc.Referrers() { fa, ok := ref.(*ssa.FieldAddr) if !ok || fa.Field != fieldIdx { @@ -1144,6 +1155,12 @@ func (a *Analyzer) isCalleValueTainted(v ssa.Value, callee *ssa.Function, call * return false } + // Prevent infinite recursion on cyclic SSA value graphs + if visited[v] { + return false + } + visited[v] = true + // If the value is a callee parameter, map it to the caller's argument if param, ok := v.(*ssa.Parameter); ok { for i, p := range callee.Params { diff --git a/hack/tools/vendor/github.com/sonatard/noctx/.goreleaser.yml b/hack/tools/vendor/github.com/sonatard/noctx/.goreleaser.yml index 2e3653cdef06..04f6a0da0d80 100644 --- a/hack/tools/vendor/github.com/sonatard/noctx/.goreleaser.yml +++ b/hack/tools/vendor/github.com/sonatard/noctx/.goreleaser.yml @@ -25,6 +25,8 @@ builds: ignore: - goos: darwin goarch: 386 + - goos: windows + goarch: arm archives: - id: noctx diff --git a/hack/tools/vendor/golang.org/x/crypto/ssh/agent/server.go b/hack/tools/vendor/golang.org/x/crypto/ssh/agent/server.go index 4e8ff86b6192..2a7658cf75c3 100644 --- a/hack/tools/vendor/golang.org/x/crypto/ssh/agent/server.go +++ b/hack/tools/vendor/golang.org/x/crypto/ssh/agent/server.go @@ -36,7 +36,7 @@ func (s *server) processRequestBytes(reqData []byte) []byte { return []byte{agentFailure} } - if err == nil && rep == nil { + if rep == nil { return []byte{agentSuccess} } diff --git a/hack/tools/vendor/golang.org/x/net/http2/http2.go b/hack/tools/vendor/golang.org/x/net/http2/http2.go index 6320f4eb4c1b..0b99d832faa9 100644 --- a/hack/tools/vendor/golang.org/x/net/http2/http2.go +++ b/hack/tools/vendor/golang.org/x/net/http2/http2.go @@ -4,13 +4,17 @@ // Package http2 implements the HTTP/2 protocol. // -// This package is low-level and intended to be used directly by very -// few people. Most users will use it indirectly through the automatic -// use by the net/http package (from Go 1.6 and later). -// For use in earlier Go versions see ConfigureServer. (Transport support -// requires Go 1.6 or later) +// Almost no users should need to import this package directly. +// The net/http package supports HTTP/2 natively. // -// See https://http2.github.io/ for more information on HTTP/2. +// To enable or disable HTTP/2 support in net/http clients and servers, see +// [http.Transport.Protocols] and [http.Server.Protocols]. +// +// To configure HTTP/2 parameters, see +// [http.Transport.HTTP2] and [http.Server.HTTP2]. +// +// To create HTTP/1 or HTTP/2 connections, see +// [http.Transport.NewClientConn]. package http2 // import "golang.org/x/net/http2" import ( diff --git a/hack/tools/vendor/golang.org/x/net/http2/server.go b/hack/tools/vendor/golang.org/x/net/http2/server.go index 7ef807f79df9..65da5175c9ba 100644 --- a/hack/tools/vendor/golang.org/x/net/http2/server.go +++ b/hack/tools/vendor/golang.org/x/net/http2/server.go @@ -164,6 +164,8 @@ type Server struct { // NewWriteScheduler constructs a write scheduler for a connection. // If nil, a default scheduler is chosen. + // + // Deprecated: User-provided write schedulers are deprecated. NewWriteScheduler func() WriteScheduler // CountError, if non-nil, is called on HTTP/2 server errors. diff --git a/hack/tools/vendor/golang.org/x/net/http2/transport.go b/hack/tools/vendor/golang.org/x/net/http2/transport.go index 8cf64b78e288..2e9c2f6a52b4 100644 --- a/hack/tools/vendor/golang.org/x/net/http2/transport.go +++ b/hack/tools/vendor/golang.org/x/net/http2/transport.go @@ -712,10 +712,6 @@ func canRetryError(err error) bool { return true } if se, ok := err.(StreamError); ok { - if se.Code == ErrCodeProtocol && se.Cause == errFromPeer { - // See golang/go#47635, golang/go#42777 - return true - } return se.Code == ErrCodeRefusedStream } return false @@ -3233,10 +3229,6 @@ func (gz *gzipReader) Close() error { return gz.body.Close() } -type errorReader struct{ err error } - -func (r errorReader) Read(p []byte) (int, error) { return 0, r.err } - // isConnectionCloseRequest reports whether req should use its own // connection for a single request and then close the connection. func isConnectionCloseRequest(req *http.Request) bool { diff --git a/hack/tools/vendor/golang.org/x/net/http2/writesched.go b/hack/tools/vendor/golang.org/x/net/http2/writesched.go index 7de27be52509..551545f313ff 100644 --- a/hack/tools/vendor/golang.org/x/net/http2/writesched.go +++ b/hack/tools/vendor/golang.org/x/net/http2/writesched.go @@ -8,6 +8,8 @@ import "fmt" // WriteScheduler is the interface implemented by HTTP/2 write schedulers. // Methods are never called concurrently. +// +// Deprecated: User-provided write schedulers are deprecated. type WriteScheduler interface { // OpenStream opens a new stream in the write scheduler. // It is illegal to call this with streamID=0 or with a streamID that is @@ -38,6 +40,8 @@ type WriteScheduler interface { } // OpenStreamOptions specifies extra options for WriteScheduler.OpenStream. +// +// Deprecated: User-provided write schedulers are deprecated. type OpenStreamOptions struct { // PusherID is zero if the stream was initiated by the client. Otherwise, // PusherID names the stream that pushed the newly opened stream. @@ -47,6 +51,8 @@ type OpenStreamOptions struct { } // FrameWriteRequest is a request to write a frame. +// +// Deprecated: User-provided write schedulers are deprecated. type FrameWriteRequest struct { // write is the interface value that does the writing, once the // WriteScheduler has selected this frame to write. The write diff --git a/hack/tools/vendor/golang.org/x/net/http2/writesched_priority_rfc7540.go b/hack/tools/vendor/golang.org/x/net/http2/writesched_priority_rfc7540.go index 7803a9261b01..c3d3e9bed632 100644 --- a/hack/tools/vendor/golang.org/x/net/http2/writesched_priority_rfc7540.go +++ b/hack/tools/vendor/golang.org/x/net/http2/writesched_priority_rfc7540.go @@ -14,6 +14,8 @@ import ( const priorityDefaultWeightRFC7540 = 15 // 16 = 15 + 1 // PriorityWriteSchedulerConfig configures a priorityWriteScheduler. +// +// Deprecated: User-provided write schedulers are deprecated. type PriorityWriteSchedulerConfig struct { // MaxClosedNodesInTree controls the maximum number of closed streams to // retain in the priority tree. Setting this to zero saves a small amount @@ -55,6 +57,9 @@ type PriorityWriteSchedulerConfig struct { // NewPriorityWriteScheduler constructs a WriteScheduler that schedules // frames by following HTTP/2 priorities as described in RFC 7540 Section 5.3. // If cfg is nil, default options are used. +// +// Deprecated: The RFC 7540 write scheduler has known bugs and performance issues, +// and RFC 7540 prioritization was deprecated in RFC 9113. func NewPriorityWriteScheduler(cfg *PriorityWriteSchedulerConfig) WriteScheduler { return newPriorityWriteSchedulerRFC7540(cfg) } diff --git a/hack/tools/vendor/golang.org/x/net/http2/writesched_random.go b/hack/tools/vendor/golang.org/x/net/http2/writesched_random.go index f2e55e05ce90..d5d4e2214897 100644 --- a/hack/tools/vendor/golang.org/x/net/http2/writesched_random.go +++ b/hack/tools/vendor/golang.org/x/net/http2/writesched_random.go @@ -10,6 +10,8 @@ import "math" // priorities. Control frames like SETTINGS and PING are written before DATA // frames, but if no control frames are queued and multiple streams have queued // HEADERS or DATA frames, Pop selects a ready stream arbitrarily. +// +// Deprecated: User-provided write schedulers are deprecated. func NewRandomWriteScheduler() WriteScheduler { return &randomWriteScheduler{sq: make(map[uint32]*writeQueue)} } diff --git a/hack/tools/vendor/golang.org/x/sync/singleflight/singleflight.go b/hack/tools/vendor/golang.org/x/sync/singleflight/singleflight.go index 4051830982ad..90ca138af31f 100644 --- a/hack/tools/vendor/golang.org/x/sync/singleflight/singleflight.go +++ b/hack/tools/vendor/golang.org/x/sync/singleflight/singleflight.go @@ -22,7 +22,7 @@ var errGoexit = errors.New("runtime.Goexit was called") // A panicError is an arbitrary value recovered from a panic // with the stack trace during the execution of given function. type panicError struct { - value interface{} + value any stack []byte } @@ -40,7 +40,7 @@ func (p *panicError) Unwrap() error { return err } -func newPanicError(v interface{}) error { +func newPanicError(v any) error { stack := debug.Stack() // The first line of the stack trace is of the form "goroutine N [status]:" @@ -58,7 +58,7 @@ type call struct { // These fields are written once before the WaitGroup is done // and are only read after the WaitGroup is done. - val interface{} + val any err error // These fields are read and written with the singleflight @@ -78,7 +78,7 @@ type Group struct { // Result holds the results of Do, so they can be passed // on a channel. type Result struct { - Val interface{} + Val any Err error Shared bool } @@ -88,7 +88,7 @@ type Result struct { // time. If a duplicate comes in, the duplicate caller waits for the // original to complete and receives the same results. // The return value shared indicates whether v was given to multiple callers. -func (g *Group) Do(key string, fn func() (interface{}, error)) (v interface{}, err error, shared bool) { +func (g *Group) Do(key string, fn func() (any, error)) (v any, err error, shared bool) { g.mu.Lock() if g.m == nil { g.m = make(map[string]*call) @@ -118,7 +118,7 @@ func (g *Group) Do(key string, fn func() (interface{}, error)) (v interface{}, e // results when they are ready. // // The returned channel will not be closed. -func (g *Group) DoChan(key string, fn func() (interface{}, error)) <-chan Result { +func (g *Group) DoChan(key string, fn func() (any, error)) <-chan Result { ch := make(chan Result, 1) g.mu.Lock() if g.m == nil { @@ -141,7 +141,7 @@ func (g *Group) DoChan(key string, fn func() (interface{}, error)) <-chan Result } // doCall handles the single call for a key. -func (g *Group) doCall(c *call, key string, fn func() (interface{}, error)) { +func (g *Group) doCall(c *call, key string, fn func() (any, error)) { normalReturn := false recovered := false diff --git a/hack/tools/vendor/golang.org/x/sys/cpu/asm_darwin_arm64_gc.s b/hack/tools/vendor/golang.org/x/sys/cpu/asm_darwin_arm64_gc.s new file mode 100644 index 000000000000..e07fa75eb582 --- /dev/null +++ b/hack/tools/vendor/golang.org/x/sys/cpu/asm_darwin_arm64_gc.s @@ -0,0 +1,12 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build darwin && arm64 && gc + +#include "textflag.h" + +TEXT libc_sysctlbyname_trampoline<>(SB),NOSPLIT,$0-0 + JMP libc_sysctlbyname(SB) +GLOBL ·libc_sysctlbyname_trampoline_addr(SB), RODATA, $8 +DATA ·libc_sysctlbyname_trampoline_addr(SB)/8, $libc_sysctlbyname_trampoline<>(SB) diff --git a/hack/tools/vendor/golang.org/x/sys/cpu/cpu_arm64.go b/hack/tools/vendor/golang.org/x/sys/cpu/cpu_arm64.go index 6d8eb784b5f5..5fc09e2935dd 100644 --- a/hack/tools/vendor/golang.org/x/sys/cpu/cpu_arm64.go +++ b/hack/tools/vendor/golang.org/x/sys/cpu/cpu_arm64.go @@ -44,14 +44,11 @@ func initOptions() { } func archInit() { - switch runtime.GOOS { - case "freebsd": + if runtime.GOOS == "freebsd" { readARM64Registers() - case "linux", "netbsd", "openbsd", "windows": + } else { + // Most platforms don't seem to allow directly reading these registers. doinit() - default: - // Many platforms don't seem to allow reading these registers. - setMinimalFeatures() } } diff --git a/hack/tools/vendor/golang.org/x/sys/cpu/cpu_darwin_arm64.go b/hack/tools/vendor/golang.org/x/sys/cpu/cpu_darwin_arm64.go new file mode 100644 index 000000000000..0b470744a0ba --- /dev/null +++ b/hack/tools/vendor/golang.org/x/sys/cpu/cpu_darwin_arm64.go @@ -0,0 +1,67 @@ +// Copyright 2026 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 darwin && arm64 && gc + +package cpu + +func doinit() { + setMinimalFeatures() + + // The feature flags are explained in [Instruction Set Detection]. + // There are some differences between MacOS versions: + // + // MacOS 11 and 12 do not have "hw.optional" sysctl values for some of the features. + // + // MacOS 13 changed some of the naming conventions to align with ARM Architecture Reference Manual. + // For example "hw.optional.armv8_2_sha512" became "hw.optional.arm.FEAT_SHA512". + // It currently checks both to stay compatible with MacOS 11 and 12. + // The old names also work with MacOS 13, however it's not clear whether + // they will continue working with future OS releases. + // + // Once MacOS 12 is no longer supported the old names can be removed. + // + // [Instruction Set Detection]: https://developer.apple.com/documentation/kernel/1387446-sysctlbyname/determining_instruction_set_characteristics + + // Encryption, hashing and checksum capabilities + + // For the following flags there are no MacOS 11 sysctl flags. + ARM64.HasAES = true || darwinSysctlEnabled([]byte("hw.optional.arm.FEAT_AES\x00")) + ARM64.HasPMULL = true || darwinSysctlEnabled([]byte("hw.optional.arm.FEAT_PMULL\x00")) + ARM64.HasSHA1 = true || darwinSysctlEnabled([]byte("hw.optional.arm.FEAT_SHA1\x00")) + ARM64.HasSHA2 = true || darwinSysctlEnabled([]byte("hw.optional.arm.FEAT_SHA256\x00")) + + ARM64.HasSHA3 = darwinSysctlEnabled([]byte("hw.optional.armv8_2_sha3\x00")) || darwinSysctlEnabled([]byte("hw.optional.arm.FEAT_SHA3\x00")) + ARM64.HasSHA512 = darwinSysctlEnabled([]byte("hw.optional.armv8_2_sha512\x00")) || darwinSysctlEnabled([]byte("hw.optional.arm.FEAT_SHA512\x00")) + + ARM64.HasCRC32 = darwinSysctlEnabled([]byte("hw.optional.armv8_crc32\x00")) + + // Atomic and memory ordering + ARM64.HasATOMICS = darwinSysctlEnabled([]byte("hw.optional.armv8_1_atomics\x00")) || darwinSysctlEnabled([]byte("hw.optional.arm.FEAT_LSE\x00")) + ARM64.HasLRCPC = darwinSysctlEnabled([]byte("hw.optional.arm.FEAT_LRCPC\x00")) + + // SIMD and floating point capabilities + ARM64.HasFPHP = darwinSysctlEnabled([]byte("hw.optional.neon_fp16\x00")) || darwinSysctlEnabled([]byte("hw.optional.arm.FEAT_FP16\x00")) + ARM64.HasASIMDHP = darwinSysctlEnabled([]byte("hw.optional.neon_hpfp\x00")) || darwinSysctlEnabled([]byte("hw.optional.AdvSIMD_HPFPCvt\x00")) + ARM64.HasASIMDRDM = darwinSysctlEnabled([]byte("hw.optional.arm.FEAT_RDM\x00")) + ARM64.HasASIMDDP = darwinSysctlEnabled([]byte("hw.optional.arm.FEAT_DotProd\x00")) + ARM64.HasASIMDFHM = darwinSysctlEnabled([]byte("hw.optional.armv8_2_fhm\x00")) || darwinSysctlEnabled([]byte("hw.optional.arm.FEAT_FHM\x00")) + ARM64.HasI8MM = darwinSysctlEnabled([]byte("hw.optional.arm.FEAT_I8MM\x00")) + + ARM64.HasJSCVT = darwinSysctlEnabled([]byte("hw.optional.arm.FEAT_JSCVT\x00")) + ARM64.HasFCMA = darwinSysctlEnabled([]byte("hw.optional.armv8_3_compnum\x00")) || darwinSysctlEnabled([]byte("hw.optional.arm.FEAT_FCMA\x00")) + + // Miscellaneous + ARM64.HasDCPOP = darwinSysctlEnabled([]byte("hw.optional.arm.FEAT_DPB\x00")) + ARM64.HasEVTSTRM = darwinSysctlEnabled([]byte("hw.optional.arm.FEAT_ECV\x00")) + ARM64.HasDIT = darwinSysctlEnabled([]byte("hw.optional.arm.FEAT_DIT\x00")) + + // Not supported, but added for completeness + ARM64.HasCPUID = false + + ARM64.HasSM3 = false // darwinSysctlEnabled([]byte("hw.optional.arm.FEAT_SM3\x00")) + ARM64.HasSM4 = false // darwinSysctlEnabled([]byte("hw.optional.arm.FEAT_SM4\x00")) + ARM64.HasSVE = false // darwinSysctlEnabled([]byte("hw.optional.arm.FEAT_SVE\x00")) + ARM64.HasSVE2 = false // darwinSysctlEnabled([]byte("hw.optional.arm.FEAT_SVE2\x00")) +} diff --git a/hack/tools/vendor/golang.org/x/sys/cpu/cpu_darwin_arm64_other.go b/hack/tools/vendor/golang.org/x/sys/cpu/cpu_darwin_arm64_other.go new file mode 100644 index 000000000000..4ee68e38d9b9 --- /dev/null +++ b/hack/tools/vendor/golang.org/x/sys/cpu/cpu_darwin_arm64_other.go @@ -0,0 +1,29 @@ +// Copyright 2026 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 darwin && arm64 && !gc + +package cpu + +func doinit() { + setMinimalFeatures() + + ARM64.HasASIMD = true + ARM64.HasFP = true + + // Go already assumes these to be available because they were on the M1 + // and these are supported on all Apple arm64 chips. + ARM64.HasAES = true + ARM64.HasPMULL = true + ARM64.HasSHA1 = true + ARM64.HasSHA2 = true + + if runtime.GOOS != "ios" { + // Apple A7 processors do not support these, however + // M-series SoCs are at least armv8.4-a + ARM64.HasCRC32 = true // armv8.1 + ARM64.HasATOMICS = true // armv8.2 + ARM64.HasJSCVT = true // armv8.3, if HasFP + } +} diff --git a/hack/tools/vendor/golang.org/x/sys/cpu/cpu_gccgo_arm64.go b/hack/tools/vendor/golang.org/x/sys/cpu/cpu_gccgo_arm64.go index 7f1946780bd3..05913081ec68 100644 --- a/hack/tools/vendor/golang.org/x/sys/cpu/cpu_gccgo_arm64.go +++ b/hack/tools/vendor/golang.org/x/sys/cpu/cpu_gccgo_arm64.go @@ -9,3 +9,4 @@ package cpu func getisar0() uint64 { return 0 } func getisar1() uint64 { return 0 } func getpfr0() uint64 { return 0 } +func getzfr0() uint64 { return 0 } diff --git a/hack/tools/vendor/golang.org/x/sys/cpu/cpu_other_arm64.go b/hack/tools/vendor/golang.org/x/sys/cpu/cpu_other_arm64.go index ff74d7afa814..6c7c5bfd5338 100644 --- a/hack/tools/vendor/golang.org/x/sys/cpu/cpu_other_arm64.go +++ b/hack/tools/vendor/golang.org/x/sys/cpu/cpu_other_arm64.go @@ -2,8 +2,10 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -//go:build !linux && !netbsd && !openbsd && !windows && arm64 +//go:build !darwin && !linux && !netbsd && !openbsd && !windows && arm64 package cpu -func doinit() {} +func doinit() { + setMinimalFeatures() +} diff --git a/hack/tools/vendor/golang.org/x/sys/cpu/syscall_darwin_arm64_gc.go b/hack/tools/vendor/golang.org/x/sys/cpu/syscall_darwin_arm64_gc.go new file mode 100644 index 000000000000..7b4e67ff9c9e --- /dev/null +++ b/hack/tools/vendor/golang.org/x/sys/cpu/syscall_darwin_arm64_gc.go @@ -0,0 +1,54 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Minimal copy from internal/cpu and runtime to make sysctl calls. + +//go:build darwin && arm64 && gc + +package cpu + +import ( + "syscall" + "unsafe" +) + +type Errno = syscall.Errno + +// adapted from internal/cpu/cpu_arm64_darwin.go +func darwinSysctlEnabled(name []byte) bool { + out := int32(0) + nout := unsafe.Sizeof(out) + if ret := sysctlbyname(&name[0], (*byte)(unsafe.Pointer(&out)), &nout, nil, 0); ret != nil { + return false + } + return out > 0 +} + +//go:cgo_import_dynamic libc_sysctl sysctl "/usr/lib/libSystem.B.dylib" + +var libc_sysctlbyname_trampoline_addr uintptr + +// adapted from runtime/sys_darwin.go in the pattern of sysctl() above, as defined in x/sys/unix +func sysctlbyname(name *byte, old *byte, oldlen *uintptr, new *byte, newlen uintptr) error { + if _, _, err := syscall_syscall6( + libc_sysctlbyname_trampoline_addr, + uintptr(unsafe.Pointer(name)), + uintptr(unsafe.Pointer(old)), + uintptr(unsafe.Pointer(oldlen)), + uintptr(unsafe.Pointer(new)), + uintptr(newlen), + 0, + ); err != 0 { + return err + } + + return nil +} + +//go:cgo_import_dynamic libc_sysctlbyname sysctlbyname "/usr/lib/libSystem.B.dylib" + +// Implemented in the runtime package (runtime/sys_darwin.go) +func syscall_syscall6(fn, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err Errno) + +//go:linkname syscall_syscall6 syscall.syscall6 diff --git a/hack/tools/vendor/golang.org/x/sys/plan9/syscall_plan9.go b/hack/tools/vendor/golang.org/x/sys/plan9/syscall_plan9.go index d079d8116e9f..761912237fa7 100644 --- a/hack/tools/vendor/golang.org/x/sys/plan9/syscall_plan9.go +++ b/hack/tools/vendor/golang.org/x/sys/plan9/syscall_plan9.go @@ -19,13 +19,7 @@ import ( // A Note is a string describing a process note. // It implements the os.Signal interface. -type Note string - -func (n Note) Signal() {} - -func (n Note) String() string { - return string(n) -} +type Note = syscall.Note var ( Stdin = 0 diff --git a/hack/tools/vendor/golang.org/x/sys/unix/ztypes_linux.go b/hack/tools/vendor/golang.org/x/sys/unix/ztypes_linux.go index c1a467017198..45476a73c61d 100644 --- a/hack/tools/vendor/golang.org/x/sys/unix/ztypes_linux.go +++ b/hack/tools/vendor/golang.org/x/sys/unix/ztypes_linux.go @@ -593,110 +593,115 @@ const ( ) const ( - NDA_UNSPEC = 0x0 - NDA_DST = 0x1 - NDA_LLADDR = 0x2 - NDA_CACHEINFO = 0x3 - NDA_PROBES = 0x4 - NDA_VLAN = 0x5 - NDA_PORT = 0x6 - NDA_VNI = 0x7 - NDA_IFINDEX = 0x8 - NDA_MASTER = 0x9 - NDA_LINK_NETNSID = 0xa - NDA_SRC_VNI = 0xb - NTF_USE = 0x1 - NTF_SELF = 0x2 - NTF_MASTER = 0x4 - NTF_PROXY = 0x8 - NTF_EXT_LEARNED = 0x10 - NTF_OFFLOADED = 0x20 - NTF_ROUTER = 0x80 - NUD_INCOMPLETE = 0x1 - NUD_REACHABLE = 0x2 - NUD_STALE = 0x4 - NUD_DELAY = 0x8 - NUD_PROBE = 0x10 - NUD_FAILED = 0x20 - NUD_NOARP = 0x40 - NUD_PERMANENT = 0x80 - NUD_NONE = 0x0 - IFA_UNSPEC = 0x0 - IFA_ADDRESS = 0x1 - IFA_LOCAL = 0x2 - IFA_LABEL = 0x3 - IFA_BROADCAST = 0x4 - IFA_ANYCAST = 0x5 - IFA_CACHEINFO = 0x6 - IFA_MULTICAST = 0x7 - IFA_FLAGS = 0x8 - IFA_RT_PRIORITY = 0x9 - IFA_TARGET_NETNSID = 0xa - IFAL_LABEL = 0x2 - IFAL_ADDRESS = 0x1 - RT_SCOPE_UNIVERSE = 0x0 - RT_SCOPE_SITE = 0xc8 - RT_SCOPE_LINK = 0xfd - RT_SCOPE_HOST = 0xfe - RT_SCOPE_NOWHERE = 0xff - RT_TABLE_UNSPEC = 0x0 - RT_TABLE_COMPAT = 0xfc - RT_TABLE_DEFAULT = 0xfd - RT_TABLE_MAIN = 0xfe - RT_TABLE_LOCAL = 0xff - RT_TABLE_MAX = 0xffffffff - RTA_UNSPEC = 0x0 - RTA_DST = 0x1 - RTA_SRC = 0x2 - RTA_IIF = 0x3 - RTA_OIF = 0x4 - RTA_GATEWAY = 0x5 - RTA_PRIORITY = 0x6 - RTA_PREFSRC = 0x7 - RTA_METRICS = 0x8 - RTA_MULTIPATH = 0x9 - RTA_FLOW = 0xb - RTA_CACHEINFO = 0xc - RTA_TABLE = 0xf - RTA_MARK = 0x10 - RTA_MFC_STATS = 0x11 - RTA_VIA = 0x12 - RTA_NEWDST = 0x13 - RTA_PREF = 0x14 - RTA_ENCAP_TYPE = 0x15 - RTA_ENCAP = 0x16 - RTA_EXPIRES = 0x17 - RTA_PAD = 0x18 - RTA_UID = 0x19 - RTA_TTL_PROPAGATE = 0x1a - RTA_IP_PROTO = 0x1b - RTA_SPORT = 0x1c - RTA_DPORT = 0x1d - RTN_UNSPEC = 0x0 - RTN_UNICAST = 0x1 - RTN_LOCAL = 0x2 - RTN_BROADCAST = 0x3 - RTN_ANYCAST = 0x4 - RTN_MULTICAST = 0x5 - RTN_BLACKHOLE = 0x6 - RTN_UNREACHABLE = 0x7 - RTN_PROHIBIT = 0x8 - RTN_THROW = 0x9 - RTN_NAT = 0xa - RTN_XRESOLVE = 0xb - SizeofNlMsghdr = 0x10 - SizeofNlMsgerr = 0x14 - SizeofRtGenmsg = 0x1 - SizeofNlAttr = 0x4 - SizeofRtAttr = 0x4 - SizeofIfInfomsg = 0x10 - SizeofIfAddrmsg = 0x8 - SizeofIfAddrlblmsg = 0xc - SizeofIfaCacheinfo = 0x10 - SizeofRtMsg = 0xc - SizeofRtNexthop = 0x8 - SizeofNdUseroptmsg = 0x10 - SizeofNdMsg = 0xc + NDA_UNSPEC = 0x0 + NDA_DST = 0x1 + NDA_LLADDR = 0x2 + NDA_CACHEINFO = 0x3 + NDA_PROBES = 0x4 + NDA_VLAN = 0x5 + NDA_PORT = 0x6 + NDA_VNI = 0x7 + NDA_IFINDEX = 0x8 + NDA_MASTER = 0x9 + NDA_LINK_NETNSID = 0xa + NDA_SRC_VNI = 0xb + NTF_USE = 0x1 + NTF_SELF = 0x2 + NTF_MASTER = 0x4 + NTF_PROXY = 0x8 + NTF_EXT_LEARNED = 0x10 + NTF_OFFLOADED = 0x20 + NTF_ROUTER = 0x80 + NUD_INCOMPLETE = 0x1 + NUD_REACHABLE = 0x2 + NUD_STALE = 0x4 + NUD_DELAY = 0x8 + NUD_PROBE = 0x10 + NUD_FAILED = 0x20 + NUD_NOARP = 0x40 + NUD_PERMANENT = 0x80 + NUD_NONE = 0x0 + IFA_UNSPEC = 0x0 + IFA_ADDRESS = 0x1 + IFA_LOCAL = 0x2 + IFA_LABEL = 0x3 + IFA_BROADCAST = 0x4 + IFA_ANYCAST = 0x5 + IFA_CACHEINFO = 0x6 + IFA_MULTICAST = 0x7 + IFA_FLAGS = 0x8 + IFA_RT_PRIORITY = 0x9 + IFA_TARGET_NETNSID = 0xa + IFAL_LABEL = 0x2 + IFAL_ADDRESS = 0x1 + RT_SCOPE_UNIVERSE = 0x0 + RT_SCOPE_SITE = 0xc8 + RT_SCOPE_LINK = 0xfd + RT_SCOPE_HOST = 0xfe + RT_SCOPE_NOWHERE = 0xff + RT_TABLE_UNSPEC = 0x0 + RT_TABLE_COMPAT = 0xfc + RT_TABLE_DEFAULT = 0xfd + RT_TABLE_MAIN = 0xfe + RT_TABLE_LOCAL = 0xff + RT_TABLE_MAX = 0xffffffff + RTA_UNSPEC = 0x0 + RTA_DST = 0x1 + RTA_SRC = 0x2 + RTA_IIF = 0x3 + RTA_OIF = 0x4 + RTA_GATEWAY = 0x5 + RTA_PRIORITY = 0x6 + RTA_PREFSRC = 0x7 + RTA_METRICS = 0x8 + RTA_MULTIPATH = 0x9 + RTA_FLOW = 0xb + RTA_CACHEINFO = 0xc + RTA_TABLE = 0xf + RTA_MARK = 0x10 + RTA_MFC_STATS = 0x11 + RTA_VIA = 0x12 + RTA_NEWDST = 0x13 + RTA_PREF = 0x14 + RTA_ENCAP_TYPE = 0x15 + RTA_ENCAP = 0x16 + RTA_EXPIRES = 0x17 + RTA_PAD = 0x18 + RTA_UID = 0x19 + RTA_TTL_PROPAGATE = 0x1a + RTA_IP_PROTO = 0x1b + RTA_SPORT = 0x1c + RTA_DPORT = 0x1d + RTN_UNSPEC = 0x0 + RTN_UNICAST = 0x1 + RTN_LOCAL = 0x2 + RTN_BROADCAST = 0x3 + RTN_ANYCAST = 0x4 + RTN_MULTICAST = 0x5 + RTN_BLACKHOLE = 0x6 + RTN_UNREACHABLE = 0x7 + RTN_PROHIBIT = 0x8 + RTN_THROW = 0x9 + RTN_NAT = 0xa + RTN_XRESOLVE = 0xb + PREFIX_UNSPEC = 0x0 + PREFIX_ADDRESS = 0x1 + PREFIX_CACHEINFO = 0x2 + SizeofNlMsghdr = 0x10 + SizeofNlMsgerr = 0x14 + SizeofRtGenmsg = 0x1 + SizeofNlAttr = 0x4 + SizeofRtAttr = 0x4 + SizeofIfInfomsg = 0x10 + SizeofPrefixmsg = 0xc + SizeofPrefixCacheinfo = 0x8 + SizeofIfAddrmsg = 0x8 + SizeofIfAddrlblmsg = 0xc + SizeofIfaCacheinfo = 0x10 + SizeofRtMsg = 0xc + SizeofRtNexthop = 0x8 + SizeofNdUseroptmsg = 0x10 + SizeofNdMsg = 0xc ) type NlMsghdr struct { @@ -735,6 +740,22 @@ type IfInfomsg struct { Change uint32 } +type Prefixmsg struct { + Family uint8 + Pad1 uint8 + Pad2 uint16 + Ifindex int32 + Type uint8 + Len uint8 + Flags uint8 + Pad3 uint8 +} + +type PrefixCacheinfo struct { + Preferred_time uint32 + Valid_time uint32 +} + type IfAddrmsg struct { Family uint8 Prefixlen uint8 diff --git a/hack/tools/vendor/golang.org/x/sys/windows/aliases.go b/hack/tools/vendor/golang.org/x/sys/windows/aliases.go index 16f90560a23a..96317966e525 100644 --- a/hack/tools/vendor/golang.org/x/sys/windows/aliases.go +++ b/hack/tools/vendor/golang.org/x/sys/windows/aliases.go @@ -8,5 +8,6 @@ package windows import "syscall" +type Signal = syscall.Signal type Errno = syscall.Errno type SysProcAttr = syscall.SysProcAttr diff --git a/hack/tools/vendor/golang.org/x/sys/windows/registry/key.go b/hack/tools/vendor/golang.org/x/sys/windows/registry/key.go index 39aeeb644f55..7cc6ff3afa09 100644 --- a/hack/tools/vendor/golang.org/x/sys/windows/registry/key.go +++ b/hack/tools/vendor/golang.org/x/sys/windows/registry/key.go @@ -198,7 +198,20 @@ type KeyInfo struct { // ModTime returns the key's last write time. func (ki *KeyInfo) ModTime() time.Time { - return time.Unix(0, ki.lastWriteTime.Nanoseconds()) + lastHigh, lastLow := ki.lastWriteTime.HighDateTime, ki.lastWriteTime.LowDateTime + // 100-nanosecond intervals since January 1, 1601 + hsec := uint64(lastHigh)<<32 + uint64(lastLow) + // Convert _before_ gauging; the nanosecond difference between Epoch (00:00:00 + // UTC, January 1, 1970) and Filetime's zero offset (January 1, 1601) is out + // of bounds for int64: -11644473600*1e7*1e2 < math.MinInt64 + sec := int64(hsec/1e7) - 11644473600 + nsec := int64(hsec%1e7) * 100 + return time.Unix(sec, nsec) +} + +// modTimeZero reports whether the key's last write time is zero. +func (ki *KeyInfo) modTimeZero() bool { + return ki.lastWriteTime.LowDateTime == 0 && ki.lastWriteTime.HighDateTime == 0 } // Stat retrieves information about the open key k. diff --git a/hack/tools/vendor/golang.org/x/sys/windows/syscall_windows.go b/hack/tools/vendor/golang.org/x/sys/windows/syscall_windows.go index 738a9f2121b9..d766436587f4 100644 --- a/hack/tools/vendor/golang.org/x/sys/windows/syscall_windows.go +++ b/hack/tools/vendor/golang.org/x/sys/windows/syscall_windows.go @@ -1490,20 +1490,6 @@ func Getgid() (gid int) { return -1 } func Getegid() (egid int) { return -1 } func Getgroups() (gids []int, err error) { return nil, syscall.EWINDOWS } -type Signal int - -func (s Signal) Signal() {} - -func (s Signal) String() string { - if 0 <= s && int(s) < len(signals) { - str := signals[s] - if str != "" { - return str - } - } - return "signal " + itoa(int(s)) -} - func LoadCreateSymbolicLink() error { return procCreateSymbolicLinkW.Find() } diff --git a/hack/tools/vendor/golang.org/x/tools/go/analysis/analysis.go b/hack/tools/vendor/golang.org/x/tools/go/analysis/analysis.go index a7df4d1fe4e7..786c29d55de5 100644 --- a/hack/tools/vendor/golang.org/x/tools/go/analysis/analysis.go +++ b/hack/tools/vendor/golang.org/x/tools/go/analysis/analysis.go @@ -11,6 +11,7 @@ import ( "go/token" "go/types" "reflect" + "time" ) // An Analyzer describes an analysis function and its options. @@ -250,7 +251,19 @@ type Fact interface { // A Module describes the module to which a package belongs. type Module struct { - Path string // module path - Version string // module version ("" if unknown, such as for workspace modules) - GoVersion string // go version used in module (e.g. "go1.22.0") + Path string // module path + Version string // module version ("" if unknown, such as for workspace modules) + Replace *Module // replaced by this module + Time *time.Time // time version was created + Main bool // is this the main module? + Indirect bool // is this module only an indirect dependency of main module? + Dir string // directory holding files for this module, if any + GoMod string // path to go.mod file used when loading this module, if any + GoVersion string // go version used in module (e.g. "go1.22.0") + Error *ModuleError // error loading module +} + +// ModuleError holds errors loading a module. +type ModuleError struct { + Err string // the error itself } diff --git a/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/lostcancel/lostcancel.go b/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/lostcancel/lostcancel.go index 28a5f6cd9367..dfc431367965 100644 --- a/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/lostcancel/lostcancel.go +++ b/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/lostcancel/lostcancel.go @@ -16,7 +16,6 @@ import ( "golang.org/x/tools/go/ast/inspector" "golang.org/x/tools/go/cfg" "golang.org/x/tools/internal/analysis/analyzerutil" - "golang.org/x/tools/internal/astutil" "golang.org/x/tools/internal/typesinternal" ) @@ -84,7 +83,7 @@ func runFunc(pass *analysis.Pass, node ast.Node) { // {FuncDecl,FuncLit,CallExpr,SelectorExpr}. // Find the set of cancel vars to analyze. - astutil.PreorderStack(node, nil, func(n ast.Node, stack []ast.Node) bool { + ast.PreorderStack(node, nil, func(n ast.Node, stack []ast.Node) bool { if _, ok := n.(*ast.FuncLit); ok && len(stack) > 0 { return false // don't stray into nested functions } diff --git a/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/modernize/atomic.go b/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/modernize/atomic.go new file mode 100644 index 000000000000..3293065c1ad1 --- /dev/null +++ b/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/modernize/atomic.go @@ -0,0 +1,255 @@ +// Copyright 2026 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 modernize + +import ( + "fmt" + "go/ast" + "go/token" + "go/types" + "strings" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" + "golang.org/x/tools/go/ast/edge" + "golang.org/x/tools/go/ast/inspector" + "golang.org/x/tools/go/types/typeutil" + "golang.org/x/tools/internal/analysis/analyzerutil" + typeindexanalyzer "golang.org/x/tools/internal/analysis/typeindex" + "golang.org/x/tools/internal/astutil" + "golang.org/x/tools/internal/goplsexport" + "golang.org/x/tools/internal/refactor" + "golang.org/x/tools/internal/typesinternal" + "golang.org/x/tools/internal/typesinternal/typeindex" + "golang.org/x/tools/internal/versions" +) + +var atomicAnalyzer = &analysis.Analyzer{ + Name: "atomic", + Doc: analyzerutil.MustExtractDoc(doc, "atomic"), + Requires: []*analysis.Analyzer{ + inspect.Analyzer, + typeindexanalyzer.Analyzer, + }, + Run: runAtomic, + URL: "https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/modernize#atomic", +} + +func init() { + // Export to gopls until this is a published modernizer. + goplsexport.AtomicModernizer = atomicAnalyzer +} + +// TODO(mkalil): support the Pointer variants. +// Consider the following function signatures for pointer loading: +// func LoadPointer(addr *unsafe.Pointer) (val unsafe.Pointer) +// func (x *Pointer[T]) Load() *T +// Since the former uses *unsafe.Pointer while the latter uses *Pointer[T], +// we would need to determine the type T to apply the transformation, and there +// will be additional edits required to remove any *unsafe.Pointer casts. +// "LoadPointer", "StorePointer", "SwapPointer", "CompareAndSwapPointer" + +// sync/atomic functions of interest. Some added in go1.19, some added in go1.23. +var syncAtomicFuncs = []string{ + // Added in go1.19. + "AddInt32", "AddInt64", "AddUint32", "AddUint64", "AddUintptr", + "CompareAndSwapInt32", "CompareAndSwapInt64", "CompareAndSwapUint32", "CompareAndSwapUint64", "CompareAndSwapUintptr", + "LoadInt32", "LoadInt64", "LoadUint32", "LoadUint64", "LoadUintptr", + "StoreInt32", "StoreInt64", "StoreUint32", "StoreUint64", "StoreUintptr", + "SwapInt32", "SwapInt64", "SwapUint32", "SwapUint64", "SwapUintptr", + // Added in go1.23. + "AndInt32", "AndInt64", "AndUint32", "AndUint64", "AndUintptr", + "OrInt32", "OrInt64", "OrUint32", "OrUint64", "OrUintptr", +} + +func runAtomic(pass *analysis.Pass) (any, error) { + if !typesinternal.Imports(pass.Pkg, "sync/atomic") { + return nil, nil // doesn't directly import sync/atomic + } + + var ( + index = pass.ResultOf[typeindexanalyzer.Analyzer].(*typeindex.Index) + info = pass.TypesInfo + ) + + // Gather all candidate variables v appearing + // in calls to atomic.AddInt32(&v, ...) et al. + var ( + atomicPkg *types.Package + vars = make(map[*types.Var]string) // maps candidate vars v to the name of the call they appear in + ) + for _, funcName := range syncAtomicFuncs { + obj := index.Object("sync/atomic", funcName) + if obj == nil { + continue + } + atomicPkg = obj.Pkg() + for curCall := range index.Calls(obj) { + call := curCall.Node().(*ast.CallExpr) + if unary, ok := call.Args[0].(*ast.UnaryExpr); ok && unary.Op == token.AND { + var v *types.Var + switch x := unary.X.(type) { + case *ast.Ident: + v, _ = info.Uses[x].(*types.Var) + case *ast.SelectorExpr: + if seln, ok := info.Selections[x]; ok { + v, _ = seln.Obj().(*types.Var) + } + } + if v != nil && !v.Exported() { + // v must be a non-exported package or local var, or a struct field. + switch v.Kind() { + case types.RecvVar, types.ParamVar, types.ResultVar: + continue // fix would change func signature + } + vars[v] = funcName + } + } + } + } + + // Check that all uses of each candidate variable + // appear in calls of the form atomic.AddInt32(&v, ...). +nextvar: + for v, funcName := range vars { + var edits []analysis.TextEdit + fixFiles := make(map[*ast.File]bool) // unique files involved in the current fix + + // Check the form of the declaration: var v int or struct { v int } + def, ok := index.Def(v) + if !ok { + continue + } + var ( + typ ast.Expr + names []*ast.Ident + ) + switch parent := def.Parent().Node().(type) { + case *ast.Field: // struct { v int } + names = parent.Names + typ = parent.Type + case *ast.ValueSpec: // var v int + if len(parent.Values) > 0 { + // e.g. var v int = 5 + // skip because rewriting as `var v atomic.Int32 = 5` is invalid + continue + } + names = parent.Names + typ = parent.Type + } + if len(names) != 1 || typ == nil { + continue // v is not the sole var declared here (e.g. var x, y int32); or no explicit type + } + oldType := info.TypeOf(typ) // e.g. "int32" + newType := strings.Title(oldType.Underlying().String()) // e.g. "Int32" + + // Get package prefix to avoid shadowing. + file := astutil.EnclosingFile(def) + pkgPrefix, impEdits := refactor.AddImport(pass.TypesInfo, file, "atomic", "sync/atomic", "", def.Node().Pos()) + if len(impEdits) > 0 { + panic("unexpected import edits") // atomic PkgName should be in scope already + } + // Edit the type. + // + // var v int32 + // ------------ + // var v atomic.Int32 + edits = append(edits, analysis.TextEdit{ + Pos: typ.Pos(), + End: typ.End(), + NewText: fmt.Appendf(nil, "%s%s", pkgPrefix, newType), + }) + fixFiles[file] = true + + // Each valid use is an Ident v or Selector expr.v within an atomic.F(&...) call. + var validUses []inspector.Cursor + for cur := range index.Uses(v) { + if v.IsField() && cur.ParentEdgeKind() == edge.KeyValueExpr_Key { + continue nextvar // we cannot fix initial an value assignment T{v: 1} + } + if cur.ParentEdgeKind() == edge.SelectorExpr_Sel { + cur = cur.Parent() // ascend from v to expr.v + } + // Inv: cur is the l-value expression denoting v. + // v must appear beneath atomic.AddInt32(&v, ...) call. + valid := false + if cur.ParentEdgeKind() == edge.UnaryExpr_X && + cur.Parent().Node().(*ast.UnaryExpr).Op == token.AND { + if ek, idx := cur.Parent().ParentEdge(); ek == edge.CallExpr_Args && idx == 0 { + curCall := cur.Parent().Parent() + call := curCall.Node().(*ast.CallExpr) + if fn, ok := typeutil.Callee(info, call).(*types.Func); ok && fn.Pkg() == atomicPkg { + valid = true + } + } + } + + if !valid { + // More complex case: reject candidate. + // + // For example, cur may be an unsynchronized load (e.g. v == 0). To + // avoid a type conversion error, we'd have to rewrite this as + // v.Load(). However, this is an invalid rewrite: if the program is + // mixing atomic operations with unsynchronized reads, the author + // might have accidentally introduced a data race and the suggested + // fix could obscure the mistake. Or, if the usage is intentional, + // rewriting may result in a behavior change. + continue nextvar + } + validUses = append(validUses, cur) + } + + for _, cur := range validUses { + vexpr := cur.Node() + call := cur.Parent().Parent().Node().(*ast.CallExpr) + fn := typeutil.Callee(info, call).(*types.Func) + // atomic.AddInt32(&v, ...) + // ----------------- ----- + // v.Add(...) + after := vexpr.End() // LoadInt32(&v⁁) + if len(call.Args) > 1 { + after = call.Args[1].Pos() // AddInt32(&v, ⁁...) + } + verb := strings.TrimSuffix(fn.Name(), newType) // "AddInt32" => "Add" + edits = append(edits, []analysis.TextEdit{ + { + Pos: call.Pos(), + End: vexpr.Pos(), + }, + { + Pos: vexpr.End(), + End: after, + NewText: fmt.Appendf(nil, ".%s(", verb), + }, + }...) + fixFiles[astutil.EnclosingFile(cur)] = true + } + + // Check minimum Go version: go1.19, or 1.23 for the And/Or functions. + if !(analyzerutil.FileUsesGoVersion(pass, file, versions.Go1_19) || + analyzerutil.FileUsesGoVersion(pass, file, versions.Go1_23) && + (strings.HasPrefix(funcName, "And") || strings.HasPrefix(funcName, "Or"))) { + continue + } + + // Skip if v is not local and the package has ignored files as it may be + // an incomplete transformation. + if !isLocal(v) && len(pass.IgnoredFiles) > 0 { + continue + } + + pass.Report(analysis.Diagnostic{ + Pos: names[0].Pos(), + End: typ.End(), + Message: fmt.Sprintf("var %s %s may be simplified using atomic.%s", v.Name(), oldType, newType), + SuggestedFixes: []analysis.SuggestedFix{{ + Message: fmt.Sprintf("Replace %s by atomic.%s", oldType, newType), + TextEdits: edits, + }}, + }) + } + + return nil, nil +} diff --git a/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/modernize/doc.go b/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/modernize/doc.go index 0425faf8d475..826f9f49e9eb 100644 --- a/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/modernize/doc.go +++ b/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/modernize/doc.go @@ -65,6 +65,26 @@ This analyzer is currently disabled by default as the transformation does not preserve the nilness of the base slice in all cases; see https://go.dev/issue/73557. +# Analyzer atomic + +atomic: replace basic types in sync/atomic calls with atomic types + +The atomic analyzer suggests replacing the primitive sync/atomic functions with +the strongly typed atomic wrapper types introduced in Go1.19 (e.g. +atomic.Int32). For example, + + var x int32 + atomic.AddInt32(&x, 1) + +would become + + var x atomic.Int32 + x.Add(1) + +The atomic types are safer because they don't allow non-atomic access, which is +a common source of bugs. These types also resolve memory alignment issues that +plagued the old atomic functions on 32-bit architectures. + # Analyzer bloop bloop: replace for-range over b.N with b.Loop @@ -263,11 +283,15 @@ is known at compile time, for example: reflect.TypeOf(uint32(0)) -> reflect.TypeFor[uint32]() reflect.TypeOf((*ast.File)(nil)) -> reflect.TypeFor[*ast.File]() -It also offers a fix to simplify the construction below, which uses +It also offers a fix to simplify the constructions below, which use reflect.TypeOf to return the runtime type for an interface type, reflect.TypeOf((*io.Reader)(nil)).Elem() +or: + + reflect.TypeOf([]io.Reader(nil)).Elem() + to: reflect.TypeFor[io.Reader]() @@ -460,14 +484,15 @@ is replaced by: This avoids quadratic memory allocation and improves performance. -The analyzer requires that all references to s except the final one +The analyzer requires that all references to s before the final uses are += operations. To avoid warning about trivial cases, at least one must appear within a loop. The variable s must be a local variable, not a global or parameter. -The sole use of the finished string must be the last reference to the -variable s. (It may appear within an intervening loop or function literal, -since even s.String() is called repeatedly, it does not allocate memory.) +All uses of the finished string must come after the last += operation. +Each such use will be replaced by a call to strings.Builder's String method. +(These may appear within an intervening loop or function literal, since even +if s.String() is called repeatedly, it does not allocate memory.) Often the addend is a call to fmt.Sprintf, as in this example: diff --git a/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/modernize/errorsastype.go b/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/modernize/errorsastype.go index 6e1070fd12cc..8603d5471212 100644 --- a/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/modernize/errorsastype.go +++ b/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/modernize/errorsastype.go @@ -125,22 +125,11 @@ func errorsastype(pass *analysis.Pass) (any, error) { errtype := types.TypeString(v.Type(), qual) // Choose a name for the "ok" variable. - // TODO(adonovan): this pattern also appears in stditerators, - // and is wanted elsewhere; factor. - okName := "ok" - if okVar := lookup(info, curCall, "ok"); okVar != nil { - // The name 'ok' is already declared, but - // don't choose a fresh name unless okVar - // is also used within the if-statement. - curIf := curCall.Parent() - for curUse := range index.Uses(okVar) { - if curIf.Contains(curUse) { - scope := info.Scopes[curIf.Node().(*ast.IfStmt)] - okName = refactor.FreshName(scope, v.Pos(), "ok") - break - } - } - } + // We generate a new name only if 'ok' is already declared at + // curCall and it also used within the if-statement. + curIf := curCall.Parent() + ifScope := info.Scopes[curIf.Node().(*ast.IfStmt)] + okName := freshName(info, index, ifScope, v.Pos(), curCall, curIf, token.NoPos, "ok") pass.Report(analysis.Diagnostic{ Pos: call.Fun.Pos(), diff --git a/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/modernize/fmtappendf.go b/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/modernize/fmtappendf.go index 389f7034663a..821065413196 100644 --- a/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/modernize/fmtappendf.go +++ b/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/modernize/fmtappendf.go @@ -7,6 +7,7 @@ package modernize import ( "fmt" "go/ast" + "go/constant" "go/types" "strings" @@ -16,6 +17,7 @@ import ( "golang.org/x/tools/internal/analysis/analyzerutil" typeindexanalyzer "golang.org/x/tools/internal/analysis/typeindex" "golang.org/x/tools/internal/astutil" + "golang.org/x/tools/internal/fmtstr" "golang.org/x/tools/internal/typesinternal/typeindex" "golang.org/x/tools/internal/versions" ) @@ -45,10 +47,24 @@ func fmtappendf(pass *analysis.Pass) (any, error) { if ek, idx := curCall.ParentEdge(); ek == edge.CallExpr_Args && idx == 0 { // Is parent a T(fmt.SprintX(...)) conversion? conv := curCall.Parent().Node().(*ast.CallExpr) - tv := pass.TypesInfo.Types[conv.Fun] - if tv.IsType() && types.Identical(tv.Type, byteSliceType) && - analyzerutil.FileUsesGoVersion(pass, astutil.EnclosingFile(curCall), versions.Go1_19) { + info := pass.TypesInfo + tv := info.Types[conv.Fun] + if tv.IsType() && types.Identical(tv.Type, byteSliceType) { // Have: []byte(fmt.SprintX(...)) + if len(call.Args) == 0 { + continue + } + // fmt.Sprint(f) and fmt.Append(f) have different nil semantics + // when the format produces an empty string: + // []byte(fmt.Sprintf("")) returns an empty but non-nil + // []byte{}, while fmt.Appendf(nil, "") returns nil) so we + // should skip these cases. + if fn.Name() == "Sprint" || fn.Name() == "Sprintf" { + format := info.Types[call.Args[0]].Value + if format != nil && mayFormatEmpty(constant.StringVal(format)) { + continue + } + } // Find "Sprint" identifier. var id *ast.Ident @@ -62,13 +78,18 @@ func fmtappendf(pass *analysis.Pass) (any, error) { old, new := fn.Name(), strings.Replace(fn.Name(), "Sprint", "Append", 1) edits := []analysis.TextEdit{ { - // delete "[]byte(" + // Delete "[]byte(", including any spaces before the first argument. Pos: conv.Pos(), - End: conv.Lparen + 1, + End: conv.Args[0].Pos(), // always exactly one argument in a valid byte slice conversion }, { - // remove ")" - Pos: conv.Rparen, + // Delete ")", including any non-args (space or + // commas) that come before the right parenthesis. + // Leaving an extra comma here produces invalid + // code. (See golang/go#74709) + // Unfortunately, this and the edit above may result + // in deleting some comments. + Pos: conv.Args[0].End(), End: conv.Rparen + 1, }, { @@ -81,19 +102,8 @@ func fmtappendf(pass *analysis.Pass) (any, error) { NewText: []byte("nil, "), }, } - if len(conv.Args) == 1 { - arg := conv.Args[0] - // Determine if we have T(fmt.SprintX(...)). If so, delete the non-args - // that come before the right parenthesis. Leaving an - // extra comma here produces invalid code. (See - // golang/go#74709) - if arg.End() < conv.Rparen { - edits = append(edits, analysis.TextEdit{ - Pos: arg.End(), - End: conv.Rparen, - }) - } + if !analyzerutil.FileUsesGoVersion(pass, astutil.EnclosingFile(curCall), versions.Go1_19) { + continue } pass.Report(analysis.Diagnostic{ Pos: conv.Pos(), @@ -110,3 +120,43 @@ func fmtappendf(pass *analysis.Pass) (any, error) { } return nil, nil } + +// mayFormatEmpty reports whether fmt.Sprintf might produce an empty string. +// It returns false in the following two cases: +// 1. formatStr contains non-operation characters. +// 2. formatStr contains formatting verbs besides s, v, x, X (verbs which may +// produce empty results) +// +// In all other cases it returns true. +func mayFormatEmpty(formatStr string) bool { + if formatStr == "" { + return true + } + operations, err := fmtstr.Parse(formatStr, 0) + if err != nil { + // If formatStr is malformed, the printf analyzer will report a + // diagnostic, so we can ignore this error. + // Calling Parse on a string without % formatters also returns an error, + // in which case we can safely return false. + return false + } + totalOpsLen := 0 + for _, op := range operations { + totalOpsLen += len(op.Text) + if !strings.ContainsRune("svxX", rune(op.Verb.Verb)) && op.Prec.Fixed != 0 { + // A non [s, v, x, X] formatter with non-zero precision cannot + // produce an empty string. + return false + } + } + // If the format string contains non-operation characters, it cannot produce + // the empty string. + if totalOpsLen != len(formatStr) { + return false + } + // If we get here, it means that all formatting verbs are %s, %v, %x, %X, + // and there are no additional non-operation characters. We conservatively + // report that this may format as an empty string, ignoring uses of + // precision and the values of the formatter args. + return true +} diff --git a/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/modernize/minmax.go b/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/modernize/minmax.go index a77ed8389936..b4b8dba3d159 100644 --- a/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/modernize/minmax.go +++ b/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/modernize/minmax.go @@ -147,6 +147,13 @@ func minmax(pass *analysis.Pass) (any, error) { lhs0 := fassign.Lhs[0] rhs0 := fassign.Rhs[0] + // If the assignment occurs within a select + // comms clause (like "case lhs0 := <-rhs0:"), + // there's no way of rewriting it into a min/max call. + if prev.ParentEdgeKind() == edge.CommClause_Comm { + return + } + if astutil.EqualSyntax(lhs, lhs0) { if astutil.EqualSyntax(rhs, a) && (astutil.EqualSyntax(rhs0, b) || astutil.EqualSyntax(lhs0, b)) { sign = +sign diff --git a/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/modernize/modernize.go b/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/modernize/modernize.go index ef28a40d1c24..0c388e96b792 100644 --- a/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/modernize/modernize.go +++ b/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/modernize/modernize.go @@ -20,6 +20,8 @@ import ( "golang.org/x/tools/go/ast/edge" "golang.org/x/tools/go/ast/inspector" "golang.org/x/tools/internal/analysis/analyzerutil" + "golang.org/x/tools/internal/refactor" + "golang.org/x/tools/internal/typesinternal/typeindex" "golang.org/x/tools/internal/moreiters" "golang.org/x/tools/internal/packagepath" @@ -33,6 +35,7 @@ var doc string // Suite lists all modernize analyzers. var Suite = []*analysis.Analyzer{ AnyAnalyzer, + atomicAnalyzer, // AppendClippedAnalyzer, // not nil-preserving! // BLoopAnalyzer, // may skew benchmark results, see golang/go#74967 FmtAppendfAnalyzer, @@ -144,3 +147,37 @@ func lookup(info *types.Info, cur inspector.Cursor, name string) types.Object { } func first[T any](x T, _ any) T { return x } + +// freshName returns a fresh name at the given pos and scope based on preferredName. +// It generates a new name using refactor.FreshName only if: +// (a) the preferred name is already defined at definedCur, and +// (b) there are references to it from within usedCur. +// If useAfterPos.IsValid(), the references must be after +// useAfterPos within usedCur in order to warrant a fresh name. +// Otherwise, it returns preferredName, since shadowing is valid in this case. +// (declaredCur and usedCur may be identical in some use cases). +func freshName(info *types.Info, index *typeindex.Index, scope *types.Scope, pos token.Pos, defCur inspector.Cursor, useCur inspector.Cursor, useAfterPos token.Pos, preferredName string) string { + obj := lookup(info, defCur, preferredName) + if obj == nil { + // preferredName has not been declared here. + return preferredName + } + for use := range index.Uses(obj) { + if useCur.Contains(use) && use.Node().Pos() >= useAfterPos { + return refactor.FreshName(scope, pos, preferredName) + } + } + // Name is taken but not used in the given block; shadowing is acceptable. + return preferredName +} + +// isLocal reports whether obj is local to some function. +// Precondition: not a struct field or interface method. +func isLocal(obj types.Object) bool { + // [... 5=stmt 4=func 3=file 2=pkg 1=universe] + var depth int + for scope := obj.Parent(); scope != nil; scope = scope.Parent() { + depth++ + } + return depth >= 4 +} diff --git a/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/modernize/rangeint.go b/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/modernize/rangeint.go index 257f9e9ec872..03c7fd4f3f9b 100644 --- a/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/modernize/rangeint.go +++ b/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/modernize/rangeint.go @@ -18,7 +18,6 @@ import ( "golang.org/x/tools/internal/analysis/analyzerutil" typeindexanalyzer "golang.org/x/tools/internal/analysis/typeindex" "golang.org/x/tools/internal/astutil" - "golang.org/x/tools/internal/moreiters" "golang.org/x/tools/internal/typesinternal" "golang.org/x/tools/internal/typesinternal/typeindex" "golang.org/x/tools/internal/versions" @@ -142,15 +141,12 @@ func rangeint(pass *analysis.Pass) (any, error) { // Find references to i within the loop body. v := info.ObjectOf(index).(*types.Var) - // TODO(adonovan): use go1.25 v.Kind() == types.PackageVar - if typesinternal.IsPackageLevel(v) { + switch v.Kind() { + case types.PackageVar: continue nextLoop - } - - // If v is a named result, it is implicitly - // used after the loop (go.dev/issue/76880). - // TODO(adonovan): use go1.25 v.Kind() == types.ResultVar. - if moreiters.Contains(enclosingSignature(curLoop, info).Results().Variables(), v) { + case types.ResultVar: + // If v is a named result, it is implicitly + // used after the loop (go.dev/issue/76880). continue nextLoop } @@ -230,7 +226,7 @@ func rangeint(pass *analysis.Pass) (any, error) { // such as "const limit = 1e3", its effective type may // differ between the two forms. // In a for loop, it must be comparable with int i, - // for i := 0; i < limit; i++ + // for i := 0; i < limit; i++ {} // but in a range loop it would become a float, // for i := range limit {} // which is a type error. We need to convert it to int @@ -249,9 +245,24 @@ func rangeint(pass *analysis.Pass) (any, error) { beforeLimit, afterLimit = fmt.Sprintf("%s(", types.TypeString(tVar, qual)), ")" info2 := &types.Info{Types: make(map[ast.Expr]types.TypeAndValue)} if types.CheckExpr(pass.Fset, pass.Pkg, limit.Pos(), limit, info2) == nil { - tLimit := types.Default(info2.TypeOf(limit)) - if types.AssignableTo(tLimit, tVar) { - beforeLimit, afterLimit = "", "" + tLimit := info2.TypeOf(limit) + // Eliminate conversion when safe. + // + // Redundant conversions are not only unsightly but may in some cases cause + // architecture-specific types (e.g. syscall.Timespec.Nsec) to be inserted + // into otherwise portable files. + // + // The operand must have an integer type (not, say, '1e6') + // even when assigning to an existing integer variable. + if isInteger(tLimit) { + // When declaring a new var from an untyped limit, + // the limit's default type is what matters. + if init.Tok != token.ASSIGN { + tLimit = types.Default(tLimit) + } + if types.AssignableTo(tLimit, tVar) { + beforeLimit, afterLimit = "", "" + } } } } diff --git a/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/modernize/reflect.go b/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/modernize/reflect.go index 1dca2be37447..1e9a54bd53f4 100644 --- a/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/modernize/reflect.go +++ b/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/modernize/reflect.go @@ -47,6 +47,14 @@ func reflecttypefor(pass *analysis.Pass) (any, error) { // Have: reflect.TypeOf(expr) expr := call.Args[0] + + // reflect.TypeFor cannot be instantiated with an untyped nil. + // We use type information rather than checking the identifier name + // to correctly handle edge cases where "nil" is shadowed (e.g. nil := "nil"). + if info.Types[expr].IsNil() { + continue + } + if !typesinternal.NoEffects(info, expr) { continue // don't eliminate operand: may have effects } @@ -54,24 +62,30 @@ func reflecttypefor(pass *analysis.Pass) (any, error) { t := info.TypeOf(expr) var edits []analysis.TextEdit - // Special case for TypeOf((*T)(nil)).Elem(), - // needed when T is an interface type. + // Special cases for TypeOf((*T)(nil)).Elem(), and + // TypeOf([]T(nil)).Elem(), needed when T is an interface type. if curCall.ParentEdgeKind() == edge.SelectorExpr_X { curSel := unparenEnclosing(curCall).Parent() if curSel.ParentEdgeKind() == edge.CallExpr_Fun { - call2 := unparenEnclosing(curSel).Parent().Node().(*ast.CallExpr) + call2 := unparenEnclosing(curSel).Parent().Node().(*ast.CallExpr) // potentially .Elem() obj := typeutil.Callee(info, call2) if typesinternal.IsMethodNamed(obj, "reflect", "Type", "Elem") { - if ptr, ok := t.(*types.Pointer); ok { + // reflect.TypeOf(expr).Elem() + // ------- + // reflect.TypeOf(expr) + removeElem := []analysis.TextEdit{{ + Pos: call.End(), + End: call2.End(), + }} + switch typ := t.(type) { + case *types.Pointer: // Have: TypeOf(expr).Elem() where expr : *T - t = ptr.Elem() - // reflect.TypeOf(expr).Elem() - // ------- - // reflect.TypeOf(expr) - edits = []analysis.TextEdit{{ - Pos: call.End(), - End: call2.End(), - }} + t = typ.Elem() + edits = removeElem + case *types.Slice: + // Have: TypeOf(expr).Elem() where expr : []T + t = typ.Elem() + edits = removeElem } } } diff --git a/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/modernize/slicescontains.go b/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/modernize/slicescontains.go index 3b3268526689..19e59783127d 100644 --- a/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/modernize/slicescontains.go +++ b/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/modernize/slicescontains.go @@ -231,7 +231,9 @@ func slicescontains(pass *analysis.Pass) (any, error) { // that might affected by melting down the loop. // // TODO(adonovan): relax check by analyzing branch target. + numBodyStmts := 0 for curBodyStmt := range curBody.Children() { + numBodyStmts += 1 if curBodyStmt != curLastStmt { for range curBodyStmt.Preorder((*ast.BranchStmt)(nil), (*ast.ReturnStmt)(nil)) { return @@ -292,7 +294,16 @@ func slicescontains(pass *analysis.Pass) (any, error) { case *ast.BranchStmt: if lastStmt.Tok == token.BREAK && lastStmt.Label == nil { // unlabeled break // Have: for ... { if ... { stmts; break } } - + if numBodyStmts == 1 { + // If the only stmt in the body is an unlabeled "break" that + // will get deleted in the fix, don't suggest a fix, as it + // produces confusing code: + // if slices.Contains(slice, f) {} + // Explicitly discarding the result isn't much better: + // _ = slices.Contains(slice, f) // just for effects + // See https://go.dev/issue/77677. + return + } var prevStmt ast.Stmt // previous statement to range (if any) if curPrev, ok := curRange.PrevSibling(); ok { // If the RangeStmt's previous sibling is a Stmt, diff --git a/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/modernize/stditerators.go b/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/modernize/stditerators.go index 1d1a9ca3ba74..86e1c8fd421b 100644 --- a/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/modernize/stditerators.go +++ b/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/modernize/stditerators.go @@ -18,7 +18,6 @@ import ( typeindexanalyzer "golang.org/x/tools/internal/analysis/typeindex" "golang.org/x/tools/internal/astutil" "golang.org/x/tools/internal/goplsexport" - "golang.org/x/tools/internal/refactor" "golang.org/x/tools/internal/stdlib" "golang.org/x/tools/internal/typesinternal/typeindex" ) @@ -182,22 +181,9 @@ func stditerators(pass *analysis.Pass) (any, error) { } loop := curBody.Parent().Node() - - // Choose a fresh name only if - // (a) the preferred name is already declared here, and - // (b) there are references to it from the loop body. - // TODO(adonovan): this pattern also appears in errorsastype, - // and is wanted elsewhere; factor. - name := row.elemname - if v := lookup(info, curBody, name); v != nil { - // is it free in body? - for curUse := range index.Uses(v) { - if curBody.Contains(curUse) { - name = refactor.FreshName(info.Scopes[loop], loop.Pos(), name) - break - } - } - } + // We generate a new name only if the preferred name is already declared here + // and is used within the loop body. + name := freshName(info, index, info.Scopes[loop], loop.Pos(), curBody, curBody, token.NoPos, row.elemname) return name, nil } diff --git a/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/modernize/stringsbuilder.go b/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/modernize/stringsbuilder.go index a6c2c1f86ef2..e89baa9b0e90 100644 --- a/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/modernize/stringsbuilder.go +++ b/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/modernize/stringsbuilder.go @@ -22,7 +22,6 @@ import ( typeindexanalyzer "golang.org/x/tools/internal/analysis/typeindex" "golang.org/x/tools/internal/astutil" "golang.org/x/tools/internal/refactor" - "golang.org/x/tools/internal/typesinternal" "golang.org/x/tools/internal/typesinternal/typeindex" ) @@ -57,7 +56,7 @@ func stringsbuilder(pass *analysis.Pass) (any, error) { assign := curAssign.Node().(*ast.AssignStmt) if assign.Tok == token.ADD_ASSIGN && is[*ast.Ident](assign.Lhs[0]) { if v, ok := pass.TypesInfo.Uses[assign.Lhs[0].(*ast.Ident)].(*types.Var); ok && - !typesinternal.IsPackageLevel(v) && // TODO(adonovan): in go1.25, use v.Kind() == types.LocalVar && + v.Kind() == types.LocalVar && types.Identical(v.Type(), builtinString.Type()) { candidates[v] = true } @@ -254,8 +253,8 @@ nextcand: // var s string // for ... { s += expr } // - // - The final use of s must be as an rvalue (e.g. use(s), not &s). - // This will become s.String(). + // - All uses of s after the last += must be rvalue uses (e.g. use(s), not &s). + // Each of these will become s.String(). // // Perhaps surprisingly, it is fine for there to be an // intervening loop or lambda w.r.t. the declaration of s: @@ -270,7 +269,7 @@ nextcand: var ( numLoopAssigns int // number of += assignments within a loop loopAssign *ast.AssignStmt // first += assignment within a loop - seenRvalueUse bool // => we've seen the sole final use of s as an rvalue + seenRvalueUse bool // => we've seen at least one rvalue use of s ) for curUse := range index.Uses(v) { // Strip enclosing parens around Ident. @@ -280,11 +279,6 @@ nextcand: ek = curUse.ParentEdgeKind() } - // The rvalueUse must be the lexically last use. - if seenRvalueUse { - continue nextcand - } - // intervening reports whether cur has an ancestor of // one of the given types that is within the scope of v. intervening := func(types ...ast.Node) bool { @@ -297,6 +291,11 @@ nextcand: } if ek == edge.AssignStmt_Lhs { + // After an rvalue use, no more assignments are allowed. + if seenRvalueUse { + continue nextcand + } + assign := curUse.Parent().Node().(*ast.AssignStmt) if assign.Tok != token.ADD_ASSIGN { continue nextcand @@ -317,9 +316,9 @@ nextcand: // ------------- - // s.WriteString(expr) edits = append(edits, []analysis.TextEdit{ - // replace += with .WriteString() + // replace " += " with ".WriteString(" { - Pos: assign.TokPos, + Pos: assign.Lhs[0].End(), End: assign.Rhs[0].Pos(), NewText: []byte(".WriteString("), }, diff --git a/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/modernize/stringscut.go b/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/modernize/stringscut.go index f963b547b4ae..6192c56fa340 100644 --- a/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/modernize/stringscut.go +++ b/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/modernize/stringscut.go @@ -22,7 +22,7 @@ import ( typeindexanalyzer "golang.org/x/tools/internal/analysis/typeindex" "golang.org/x/tools/internal/astutil" "golang.org/x/tools/internal/goplsexport" - "golang.org/x/tools/internal/refactor" + "golang.org/x/tools/internal/moreiters" "golang.org/x/tools/internal/typesinternal" "golang.org/x/tools/internal/typesinternal/typeindex" "golang.org/x/tools/internal/versions" @@ -124,6 +124,8 @@ func stringscut(pass *analysis.Pass) (any, error) { bytesIndexByte = index.Object("bytes", "IndexByte") ) + scopeFixCount := make(map[*types.Scope]int) // the number of times we have offered a fix within a given scope in the current pass + for _, obj := range []types.Object{ stringsIndex, stringsIndexByte, @@ -183,7 +185,7 @@ func stringscut(pass *analysis.Pass) (any, error) { // len(substr)]), then we can replace the call to Index() // with a call to Cut() and use the returned ok, before, // and after variables accordingly. - negative, nonnegative, beforeSlice, afterSlice := checkIdxUses(pass.TypesInfo, index.Uses(iObj), s, substr) + negative, nonnegative, beforeSlice, afterSlice := checkIdxUses(pass.TypesInfo, index.Uses(iObj), s, substr, iObj) // Either there are no uses of before, after, or ok, or some use // of i does not match our criteria - don't suggest a fix. @@ -194,14 +196,48 @@ func stringscut(pass *analysis.Pass) (any, error) { // If the only uses are ok and !ok, don't suggest a Cut() fix - these should be using Contains() isContains := (len(negative) > 0 || len(nonnegative) > 0) && len(beforeSlice) == 0 && len(afterSlice) == 0 + enclosingBlock, ok := moreiters.First(curCall.Enclosing((*ast.BlockStmt)(nil))) + if !ok { + continue + } scope := iObj.Parent() - var ( - // TODO(adonovan): avoid FreshName when not needed; see errorsastype. - okVarName = refactor.FreshName(scope, iIdent.Pos(), "ok") - beforeVarName = refactor.FreshName(scope, iIdent.Pos(), "before") - afterVarName = refactor.FreshName(scope, iIdent.Pos(), "after") - foundVarName = refactor.FreshName(scope, iIdent.Pos(), "found") // for Contains() - ) + // Generate fresh names for ok, before, after, found, but only if + // they are defined by the end of the enclosing block and used + // within the enclosing block after the Index call. We need a Cursor + // for the end of the enclosing block, but we can't just find the + // Cursor at scope.End() because it corresponds to the entire + // enclosingBlock. Instead, get the last child of the enclosing + // block. + lastStmtCur, _ := enclosingBlock.LastChild() + lastStmt := lastStmtCur.Node() + + fresh := func(preferred string) string { + return freshName(info, index, scope, lastStmt.End(), lastStmtCur, enclosingBlock, iIdent.Pos(), preferred) + } + + var okVarName, beforeVarName, afterVarName, foundVarName string + if isContains { + foundVarName = fresh("found") + } else { + okVarName = fresh("ok") + beforeVarName = fresh("before") + afterVarName = fresh("after") + } + + // If we are already suggesting a fix within the index's scope, we + // must get fresh names for before, after and ok. + // This is a specific symptom of the general problem that analyzers + // can generate conflicting fixes. + if scopeFixCount[scope] > 0 { + suffix := scopeFixCount[scope] - 1 // start at 0 + if isContains { + foundVarName = fresh(fmt.Sprintf("%s%d", foundVarName, suffix)) + } else { + okVarName = fresh(fmt.Sprintf("%s%d", okVarName, suffix)) + beforeVarName = fresh(fmt.Sprintf("%s%d", beforeVarName, suffix)) + afterVarName = fresh(fmt.Sprintf("%s%d", afterVarName, suffix)) + } + } // If there will be no uses of ok, before, or after, use the // blank identifier instead. @@ -313,6 +349,7 @@ func stringscut(pass *analysis.Pass) (any, error) { }...) } } + scopeFixCount[scope]++ pass.Report(analysis.Diagnostic{ Pos: indexCall.Fun.Pos(), End: indexCall.Fun.End(), @@ -374,14 +411,31 @@ func indexArgValid(info *types.Info, index *typeindex.Index, expr ast.Expr, afte // 2. nonnegative - a condition equivalent to i >= 0 // 3. beforeSlice - a slice of `s` that matches either s[:i], s[0:i] // 4. afterSlice - a slice of `s` that matches one of: s[i+len(substr):], s[len(substr) + i:], s[i + const], s[k + i] (where k = len(substr)) -func checkIdxUses(info *types.Info, uses iter.Seq[inspector.Cursor], s, substr ast.Expr) (negative, nonnegative, beforeSlice, afterSlice []ast.Expr) { +// +// Additionally, all beforeSlice and afterSlice uses must be dominated by a +// nonnegative guard on i (i.e., inside the body of an if whose condition +// checks i >= 0, or in the else of a negative check, or after an +// early-return negative check). This ensures that the rewrite from +// s[i+len(sep):] to "after" preserves semantics, since when i == -1, +// s[i+len(sep):] may yield a valid substring (e.g. s[0:] for single-byte +// separators), but "after" would be "". +// +// When len(substr)==1, it's safe to use s[i+1:] even when i < 0. +// Otherwise, each replacement of s[i+1:] must be guarded by a check +// that i is nonnegative. +func checkIdxUses(info *types.Info, uses iter.Seq[inspector.Cursor], s, substr ast.Expr, iObj types.Object) (negative, nonnegative, beforeSlice, afterSlice []ast.Expr) { + requireGuard := true + if l := constSubstrLen(info, substr); l != -1 && l != 1 { + requireGuard = false + } + use := func(cur inspector.Cursor) bool { ek := cur.ParentEdgeKind() n := cur.Parent().Node() switch ek { case edge.BinaryExpr_X, edge.BinaryExpr_Y: check := n.(*ast.BinaryExpr) - switch checkIdxComparison(info, check) { + switch checkIdxComparison(info, check, iObj) { case -1: negative = append(negative, check) return true @@ -397,10 +451,10 @@ func checkIdxUses(info *types.Info, uses iter.Seq[inspector.Cursor], s, substr a if slice, ok := cur.Parent().Parent().Node().(*ast.SliceExpr); ok && sameObject(info, s, slice.X) && slice.Max == nil { - if isBeforeSlice(info, ek, slice) { + if isBeforeSlice(info, ek, slice) && (!requireGuard || isSliceIndexGuarded(info, cur, iObj)) { beforeSlice = append(beforeSlice, slice) return true - } else if isAfterSlice(info, ek, slice, substr) { + } else if isAfterSlice(info, ek, slice, substr) && (!requireGuard || isSliceIndexGuarded(info, cur, iObj)) { afterSlice = append(afterSlice, slice) return true } @@ -410,10 +464,10 @@ func checkIdxUses(info *types.Info, uses iter.Seq[inspector.Cursor], s, substr a // Check that the thing being sliced is s and that the slice doesn't // have a max index. if sameObject(info, s, slice.X) && slice.Max == nil { - if isBeforeSlice(info, ek, slice) { + if isBeforeSlice(info, ek, slice) && (!requireGuard || isSliceIndexGuarded(info, cur, iObj)) { beforeSlice = append(beforeSlice, slice) return true - } else if isAfterSlice(info, ek, slice, substr) { + } else if isAfterSlice(info, ek, slice, substr) && (!requireGuard || isSliceIndexGuarded(info, cur, iObj)) { afterSlice = append(afterSlice, slice) return true } @@ -465,8 +519,15 @@ func hasModifyingUses(info *types.Info, uses iter.Seq[inspector.Cursor], afterPo // Since strings.Index returns exactly -1 if the substring is not found, we // don't need to handle expressions like i <= -3. // We return 0 if the expression does not match any of these options. -// We assume that a check passed to checkIdxComparison has i as one of its operands. -func checkIdxComparison(info *types.Info, check *ast.BinaryExpr) int { +func checkIdxComparison(info *types.Info, check *ast.BinaryExpr, iObj types.Object) int { + isI := func(e ast.Expr) bool { + id, ok := e.(*ast.Ident) + return ok && info.Uses[id] == iObj + } + if !isI(check.X) && !isI(check.Y) { + return 0 + } + // Ensure that the constant (if any) is on the right. x, op, y := check.X, check.Op, check.Y if info.Types[x].Value != nil { @@ -515,43 +576,48 @@ func isBeforeSlice(info *types.Info, ek edge.Kind, slice *ast.SliceExpr) bool { return ek == edge.SliceExpr_High && (slice.Low == nil || isZeroIntConst(info, slice.Low)) } -// isAfterSlice reports whether the SliceExpr is of the form s[i+len(substr):], -// or s[i + k:] where k is a const is equal to len(substr). -func isAfterSlice(info *types.Info, ek edge.Kind, slice *ast.SliceExpr, substr ast.Expr) bool { - lowExpr, ok := slice.Low.(*ast.BinaryExpr) - if !ok || slice.High != nil { - return false - } - // Returns true if the expression is a call to len(substr). - isLenCall := func(expr ast.Expr) bool { - call, ok := expr.(*ast.CallExpr) - if !ok || len(call.Args) != 1 { - return false - } - return sameObject(info, substr, call.Args[0]) && typeutil.Callee(info, call) == builtinLen - } - +// constSubstrLen returns the constant length of substr, or -1 if unknown. +func constSubstrLen(info *types.Info, substr ast.Expr) int { // Handle len([]byte(substr)) - if is[*ast.CallExpr](substr) { - call := substr.(*ast.CallExpr) + if call, ok := substr.(*ast.CallExpr); ok { tv := info.Types[call.Fun] if tv.IsType() && types.Identical(tv.Type, byteSliceType) { // Only one arg in []byte conversion. substr = call.Args[0] } } - substrLen := -1 substrVal := info.Types[substr].Value if substrVal != nil { switch substrVal.Kind() { case constant.String: - substrLen = len(constant.StringVal(substrVal)) + return len(constant.StringVal(substrVal)) case constant.Int: // constant.Value is a byte literal, e.g. bytes.IndexByte(_, 'a') // or a numeric byte literal, e.g. bytes.IndexByte(_, 65) - substrLen = 1 + // ([]byte(rune) is not legal.) + return 1 } } + return -1 +} + +// isAfterSlice reports whether the SliceExpr is of the form s[i+len(substr):], +// or s[i + k:] where k is a const is equal to len(substr). +func isAfterSlice(info *types.Info, ek edge.Kind, slice *ast.SliceExpr, substr ast.Expr) bool { + lowExpr, ok := slice.Low.(*ast.BinaryExpr) + if !ok || slice.High != nil { + return false + } + // Returns true if the expression is a call to len(substr). + isLenCall := func(expr ast.Expr) bool { + call, ok := expr.(*ast.CallExpr) + if !ok || len(call.Args) != 1 { + return false + } + return sameObject(info, substr, call.Args[0]) && typeutil.Callee(info, call) == builtinLen + } + + substrLen := constSubstrLen(info, substr) switch ek { case edge.BinaryExpr_X: @@ -578,6 +644,75 @@ func isAfterSlice(info *types.Info, ek edge.Kind, slice *ast.SliceExpr, substr a return false } +// isSliceIndexGuarded reports whether a use of the index variable i (at the given cursor) +// inside a slice expression is dominated by a nonnegative guard. +// A use is considered guarded if any of the following are true: +// - It is inside the Body of an IfStmt whose condition is a nonnegative check on i. +// - It is inside the Else of an IfStmt whose condition is a negative check on i. +// - It is preceded (in the same block) by an IfStmt whose condition is a +// negative check on i with a terminating body (e.g., early return). +// +// Conversely, a use is immediately rejected if: +// - It is inside the Body of an IfStmt whose condition is a negative check on i. +// - It is inside the Else of an IfStmt whose condition is a nonnegative check on i. +// +// We have already checked (see [hasModifyingUses]) that there are no +// intervening uses (incl. via aliases) of i that might alter its value. +func isSliceIndexGuarded(info *types.Info, cur inspector.Cursor, iObj types.Object) bool { + for anc := range cur.Enclosing() { + switch anc.ParentEdgeKind() { + case edge.IfStmt_Body, edge.IfStmt_Else: + ifStmt := anc.Parent().Node().(*ast.IfStmt) + check := condChecksIdx(info, ifStmt.Cond, iObj) + if anc.ParentEdgeKind() == edge.IfStmt_Else { + check = -check + } + if check > 0 { + return true // inside nonnegative-guarded block (i >= 0 here) + } + if check < 0 { + return false // inside negative-guarded block (i < 0 here) + } + case edge.BlockStmt_List: + // Check preceding siblings for early-return negative checks. + for sib, ok := anc.PrevSibling(); ok; sib, ok = sib.PrevSibling() { + ifStmt, ok := sib.Node().(*ast.IfStmt) + if ok && condChecksIdx(info, ifStmt.Cond, iObj) < 0 && bodyTerminates(ifStmt.Body) { + return true // preceded by early-return negative check + } + } + case edge.FuncDecl_Body, edge.FuncLit_Body: + return false // stop at function boundary + } + } + return false +} + +// condChecksIdx reports whether cond is a BinaryExpr that checks +// the index variable iObj for negativity or non-negativity. +// Returns -1 for negative (e.g. i < 0), +1 for nonnegative (e.g. i >= 0), 0 otherwise. +func condChecksIdx(info *types.Info, cond ast.Expr, iObj types.Object) int { + binExpr, ok := cond.(*ast.BinaryExpr) + if !ok { + return 0 + } + return checkIdxComparison(info, binExpr, iObj) +} + +// bodyTerminates reports whether the given block statement unconditionally +// terminates execution (via return, break, continue, or goto). +func bodyTerminates(block *ast.BlockStmt) bool { + if len(block.List) == 0 { + return false + } + last := block.List[len(block.List)-1] + switch last.(type) { + case *ast.ReturnStmt, *ast.BranchStmt: + return true // return, break, continue, goto + } + return false +} + // sameObject reports whether we know that the expressions resolve to the same object. func sameObject(info *types.Info, expr1, expr2 ast.Expr) bool { if ident1, ok := expr1.(*ast.Ident); ok { diff --git a/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/modernize/stringscutprefix.go b/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/modernize/stringscutprefix.go index 7dc11308dddb..ae6345400583 100644 --- a/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/modernize/stringscutprefix.go +++ b/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/modernize/stringscutprefix.go @@ -201,8 +201,7 @@ func stringscutprefix(pass *analysis.Pass) (any, error) { if astutil.EqualSyntax(lhs, bin.X) && astutil.EqualSyntax(call.Args[0], bin.Y) || (astutil.EqualSyntax(lhs, bin.Y) && astutil.EqualSyntax(call.Args[0], bin.X)) { - // TODO(adonovan): avoid FreshName when not needed; see errorsastype. - okVarName := refactor.FreshName(info.Scopes[ifStmt], ifStmt.Pos(), "ok") + okVarName := freshName(info, index, info.Scopes[ifStmt], ifStmt.Pos(), curIfStmt, curIfStmt, token.NoPos, "ok") // Have one of: // if rest := TrimPrefix(s, prefix); rest != s { (ditto Suffix) // if rest := TrimPrefix(s, prefix); s != rest { (ditto Suffix) diff --git a/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/modernize/unsafefuncs.go b/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/modernize/unsafefuncs.go index 0b36908ec3ce..191eba95c946 100644 --- a/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/modernize/unsafefuncs.go +++ b/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/modernize/unsafefuncs.go @@ -56,11 +56,6 @@ func unsafefuncs(pass *analysis.Pass) (any, error) { tUnsafePointer = types.Typ[types.UnsafePointer] ) - isInteger := func(t types.Type) bool { - basic, ok := t.Underlying().(*types.Basic) - return ok && basic.Info()&types.IsInteger != 0 - } - // isConversion reports whether e is a conversion T(x). // If so, it returns T and x. isConversion := func(curExpr inspector.Cursor) (t types.Type, x inspector.Cursor) { @@ -208,3 +203,8 @@ func deleteConv(cur inspector.Cursor) []analysis.TextEdit { }, } } + +func isInteger(t types.Type) bool { + basic, ok := t.Underlying().(*types.Basic) + return ok && basic.Info()&types.IsInteger != 0 +} diff --git a/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/modernize/waitgroup.go b/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/modernize/waitgroup.go index abf5885cee28..5e425871056a 100644 --- a/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/modernize/waitgroup.go +++ b/hack/tools/vendor/golang.org/x/tools/go/analysis/passes/modernize/waitgroup.go @@ -97,6 +97,9 @@ func waitgroup(pass *analysis.Pass) (any, error) { if !ok || len(goStmt.Call.Args) != 0 { continue // go argument is not func(){...}() } + if lit.Type.Results != nil && len(lit.Type.Results.List) > 0 { + continue // function literal has return values; wg.Go requires func() + } list := lit.Body.List if len(list) == 0 { continue diff --git a/hack/tools/vendor/golang.org/x/tools/go/packages/golist.go b/hack/tools/vendor/golang.org/x/tools/go/packages/golist.go index 680a70ca8f0d..a6c17cf6346c 100644 --- a/hack/tools/vendor/golang.org/x/tools/go/packages/golist.go +++ b/hack/tools/vendor/golang.org/x/tools/go/packages/golist.go @@ -61,13 +61,42 @@ func (r *responseDeduper) addAll(dr *DriverResponse) { } func (r *responseDeduper) addPackage(p *Package) { - if r.seenPackages[p.ID] != nil { + if prev := r.seenPackages[p.ID]; prev != nil { + // Package already seen in a previous response. Merge the file lists, + // removing duplicates. This can happen when the same package appears + // in multiple driver responses that are being merged together. + prev.GoFiles = appendUniqueStrings(prev.GoFiles, p.GoFiles) + prev.CompiledGoFiles = appendUniqueStrings(prev.CompiledGoFiles, p.CompiledGoFiles) + prev.OtherFiles = appendUniqueStrings(prev.OtherFiles, p.OtherFiles) + prev.IgnoredFiles = appendUniqueStrings(prev.IgnoredFiles, p.IgnoredFiles) + prev.EmbedFiles = appendUniqueStrings(prev.EmbedFiles, p.EmbedFiles) + prev.EmbedPatterns = appendUniqueStrings(prev.EmbedPatterns, p.EmbedPatterns) return } r.seenPackages[p.ID] = p r.dr.Packages = append(r.dr.Packages, p) } +// appendUniqueStrings appends elements from src to dst, skipping duplicates. +func appendUniqueStrings(dst, src []string) []string { + if len(src) == 0 { + return dst + } + + seen := make(map[string]bool, len(dst)) + for _, s := range dst { + seen[s] = true + } + + for _, s := range src { + if !seen[s] { + dst = append(dst, s) + } + } + + return dst +} + func (r *responseDeduper) addRoot(id string) { if r.seenRoots[id] { return @@ -832,6 +861,8 @@ func golistargs(cfg *Config, words []string, goVersion int) []string { // go list doesn't let you pass -test and -find together, // probably because you'd just get the TestMain. fmt.Sprintf("-find=%t", !cfg.Tests && cfg.Mode&findFlags == 0 && !usesExportData(cfg)), + // VCS information is not needed when not printing Stale or StaleReason fields + "-buildvcs=false", } // golang/go#60456: with go1.21 and later, go list serves pgo variants, which diff --git a/hack/tools/vendor/golang.org/x/tools/go/packages/packages.go b/hack/tools/vendor/golang.org/x/tools/go/packages/packages.go index b249a5c7efd3..412ba06b56da 100644 --- a/hack/tools/vendor/golang.org/x/tools/go/packages/packages.go +++ b/hack/tools/vendor/golang.org/x/tools/go/packages/packages.go @@ -403,6 +403,10 @@ func mergeResponses(responses ...*DriverResponse) *DriverResponse { if len(responses) == 0 { return nil } + // No dedup needed + if len(responses) == 1 { + return responses[0] + } response := newDeduper() response.dr.NotHandled = false response.dr.Compiler = responses[0].Compiler diff --git a/hack/tools/vendor/golang.org/x/tools/go/ssa/builder.go b/hack/tools/vendor/golang.org/x/tools/go/ssa/builder.go index a75257c8b167..3336203b1461 100644 --- a/hack/tools/vendor/golang.org/x/tools/go/ssa/builder.go +++ b/hack/tools/vendor/golang.org/x/tools/go/ssa/builder.go @@ -1467,13 +1467,14 @@ func (b *builder) switchStmt(fn *Function, s *ast.SwitchStmt, label *lblock) { var nextCond *BasicBlock for _, cond := range cc.List { nextCond = fn.newBasicBlock("switch.next") - // TODO(adonovan): opt: when tag==vTrue, we'd - // get better code if we use b.cond(cond) - // instead of BinOp(EQL, tag, b.expr(cond)) - // followed by If. Don't forget conversions - // though. - cond := emitCompare(fn, token.EQL, tag, b.expr(fn, cond), cond.Pos()) - emitIf(fn, cond, body, nextCond) + // For boolean switches, emit short-circuit control flow, + // just like an if/else-chain. + if tag == vTrue && !isNonTypeParamInterface(fn.info.Types[cond].Type) { + b.cond(fn, cond, body, nextCond) + } else { + c := emitCompare(fn, token.EQL, tag, b.expr(fn, cond), cond.Pos()) + emitIf(fn, c, body, nextCond) + } fn.currentBlock = nextCond } fn.currentBlock = body diff --git a/hack/tools/vendor/golang.org/x/tools/internal/astutil/comment.go b/hack/tools/vendor/golang.org/x/tools/internal/astutil/comment.go index 7e52aeaaac59..5ed4765c723d 100644 --- a/hack/tools/vendor/golang.org/x/tools/internal/astutil/comment.go +++ b/hack/tools/vendor/golang.org/x/tools/internal/astutil/comment.go @@ -31,7 +31,7 @@ func Deprecation(doc *ast.CommentGroup) string { // -- plundered from the future (CL 605517, issue #68021) -- -// TODO(adonovan): replace with ast.Directive after go1.25 (#68021). +// TODO(adonovan): replace with ast.Directive in go1.26 (#68021). // Beware of our local mods to handle analysistest // "want" comments on the same line. diff --git a/hack/tools/vendor/golang.org/x/tools/internal/astutil/stringlit.go b/hack/tools/vendor/golang.org/x/tools/internal/astutil/stringlit.go index ce1e7de882d9..eb49d451259e 100644 --- a/hack/tools/vendor/golang.org/x/tools/internal/astutil/stringlit.go +++ b/hack/tools/vendor/golang.org/x/tools/internal/astutil/stringlit.go @@ -40,20 +40,64 @@ func PosInStringLiteral(lit *ast.BasicLit, offset int) (token.Pos, error) { return 0, fmt.Errorf("invalid offset") } + pos, _ := walkStringLiteral(lit, lit.End(), offset) + return pos, nil +} + +// OffsetInStringLiteral returns the byte offset within the logical (unquoted) +// string corresponding to the specified source position. +func OffsetInStringLiteral(lit *ast.BasicLit, pos token.Pos) (int, error) { + if !NodeContainsPos(lit, pos) { + return 0, fmt.Errorf("invalid position") + } + + raw := lit.Value + + value, err := strconv.Unquote(raw) + if err != nil { + return 0, err + } + + _, offset := walkStringLiteral(lit, pos, len(value)) + return offset, nil +} + +// walkStringLiteral iterates through the raw string literal to map between +// a file position and a logical byte offset. It stops when it reaches +// either the targetPos or the targetOffset. +// +// TODO(hxjiang): consider making an iterator. +func walkStringLiteral(lit *ast.BasicLit, targetPos token.Pos, targetOffset int) (token.Pos, int) { + raw := lit.Value + norm := int(lit.End()-lit.Pos()) > len(lit.Value) + // remove quotes quote := raw[0] // '"' or '`' raw = raw[1 : len(raw)-1] var ( - i = 0 // byte index within logical value - pos = lit.ValuePos + 1 // position within literal + i = 0 // byte index within logical value + pos = lit.Pos() + 1 // position within literal ) - for raw != "" && i < offset { + + for raw != "" { r, _, rest, _ := strconv.UnquoteChar(raw, quote) // can't fail sz := len(raw) - len(rest) // length of literal char in raw bytes - pos += token.Pos(sz) + + nextPos := pos + token.Pos(sz) + if norm && r == '\n' { + nextPos++ + } + nextI := i + utf8.RuneLen(r) // length of logical char in "cooked" bytes + + if nextPos > targetPos || nextI > targetOffset { + break + } + raw = raw[sz:] - i += utf8.RuneLen(r) + i = nextI + pos = nextPos } - return pos, nil + + return pos, i } diff --git a/hack/tools/vendor/golang.org/x/tools/internal/astutil/util.go b/hack/tools/vendor/golang.org/x/tools/internal/astutil/util.go index 6378b50c5524..f211d2cc3d84 100644 --- a/hack/tools/vendor/golang.org/x/tools/internal/astutil/util.go +++ b/hack/tools/vendor/golang.org/x/tools/internal/astutil/util.go @@ -15,40 +15,6 @@ import ( "golang.org/x/tools/internal/moreiters" ) -// PreorderStack traverses the tree rooted at root, -// calling f before visiting each node. -// -// Each call to f provides the current node and traversal stack, -// consisting of the original value of stack appended with all nodes -// from root to n, excluding n itself. (This design allows calls -// to PreorderStack to be nested without double counting.) -// -// If f returns false, the traversal skips over that subtree. Unlike -// [ast.Inspect], no second call to f is made after visiting node n. -// In practice, the second call is nearly always used only to pop the -// stack, and it is surprisingly tricky to do this correctly; see -// https://go.dev/issue/73319. -// -// TODO(adonovan): replace with [ast.PreorderStack] when go1.25 is assured. -func PreorderStack(root ast.Node, stack []ast.Node, f func(n ast.Node, stack []ast.Node) bool) { - before := len(stack) - ast.Inspect(root, func(n ast.Node) bool { - if n != nil { - if !f(n, stack) { - // Do not push, as there will be no corresponding pop. - return false - } - stack = append(stack, n) // push - } else { - stack = stack[:len(stack)-1] // pop - } - return true - }) - if len(stack) != before { - panic("push/pop mismatch") - } -} - // NodeContains reports whether the Pos/End range of node n encloses // the given range. // diff --git a/hack/tools/vendor/golang.org/x/tools/internal/goplsexport/export.go b/hack/tools/vendor/golang.org/x/tools/internal/goplsexport/export.go index b0572f5968e5..231e3f218949 100644 --- a/hack/tools/vendor/golang.org/x/tools/internal/goplsexport/export.go +++ b/hack/tools/vendor/golang.org/x/tools/internal/goplsexport/export.go @@ -14,4 +14,5 @@ var ( PlusBuildModernizer *analysis.Analyzer // = modernize.plusbuildAnalyzer StringsCutModernizer *analysis.Analyzer // = modernize.stringscutAnalyzer UnsafeFuncsModernizer *analysis.Analyzer // = modernize.unsafeFuncsAnalyzer + AtomicModernizer *analysis.Analyzer // = modernize.atomicAnalyzer ) diff --git a/hack/tools/vendor/golang.org/x/tools/internal/refactor/refactor.go b/hack/tools/vendor/golang.org/x/tools/internal/refactor/refactor.go index 8664377f8549..1d6c05433288 100644 --- a/hack/tools/vendor/golang.org/x/tools/internal/refactor/refactor.go +++ b/hack/tools/vendor/golang.org/x/tools/internal/refactor/refactor.go @@ -17,10 +17,9 @@ import ( // FreshName returns the name of an identifier that is undefined // at the specified position, based on the preferred name. // -// TODO(adonovan): refine this to choose a fresh name only when there -// would be a conflict with the existing declaration: it's fine to -// redeclare a name in a narrower scope so long as there are no free -// references to the outer name from within the narrower scope. +// export/use freshName in go/analysis/passes/modernize/modernize.go if you want +// to generate a fresh name only when necessary (i.e., there is both an existing +// declaration and some free reference to the name within a narrower scope) func FreshName(scope *types.Scope, pos token.Pos, preferred string) string { newName := preferred for i := 0; ; i++ { diff --git a/hack/tools/vendor/golang.org/x/tools/refactor/satisfy/find.go b/hack/tools/vendor/golang.org/x/tools/refactor/satisfy/find.go index bb3837553173..3d21ce6d26e8 100644 --- a/hack/tools/vendor/golang.org/x/tools/refactor/satisfy/find.go +++ b/hack/tools/vendor/golang.org/x/tools/refactor/satisfy/find.go @@ -395,8 +395,11 @@ func (f *Finder) expr(e ast.Expr) types.Type { f.expr(e.X) case *ast.SelectorExpr: - if _, ok := f.info.Selections[e]; ok { - f.expr(e.X) // selection + if seln, ok := f.info.Selections[e]; ok { + // If e.X is a type (e.g., e is interface{ m() }.m), don't visit it. + if seln.Kind() != types.MethodExpr { + f.expr(e.X) + } } else { return f.info.Uses[e.Sel].Type() // qualified identifier } diff --git a/hack/tools/vendor/modules.txt b/hack/tools/vendor/modules.txt index 426fabd0efd9..35e536c42782 100644 --- a/hack/tools/vendor/modules.txt +++ b/hack/tools/vendor/modules.txt @@ -308,8 +308,8 @@ github.com/emirpasic/gods/utils # github.com/ettle/strcase v0.2.0 ## explicit; go 1.12 github.com/ettle/strcase -# github.com/fatih/color v1.18.0 -## explicit; go 1.17 +# github.com/fatih/color v1.19.0 +## explicit; go 1.25.0 github.com/fatih/color # github.com/fatih/structtag v1.2.0 ## explicit; go 1.12 @@ -554,7 +554,7 @@ github.com/golangci/go-printf-func-name/pkg/analyzer # github.com/golangci/gofmt v0.0.0-20250106114630-d62b90e6713d ## explicit; go 1.22.0 github.com/golangci/gofmt/gofmt -# github.com/golangci/golangci-lint/v2 v2.11.1 +# github.com/golangci/golangci-lint/v2 v2.11.4 ## explicit; go 1.25.0 github.com/golangci/golangci-lint/v2/cmd/golangci-lint github.com/golangci/golangci-lint/v2/internal/cache @@ -564,10 +564,9 @@ github.com/golangci/golangci-lint/v2/internal/go/cache github.com/golangci/golangci-lint/v2/internal/go/cacheprog github.com/golangci/golangci-lint/v2/internal/go/mmap github.com/golangci/golangci-lint/v2/internal/go/quoted -github.com/golangci/golangci-lint/v2/internal/x/tools/analysisflags -github.com/golangci/golangci-lint/v2/internal/x/tools/analysisinternal github.com/golangci/golangci-lint/v2/internal/x/tools/diff github.com/golangci/golangci-lint/v2/internal/x/tools/diff/lcs +github.com/golangci/golangci-lint/v2/internal/x/tools/driverutil github.com/golangci/golangci-lint/v2/pkg/commands github.com/golangci/golangci-lint/v2/pkg/commands/internal github.com/golangci/golangci-lint/v2/pkg/commands/internal/migrate @@ -1131,8 +1130,8 @@ github.com/russross/blackfriday/v2 # github.com/ryancurrah/gomodguard v1.4.1 ## explicit; go 1.23.0 github.com/ryancurrah/gomodguard -# github.com/ryanrolds/sqlclosecheck v0.5.1 -## explicit; go 1.20 +# github.com/ryanrolds/sqlclosecheck v0.6.0 +## explicit; go 1.25.0 github.com/ryanrolds/sqlclosecheck/pkg/analyzer # github.com/sagikazarmark/locafero v0.7.0 ## explicit; go 1.21 @@ -1151,7 +1150,7 @@ github.com/sashamelentyev/interfacebloat/pkg/analyzer ## explicit; go 1.23.0 github.com/sashamelentyev/usestdlibvars/pkg/analyzer github.com/sashamelentyev/usestdlibvars/pkg/analyzer/internal/mapping -# github.com/securego/gosec/v2 v2.24.7 +# github.com/securego/gosec/v2 v2.24.8-0.20260309165252-619ce2117e08 ## explicit; go 1.25.0 github.com/securego/gosec/v2 github.com/securego/gosec/v2/analyzers @@ -1175,7 +1174,7 @@ github.com/sivchari/containedctx # github.com/skeema/knownhosts v1.3.1 ## explicit; go 1.22 github.com/skeema/knownhosts -# github.com/sonatard/noctx v0.5.0 +# github.com/sonatard/noctx v0.5.1 ## explicit; go 1.23.0 github.com/sonatard/noctx # github.com/sourcegraph/conc v0.3.0 @@ -1409,8 +1408,8 @@ go.yaml.in/yaml/v2 # go.yaml.in/yaml/v3 v3.0.4 ## explicit; go 1.16 go.yaml.in/yaml/v3 -# golang.org/x/crypto v0.48.0 -## explicit; go 1.24.0 +# golang.org/x/crypto v0.49.0 +## explicit; go 1.25.0 golang.org/x/crypto/argon2 golang.org/x/crypto/blake2b golang.org/x/crypto/blowfish @@ -1433,14 +1432,14 @@ golang.org/x/exp/slices # golang.org/x/exp/typeparams v0.0.0-20260209203927-2842357ff358 ## explicit; go 1.24.0 golang.org/x/exp/typeparams -# golang.org/x/mod v0.33.0 -## explicit; go 1.24.0 +# golang.org/x/mod v0.34.0 +## explicit; go 1.25.0 golang.org/x/mod/internal/lazyregexp golang.org/x/mod/modfile golang.org/x/mod/module golang.org/x/mod/semver golang.org/x/mod/sumdb/dirhash -# golang.org/x/net v0.51.0 +# golang.org/x/net v0.52.0 ## explicit; go 1.25.0 golang.org/x/net/context golang.org/x/net/html @@ -1460,24 +1459,24 @@ golang.org/x/net/trace ## explicit; go 1.24.0 golang.org/x/oauth2 golang.org/x/oauth2/internal -# golang.org/x/sync v0.19.0 -## explicit; go 1.24.0 +# golang.org/x/sync v0.20.0 +## explicit; go 1.25.0 golang.org/x/sync/errgroup golang.org/x/sync/semaphore golang.org/x/sync/singleflight -# golang.org/x/sys v0.41.0 -## explicit; go 1.24.0 +# golang.org/x/sys v0.42.0 +## explicit; go 1.25.0 golang.org/x/sys/cpu golang.org/x/sys/execabs golang.org/x/sys/plan9 golang.org/x/sys/unix golang.org/x/sys/windows golang.org/x/sys/windows/registry -# golang.org/x/term v0.40.0 -## explicit; go 1.24.0 +# golang.org/x/term v0.41.0 +## explicit; go 1.25.0 golang.org/x/term -# golang.org/x/text v0.34.0 -## explicit; go 1.24.0 +# golang.org/x/text v0.35.0 +## explicit; go 1.25.0 golang.org/x/text/cases golang.org/x/text/encoding golang.org/x/text/encoding/charmap @@ -1511,8 +1510,8 @@ golang.org/x/text/width # golang.org/x/time v0.14.0 ## explicit; go 1.24.0 golang.org/x/time/rate -# golang.org/x/tools v0.42.0 -## explicit; go 1.24.0 +# golang.org/x/tools v0.43.0 +## explicit; go 1.25.0 golang.org/x/tools/go/analysis golang.org/x/tools/go/analysis/passes/appends golang.org/x/tools/go/analysis/passes/asmdecl