rebase: make use of v0.0.8 of kmip go client

The new release has some important fixes available with it
Ref: https://github.com/ThalesGroup/kmip-go/releases/tag/v0.0.8

Signed-off-by: Humble Chirammal <hchiramm@redhat.com>
This commit is contained in:
Humble Chirammal 2022-10-06 15:54:15 +05:30 committed by mergify[bot]
parent d63185b061
commit 0f2daca5c2
190 changed files with 8212 additions and 2146 deletions

12
go.mod
View File

@ -12,7 +12,7 @@ require (
github.com/container-storage-interface/spec v1.6.0 github.com/container-storage-interface/spec v1.6.0
github.com/csi-addons/replication-lib-utils v0.2.0 github.com/csi-addons/replication-lib-utils v0.2.0
github.com/csi-addons/spec v0.1.2-0.20220906123848-52ce69f90900 github.com/csi-addons/spec v0.1.2-0.20220906123848-52ce69f90900
github.com/gemalto/kmip-go v0.0.8-0.20220721195433-3fe83e2d3f26 github.com/gemalto/kmip-go v0.0.8
github.com/golang/protobuf v1.5.2 github.com/golang/protobuf v1.5.2
github.com/google/fscrypt v0.3.3 github.com/google/fscrypt v0.3.3
github.com/google/uuid v1.3.0 github.com/google/uuid v1.3.0
@ -29,7 +29,7 @@ require (
github.com/stretchr/testify v1.8.0 github.com/stretchr/testify v1.8.0
golang.org/x/crypto v0.0.0-20220315160706-3147a52a75dd golang.org/x/crypto v0.0.0-20220315160706-3147a52a75dd
golang.org/x/net v0.0.0-20220722155237-a158d28d115b golang.org/x/net v0.0.0-20220722155237-a158d28d115b
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f golang.org/x/sys v0.0.0-20220928140112-f11e5e49a4ec
google.golang.org/grpc v1.49.0 google.golang.org/grpc v1.49.0
google.golang.org/protobuf v1.28.0 google.golang.org/protobuf v1.28.0
k8s.io/api v0.25.0 k8s.io/api v0.25.0
@ -109,8 +109,8 @@ require (
github.com/json-iterator/go v1.1.12 // indirect github.com/json-iterator/go v1.1.12 // indirect
github.com/kr/pretty v0.2.1 // indirect github.com/kr/pretty v0.2.1 // indirect
github.com/mailru/easyjson v0.7.6 // indirect github.com/mailru/easyjson v0.7.6 // indirect
github.com/mattn/go-colorable v0.1.12 // indirect github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.14 // indirect github.com/mattn/go-isatty v0.0.16 // indirect
github.com/matttproud/golang_protobuf_extensions v1.0.2-0.20181231171920-c182affec369 // indirect github.com/matttproud/golang_protobuf_extensions v1.0.2-0.20181231171920-c182affec369 // indirect
github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d // indirect github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d // indirect
github.com/mitchellh/copystructure v1.0.0 // indirect github.com/mitchellh/copystructure v1.0.0 // indirect
@ -146,9 +146,9 @@ require (
go.opentelemetry.io/otel/sdk/metric v0.20.0 // indirect go.opentelemetry.io/otel/sdk/metric v0.20.0 // indirect
go.opentelemetry.io/otel/trace v0.20.0 // indirect go.opentelemetry.io/otel/trace v0.20.0 // indirect
go.opentelemetry.io/proto/otlp v0.7.0 // indirect go.opentelemetry.io/proto/otlp v0.7.0 // indirect
go.uber.org/atomic v1.9.0 // indirect go.uber.org/atomic v1.10.0 // indirect
go.uber.org/multierr v1.8.0 // indirect go.uber.org/multierr v1.8.0 // indirect
go.uber.org/zap v1.21.0 // indirect go.uber.org/zap v1.23.0 // indirect
golang.org/x/oauth2 v0.0.0-20211104180415-d3ed0bb246c8 // indirect golang.org/x/oauth2 v0.0.0-20211104180415-d3ed0bb246c8 // indirect
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211 // indirect golang.org/x/term v0.0.0-20210927222741-03fcf44c2211 // indirect
golang.org/x/text v0.3.8 // indirect golang.org/x/text v0.3.8 // indirect

20
go.sum
View File

@ -371,8 +371,8 @@ github.com/gammazero/deque v0.0.0-20190130191400-2afb3858e9c7/go.mod h1:GeIq9qoE
github.com/gammazero/workerpool v0.0.0-20190406235159-88d534f22b56/go.mod h1:w9RqFVO2BM3xwWEcAB8Fwp0OviTBBEiRmSBDfbXnd3w= github.com/gammazero/workerpool v0.0.0-20190406235159-88d534f22b56/go.mod h1:w9RqFVO2BM3xwWEcAB8Fwp0OviTBBEiRmSBDfbXnd3w=
github.com/gemalto/flume v0.13.0 h1:EEeQvAxyFys3BH8IxEU7ZpM6Kr1sYn20HuZq6dgyMR8= github.com/gemalto/flume v0.13.0 h1:EEeQvAxyFys3BH8IxEU7ZpM6Kr1sYn20HuZq6dgyMR8=
github.com/gemalto/flume v0.13.0/go.mod h1:3iOEZiK/HD8SnFTqHCQoOHQKaHlBY0b6z55P8SLaOzk= github.com/gemalto/flume v0.13.0/go.mod h1:3iOEZiK/HD8SnFTqHCQoOHQKaHlBY0b6z55P8SLaOzk=
github.com/gemalto/kmip-go v0.0.8-0.20220721195433-3fe83e2d3f26 h1:AGbIx+qTKLkYrrxL6QuwjAR5MvbuX06uMHJFb8mG+ro= github.com/gemalto/kmip-go v0.0.8 h1:RvKWTd2ACxOs7OF1f6SvPYebjmQbN0myfDHVQmX/k8g=
github.com/gemalto/kmip-go v0.0.8-0.20220721195433-3fe83e2d3f26/go.mod h1:7bAnjuzri8yGoJMwngnAd0HdXMRDQU+l1Zaiz12Tr68= github.com/gemalto/kmip-go v0.0.8/go.mod h1:7bAnjuzri8yGoJMwngnAd0HdXMRDQU+l1Zaiz12Tr68=
github.com/getkin/kin-openapi v0.76.0/go.mod h1:660oXbgy5JFMKreazJaQTw7o+X00qeSyhcnluiMv+Xg= github.com/getkin/kin-openapi v0.76.0/go.mod h1:660oXbgy5JFMKreazJaQTw7o+X00qeSyhcnluiMv+Xg=
github.com/getsentry/raven-go v0.2.0/go.mod h1:KungGk8q33+aIAZUIVWZDr2OfAEBsO49PX4NzFV5kcQ= github.com/getsentry/raven-go v0.2.0/go.mod h1:KungGk8q33+aIAZUIVWZDr2OfAEBsO49PX4NzFV5kcQ=
github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=
@ -833,8 +833,9 @@ github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaO
github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
github.com/mattn/go-colorable v0.1.6/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= github.com/mattn/go-colorable v0.1.6/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
github.com/mattn/go-colorable v0.1.8/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= github.com/mattn/go-colorable v0.1.8/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
github.com/mattn/go-colorable v0.1.12 h1:jF+Du6AlPIjs2BiUiQlKOX0rt3SujHxPnksPKZbaA40=
github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4= github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4=
github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4=
github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
@ -842,8 +843,9 @@ github.com/mattn/go-isatty v0.0.10/go.mod h1:qgIWMr58cqv1PHHyhnkY9lrL7etaEgOFcME
github.com/mattn/go-isatty v0.0.11/go.mod h1:PhnuNfih5lzO57/f3n+odYbM4JtupLOxQOAqxQCu2WE= github.com/mattn/go-isatty v0.0.11/go.mod h1:PhnuNfih5lzO57/f3n+odYbM4JtupLOxQOAqxQCu2WE=
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
github.com/mattn/go-isatty v0.0.13/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= github.com/mattn/go-isatty v0.0.13/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
github.com/mattn/go-isatty v0.0.14 h1:yVuAays6BHfxijgZPzw+3Zlu5yQgKGP2/hcQbHb7S9Y=
github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94=
github.com/mattn/go-isatty v0.0.16 h1:bq3VjFmv/sOjHtdEhmkEV4x1AJtvUvOJ2PFAZ5+peKQ=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-runewidth v0.0.2/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= github.com/mattn/go-runewidth v0.0.2/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU=
github.com/mattn/go-runewidth v0.0.7/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= github.com/mattn/go-runewidth v0.0.7/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
github.com/mattn/go-shellwords v1.0.5/go.mod h1:3xCvwCdWdlDJUrvuMn7Wuy9eWs4pE8vqg+NOMyg4B2o= github.com/mattn/go-shellwords v1.0.5/go.mod h1:3xCvwCdWdlDJUrvuMn7Wuy9eWs4pE8vqg+NOMyg4B2o=
@ -1214,8 +1216,9 @@ go.starlark.net v0.0.0-20200306205701-8dd3e2ee1dd5/go.mod h1:nmDLcffg48OtT/PSW0H
go.uber.org/atomic v1.3.2/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= go.uber.org/atomic v1.3.2/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE=
go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE=
go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE=
go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
go.uber.org/atomic v1.10.0 h1:9qC72Qh0+3MqyJbAn8YU5xVq1frD8bn3JtD2oXtafVQ=
go.uber.org/atomic v1.10.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
go.uber.org/goleak v1.1.10/go.mod h1:8a7PlsEVH3e/a/GLqe5IIrQx6GzcnRmZEufDUTk4A7A= go.uber.org/goleak v1.1.10/go.mod h1:8a7PlsEVH3e/a/GLqe5IIrQx6GzcnRmZEufDUTk4A7A=
go.uber.org/goleak v1.1.11-0.20210813005559-691160354723/go.mod h1:cwTWslyiVhfpKIDGSZEM2HlOvcqm+tG4zioyIeLoqMQ= go.uber.org/goleak v1.1.11-0.20210813005559-691160354723/go.mod h1:cwTWslyiVhfpKIDGSZEM2HlOvcqm+tG4zioyIeLoqMQ=
go.uber.org/goleak v1.1.11/go.mod h1:cwTWslyiVhfpKIDGSZEM2HlOvcqm+tG4zioyIeLoqMQ= go.uber.org/goleak v1.1.11/go.mod h1:cwTWslyiVhfpKIDGSZEM2HlOvcqm+tG4zioyIeLoqMQ=
@ -1232,8 +1235,9 @@ go.uber.org/zap v1.17.0/go.mod h1:MXVU+bhUf/A7Xi2HNOnopQOrmycQ5Ih87HtOu4q5SSo=
go.uber.org/zap v1.18.1/go.mod h1:xg/QME4nWcxGxrpdeYfq7UvYrLh66cuVKdrbD1XF/NI= go.uber.org/zap v1.18.1/go.mod h1:xg/QME4nWcxGxrpdeYfq7UvYrLh66cuVKdrbD1XF/NI=
go.uber.org/zap v1.19.0/go.mod h1:xg/QME4nWcxGxrpdeYfq7UvYrLh66cuVKdrbD1XF/NI= go.uber.org/zap v1.19.0/go.mod h1:xg/QME4nWcxGxrpdeYfq7UvYrLh66cuVKdrbD1XF/NI=
go.uber.org/zap v1.19.1/go.mod h1:j3DNczoxDZroyBnOT1L/Q79cfUMGZxlv/9dzN7SM1rI= go.uber.org/zap v1.19.1/go.mod h1:j3DNczoxDZroyBnOT1L/Q79cfUMGZxlv/9dzN7SM1rI=
go.uber.org/zap v1.21.0 h1:WefMeulhovoZ2sYXz7st6K0sLj7bBhpiFaud4r4zST8=
go.uber.org/zap v1.21.0/go.mod h1:wjWOCqI0f2ZZrJF/UufIOkiC8ii6tm1iqIsLo76RfJw= go.uber.org/zap v1.21.0/go.mod h1:wjWOCqI0f2ZZrJF/UufIOkiC8ii6tm1iqIsLo76RfJw=
go.uber.org/zap v1.23.0 h1:OjGQ5KQDEUawVHxNwQgPpiypGHOxo2mNZsOqTak4fFY=
go.uber.org/zap v1.23.0/go.mod h1:D+nX8jyLsMHMYrln8A0rJjFt/T/9/bGgIhAqxv5URuY=
golang.org/x/arch v0.0.0-20180920145803-b19384d3c130/go.mod h1:cYlCBUl1MsqxdiKgmc4uh7TxZfWSFLOGSRR090WDxt8= golang.org/x/arch v0.0.0-20180920145803-b19384d3c130/go.mod h1:cYlCBUl1MsqxdiKgmc4uh7TxZfWSFLOGSRR090WDxt8=
golang.org/x/crypto v0.0.0-20180820150726-614d502a4dac/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20180820150726-614d502a4dac/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
@ -1505,8 +1509,10 @@ golang.org/x/sys v0.0.0-20220328115105-d36c6a25d886/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.0.0-20220408201424-a24fb2fb8a0f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220408201424-a24fb2fb8a0f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220422013727-9388b58f7150/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220422013727-9388b58f7150/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f h1:v4INt8xihDGvnrfjMDVXGxw9wrfxYyCjk0KbXjhR55s=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220928140112-f11e5e49a4ec h1:BkDtF2Ih9xZ7le9ndzTA7KJow28VbQW3odyk/8drmuI=
golang.org/x/sys v0.0.0-20220928140112-f11e5e49a4ec/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210422114643-f5beecf764ed/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210422114643-f5beecf764ed/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=

View File

@ -58,7 +58,6 @@ linters-settings:
gocritic: gocritic:
# Which checks should be disabled; can't be combined with 'enabled-checks'; default is empty # Which checks should be disabled; can't be combined with 'enabled-checks'; default is empty
disabled-checks: disabled-checks:
- commentFormatting
revive: revive:
ignore-generated-header: true ignore-generated-header: true
wsl: wsl:
@ -120,7 +119,6 @@ linters:
- goprintffuncname - goprintffuncname
- gosec - gosec
- grouper - grouper
- ifshort
- importas - importas
# - ireturn # there are valid use cases for this pattern. too strict. # - ireturn # there are valid use cases for this pattern. too strict.
## - lll # checks line length. not enforced ## - lll # checks line length. not enforced

View File

@ -101,17 +101,17 @@ type AttestationCredentialValue struct {
// A Key Block object is a structure (see Table 7) used to encapsulate all of the information that is // A Key Block object is a structure (see Table 7) used to encapsulate all of the information that is
// closely associated with a cryptographic key. It contains a Key Value of one of the following Key Format Types: // closely associated with a cryptographic key. It contains a Key Value of one of the following Key Format Types:
// //
// · Raw This is a key that contains only cryptographic key material, encoded as a string of bytes. // - Raw This is a key that contains only cryptographic key material, encoded as a string of bytes.
// · Opaque This is an encoded key for which the encoding is unknown to the key management system. // - Opaque This is an encoded key for which the encoding is unknown to the key management system.
// It is encoded as a string of bytes. // It is encoded as a string of bytes.
// · PKCS1 This is an encoded private key, expressed as a DER-encoded ASN.1 PKCS#1 object. // - PKCS1 This is an encoded private key, expressed as a DER-encoded ASN.1 PKCS#1 object.
// · PKCS8 This is an encoded private key, expressed as a DER-encoded ASN.1 PKCS#8 object, supporting both // - PKCS8 This is an encoded private key, expressed as a DER-encoded ASN.1 PKCS#8 object, supporting both
// the RSAPrivateKey syntax and EncryptedPrivateKey. // the RSAPrivateKey syntax and EncryptedPrivateKey.
// · X.509 This is an encoded object, expressed as a DER-encoded ASN.1 X.509 object. // - X.509 This is an encoded object, expressed as a DER-encoded ASN.1 X.509 object.
// · ECPrivateKey This is an ASN.1 encoded elliptic curve private key. // - ECPrivateKey This is an ASN.1 encoded elliptic curve private key.
// · Several Transparent Key types These are algorithm-specific structures containing defined values // - Several Transparent Key types These are algorithm-specific structures containing defined values
// for the various key types, as defined in Section 2.1.7. // for the various key types, as defined in Section 2.1.7.
// · Extensions These are vendor-specific extensions to allow for proprietary or legacy key formats. // - Extensions These are vendor-specific extensions to allow for proprietary or legacy key formats.
// //
// The Key Block MAY contain the Key Compression Type, which indicates the format of the elliptic curve public // The Key Block MAY contain the Key Compression Type, which indicates the format of the elliptic curve public
// key. By default, the public key is uncompressed. // key. By default, the public key is uncompressed.
@ -119,13 +119,12 @@ type AttestationCredentialValue struct {
// The Key Block also has the Cryptographic Algorithm and the Cryptographic Length of the key contained // The Key Block also has the Cryptographic Algorithm and the Cryptographic Length of the key contained
// in the Key Value field. Some example values are: // in the Key Value field. Some example values are:
// //
// · RSA keys are typically 1024, 2048 or 3072 bits in length. // - RSA keys are typically 1024, 2048 or 3072 bits in length.
// · 3DES keys are typically from 112 to 192 bits (depending upon key length and the presence of parity bits). // - 3DES keys are typically from 112 to 192 bits (depending upon key length and the presence of parity bits).
// · AES keys are 128, 192 or 256 bits in length. // - AES keys are 128, 192 or 256 bits in length.
// //
// The Key Block SHALL contain a Key Wrapping Data structure if the key in the Key Value field is // The Key Block SHALL contain a Key Wrapping Data structure if the key in the Key Value field is
// wrapped (i.e., encrypted, or MACed/signed, or both). // wrapped (i.e., encrypted, or MACed/signed, or both).
type KeyBlock struct { type KeyBlock struct {
KeyFormatType kmip14.KeyFormatType KeyFormatType kmip14.KeyFormatType
KeyCompressionType kmip14.KeyCompressionType `ttlv:",omitempty"` KeyCompressionType kmip14.KeyCompressionType `ttlv:",omitempty"`
@ -139,12 +138,12 @@ type KeyBlock struct {
// //
// The Key Value is used only inside a Key Block and is either a Byte String or a structure (see Table 8): // The Key Value is used only inside a Key Block and is either a Byte String or a structure (see Table 8):
// //
// · The Key Value structure contains the key material, either as a byte string or as a Transparent Key // - The Key Value structure contains the key material, either as a byte string or as a Transparent Key
// structure (see Section 2.1.7), and OPTIONAL attribute information that is associated and encapsulated // structure (see Section 2.1.7), and OPTIONAL attribute information that is associated and encapsulated
// with the key material. This attribute information differs from the attributes associated with Managed // with the key material. This attribute information differs from the attributes associated with Managed
// Objects, and is obtained via the Get Attributes operation, only by the fact that it is encapsulated with // Objects, and is obtained via the Get Attributes operation, only by the fact that it is encapsulated with
// (and possibly wrapped with) the key material itself. // (and possibly wrapped with) the key material itself.
// · The Key Value Byte String is either the wrapped TTLV-encoded (see Section 9.1) Key Value structure, or // - The Key Value Byte String is either the wrapped TTLV-encoded (see Section 9.1) Key Value structure, or
// the wrapped un-encoded value of the Byte String Key Material field. // the wrapped un-encoded value of the Byte String Key Material field.
// //
// TODO: Unmarshaler impl which unmarshals correct KeyMaterial type. // TODO: Unmarshaler impl which unmarshals correct KeyMaterial type.
@ -163,14 +162,14 @@ type KeyValue struct {
// //
// This structure contains fields for: // This structure contains fields for:
// //
// · A Wrapping Method, which indicates the method used to wrap the Key Value. // - A Wrapping Method, which indicates the method used to wrap the Key Value.
// · Encryption Key Information, which contains the Unique Identifier (see 3.1) value of the encryption key // - Encryption Key Information, which contains the Unique Identifier (see 3.1) value of the encryption key
// and associated cryptographic parameters. // and associated cryptographic parameters.
// · MAC/Signature Key Information, which contains the Unique Identifier value of the MAC/signature key // - MAC/Signature Key Information, which contains the Unique Identifier value of the MAC/signature key
// and associated cryptographic parameters. // and associated cryptographic parameters.
// · A MAC/Signature, which contains a MAC or signature of the Key Value. // - A MAC/Signature, which contains a MAC or signature of the Key Value.
// · An IV/Counter/Nonce, if REQUIRED by the wrapping method. // - An IV/Counter/Nonce, if REQUIRED by the wrapping method.
// · An Encoding Option, specifying the encoding of the Key Material within the Key Value structure of the // - An Encoding Option, specifying the encoding of the Key Material within the Key Value structure of the
// Key Block that has been wrapped. If No Encoding is specified, then the Key Value structure SHALL NOT contain // Key Block that has been wrapped. If No Encoding is specified, then the Key Value structure SHALL NOT contain
// any attributes. // any attributes.
// //
@ -184,17 +183,17 @@ type KeyValue struct {
// //
// The following wrapping methods are currently defined: // The following wrapping methods are currently defined:
// //
// · Encrypt only (i.e., encryption using a symmetric key or public key, or authenticated encryption algorithms that use a single key). // - Encrypt only (i.e., encryption using a symmetric key or public key, or authenticated encryption algorithms that use a single key).
// · MAC/sign only (i.e., either MACing the Key Value with a symmetric key, or signing the Key Value with a private key). // - MAC/sign only (i.e., either MACing the Key Value with a symmetric key, or signing the Key Value with a private key).
// · Encrypt then MAC/sign. // - Encrypt then MAC/sign.
// · MAC/sign then encrypt. // - MAC/sign then encrypt.
// · TR-31. // - TR-31.
// · Extensions. // - Extensions.
// //
// The following encoding options are currently defined: // The following encoding options are currently defined:
// //
// · No Encoding (i.e., the wrapped un-encoded value of the Byte String Key Material field in the Key Value structure). // - No Encoding (i.e., the wrapped un-encoded value of the Byte String Key Material field in the Key Value structure).
// · TTLV Encoding (i.e., the wrapped TTLV-encoded Key Value structure). // - TTLV Encoding (i.e., the wrapped TTLV-encoded Key Value structure).
type KeyWrappingData struct { type KeyWrappingData struct {
WrappingMethod kmip14.WrappingMethod WrappingMethod kmip14.WrappingMethod
EncryptionKeyInformation *EncryptionKeyInformation EncryptionKeyInformation *EncryptionKeyInformation
@ -254,9 +253,9 @@ type TransparentDSAPublicKey struct {
// //
// One of the following SHALL be present (refer to [PKCS#1]): // One of the following SHALL be present (refer to [PKCS#1]):
// //
// · Private Exponent, // - Private Exponent,
// · P and Q (the first two prime factors of Modulus), or // - P and Q (the first two prime factors of Modulus), or
// · Prime Exponent P and Prime Exponent Q. // - Prime Exponent P and Prime Exponent Q.
type TransparentRSAPrivateKey struct { type TransparentRSAPrivateKey struct {
Modulus *big.Int `validate:"required"` Modulus *big.Int `validate:"required"`
PrivateExponent, PublicExponent *big.Int PrivateExponent, PublicExponent *big.Int
@ -395,10 +394,10 @@ type TransparentECPublicKey struct {
// //
// The Template-Attribute, Common Template-Attribute, Private Key Template-Attribute, and Public Key // The Template-Attribute, Common Template-Attribute, Private Key Template-Attribute, and Public Key
// Template-Attribute structures are defined identically as follows: // Template-Attribute structures are defined identically as follows:
//
// type TemplateAttribute struct { // type TemplateAttribute struct {
// Attribute []Attribute // Attribute []Attribute
// } // }
type TemplateAttribute struct { type TemplateAttribute struct {
Name []Name Name []Name
Attribute []Attribute Attribute []Attribute

View File

@ -17,7 +17,7 @@ func init() {
Register(&ttlv.DefaultRegistry) Register(&ttlv.DefaultRegistry)
} }
// Register registers the 1.4 enumeration values with the registry. // Registers the 1.4 enumeration values with the registry.
func Register(registry *ttlv.Registry) { func Register(registry *ttlv.Registry) {
RegisterGeneratedDefinitions(registry) RegisterGeneratedDefinitions(registry)
} }

View File

@ -5,7 +5,6 @@ import (
) )
// DestroyRequestPayload //////////////////////////////////////// // DestroyRequestPayload ////////////////////////////////////////
//
type DestroyRequestPayload struct { type DestroyRequestPayload struct {
UniqueIdentifier string UniqueIdentifier string
} }

View File

@ -7,7 +7,6 @@ import (
) )
// GetRequestPayload //////////////////////////////////////// // GetRequestPayload ////////////////////////////////////////
//
type GetRequestPayload struct { type GetRequestPayload struct {
UniqueIdentifier string UniqueIdentifier string
} }

View File

@ -50,7 +50,7 @@ var ErrUnexpectedValue = errors.New("no field was found to unmarshal value into"
// cause ErrUnsupportedTypeError is returned. If the source value's type is not recognized, // cause ErrUnsupportedTypeError is returned. If the source value's type is not recognized,
// *UnmarshalerError with cause ErrInvalidType is returned. // *UnmarshalerError with cause ErrInvalidType is returned.
// //
// Unmarshaling Structure // # Unmarshaling Structure
// //
// Unmarshal will try to match the values in the Structure with the fields in the // Unmarshal will try to match the values in the Structure with the fields in the
// destination struct. Structure is an array of values, while a struct is more like // destination struct. Structure is an array of values, while a struct is more like
@ -64,11 +64,13 @@ var ErrUnexpectedValue = errors.New("no field was found to unmarshal value into"
// 1. If the type of a field is a struct, and the struct contains a field named "TTLVTag", and the field // 1. If the type of a field is a struct, and the struct contains a field named "TTLVTag", and the field
// has a "ttlv" struct tag, the value of the struct tag will be parsed using ParseTag(). If // has a "ttlv" struct tag, the value of the struct tag will be parsed using ParseTag(). If
// parsing fails, an error is returned. The type and value of the TTLVTag field is ignored. // parsing fails, an error is returned. The type and value of the TTLVTag field is ignored.
// In this example, the F field will map to TagDeactivationDate: //
// In this example, the F field will map to TagDeactivationDate.
// //
// type Bar struct { // type Bar struct {
// F Foo // F Foo
// } // }
//
// type Foo struct { // type Foo struct {
// TTLVTag struct{} `ttlv:"DeactivationDate"` // TTLVTag struct{} `ttlv:"DeactivationDate"`
// } // }
@ -81,6 +83,7 @@ var ErrUnexpectedValue = errors.New("no field was found to unmarshal value into"
// // conflicts with Foo's intrinsic tag // // conflicts with Foo's intrinsic tag
// F2 Foo `ttlv:"0x420034"` // the value can also be hex // F2 Foo `ttlv:"0x420034"` // the value can also be hex
// } // }
//
// 2. If the type of the field is a struct, and the struct contains a field named "TTLVTag", // 2. If the type of the field is a struct, and the struct contains a field named "TTLVTag",
// and that field is of type ttlv.Tag and is not empty, the value of the field will be the // and that field is of type ttlv.Tag and is not empty, the value of the field will be the
// inferred Tag. For example: // inferred Tag. For example:
@ -91,8 +94,9 @@ var ErrUnexpectedValue = errors.New("no field was found to unmarshal value into"
// f := Foo{TTLVTag: ttlv.TagState} // f := Foo{TTLVTag: ttlv.TagState}
// //
// This allows you to dynamically set the KMIP tag that a value will marshal to. // This allows you to dynamically set the KMIP tag that a value will marshal to.
//
// 3. The "ttlv" struct tag can be used to indicate the tag for a field. The value will // 3. The "ttlv" struct tag can be used to indicate the tag for a field. The value will
// be parsed with ParseTag() // be parsed with ParseTag():
// //
// type Bar struct { // type Bar struct {
// F Foo `ttlv:"DerivationData"` // F Foo `ttlv:"DerivationData"`

View File

@ -40,7 +40,9 @@ var (
// and from the inferred KMIP tag, according to these rules: // and from the inferred KMIP tag, according to these rules:
// //
// 1. If the value is a TTLV, it is copied byte for byte // 1. If the value is a TTLV, it is copied byte for byte
//
// 2. If the value implements Marshaler, call that // 2. If the value implements Marshaler, call that
//
// 3. If the struct field has an "omitempty" flag, and the value is // 3. If the struct field has an "omitempty" flag, and the value is
// zero, skip the field: // zero, skip the field:
// //
@ -50,8 +52,10 @@ var (
// //
// 4. If the value is a slice (except []byte) or array, marshal all // 4. If the value is a slice (except []byte) or array, marshal all
// values concatenated // values concatenated
//
// 5. If a tag has not been inferred at this point, return *MarshalerError with // 5. If a tag has not been inferred at this point, return *MarshalerError with
// cause ErrNoTag // cause ErrNoTag
//
// 6. If the Tag is registered as an enum, or has the "enum" struct tag flag, attempt // 6. If the Tag is registered as an enum, or has the "enum" struct tag flag, attempt
// to marshal as an Enumeration. int, int8, int16, int32, and their uint counterparts // to marshal as an Enumeration. int, int8, int16, int32, and their uint counterparts
// can be marshaled as an Enumeration. A string can be marshaled to an Enumeration // can be marshaled as an Enumeration. A string can be marshaled to an Enumeration
@ -70,9 +74,11 @@ var (
// If the string can't be interpreted as an enum value, it will be encoded as a TextString. If // If the string can't be interpreted as an enum value, it will be encoded as a TextString. If
// the "enum" struct flag is set, the value *must* successfully encode to an Enumeration using // the "enum" struct flag is set, the value *must* successfully encode to an Enumeration using
// above rules, or an error is returned. // above rules, or an error is returned.
//
// 7. If the Tag is registered as a bitmask, or has the "bitmask" struct tag flag, attempt // 7. If the Tag is registered as a bitmask, or has the "bitmask" struct tag flag, attempt
// to marshal to an Integer, following the same rules as for Enumerations. The ParseInt() // to marshal to an Integer, following the same rules as for Enumerations. The ParseInt()
// function is used to parse string values. // function is used to parse string values.
//
// 9. time.Time marshals to DateTime. If the field has the "datetimeextended" struct flag, // 9. time.Time marshals to DateTime. If the field has the "datetimeextended" struct flag,
// marshal as DateTimeExtended. Example: // marshal as DateTimeExtended. Example:
// //
@ -81,13 +87,20 @@ var (
// } // }
// //
// 10. big.Int marshals to BigInteger // 10. big.Int marshals to BigInteger
//
// 11. time.Duration marshals to Interval // 11. time.Duration marshals to Interval
//
// 12. string marshals to TextString // 12. string marshals to TextString
//
// 13. []byte marshals to ByteString // 13. []byte marshals to ByteString
//
// 14. all int and uint variants except int64 and uint64 marshal to Integer. If the golang // 14. all int and uint variants except int64 and uint64 marshal to Integer. If the golang
// value overflows the KMIP value, *MarshalerError with cause ErrIntOverflow is returned // value overflows the KMIP value, *MarshalerError with cause ErrIntOverflow is returned
//
// 15. int64 and uint64 marshal to LongInteger // 15. int64 and uint64 marshal to LongInteger
//
// 16. bool marshals to Boolean // 16. bool marshals to Boolean
//
// 17. structs marshal to Structure. Each field of the struct will be marshaled into the // 17. structs marshal to Structure. Each field of the struct will be marshaled into the
// values of the Structure according to the above rules. // values of the Structure according to the above rules.
// //

View File

@ -289,7 +289,6 @@ func ParseType(s string, enumMap EnumMap) (Type, error) {
// be the name from the spec. Names should be in the normalized format // be the name from the spec. Names should be in the normalized format
// described in the KMIP spec (see NormalizeName()). // described in the KMIP spec (see NormalizeName()).
// //
//
// Value enumerations are used for encoding and decoding KMIP Enumeration values, // Value enumerations are used for encoding and decoding KMIP Enumeration values,
// KMIP Integer bitmask values, Types, and Tags. // KMIP Integer bitmask values, Types, and Tags.
type EnumMap interface { type EnumMap interface {

View File

@ -94,7 +94,8 @@ func (t DateTimeExtended) MarshalTTLV(e *Encoder, tag Tag) error {
// bytes and native go types. It's useful in tests, or where you want to construct // bytes and native go types. It's useful in tests, or where you want to construct
// an arbitrary TTLV structure in code without declaring a bespoke type, e.g.: // an arbitrary TTLV structure in code without declaring a bespoke type, e.g.:
// //
// v := ttlv.Value{Tag: TagBatchCount, Value: Values{ // v := ttlv.Value{
// Tag: TagBatchCount, Value: Values{
// Value{Tag: TagComment, Value: "red"}, // Value{Tag: TagComment, Value: "red"},
// Value{Tag: TagComment, Value: "blue"}, // Value{Tag: TagComment, Value: "blue"},
// Value{Tag: TagComment, Value: "green"}, // Value{Tag: TagComment, Value: "green"},

View File

@ -4,6 +4,23 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [1.10.0] - 2022-08-11
### Added
- Add `atomic.Float32` type for atomic operations on `float32`.
- Add `CompareAndSwap` and `Swap` methods to `atomic.String`, `atomic.Error`,
and `atomic.Value`.
- Add generic `atomic.Pointer[T]` type for atomic operations on pointers of any
type. This is present only for Go 1.18 or higher, and is a drop-in for
replacement for the standard library's `sync/atomic.Pointer` type.
### Changed
- Deprecate `CAS` methods on all types in favor of corresponding
`CompareAndSwap` methods.
Thanks to @eNV25 and @icpd for their contributions to this release.
[1.10.0]: https://github.com/uber-go/atomic/compare/v1.9.0...v1.10.0
## [1.9.0] - 2021-07-15 ## [1.9.0] - 2021-07-15
### Added ### Added
- Add `Float64.Swap` to match int atomic operations. - Add `Float64.Swap` to match int atomic operations.

11
vendor/go.uber.org/atomic/bool.go generated vendored
View File

@ -1,6 +1,6 @@
// @generated Code generated by gen-atomicwrapper. // @generated Code generated by gen-atomicwrapper.
// Copyright (c) 2020-2021 Uber Technologies, Inc. // Copyright (c) 2020-2022 Uber Technologies, Inc.
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@ -55,8 +55,15 @@ func (x *Bool) Store(val bool) {
} }
// CAS is an atomic compare-and-swap for bool values. // CAS is an atomic compare-and-swap for bool values.
//
// Deprecated: Use CompareAndSwap.
func (x *Bool) CAS(old, new bool) (swapped bool) { func (x *Bool) CAS(old, new bool) (swapped bool) {
return x.v.CAS(boolToInt(old), boolToInt(new)) return x.CompareAndSwap(old, new)
}
// CompareAndSwap is an atomic compare-and-swap for bool values.
func (x *Bool) CompareAndSwap(old, new bool) (swapped bool) {
return x.v.CompareAndSwap(boolToInt(old), boolToInt(new))
} }
// Swap atomically stores the given bool and returns the old // Swap atomically stores the given bool and returns the old

View File

@ -1,6 +1,6 @@
// @generated Code generated by gen-atomicwrapper. // @generated Code generated by gen-atomicwrapper.
// Copyright (c) 2020-2021 Uber Technologies, Inc. // Copyright (c) 2020-2022 Uber Technologies, Inc.
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@ -56,8 +56,15 @@ func (x *Duration) Store(val time.Duration) {
} }
// CAS is an atomic compare-and-swap for time.Duration values. // CAS is an atomic compare-and-swap for time.Duration values.
//
// Deprecated: Use CompareAndSwap.
func (x *Duration) CAS(old, new time.Duration) (swapped bool) { func (x *Duration) CAS(old, new time.Duration) (swapped bool) {
return x.v.CAS(int64(old), int64(new)) return x.CompareAndSwap(old, new)
}
// CompareAndSwap is an atomic compare-and-swap for time.Duration values.
func (x *Duration) CompareAndSwap(old, new time.Duration) (swapped bool) {
return x.v.CompareAndSwap(int64(old), int64(new))
} }
// Swap atomically stores the given time.Duration and returns the old // Swap atomically stores the given time.Duration and returns the old

13
vendor/go.uber.org/atomic/error.go generated vendored
View File

@ -1,6 +1,6 @@
// @generated Code generated by gen-atomicwrapper. // @generated Code generated by gen-atomicwrapper.
// Copyright (c) 2020-2021 Uber Technologies, Inc. // Copyright (c) 2020-2022 Uber Technologies, Inc.
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@ -49,3 +49,14 @@ func (x *Error) Load() error {
func (x *Error) Store(val error) { func (x *Error) Store(val error) {
x.v.Store(packError(val)) x.v.Store(packError(val))
} }
// CompareAndSwap is an atomic compare-and-swap for error values.
func (x *Error) CompareAndSwap(old, new error) (swapped bool) {
return x.v.CompareAndSwap(packError(old), packError(new))
}
// Swap atomically stores the given error and returns the old
// value.
func (x *Error) Swap(val error) (old error) {
return unpackError(x.v.Swap(packError(val)))
}

View File

@ -1,4 +1,4 @@
// Copyright (c) 2020 Uber Technologies, Inc. // Copyright (c) 2020-2022 Uber Technologies, Inc.
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@ -23,7 +23,7 @@ package atomic
// atomic.Value panics on nil inputs, or if the underlying type changes. // atomic.Value panics on nil inputs, or if the underlying type changes.
// Stabilize by always storing a custom struct that we control. // Stabilize by always storing a custom struct that we control.
//go:generate bin/gen-atomicwrapper -name=Error -type=error -wrapped=Value -pack=packError -unpack=unpackError -file=error.go //go:generate bin/gen-atomicwrapper -name=Error -type=error -wrapped=Value -pack=packError -unpack=unpackError -compareandswap -swap -file=error.go
type packedError struct{ Value error } type packedError struct{ Value error }

77
vendor/go.uber.org/atomic/float32.go generated vendored Normal file
View File

@ -0,0 +1,77 @@
// @generated Code generated by gen-atomicwrapper.
// Copyright (c) 2020-2022 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package atomic
import (
"encoding/json"
"math"
)
// Float32 is an atomic type-safe wrapper for float32 values.
type Float32 struct {
_ nocmp // disallow non-atomic comparison
v Uint32
}
var _zeroFloat32 float32
// NewFloat32 creates a new Float32.
func NewFloat32(val float32) *Float32 {
x := &Float32{}
if val != _zeroFloat32 {
x.Store(val)
}
return x
}
// Load atomically loads the wrapped float32.
func (x *Float32) Load() float32 {
return math.Float32frombits(x.v.Load())
}
// Store atomically stores the passed float32.
func (x *Float32) Store(val float32) {
x.v.Store(math.Float32bits(val))
}
// Swap atomically stores the given float32 and returns the old
// value.
func (x *Float32) Swap(val float32) (old float32) {
return math.Float32frombits(x.v.Swap(math.Float32bits(val)))
}
// MarshalJSON encodes the wrapped float32 into JSON.
func (x *Float32) MarshalJSON() ([]byte, error) {
return json.Marshal(x.Load())
}
// UnmarshalJSON decodes a float32 from JSON.
func (x *Float32) UnmarshalJSON(b []byte) error {
var v float32
if err := json.Unmarshal(b, &v); err != nil {
return err
}
x.Store(v)
return nil
}

76
vendor/go.uber.org/atomic/float32_ext.go generated vendored Normal file
View File

@ -0,0 +1,76 @@
// Copyright (c) 2020-2022 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package atomic
import (
"math"
"strconv"
)
//go:generate bin/gen-atomicwrapper -name=Float32 -type=float32 -wrapped=Uint32 -pack=math.Float32bits -unpack=math.Float32frombits -swap -json -imports math -file=float32.go
// Add atomically adds to the wrapped float32 and returns the new value.
func (f *Float32) Add(delta float32) float32 {
for {
old := f.Load()
new := old + delta
if f.CAS(old, new) {
return new
}
}
}
// Sub atomically subtracts from the wrapped float32 and returns the new value.
func (f *Float32) Sub(delta float32) float32 {
return f.Add(-delta)
}
// CAS is an atomic compare-and-swap for float32 values.
//
// Deprecated: Use CompareAndSwap
func (f *Float32) CAS(old, new float32) (swapped bool) {
return f.CompareAndSwap(old, new)
}
// CompareAndSwap is an atomic compare-and-swap for float32 values.
//
// Note: CompareAndSwap handles NaN incorrectly. NaN != NaN using Go's inbuilt operators
// but CompareAndSwap allows a stored NaN to compare equal to a passed in NaN.
// This avoids typical CompareAndSwap loops from blocking forever, e.g.,
//
// for {
// old := atom.Load()
// new = f(old)
// if atom.CompareAndSwap(old, new) {
// break
// }
// }
//
// If CompareAndSwap did not match NaN to match, then the above would loop forever.
func (f *Float32) CompareAndSwap(old, new float32) (swapped bool) {
return f.v.CompareAndSwap(math.Float32bits(old), math.Float32bits(new))
}
// String encodes the wrapped value as a string.
func (f *Float32) String() string {
// 'g' is the behavior for floats with %v.
return strconv.FormatFloat(float64(f.Load()), 'g', -1, 32)
}

View File

@ -1,6 +1,6 @@
// @generated Code generated by gen-atomicwrapper. // @generated Code generated by gen-atomicwrapper.
// Copyright (c) 2020-2021 Uber Technologies, Inc. // Copyright (c) 2020-2022 Uber Technologies, Inc.
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal

View File

@ -1,4 +1,4 @@
// Copyright (c) 2020 Uber Technologies, Inc. // Copyright (c) 2020-2022 Uber Technologies, Inc.
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@ -45,21 +45,28 @@ func (f *Float64) Sub(delta float64) float64 {
// CAS is an atomic compare-and-swap for float64 values. // CAS is an atomic compare-and-swap for float64 values.
// //
// Note: CAS handles NaN incorrectly. NaN != NaN using Go's inbuilt operators // Deprecated: Use CompareAndSwap
// but CAS allows a stored NaN to compare equal to a passed in NaN. func (f *Float64) CAS(old, new float64) (swapped bool) {
// This avoids typical CAS loops from blocking forever, e.g., return f.CompareAndSwap(old, new)
}
// CompareAndSwap is an atomic compare-and-swap for float64 values.
//
// Note: CompareAndSwap handles NaN incorrectly. NaN != NaN using Go's inbuilt operators
// but CompareAndSwap allows a stored NaN to compare equal to a passed in NaN.
// This avoids typical CompareAndSwap loops from blocking forever, e.g.,
// //
// for { // for {
// old := atom.Load() // old := atom.Load()
// new = f(old) // new = f(old)
// if atom.CAS(old, new) { // if atom.CompareAndSwap(old, new) {
// break // break
// } // }
// } // }
// //
// If CAS did not match NaN to match, then the above would loop forever. // If CompareAndSwap did not match NaN to match, then the above would loop forever.
func (f *Float64) CAS(old, new float64) (swapped bool) { func (f *Float64) CompareAndSwap(old, new float64) (swapped bool) {
return f.v.CAS(math.Float64bits(old), math.Float64bits(new)) return f.v.CompareAndSwap(math.Float64bits(old), math.Float64bits(new))
} }
// String encodes the wrapped value as a string. // String encodes the wrapped value as a string.

9
vendor/go.uber.org/atomic/int32.go generated vendored
View File

@ -1,6 +1,6 @@
// @generated Code generated by gen-atomicint. // @generated Code generated by gen-atomicint.
// Copyright (c) 2020-2021 Uber Technologies, Inc. // Copyright (c) 2020-2022 Uber Technologies, Inc.
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@ -66,7 +66,14 @@ func (i *Int32) Dec() int32 {
} }
// CAS is an atomic compare-and-swap. // CAS is an atomic compare-and-swap.
//
// Deprecated: Use CompareAndSwap.
func (i *Int32) CAS(old, new int32) (swapped bool) { func (i *Int32) CAS(old, new int32) (swapped bool) {
return i.CompareAndSwap(old, new)
}
// CompareAndSwap is an atomic compare-and-swap.
func (i *Int32) CompareAndSwap(old, new int32) (swapped bool) {
return atomic.CompareAndSwapInt32(&i.v, old, new) return atomic.CompareAndSwapInt32(&i.v, old, new)
} }

9
vendor/go.uber.org/atomic/int64.go generated vendored
View File

@ -1,6 +1,6 @@
// @generated Code generated by gen-atomicint. // @generated Code generated by gen-atomicint.
// Copyright (c) 2020-2021 Uber Technologies, Inc. // Copyright (c) 2020-2022 Uber Technologies, Inc.
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@ -66,7 +66,14 @@ func (i *Int64) Dec() int64 {
} }
// CAS is an atomic compare-and-swap. // CAS is an atomic compare-and-swap.
//
// Deprecated: Use CompareAndSwap.
func (i *Int64) CAS(old, new int64) (swapped bool) { func (i *Int64) CAS(old, new int64) (swapped bool) {
return i.CompareAndSwap(old, new)
}
// CompareAndSwap is an atomic compare-and-swap.
func (i *Int64) CompareAndSwap(old, new int64) (swapped bool) {
return atomic.CompareAndSwapInt64(&i.v, old, new) return atomic.CompareAndSwapInt64(&i.v, old, new)
} }

60
vendor/go.uber.org/atomic/pointer_go118.go generated vendored Normal file
View File

@ -0,0 +1,60 @@
// Copyright (c) 2022 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//go:build go1.18 && !go1.19
// +build go1.18,!go1.19
package atomic
import "unsafe"
type Pointer[T any] struct {
_ nocmp // disallow non-atomic comparison
p UnsafePointer
}
// NewPointer creates a new Pointer.
func NewPointer[T any](v *T) *Pointer[T] {
var p Pointer[T]
if v != nil {
p.p.Store(unsafe.Pointer(v))
}
return &p
}
// Load atomically loads the wrapped value.
func (p *Pointer[T]) Load() *T {
return (*T)(p.p.Load())
}
// Store atomically stores the passed value.
func (p *Pointer[T]) Store(val *T) {
p.p.Store(unsafe.Pointer(val))
}
// Swap atomically swaps the wrapped pointer and returns the old value.
func (p *Pointer[T]) Swap(val *T) (old *T) {
return (*T)(p.p.Swap(unsafe.Pointer(val)))
}
// CompareAndSwap is an atomic compare-and-swap.
func (p *Pointer[T]) CompareAndSwap(old, new *T) (swapped bool) {
return p.p.CompareAndSwap(unsafe.Pointer(old), unsafe.Pointer(new))
}

61
vendor/go.uber.org/atomic/pointer_go119.go generated vendored Normal file
View File

@ -0,0 +1,61 @@
// Copyright (c) 2022 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//go:build go1.19
// +build go1.19
package atomic
import "sync/atomic"
// Pointer is an atomic pointer of type *T.
type Pointer[T any] struct {
_ nocmp // disallow non-atomic comparison
p atomic.Pointer[T]
}
// NewPointer creates a new Pointer.
func NewPointer[T any](v *T) *Pointer[T] {
var p Pointer[T]
if v != nil {
p.p.Store(v)
}
return &p
}
// Load atomically loads the wrapped value.
func (p *Pointer[T]) Load() *T {
return p.p.Load()
}
// Store atomically stores the passed value.
func (p *Pointer[T]) Store(val *T) {
p.p.Store(val)
}
// Swap atomically swaps the wrapped pointer and returns the old value.
func (p *Pointer[T]) Swap(val *T) (old *T) {
return p.p.Swap(val)
}
// CompareAndSwap is an atomic compare-and-swap.
func (p *Pointer[T]) CompareAndSwap(old, new *T) (swapped bool) {
return p.p.CompareAndSwap(old, new)
}

13
vendor/go.uber.org/atomic/string.go generated vendored
View File

@ -1,6 +1,6 @@
// @generated Code generated by gen-atomicwrapper. // @generated Code generated by gen-atomicwrapper.
// Copyright (c) 2020-2021 Uber Technologies, Inc. // Copyright (c) 2020-2022 Uber Technologies, Inc.
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@ -52,3 +52,14 @@ func (x *String) Load() string {
func (x *String) Store(val string) { func (x *String) Store(val string) {
x.v.Store(val) x.v.Store(val)
} }
// CompareAndSwap is an atomic compare-and-swap for string values.
func (x *String) CompareAndSwap(old, new string) (swapped bool) {
return x.v.CompareAndSwap(old, new)
}
// Swap atomically stores the given string and returns the old
// value.
func (x *String) Swap(val string) (old string) {
return x.v.Swap(val).(string)
}

View File

@ -1,4 +1,4 @@
// Copyright (c) 2020 Uber Technologies, Inc. // Copyright (c) 2020-2022 Uber Technologies, Inc.
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@ -20,9 +20,7 @@
package atomic package atomic
//go:generate bin/gen-atomicwrapper -name=String -type=string -wrapped=Value -file=string.go //go:generate bin/gen-atomicwrapper -name=String -type=string -wrapped=Value -compareandswap -swap -file=string.go
// Note: No Swap as String wraps Value, which wraps the stdlib sync/atomic.Value which
// only supports Swap as of go1.17: https://github.com/golang/go/issues/39351
// String returns the wrapped value. // String returns the wrapped value.
func (s *String) String() string { func (s *String) String() string {

2
vendor/go.uber.org/atomic/time.go generated vendored
View File

@ -1,6 +1,6 @@
// @generated Code generated by gen-atomicwrapper. // @generated Code generated by gen-atomicwrapper.
// Copyright (c) 2020-2021 Uber Technologies, Inc. // Copyright (c) 2020-2022 Uber Technologies, Inc.
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal

View File

@ -1,6 +1,6 @@
// @generated Code generated by gen-atomicint. // @generated Code generated by gen-atomicint.
// Copyright (c) 2020-2021 Uber Technologies, Inc. // Copyright (c) 2020-2022 Uber Technologies, Inc.
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@ -66,7 +66,14 @@ func (i *Uint32) Dec() uint32 {
} }
// CAS is an atomic compare-and-swap. // CAS is an atomic compare-and-swap.
//
// Deprecated: Use CompareAndSwap.
func (i *Uint32) CAS(old, new uint32) (swapped bool) { func (i *Uint32) CAS(old, new uint32) (swapped bool) {
return i.CompareAndSwap(old, new)
}
// CompareAndSwap is an atomic compare-and-swap.
func (i *Uint32) CompareAndSwap(old, new uint32) (swapped bool) {
return atomic.CompareAndSwapUint32(&i.v, old, new) return atomic.CompareAndSwapUint32(&i.v, old, new)
} }

View File

@ -1,6 +1,6 @@
// @generated Code generated by gen-atomicint. // @generated Code generated by gen-atomicint.
// Copyright (c) 2020-2021 Uber Technologies, Inc. // Copyright (c) 2020-2022 Uber Technologies, Inc.
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@ -66,7 +66,14 @@ func (i *Uint64) Dec() uint64 {
} }
// CAS is an atomic compare-and-swap. // CAS is an atomic compare-and-swap.
//
// Deprecated: Use CompareAndSwap.
func (i *Uint64) CAS(old, new uint64) (swapped bool) { func (i *Uint64) CAS(old, new uint64) (swapped bool) {
return i.CompareAndSwap(old, new)
}
// CompareAndSwap is an atomic compare-and-swap.
func (i *Uint64) CompareAndSwap(old, new uint64) (swapped bool) {
return atomic.CompareAndSwapUint64(&i.v, old, new) return atomic.CompareAndSwapUint64(&i.v, old, new)
} }

View File

@ -1,6 +1,6 @@
// @generated Code generated by gen-atomicint. // @generated Code generated by gen-atomicint.
// Copyright (c) 2020-2021 Uber Technologies, Inc. // Copyright (c) 2020-2022 Uber Technologies, Inc.
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@ -66,7 +66,14 @@ func (i *Uintptr) Dec() uintptr {
} }
// CAS is an atomic compare-and-swap. // CAS is an atomic compare-and-swap.
//
// Deprecated: Use CompareAndSwap.
func (i *Uintptr) CAS(old, new uintptr) (swapped bool) { func (i *Uintptr) CAS(old, new uintptr) (swapped bool) {
return i.CompareAndSwap(old, new)
}
// CompareAndSwap is an atomic compare-and-swap.
func (i *Uintptr) CompareAndSwap(old, new uintptr) (swapped bool) {
return atomic.CompareAndSwapUintptr(&i.v, old, new) return atomic.CompareAndSwapUintptr(&i.v, old, new)
} }

View File

@ -1,4 +1,4 @@
// Copyright (c) 2021 Uber Technologies, Inc. // Copyright (c) 2021-2022 Uber Technologies, Inc.
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@ -53,6 +53,13 @@ func (p *UnsafePointer) Swap(val unsafe.Pointer) (old unsafe.Pointer) {
} }
// CAS is an atomic compare-and-swap. // CAS is an atomic compare-and-swap.
//
// Deprecated: Use CompareAndSwap
func (p *UnsafePointer) CAS(old, new unsafe.Pointer) (swapped bool) { func (p *UnsafePointer) CAS(old, new unsafe.Pointer) (swapped bool) {
return p.CompareAndSwap(old, new)
}
// CompareAndSwap is an atomic compare-and-swap.
func (p *UnsafePointer) CompareAndSwap(old, new unsafe.Pointer) (swapped bool) {
return atomic.CompareAndSwapPointer(&p.v, old, new) return atomic.CompareAndSwapPointer(&p.v, old, new)
} }

4
vendor/go.uber.org/atomic/value.go generated vendored
View File

@ -25,7 +25,7 @@ import "sync/atomic"
// Value shadows the type of the same name from sync/atomic // Value shadows the type of the same name from sync/atomic
// https://godoc.org/sync/atomic#Value // https://godoc.org/sync/atomic#Value
type Value struct { type Value struct {
atomic.Value
_ nocmp // disallow non-atomic comparison _ nocmp // disallow non-atomic comparison
atomic.Value
} }

40
vendor/go.uber.org/zap/CHANGELOG.md generated vendored
View File

@ -3,6 +3,46 @@ All notable changes to this project will be documented in this file.
This project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). This project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
## 1.23.0 (24 Aug 2022)
Enhancements:
* [#1147][]: Add a `zapcore.LevelOf` function to determine the level of a
`LevelEnabler` or `Core`.
* [#1155][]: Add `zap.Stringers` field constructor to log arrays of objects
that implement `String() string`.
[#1147]: https://github.com/uber-go/zap/pull/1147
[#1155]: https://github.com/uber-go/zap/pull/1155
## 1.22.0 (8 Aug 2022)
Enhancements:
* [#1071][]: Add `zap.Objects` and `zap.ObjectValues` field constructors to log
arrays of objects. With these two constructors, you don't need to implement
`zapcore.ArrayMarshaler` for use with `zap.Array` if those objects implement
`zapcore.ObjectMarshaler`.
* [#1079][]: Add `SugaredLogger.WithOptions` to build a copy of an existing
`SugaredLogger` with the provided options applied.
* [#1080][]: Add `*ln` variants to `SugaredLogger` for each log level.
These functions provide a string joining behavior similar to `fmt.Println`.
* [#1088][]: Add `zap.WithFatalHook` option to control the behavior of the
logger for `Fatal`-level log entries. This defaults to exiting the program.
* [#1108][]: Add a `zap.Must` function that you can use with `NewProduction` or
`NewDevelopment` to panic if the system was unable to build the logger.
* [#1118][]: Add a `Logger.Log` method that allows specifying the log level for
a statement dynamically.
Thanks to @cardil, @craigpastro, @sashamelentyev, @shota3506, and @zhupeijun
for their contributions to this release.
[#1071]: https://github.com/uber-go/zap/pull/1071
[#1079]: https://github.com/uber-go/zap/pull/1079
[#1080]: https://github.com/uber-go/zap/pull/1080
[#1088]: https://github.com/uber-go/zap/pull/1088
[#1108]: https://github.com/uber-go/zap/pull/1108
[#1118]: https://github.com/uber-go/zap/pull/1118
## 1.21.0 (7 Feb 2022) ## 1.21.0 (7 Feb 2022)
Enhancements: Enhancements:

View File

@ -16,7 +16,7 @@ you to accept the CLA when you open your pull request.
[Fork][fork], then clone the repository: [Fork][fork], then clone the repository:
``` ```bash
mkdir -p $GOPATH/src/go.uber.org mkdir -p $GOPATH/src/go.uber.org
cd $GOPATH/src/go.uber.org cd $GOPATH/src/go.uber.org
git clone git@github.com:your_github_username/zap.git git clone git@github.com:your_github_username/zap.git
@ -27,21 +27,16 @@ git fetch upstream
Make sure that the tests and the linters pass: Make sure that the tests and the linters pass:
``` ```bash
make test make test
make lint make lint
``` ```
If you're not using the minor version of Go specified in the Makefile's
`LINTABLE_MINOR_VERSIONS` variable, `make lint` doesn't do anything. This is
fine, but it means that you'll only discover lint failures after you open your
pull request.
## Making Changes ## Making Changes
Start by creating a new branch for your changes: Start by creating a new branch for your changes:
``` ```bash
cd $GOPATH/src/go.uber.org/zap cd $GOPATH/src/go.uber.org/zap
git checkout master git checkout master
git fetch upstream git fetch upstream
@ -52,22 +47,22 @@ git checkout -b cool_new_feature
Make your changes, then ensure that `make lint` and `make test` still pass. If Make your changes, then ensure that `make lint` and `make test` still pass. If
you're satisfied with your changes, push them to your fork. you're satisfied with your changes, push them to your fork.
``` ```bash
git push origin cool_new_feature git push origin cool_new_feature
``` ```
Then use the GitHub UI to open a pull request. Then use the GitHub UI to open a pull request.
At this point, you're waiting on us to review your changes. We *try* to respond At this point, you're waiting on us to review your changes. We _try_ to respond
to issues and pull requests within a few business days, and we may suggest some to issues and pull requests within a few business days, and we may suggest some
improvements or alternatives. Once your changes are approved, one of the improvements or alternatives. Once your changes are approved, one of the
project maintainers will merge them. project maintainers will merge them.
We're much more likely to approve your changes if you: We're much more likely to approve your changes if you:
* Add tests for new functionality. - Add tests for new functionality.
* Write a [good commit message][commit-message]. - Write a [good commit message][commit-message].
* Maintain backward compatibility. - Maintain backward compatibility.
[fork]: https://github.com/uber-go/zap/fork [fork]: https://github.com/uber-go/zap/fork
[open-issue]: https://github.com/uber-go/zap/issues/new [open-issue]: https://github.com/uber-go/zap/issues/new

53
vendor/go.uber.org/zap/README.md generated vendored
View File

@ -54,7 +54,7 @@ and make many small allocations. Put differently, using `encoding/json` and
Zap takes a different approach. It includes a reflection-free, zero-allocation Zap takes a different approach. It includes a reflection-free, zero-allocation
JSON encoder, and the base `Logger` strives to avoid serialization overhead JSON encoder, and the base `Logger` strives to avoid serialization overhead
and allocations wherever possible. By building the high-level `SugaredLogger` and allocations wherever possible. By building the high-level `SugaredLogger`
on that foundation, zap lets users *choose* when they need to count every on that foundation, zap lets users _choose_ when they need to count every
allocation and when they'd prefer a more familiar, loosely typed API. allocation and when they'd prefer a more familiar, loosely typed API.
As measured by its own [benchmarking suite][], not only is zap more performant As measured by its own [benchmarking suite][], not only is zap more performant
@ -65,39 +65,39 @@ id="anchor-versions">[1](#footnote-versions)</sup>
Log a message and 10 fields: Log a message and 10 fields:
| Package | Time | Time % to zap | Objects Allocated | | Package | Time | Time % to zap | Objects Allocated |
| :------ | :--: | :-----------: | :---------------: | | :------------------ | :---------: | :-----------: | :---------------: |
| :zap: zap | 2900 ns/op | +0% | 5 allocs/op | :zap: zap | 2900 ns/op | +0% | 5 allocs/op |
| :zap: zap (sugared) | 3475 ns/op | +20% | 10 allocs/op | :zap: zap (sugared) | 3475 ns/op | +20% | 10 allocs/op |
| zerolog | 10639 ns/op | +267% | 32 allocs/op | zerolog | 10639 ns/op | +267% | 32 allocs/op |
| go-kit | 14434 ns/op | +398% | 59 allocs/op | go-kit | 14434 ns/op | +398% | 59 allocs/op |
| logrus | 17104 ns/op | +490% | 81 allocs/op | logrus | 17104 ns/op | +490% | 81 allocs/op |
| apex/log | 32424 ns/op | +1018% | 66 allocs/op | apex/log | 32424 ns/op | +1018% | 66 allocs/op |
| log15 | 33579 ns/op | +1058% | 76 allocs/op | log15 | 33579 ns/op | +1058% | 76 allocs/op |
Log a message with a logger that already has 10 fields of context: Log a message with a logger that already has 10 fields of context:
| Package | Time | Time % to zap | Objects Allocated | | Package | Time | Time % to zap | Objects Allocated |
| :------ | :--: | :-----------: | :---------------: | | :------------------ | :---------: | :-----------: | :---------------: |
| :zap: zap | 373 ns/op | +0% | 0 allocs/op | :zap: zap | 373 ns/op | +0% | 0 allocs/op |
| :zap: zap (sugared) | 452 ns/op | +21% | 1 allocs/op | :zap: zap (sugared) | 452 ns/op | +21% | 1 allocs/op |
| zerolog | 288 ns/op | -23% | 0 allocs/op | zerolog | 288 ns/op | -23% | 0 allocs/op |
| go-kit | 11785 ns/op | +3060% | 58 allocs/op | go-kit | 11785 ns/op | +3060% | 58 allocs/op |
| logrus | 19629 ns/op | +5162% | 70 allocs/op | logrus | 19629 ns/op | +5162% | 70 allocs/op |
| log15 | 21866 ns/op | +5762% | 72 allocs/op | log15 | 21866 ns/op | +5762% | 72 allocs/op |
| apex/log | 30890 ns/op | +8182% | 55 allocs/op | apex/log | 30890 ns/op | +8182% | 55 allocs/op |
Log a static string, without any context or `printf`-style templating: Log a static string, without any context or `printf`-style templating:
| Package | Time | Time % to zap | Objects Allocated | | Package | Time | Time % to zap | Objects Allocated |
| :------ | :--: | :-----------: | :---------------: | | :------------------ | :--------: | :-----------: | :---------------: |
| :zap: zap | 381 ns/op | +0% | 0 allocs/op | :zap: zap | 381 ns/op | +0% | 0 allocs/op |
| :zap: zap (sugared) | 410 ns/op | +8% | 1 allocs/op | :zap: zap (sugared) | 410 ns/op | +8% | 1 allocs/op |
| zerolog | 369 ns/op | -3% | 0 allocs/op | zerolog | 369 ns/op | -3% | 0 allocs/op |
| standard library | 385 ns/op | +1% | 2 allocs/op | standard library | 385 ns/op | +1% | 2 allocs/op |
| go-kit | 606 ns/op | +59% | 11 allocs/op | go-kit | 606 ns/op | +59% | 11 allocs/op |
| logrus | 1730 ns/op | +354% | 25 allocs/op | logrus | 1730 ns/op | +354% | 25 allocs/op |
| apex/log | 1998 ns/op | +424% | 7 allocs/op | apex/log | 1998 ns/op | +424% | 7 allocs/op |
| log15 | 4546 ns/op | +1093% | 22 allocs/op | log15 | 4546 ns/op | +1093% | 22 allocs/op |
## Development Status: Stable ## Development Status: Stable
@ -131,4 +131,3 @@ pinned in the [benchmarks/go.mod][] file. [↩](#anchor-versions)
[cov]: https://codecov.io/gh/uber-go/zap [cov]: https://codecov.io/gh/uber-go/zap
[benchmarking suite]: https://github.com/uber-go/zap/tree/master/benchmarks [benchmarking suite]: https://github.com/uber-go/zap/tree/master/benchmarks
[benchmarks/go.mod]: https://github.com/uber-go/zap/blob/master/benchmarks/go.mod [benchmarks/go.mod]: https://github.com/uber-go/zap/blob/master/benchmarks/go.mod

156
vendor/go.uber.org/zap/array_go118.go generated vendored Normal file
View File

@ -0,0 +1,156 @@
// Copyright (c) 2022 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//go:build go1.18
// +build go1.18
package zap
import (
"fmt"
"go.uber.org/zap/zapcore"
)
// Objects constructs a field with the given key, holding a list of the
// provided objects that can be marshaled by Zap.
//
// Note that these objects must implement zapcore.ObjectMarshaler directly.
// That is, if you're trying to marshal a []Request, the MarshalLogObject
// method must be declared on the Request type, not its pointer (*Request).
// If it's on the pointer, use ObjectValues.
//
// Given an object that implements MarshalLogObject on the value receiver, you
// can log a slice of those objects with Objects like so:
//
// type Author struct{ ... }
// func (a Author) MarshalLogObject(enc zapcore.ObjectEncoder) error
//
// var authors []Author = ...
// logger.Info("loading article", zap.Objects("authors", authors))
//
// Similarly, given a type that implements MarshalLogObject on its pointer
// receiver, you can log a slice of pointers to that object with Objects like
// so:
//
// type Request struct{ ... }
// func (r *Request) MarshalLogObject(enc zapcore.ObjectEncoder) error
//
// var requests []*Request = ...
// logger.Info("sending requests", zap.Objects("requests", requests))
//
// If instead, you have a slice of values of such an object, use the
// ObjectValues constructor.
//
// var requests []Request = ...
// logger.Info("sending requests", zap.ObjectValues("requests", requests))
func Objects[T zapcore.ObjectMarshaler](key string, values []T) Field {
return Array(key, objects[T](values))
}
type objects[T zapcore.ObjectMarshaler] []T
func (os objects[T]) MarshalLogArray(arr zapcore.ArrayEncoder) error {
for _, o := range os {
if err := arr.AppendObject(o); err != nil {
return err
}
}
return nil
}
// objectMarshalerPtr is a constraint that specifies that the given type
// implements zapcore.ObjectMarshaler on a pointer receiver.
type objectMarshalerPtr[T any] interface {
*T
zapcore.ObjectMarshaler
}
// ObjectValues constructs a field with the given key, holding a list of the
// provided objects, where pointers to these objects can be marshaled by Zap.
//
// Note that pointers to these objects must implement zapcore.ObjectMarshaler.
// That is, if you're trying to marshal a []Request, the MarshalLogObject
// method must be declared on the *Request type, not the value (Request).
// If it's on the value, use Objects.
//
// Given an object that implements MarshalLogObject on the pointer receiver,
// you can log a slice of those objects with ObjectValues like so:
//
// type Request struct{ ... }
// func (r *Request) MarshalLogObject(enc zapcore.ObjectEncoder) error
//
// var requests []Request = ...
// logger.Info("sending requests", zap.ObjectValues("requests", requests))
//
// If instead, you have a slice of pointers of such an object, use the Objects
// field constructor.
//
// var requests []*Request = ...
// logger.Info("sending requests", zap.Objects("requests", requests))
func ObjectValues[T any, P objectMarshalerPtr[T]](key string, values []T) Field {
return Array(key, objectValues[T, P](values))
}
type objectValues[T any, P objectMarshalerPtr[T]] []T
func (os objectValues[T, P]) MarshalLogArray(arr zapcore.ArrayEncoder) error {
for i := range os {
// It is necessary for us to explicitly reference the "P" type.
// We cannot simply pass "&os[i]" to AppendObject because its type
// is "*T", which the type system does not consider as
// implementing ObjectMarshaler.
// Only the type "P" satisfies ObjectMarshaler, which we have
// to convert "*T" to explicitly.
var p P = &os[i]
if err := arr.AppendObject(p); err != nil {
return err
}
}
return nil
}
// Stringers constructs a field with the given key, holding a list of the
// output provided by the value's String method
//
// Given an object that implements String on the value receiver, you
// can log a slice of those objects with Objects like so:
//
// type Request struct{ ... }
// func (a Request) String() string
//
// var requests []Request = ...
// logger.Info("sending requests", zap.Stringers("requests", requests))
//
// Note that these objects must implement fmt.Stringer directly.
// That is, if you're trying to marshal a []Request, the String method
// must be declared on the Request type, not its pointer (*Request).
func Stringers[T fmt.Stringer](key string, values []T) Field {
return Array(key, stringers[T](values))
}
type stringers[T fmt.Stringer] []T
func (os stringers[T]) MarshalLogArray(arr zapcore.ArrayEncoder) error {
for _, o := range os {
arr.AppendString(o.String())
}
return nil
}

4
vendor/go.uber.org/zap/config.go generated vendored
View File

@ -21,7 +21,7 @@
package zap package zap
import ( import (
"fmt" "errors"
"sort" "sort"
"time" "time"
@ -182,7 +182,7 @@ func (cfg Config) Build(opts ...Option) (*Logger, error) {
} }
if cfg.Level == (AtomicLevel{}) { if cfg.Level == (AtomicLevel{}) {
return nil, fmt.Errorf("missing Level") return nil, errors.New("missing Level")
} }
log := New( log := New(

12
vendor/go.uber.org/zap/doc.go generated vendored
View File

@ -32,7 +32,7 @@
// they need to count every allocation and when they'd prefer a more familiar, // they need to count every allocation and when they'd prefer a more familiar,
// loosely typed API. // loosely typed API.
// //
// Choosing a Logger // # Choosing a Logger
// //
// In contexts where performance is nice, but not critical, use the // In contexts where performance is nice, but not critical, use the
// SugaredLogger. It's 4-10x faster than other structured logging packages and // SugaredLogger. It's 4-10x faster than other structured logging packages and
@ -41,6 +41,7 @@
// variadic number of key-value pairs. (For more advanced use cases, they also // variadic number of key-value pairs. (For more advanced use cases, they also
// accept strongly typed fields - see the SugaredLogger.With documentation for // accept strongly typed fields - see the SugaredLogger.With documentation for
// details.) // details.)
//
// sugar := zap.NewExample().Sugar() // sugar := zap.NewExample().Sugar()
// defer sugar.Sync() // defer sugar.Sync()
// sugar.Infow("failed to fetch URL", // sugar.Infow("failed to fetch URL",
@ -57,6 +58,7 @@
// In the rare contexts where every microsecond and every allocation matter, // In the rare contexts where every microsecond and every allocation matter,
// use the Logger. It's even faster than the SugaredLogger and allocates far // use the Logger. It's even faster than the SugaredLogger and allocates far
// less, but it only supports strongly-typed, structured logging. // less, but it only supports strongly-typed, structured logging.
//
// logger := zap.NewExample() // logger := zap.NewExample()
// defer logger.Sync() // defer logger.Sync()
// logger.Info("failed to fetch URL", // logger.Info("failed to fetch URL",
@ -68,16 +70,18 @@
// Choosing between the Logger and SugaredLogger doesn't need to be an // Choosing between the Logger and SugaredLogger doesn't need to be an
// application-wide decision: converting between the two is simple and // application-wide decision: converting between the two is simple and
// inexpensive. // inexpensive.
//
// logger := zap.NewExample() // logger := zap.NewExample()
// defer logger.Sync() // defer logger.Sync()
// sugar := logger.Sugar() // sugar := logger.Sugar()
// plain := sugar.Desugar() // plain := sugar.Desugar()
// //
// Configuring Zap // # Configuring Zap
// //
// The simplest way to build a Logger is to use zap's opinionated presets: // The simplest way to build a Logger is to use zap's opinionated presets:
// NewExample, NewProduction, and NewDevelopment. These presets build a logger // NewExample, NewProduction, and NewDevelopment. These presets build a logger
// with a single function call: // with a single function call:
//
// logger, err := zap.NewProduction() // logger, err := zap.NewProduction()
// if err != nil { // if err != nil {
// log.Fatalf("can't initialize zap logger: %v", err) // log.Fatalf("can't initialize zap logger: %v", err)
@ -94,7 +98,7 @@
// go.uber.org/zap/zapcore. See the package-level AdvancedConfiguration // go.uber.org/zap/zapcore. See the package-level AdvancedConfiguration
// example for sample code. // example for sample code.
// //
// Extending Zap // # Extending Zap
// //
// The zap package itself is a relatively thin wrapper around the interfaces // The zap package itself is a relatively thin wrapper around the interfaces
// in go.uber.org/zap/zapcore. Extending zap to support a new encoding (e.g., // in go.uber.org/zap/zapcore. Extending zap to support a new encoding (e.g.,
@ -106,7 +110,7 @@
// Similarly, package authors can use the high-performance Encoder and Core // Similarly, package authors can use the high-performance Encoder and Core
// implementations in the zapcore package to build their own loggers. // implementations in the zapcore package to build their own loggers.
// //
// Frequently Asked Questions // # Frequently Asked Questions
// //
// An FAQ covering everything from installation errors to design decisions is // An FAQ covering everything from installation errors to design decisions is
// available at https://github.com/uber-go/zap/blob/master/FAQ.md. // available at https://github.com/uber-go/zap/blob/master/FAQ.md.

2
vendor/go.uber.org/zap/encoder.go generated vendored
View File

@ -63,7 +63,7 @@ func RegisterEncoder(name string, constructor func(zapcore.EncoderConfig) (zapco
func newEncoder(name string, encoderConfig zapcore.EncoderConfig) (zapcore.Encoder, error) { func newEncoder(name string, encoderConfig zapcore.EncoderConfig) (zapcore.Encoder, error) {
if encoderConfig.TimeKey != "" && encoderConfig.EncodeTime == nil { if encoderConfig.TimeKey != "" && encoderConfig.EncodeTime == nil {
return nil, fmt.Errorf("missing EncodeTime in EncoderConfig") return nil, errors.New("missing EncodeTime in EncoderConfig")
} }
_encoderMutex.RLock() _encoderMutex.RLock()

View File

@ -22,6 +22,7 @@ package zap
import ( import (
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"io" "io"
"net/http" "net/http"
@ -32,12 +33,13 @@ import (
// ServeHTTP is a simple JSON endpoint that can report on or change the current // ServeHTTP is a simple JSON endpoint that can report on or change the current
// logging level. // logging level.
// //
// GET // # GET
// //
// The GET request returns a JSON description of the current logging level like: // The GET request returns a JSON description of the current logging level like:
//
// {"level":"info"} // {"level":"info"}
// //
// PUT // # PUT
// //
// The PUT request changes the logging level. It is perfectly safe to change the // The PUT request changes the logging level. It is perfectly safe to change the
// logging level while a program is running. Two content types are supported: // logging level while a program is running. Two content types are supported:
@ -66,7 +68,6 @@ import (
// An example curl request could look like this: // An example curl request could look like this:
// //
// curl -X PUT localhost:8080/log/level -H "Content-Type: application/json" -d '{"level":"debug"}' // curl -X PUT localhost:8080/log/level -H "Content-Type: application/json" -d '{"level":"debug"}'
//
func (lvl AtomicLevel) ServeHTTP(w http.ResponseWriter, r *http.Request) { func (lvl AtomicLevel) ServeHTTP(w http.ResponseWriter, r *http.Request) {
type errorResponse struct { type errorResponse struct {
Error string `json:"error"` Error string `json:"error"`
@ -108,7 +109,7 @@ func decodePutRequest(contentType string, r *http.Request) (zapcore.Level, error
func decodePutURL(r *http.Request) (zapcore.Level, error) { func decodePutURL(r *http.Request) (zapcore.Level, error) {
lvl := r.FormValue("level") lvl := r.FormValue("level")
if lvl == "" { if lvl == "" {
return 0, fmt.Errorf("must specify logging level") return 0, errors.New("must specify logging level")
} }
var l zapcore.Level var l zapcore.Level
if err := l.UnmarshalText([]byte(lvl)); err != nil { if err := l.UnmarshalText([]byte(lvl)); err != nil {
@ -125,7 +126,7 @@ func decodePutJSON(body io.Reader) (zapcore.Level, error) {
return 0, fmt.Errorf("malformed request body: %v", err) return 0, fmt.Errorf("malformed request body: %v", err)
} }
if pld.Level == nil { if pld.Level == nil {
return 0, fmt.Errorf("must specify logging level") return 0, errors.New("must specify logging level")
} }
return *pld.Level, nil return *pld.Level, nil

View File

@ -24,24 +24,25 @@ package exit
import "os" import "os"
var real = func() { os.Exit(1) } var _exit = os.Exit
// Exit normally terminates the process by calling os.Exit(1). If the package // With terminates the process by calling os.Exit(code). If the package is
// is stubbed, it instead records a call in the testing spy. // stubbed, it instead records a call in the testing spy.
func Exit() { func With(code int) {
real() _exit(code)
} }
// A StubbedExit is a testing fake for os.Exit. // A StubbedExit is a testing fake for os.Exit.
type StubbedExit struct { type StubbedExit struct {
Exited bool Exited bool
prev func() Code int
prev func(code int)
} }
// Stub substitutes a fake for the call to os.Exit(1). // Stub substitutes a fake for the call to os.Exit(1).
func Stub() *StubbedExit { func Stub() *StubbedExit {
s := &StubbedExit{prev: real} s := &StubbedExit{prev: _exit}
real = s.exit _exit = s.exit
return s return s
} }
@ -56,9 +57,10 @@ func WithStub(f func()) *StubbedExit {
// Unstub restores the previous exit function. // Unstub restores the previous exit function.
func (se *StubbedExit) Unstub() { func (se *StubbedExit) Unstub() {
real = se.prev _exit = se.prev
} }
func (se *StubbedExit) exit() { func (se *StubbedExit) exit(code int) {
se.Exited = true se.Exited = true
se.Code = code
} }

35
vendor/go.uber.org/zap/internal/level_enabler.go generated vendored Normal file
View File

@ -0,0 +1,35 @@
// Copyright (c) 2022 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package internal
import "go.uber.org/zap/zapcore"
// LeveledEnabler is an interface satisfied by LevelEnablers that are able to
// report their own level.
//
// This interface is defined to use more conveniently in tests and non-zapcore
// packages.
// This cannot be imported from zapcore because of the cyclic dependency.
type LeveledEnabler interface {
zapcore.LevelEnabler
Level() zapcore.Level
}

3
vendor/go.uber.org/zap/level.go generated vendored
View File

@ -22,6 +22,7 @@ package zap
import ( import (
"go.uber.org/atomic" "go.uber.org/atomic"
"go.uber.org/zap/internal"
"go.uber.org/zap/zapcore" "go.uber.org/zap/zapcore"
) )
@ -70,6 +71,8 @@ type AtomicLevel struct {
l *atomic.Int32 l *atomic.Int32
} }
var _ internal.LeveledEnabler = AtomicLevel{}
// NewAtomicLevel creates an AtomicLevel with InfoLevel and above logging // NewAtomicLevel creates an AtomicLevel with InfoLevel and above logging
// enabled. // enabled.
func NewAtomicLevel() AtomicLevel { func NewAtomicLevel() AtomicLevel {

48
vendor/go.uber.org/zap/logger.go generated vendored
View File

@ -22,7 +22,7 @@ package zap
import ( import (
"fmt" "fmt"
"io/ioutil" "io"
"os" "os"
"strings" "strings"
@ -42,7 +42,7 @@ type Logger struct {
development bool development bool
addCaller bool addCaller bool
onFatal zapcore.CheckWriteAction // default is WriteThenFatal onFatal zapcore.CheckWriteHook // default is WriteThenFatal
name string name string
errorOutput zapcore.WriteSyncer errorOutput zapcore.WriteSyncer
@ -85,7 +85,7 @@ func New(core zapcore.Core, options ...Option) *Logger {
func NewNop() *Logger { func NewNop() *Logger {
return &Logger{ return &Logger{
core: zapcore.NewNopCore(), core: zapcore.NewNopCore(),
errorOutput: zapcore.AddSync(ioutil.Discard), errorOutput: zapcore.AddSync(io.Discard),
addStack: zapcore.FatalLevel + 1, addStack: zapcore.FatalLevel + 1,
clock: zapcore.DefaultClock, clock: zapcore.DefaultClock,
} }
@ -107,6 +107,19 @@ func NewDevelopment(options ...Option) (*Logger, error) {
return NewDevelopmentConfig().Build(options...) return NewDevelopmentConfig().Build(options...)
} }
// Must is a helper that wraps a call to a function returning (*Logger, error)
// and panics if the error is non-nil. It is intended for use in variable
// initialization such as:
//
// var logger = zap.Must(zap.NewProduction())
func Must(logger *Logger, err error) *Logger {
if err != nil {
panic(err)
}
return logger
}
// NewExample builds a Logger that's designed for use in zap's testable // NewExample builds a Logger that's designed for use in zap's testable
// examples. It writes DebugLevel and above logs to standard out as JSON, but // examples. It writes DebugLevel and above logs to standard out as JSON, but
// omits the timestamp and calling function to keep example output // omits the timestamp and calling function to keep example output
@ -177,6 +190,14 @@ func (log *Logger) Check(lvl zapcore.Level, msg string) *zapcore.CheckedEntry {
return log.check(lvl, msg) return log.check(lvl, msg)
} }
// Log logs a message at the specified level. The message includes any fields
// passed at the log site, as well as any fields accumulated on the logger.
func (log *Logger) Log(lvl zapcore.Level, msg string, fields ...Field) {
if ce := log.check(lvl, msg); ce != nil {
ce.Write(fields...)
}
}
// Debug logs a message at DebugLevel. The message includes any fields passed // Debug logs a message at DebugLevel. The message includes any fields passed
// at the log site, as well as any fields accumulated on the logger. // at the log site, as well as any fields accumulated on the logger.
func (log *Logger) Debug(msg string, fields ...Field) { func (log *Logger) Debug(msg string, fields ...Field) {
@ -285,18 +306,27 @@ func (log *Logger) check(lvl zapcore.Level, msg string) *zapcore.CheckedEntry {
// Set up any required terminal behavior. // Set up any required terminal behavior.
switch ent.Level { switch ent.Level {
case zapcore.PanicLevel: case zapcore.PanicLevel:
ce = ce.Should(ent, zapcore.WriteThenPanic) ce = ce.After(ent, zapcore.WriteThenPanic)
case zapcore.FatalLevel: case zapcore.FatalLevel:
onFatal := log.onFatal onFatal := log.onFatal
// Noop is the default value for CheckWriteAction, and it leads to // nil or WriteThenNoop will lead to continued execution after
// continued execution after a Fatal which is unexpected. // a Fatal log entry, which is unexpected. For example,
if onFatal == zapcore.WriteThenNoop { //
// f, err := os.Open(..)
// if err != nil {
// log.Fatal("cannot open", zap.Error(err))
// }
// fmt.Println(f.Name())
//
// The f.Name() will panic if we continue execution after the
// log.Fatal.
if onFatal == nil || onFatal == zapcore.WriteThenNoop {
onFatal = zapcore.WriteThenFatal onFatal = zapcore.WriteThenFatal
} }
ce = ce.Should(ent, onFatal) ce = ce.After(ent, onFatal)
case zapcore.DPanicLevel: case zapcore.DPanicLevel:
if log.development { if log.development {
ce = ce.Should(ent, zapcore.WriteThenPanic) ce = ce.After(ent, zapcore.WriteThenPanic)
} }
} }

20
vendor/go.uber.org/zap/options.go generated vendored
View File

@ -133,9 +133,27 @@ func IncreaseLevel(lvl zapcore.LevelEnabler) Option {
} }
// OnFatal sets the action to take on fatal logs. // OnFatal sets the action to take on fatal logs.
// Deprecated: Use WithFatalHook instead.
func OnFatal(action zapcore.CheckWriteAction) Option { func OnFatal(action zapcore.CheckWriteAction) Option {
return WithFatalHook(action)
}
// WithFatalHook sets a CheckWriteHook to run on fatal logs.
// Zap will call this hook after writing a log statement with a Fatal level.
//
// For example, the following builds a logger that will exit the current
// goroutine after writing a fatal log message, but it will not exit the
// program.
//
// zap.New(core, zap.WithFatalHook(zapcore.WriteThenGoexit))
//
// It is important that the provided CheckWriteHook stops the control flow at
// the current statement to meet expectations of callers of the logger.
// We recommend calling os.Exit or runtime.Goexit inside custom hooks at
// minimum.
func WithFatalHook(hook zapcore.CheckWriteHook) Option {
return optionFunc(func(log *Logger) { return optionFunc(func(log *Logger) {
log.onFatal = action log.onFatal = hook
}) })
} }

86
vendor/go.uber.org/zap/sugar.go generated vendored
View File

@ -38,10 +38,19 @@ const (
// method. // method.
// //
// Unlike the Logger, the SugaredLogger doesn't insist on structured logging. // Unlike the Logger, the SugaredLogger doesn't insist on structured logging.
// For each log level, it exposes three methods: one for loosely-typed // For each log level, it exposes four methods:
// structured logging, one for println-style formatting, and one for //
// printf-style formatting. For example, SugaredLoggers can produce InfoLevel // - methods named after the log level for log.Print-style logging
// output with Infow ("info with" structured context), Info, or Infof. // - methods ending in "w" for loosely-typed structured logging
// - methods ending in "f" for log.Printf-style logging
// - methods ending in "ln" for log.Println-style logging
//
// For example, the methods for InfoLevel are:
//
// Info(...any) Print-style logging
// Infow(...any) Structured logging (read as "info with")
// Infof(string, ...any) Printf-style logging
// Infoln(...any) Println-style logging
type SugaredLogger struct { type SugaredLogger struct {
base *Logger base *Logger
} }
@ -61,12 +70,23 @@ func (s *SugaredLogger) Named(name string) *SugaredLogger {
return &SugaredLogger{base: s.base.Named(name)} return &SugaredLogger{base: s.base.Named(name)}
} }
// WithOptions clones the current SugaredLogger, applies the supplied Options,
// and returns the result. It's safe to use concurrently.
func (s *SugaredLogger) WithOptions(opts ...Option) *SugaredLogger {
base := s.base.clone()
for _, opt := range opts {
opt.apply(base)
}
return &SugaredLogger{base: base}
}
// With adds a variadic number of fields to the logging context. It accepts a // With adds a variadic number of fields to the logging context. It accepts a
// mix of strongly-typed Field objects and loosely-typed key-value pairs. When // mix of strongly-typed Field objects and loosely-typed key-value pairs. When
// processing pairs, the first element of the pair is used as the field key // processing pairs, the first element of the pair is used as the field key
// and the second as the field value. // and the second as the field value.
// //
// For example, // For example,
//
// sugaredLogger.With( // sugaredLogger.With(
// "hello", "world", // "hello", "world",
// "failure", errors.New("oh no"), // "failure", errors.New("oh no"),
@ -74,7 +94,9 @@ func (s *SugaredLogger) Named(name string) *SugaredLogger {
// "count", 42, // "count", 42,
// "user", User{Name: "alice"}, // "user", User{Name: "alice"},
// ) // )
//
// is the equivalent of // is the equivalent of
//
// unsugared.With( // unsugared.With(
// String("hello", "world"), // String("hello", "world"),
// String("failure", "oh no"), // String("failure", "oh no"),
@ -168,6 +190,7 @@ func (s *SugaredLogger) Fatalf(template string, args ...interface{}) {
// pairs are treated as they are in With. // pairs are treated as they are in With.
// //
// When debug-level logging is disabled, this is much faster than // When debug-level logging is disabled, this is much faster than
//
// s.With(keysAndValues).Debug(msg) // s.With(keysAndValues).Debug(msg)
func (s *SugaredLogger) Debugw(msg string, keysAndValues ...interface{}) { func (s *SugaredLogger) Debugw(msg string, keysAndValues ...interface{}) {
s.log(DebugLevel, msg, nil, keysAndValues) s.log(DebugLevel, msg, nil, keysAndValues)
@ -210,11 +233,48 @@ func (s *SugaredLogger) Fatalw(msg string, keysAndValues ...interface{}) {
s.log(FatalLevel, msg, nil, keysAndValues) s.log(FatalLevel, msg, nil, keysAndValues)
} }
// Debugln uses fmt.Sprintln to construct and log a message.
func (s *SugaredLogger) Debugln(args ...interface{}) {
s.logln(DebugLevel, args, nil)
}
// Infoln uses fmt.Sprintln to construct and log a message.
func (s *SugaredLogger) Infoln(args ...interface{}) {
s.logln(InfoLevel, args, nil)
}
// Warnln uses fmt.Sprintln to construct and log a message.
func (s *SugaredLogger) Warnln(args ...interface{}) {
s.logln(WarnLevel, args, nil)
}
// Errorln uses fmt.Sprintln to construct and log a message.
func (s *SugaredLogger) Errorln(args ...interface{}) {
s.logln(ErrorLevel, args, nil)
}
// DPanicln uses fmt.Sprintln to construct and log a message. In development, the
// logger then panics. (See DPanicLevel for details.)
func (s *SugaredLogger) DPanicln(args ...interface{}) {
s.logln(DPanicLevel, args, nil)
}
// Panicln uses fmt.Sprintln to construct and log a message, then panics.
func (s *SugaredLogger) Panicln(args ...interface{}) {
s.logln(PanicLevel, args, nil)
}
// Fatalln uses fmt.Sprintln to construct and log a message, then calls os.Exit.
func (s *SugaredLogger) Fatalln(args ...interface{}) {
s.logln(FatalLevel, args, nil)
}
// Sync flushes any buffered log entries. // Sync flushes any buffered log entries.
func (s *SugaredLogger) Sync() error { func (s *SugaredLogger) Sync() error {
return s.base.Sync() return s.base.Sync()
} }
// log message with Sprint, Sprintf, or neither.
func (s *SugaredLogger) log(lvl zapcore.Level, template string, fmtArgs []interface{}, context []interface{}) { func (s *SugaredLogger) log(lvl zapcore.Level, template string, fmtArgs []interface{}, context []interface{}) {
// If logging at this level is completely disabled, skip the overhead of // If logging at this level is completely disabled, skip the overhead of
// string formatting. // string formatting.
@ -228,6 +288,18 @@ func (s *SugaredLogger) log(lvl zapcore.Level, template string, fmtArgs []interf
} }
} }
// logln message with Sprintln
func (s *SugaredLogger) logln(lvl zapcore.Level, fmtArgs []interface{}, context []interface{}) {
if lvl < DPanicLevel && !s.base.Core().Enabled(lvl) {
return
}
msg := getMessageln(fmtArgs)
if ce := s.base.Check(lvl, msg); ce != nil {
ce.Write(s.sweetenFields(context)...)
}
}
// getMessage format with Sprint, Sprintf, or neither. // getMessage format with Sprint, Sprintf, or neither.
func getMessage(template string, fmtArgs []interface{}) string { func getMessage(template string, fmtArgs []interface{}) string {
if len(fmtArgs) == 0 { if len(fmtArgs) == 0 {
@ -246,6 +318,12 @@ func getMessage(template string, fmtArgs []interface{}) string {
return fmt.Sprint(fmtArgs...) return fmt.Sprint(fmtArgs...)
} }
// getMessageln format with Sprintln.
func getMessageln(fmtArgs []interface{}) string {
msg := fmt.Sprintln(fmtArgs...)
return msg[:len(msg)-1]
}
func (s *SugaredLogger) sweetenFields(args []interface{}) []Field { func (s *SugaredLogger) sweetenFields(args []interface{}) []Field {
if len(args) == 0 { if len(args) == 0 {
return nil return nil

9
vendor/go.uber.org/zap/writer.go generated vendored
View File

@ -1,4 +1,4 @@
// Copyright (c) 2016 Uber Technologies, Inc. // Copyright (c) 2016-2022 Uber Technologies, Inc.
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@ -23,7 +23,6 @@ package zap
import ( import (
"fmt" "fmt"
"io" "io"
"io/ioutil"
"go.uber.org/zap/zapcore" "go.uber.org/zap/zapcore"
@ -71,7 +70,7 @@ func open(paths []string) ([]zapcore.WriteSyncer, func(), error) {
for _, path := range paths { for _, path := range paths {
sink, err := newSink(path) sink, err := newSink(path)
if err != nil { if err != nil {
openErr = multierr.Append(openErr, fmt.Errorf("couldn't open sink %q: %v", path, err)) openErr = multierr.Append(openErr, fmt.Errorf("open sink %q: %w", path, err))
continue continue
} }
writers = append(writers, sink) writers = append(writers, sink)
@ -79,7 +78,7 @@ func open(paths []string) ([]zapcore.WriteSyncer, func(), error) {
} }
if openErr != nil { if openErr != nil {
close() close()
return writers, nil, openErr return nil, nil, openErr
} }
return writers, close, nil return writers, close, nil
@ -93,7 +92,7 @@ func open(paths []string) ([]zapcore.WriteSyncer, func(), error) {
// using zapcore.NewMultiWriteSyncer and zapcore.Lock individually. // using zapcore.NewMultiWriteSyncer and zapcore.Lock individually.
func CombineWriteSyncers(writers ...zapcore.WriteSyncer) zapcore.WriteSyncer { func CombineWriteSyncers(writers ...zapcore.WriteSyncer) zapcore.WriteSyncer {
if len(writers) == 0 { if len(writers) == 0 {
return zapcore.AddSync(ioutil.Discard) return zapcore.AddSync(io.Discard)
} }
return zapcore.Lock(zapcore.NewMultiWriteSyncer(writers...)) return zapcore.Lock(zapcore.NewMultiWriteSyncer(writers...))
} }

View File

@ -43,6 +43,37 @@ const (
// //
// BufferedWriteSyncer is safe for concurrent use. You don't need to use // BufferedWriteSyncer is safe for concurrent use. You don't need to use
// zapcore.Lock for WriteSyncers with BufferedWriteSyncer. // zapcore.Lock for WriteSyncers with BufferedWriteSyncer.
//
// To set up a BufferedWriteSyncer, construct a WriteSyncer for your log
// destination (*os.File is a valid WriteSyncer), wrap it with
// BufferedWriteSyncer, and defer a Stop() call for when you no longer need the
// object.
//
// func main() {
// ws := ... // your log destination
// bws := &zapcore.BufferedWriteSyncer{WS: ws}
// defer bws.Stop()
//
// // ...
// core := zapcore.NewCore(enc, bws, lvl)
// logger := zap.New(core)
//
// // ...
// }
//
// By default, a BufferedWriteSyncer will buffer up to 256 kilobytes of logs,
// waiting at most 30 seconds between flushes.
// You can customize these parameters by setting the Size or FlushInterval
// fields.
// For example, the following buffers up to 512 kB of logs before flushing them
// to Stderr, with a maximum of one minute between each flush.
//
// ws := &BufferedWriteSyncer{
// WS: os.Stderr,
// Size: 512 * 1024, // 512 kB
// FlushInterval: time.Minute,
// }
// defer ws.Stop()
type BufferedWriteSyncer struct { type BufferedWriteSyncer struct {
// WS is the WriteSyncer around which BufferedWriteSyncer will buffer // WS is the WriteSyncer around which BufferedWriteSyncer will buffer
// writes. // writes.

View File

@ -69,6 +69,15 @@ type ioCore struct {
out WriteSyncer out WriteSyncer
} }
var (
_ Core = (*ioCore)(nil)
_ leveledEnabler = (*ioCore)(nil)
)
func (c *ioCore) Level() Level {
return LevelOf(c.LevelEnabler)
}
func (c *ioCore) With(fields []Field) Core { func (c *ioCore) With(fields []Field) Core {
clone := c.clone() clone := c.clone()
addFields(clone.enc, fields) addFields(clone.enc, fields)

View File

@ -188,9 +188,12 @@ func (e *TimeEncoder) UnmarshalText(text []byte) error {
// UnmarshalYAML unmarshals YAML to a TimeEncoder. // UnmarshalYAML unmarshals YAML to a TimeEncoder.
// If value is an object with a "layout" field, it will be unmarshaled to TimeEncoder with given layout. // If value is an object with a "layout" field, it will be unmarshaled to TimeEncoder with given layout.
//
// timeEncoder: // timeEncoder:
// layout: 06/01/02 03:04pm // layout: 06/01/02 03:04pm
//
// If value is string, it uses UnmarshalText. // If value is string, it uses UnmarshalText.
//
// timeEncoder: iso8601 // timeEncoder: iso8601
func (e *TimeEncoder) UnmarshalYAML(unmarshal func(interface{}) error) error { func (e *TimeEncoder) UnmarshalYAML(unmarshal func(interface{}) error) error {
var o struct { var o struct {

View File

@ -27,10 +27,9 @@ import (
"sync" "sync"
"time" "time"
"go.uber.org/multierr"
"go.uber.org/zap/internal/bufferpool" "go.uber.org/zap/internal/bufferpool"
"go.uber.org/zap/internal/exit" "go.uber.org/zap/internal/exit"
"go.uber.org/multierr"
) )
var ( var (
@ -152,6 +151,27 @@ type Entry struct {
Stack string Stack string
} }
// CheckWriteHook is a custom action that may be executed after an entry is
// written.
//
// Register one on a CheckedEntry with the After method.
//
// if ce := logger.Check(...); ce != nil {
// ce = ce.After(hook)
// ce.Write(...)
// }
//
// You can configure the hook for Fatal log statements at the logger level with
// the zap.WithFatalHook option.
type CheckWriteHook interface {
// OnWrite is invoked with the CheckedEntry that was written and a list
// of fields added with that entry.
//
// The list of fields DOES NOT include fields that were already added
// to the logger with the With method.
OnWrite(*CheckedEntry, []Field)
}
// CheckWriteAction indicates what action to take after a log entry is // CheckWriteAction indicates what action to take after a log entry is
// processed. Actions are ordered in increasing severity. // processed. Actions are ordered in increasing severity.
type CheckWriteAction uint8 type CheckWriteAction uint8
@ -164,21 +184,36 @@ const (
WriteThenGoexit WriteThenGoexit
// WriteThenPanic causes a panic after Write. // WriteThenPanic causes a panic after Write.
WriteThenPanic WriteThenPanic
// WriteThenFatal causes a fatal os.Exit after Write. // WriteThenFatal causes an os.Exit(1) after Write.
WriteThenFatal WriteThenFatal
) )
// OnWrite implements the OnWrite method to keep CheckWriteAction compatible
// with the new CheckWriteHook interface which deprecates CheckWriteAction.
func (a CheckWriteAction) OnWrite(ce *CheckedEntry, _ []Field) {
switch a {
case WriteThenGoexit:
runtime.Goexit()
case WriteThenPanic:
panic(ce.Message)
case WriteThenFatal:
exit.With(1)
}
}
var _ CheckWriteHook = CheckWriteAction(0)
// CheckedEntry is an Entry together with a collection of Cores that have // CheckedEntry is an Entry together with a collection of Cores that have
// already agreed to log it. // already agreed to log it.
// //
// CheckedEntry references should be created by calling AddCore or Should on a // CheckedEntry references should be created by calling AddCore or After on a
// nil *CheckedEntry. References are returned to a pool after Write, and MUST // nil *CheckedEntry. References are returned to a pool after Write, and MUST
// NOT be retained after calling their Write method. // NOT be retained after calling their Write method.
type CheckedEntry struct { type CheckedEntry struct {
Entry Entry
ErrorOutput WriteSyncer ErrorOutput WriteSyncer
dirty bool // best-effort detection of pool misuse dirty bool // best-effort detection of pool misuse
should CheckWriteAction after CheckWriteHook
cores []Core cores []Core
} }
@ -186,7 +221,7 @@ func (ce *CheckedEntry) reset() {
ce.Entry = Entry{} ce.Entry = Entry{}
ce.ErrorOutput = nil ce.ErrorOutput = nil
ce.dirty = false ce.dirty = false
ce.should = WriteThenNoop ce.after = nil
for i := range ce.cores { for i := range ce.cores {
// don't keep references to cores // don't keep references to cores
ce.cores[i] = nil ce.cores[i] = nil
@ -224,17 +259,11 @@ func (ce *CheckedEntry) Write(fields ...Field) {
ce.ErrorOutput.Sync() ce.ErrorOutput.Sync()
} }
should, msg := ce.should, ce.Message hook := ce.after
putCheckedEntry(ce) if hook != nil {
hook.OnWrite(ce, fields)
switch should {
case WriteThenPanic:
panic(msg)
case WriteThenFatal:
exit.Exit()
case WriteThenGoexit:
runtime.Goexit()
} }
putCheckedEntry(ce)
} }
// AddCore adds a Core that has agreed to log this CheckedEntry. It's intended to be // AddCore adds a Core that has agreed to log this CheckedEntry. It's intended to be
@ -252,11 +281,19 @@ func (ce *CheckedEntry) AddCore(ent Entry, core Core) *CheckedEntry {
// Should sets this CheckedEntry's CheckWriteAction, which controls whether a // Should sets this CheckedEntry's CheckWriteAction, which controls whether a
// Core will panic or fatal after writing this log entry. Like AddCore, it's // Core will panic or fatal after writing this log entry. Like AddCore, it's
// safe to call on nil CheckedEntry references. // safe to call on nil CheckedEntry references.
// Deprecated: Use After(ent Entry, after CheckWriteHook) instead.
func (ce *CheckedEntry) Should(ent Entry, should CheckWriteAction) *CheckedEntry { func (ce *CheckedEntry) Should(ent Entry, should CheckWriteAction) *CheckedEntry {
return ce.After(ent, should)
}
// After sets this CheckEntry's CheckWriteHook, which will be called after this
// log entry has been written. It's safe to call this on nil CheckedEntry
// references.
func (ce *CheckedEntry) After(ent Entry, hook CheckWriteHook) *CheckedEntry {
if ce == nil { if ce == nil {
ce = getCheckedEntry() ce = getCheckedEntry()
ce.Entry = ent ce.Entry = ent
} }
ce.should = should ce.after = hook
return ce return ce
} }

View File

@ -27,6 +27,11 @@ type hooked struct {
funcs []func(Entry) error funcs []func(Entry) error
} }
var (
_ Core = (*hooked)(nil)
_ leveledEnabler = (*hooked)(nil)
)
// RegisterHooks wraps a Core and runs a collection of user-defined callback // RegisterHooks wraps a Core and runs a collection of user-defined callback
// hooks each time a message is logged. Execution of the callbacks is blocking. // hooks each time a message is logged. Execution of the callbacks is blocking.
// //
@ -40,6 +45,10 @@ func RegisterHooks(core Core, hooks ...func(Entry) error) Core {
} }
} }
func (h *hooked) Level() Level {
return LevelOf(h.Core)
}
func (h *hooked) Check(ent Entry, ce *CheckedEntry) *CheckedEntry { func (h *hooked) Check(ent Entry, ce *CheckedEntry) *CheckedEntry {
// Let the wrapped Core decide whether to log this message or not. This // Let the wrapped Core decide whether to log this message or not. This
// also gives the downstream a chance to register itself directly with the // also gives the downstream a chance to register itself directly with the

View File

@ -27,6 +27,11 @@ type levelFilterCore struct {
level LevelEnabler level LevelEnabler
} }
var (
_ Core = (*levelFilterCore)(nil)
_ leveledEnabler = (*levelFilterCore)(nil)
)
// NewIncreaseLevelCore creates a core that can be used to increase the level of // NewIncreaseLevelCore creates a core that can be used to increase the level of
// an existing Core. It cannot be used to decrease the logging level, as it acts // an existing Core. It cannot be used to decrease the logging level, as it acts
// as a filter before calling the underlying core. If level decreases the log level, // as a filter before calling the underlying core. If level decreases the log level,
@ -45,6 +50,10 @@ func (c *levelFilterCore) Enabled(lvl Level) bool {
return c.level.Enabled(lvl) return c.level.Enabled(lvl)
} }
func (c *levelFilterCore) Level() Level {
return LevelOf(c.level)
}
func (c *levelFilterCore) With(fields []Field) Core { func (c *levelFilterCore) With(fields []Field) Core {
return &levelFilterCore{c.core.With(fields), c.level} return &levelFilterCore{c.core.With(fields), c.level}
} }

View File

@ -71,7 +71,9 @@ type jsonEncoder struct {
// //
// Note that the encoder doesn't deduplicate keys, so it's possible to produce // Note that the encoder doesn't deduplicate keys, so it's possible to produce
// a message like // a message like
//
// {"foo":"bar","foo":"baz"} // {"foo":"bar","foo":"baz"}
//
// This is permitted by the JSON specification, but not encouraged. Many // This is permitted by the JSON specification, but not encouraged. Many
// libraries will ignore duplicate key-value pairs (typically keeping the last // libraries will ignore duplicate key-value pairs (typically keeping the last
// pair) when unmarshaling, but users should attempt to avoid adding duplicate // pair) when unmarshaling, but users should attempt to avoid adding duplicate

View File

@ -53,6 +53,11 @@ const (
_minLevel = DebugLevel _minLevel = DebugLevel
_maxLevel = FatalLevel _maxLevel = FatalLevel
// InvalidLevel is an invalid value for Level.
//
// Core implementations may panic if they see messages of this level.
InvalidLevel = _maxLevel + 1
) )
// ParseLevel parses a level based on the lower-case or all-caps ASCII // ParseLevel parses a level based on the lower-case or all-caps ASCII
@ -67,6 +72,43 @@ func ParseLevel(text string) (Level, error) {
return level, err return level, err
} }
type leveledEnabler interface {
LevelEnabler
Level() Level
}
// LevelOf reports the minimum enabled log level for the given LevelEnabler
// from Zap's supported log levels, or [InvalidLevel] if none of them are
// enabled.
//
// A LevelEnabler may implement a 'Level() Level' method to override the
// behavior of this function.
//
// func (c *core) Level() Level {
// return c.currentLevel
// }
//
// It is recommended that [Core] implementations that wrap other cores use
// LevelOf to retrieve the level of the wrapped core. For example,
//
// func (c *coreWrapper) Level() Level {
// return zapcore.LevelOf(c.wrappedCore)
// }
func LevelOf(enab LevelEnabler) Level {
if lvler, ok := enab.(leveledEnabler); ok {
return lvler.Level()
}
for lvl := _minLevel; lvl <= _maxLevel; lvl++ {
if enab.Enabled(lvl) {
return lvl
}
}
return InvalidLevel
}
// String returns a lower-case ASCII representation of the log level. // String returns a lower-case ASCII representation of the log level.
func (l Level) String() string { func (l Level) String() string {
switch l { switch l {

View File

@ -1,4 +1,4 @@
// Copyright (c) 2016 Uber Technologies, Inc. // Copyright (c) 2016-2022 Uber Technologies, Inc.
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@ -175,6 +175,11 @@ type sampler struct {
hook func(Entry, SamplingDecision) hook func(Entry, SamplingDecision)
} }
var (
_ Core = (*sampler)(nil)
_ leveledEnabler = (*sampler)(nil)
)
// NewSampler creates a Core that samples incoming entries, which // NewSampler creates a Core that samples incoming entries, which
// caps the CPU and I/O load of logging while attempting to preserve a // caps the CPU and I/O load of logging while attempting to preserve a
// representative subset of your logs. // representative subset of your logs.
@ -192,6 +197,10 @@ func NewSampler(core Core, tick time.Duration, first, thereafter int) Core {
return NewSamplerWithOptions(core, tick, first, thereafter) return NewSamplerWithOptions(core, tick, first, thereafter)
} }
func (s *sampler) Level() Level {
return LevelOf(s.Core)
}
func (s *sampler) With(fields []Field) Core { func (s *sampler) With(fields []Field) Core {
return &sampler{ return &sampler{
Core: s.Core.With(fields), Core: s.Core.With(fields),

View File

@ -1,4 +1,4 @@
// Copyright (c) 2016 Uber Technologies, Inc. // Copyright (c) 2016-2022 Uber Technologies, Inc.
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal // of this software and associated documentation files (the "Software"), to deal
@ -24,6 +24,11 @@ import "go.uber.org/multierr"
type multiCore []Core type multiCore []Core
var (
_ leveledEnabler = multiCore(nil)
_ Core = multiCore(nil)
)
// NewTee creates a Core that duplicates log entries into two or more // NewTee creates a Core that duplicates log entries into two or more
// underlying Cores. // underlying Cores.
// //
@ -48,6 +53,16 @@ func (mc multiCore) With(fields []Field) Core {
return clone return clone
} }
func (mc multiCore) Level() Level {
minLvl := _maxLevel // mc is never empty
for i := range mc {
if lvl := LevelOf(mc[i]); lvl < minLvl {
minLvl = lvl
}
}
return minLvl
}
func (mc multiCore) Enabled(lvl Level) bool { func (mc multiCore) Enabled(lvl Level) bool {
for i := range mc { for i := range mc {
if mc[i].Enabled(lvl) { if mc[i].Enabled(lvl) {

View File

@ -6,7 +6,10 @@ package cpu
import "runtime" import "runtime"
const cacheLineSize = 64 // cacheLineSize is used to prevent false sharing of cache lines.
// We choose 128 because Apple Silicon, a.k.a. M1, has 128-byte cache line size.
// It doesn't cost much and is much more future-proof.
const cacheLineSize = 128
func initOptions() { func initOptions() {
options = []option{ options = []option{
@ -41,13 +44,10 @@ func archInit() {
switch runtime.GOOS { switch runtime.GOOS {
case "freebsd": case "freebsd":
readARM64Registers() readARM64Registers()
case "linux", "netbsd": case "linux", "netbsd", "openbsd":
doinit() doinit()
default: default:
// Most platforms don't seem to allow reading these registers. // Many platforms don't seem to allow reading these registers.
//
// OpenBSD:
// See https://golang.org/issue/31746
setMinimalFeatures() setMinimalFeatures()
} }
} }

65
vendor/golang.org/x/sys/cpu/cpu_openbsd_arm64.go generated vendored Normal file
View File

@ -0,0 +1,65 @@
// Copyright 2022 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 cpu
import (
"syscall"
"unsafe"
)
// Minimal copy of functionality from x/sys/unix so the cpu package can call
// sysctl without depending on x/sys/unix.
const (
// From OpenBSD's sys/sysctl.h.
_CTL_MACHDEP = 7
// From OpenBSD's machine/cpu.h.
_CPU_ID_AA64ISAR0 = 2
_CPU_ID_AA64ISAR1 = 3
)
// Implemented in the runtime package (runtime/sys_openbsd3.go)
func syscall_syscall6(fn, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno)
//go:linkname syscall_syscall6 syscall.syscall6
func sysctl(mib []uint32, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) {
_, _, errno := syscall_syscall6(libc_sysctl_trampoline_addr, uintptr(unsafe.Pointer(&mib[0])), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen))
if errno != 0 {
return errno
}
return nil
}
var libc_sysctl_trampoline_addr uintptr
//go:cgo_import_dynamic libc_sysctl sysctl "libc.so"
func sysctlUint64(mib []uint32) (uint64, bool) {
var out uint64
nout := unsafe.Sizeof(out)
if err := sysctl(mib, (*byte)(unsafe.Pointer(&out)), &nout, nil, 0); err != nil {
return 0, false
}
return out, true
}
func doinit() {
setMinimalFeatures()
// Get ID_AA64ISAR0 and ID_AA64ISAR1 from sysctl.
isar0, ok := sysctlUint64([]uint32{_CTL_MACHDEP, _CPU_ID_AA64ISAR0})
if !ok {
return
}
isar1, ok := sysctlUint64([]uint32{_CTL_MACHDEP, _CPU_ID_AA64ISAR1})
if !ok {
return
}
parseARM64SystemRegisters(isar0, isar1, 0)
Initialized = true
}

11
vendor/golang.org/x/sys/cpu/cpu_openbsd_arm64.s generated vendored Normal file
View File

@ -0,0 +1,11 @@
// Copyright 2022 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.
#include "textflag.h"
TEXT libc_sysctl_trampoline<>(SB),NOSPLIT,$0-0
JMP libc_sysctl(SB)
GLOBL ·libc_sysctl_trampoline_addr(SB), RODATA, $8
DATA ·libc_sysctl_trampoline_addr(SB)/8, $libc_sysctl_trampoline<>(SB)

View File

@ -2,8 +2,8 @@
// Use of this source code is governed by a BSD-style // Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
//go:build !linux && !netbsd && arm64 //go:build !linux && !netbsd && !openbsd && arm64
// +build !linux,!netbsd,arm64 // +build !linux,!netbsd,!openbsd,arm64
package cpu package cpu

View File

@ -29,8 +29,6 @@ import (
"bytes" "bytes"
"strings" "strings"
"unsafe" "unsafe"
"golang.org/x/sys/internal/unsafeheader"
) )
// ByteSliceFromString returns a NUL-terminated slice of bytes // ByteSliceFromString returns a NUL-terminated slice of bytes
@ -82,13 +80,7 @@ func BytePtrToString(p *byte) string {
ptr = unsafe.Pointer(uintptr(ptr) + 1) ptr = unsafe.Pointer(uintptr(ptr) + 1)
} }
var s []byte return string(unsafe.Slice(p, n))
h := (*unsafeheader.Slice)(unsafe.Pointer(&s))
h.Data = unsafe.Pointer(p)
h.Len = n
h.Cap = n
return string(s)
} }
// Single-word zero for use when we need a valid pointer to 0 bytes. // Single-word zero for use when we need a valid pointer to 0 bytes.

View File

@ -4,9 +4,7 @@
package unix package unix
import ( import "unsafe"
"unsafe"
)
// IoctlRetInt performs an ioctl operation specified by req on a device // IoctlRetInt performs an ioctl operation specified by req on a device
// associated with opened file descriptor fd, and returns a non-negative // associated with opened file descriptor fd, and returns a non-negative
@ -217,3 +215,19 @@ func IoctlKCMAttach(fd int, info KCMAttach) error {
func IoctlKCMUnattach(fd int, info KCMUnattach) error { func IoctlKCMUnattach(fd int, info KCMUnattach) error {
return ioctlPtr(fd, SIOCKCMUNATTACH, unsafe.Pointer(&info)) return ioctlPtr(fd, SIOCKCMUNATTACH, unsafe.Pointer(&info))
} }
// IoctlLoopGetStatus64 gets the status of the loop device associated with the
// file descriptor fd using the LOOP_GET_STATUS64 operation.
func IoctlLoopGetStatus64(fd int) (*LoopInfo64, error) {
var value LoopInfo64
if err := ioctlPtr(fd, LOOP_GET_STATUS64, unsafe.Pointer(&value)); err != nil {
return nil, err
}
return &value, nil
}
// IoctlLoopSetStatus64 sets the status of the loop device associated with the
// file descriptor fd using the LOOP_SET_STATUS64 operation.
func IoctlLoopSetStatus64(fd int, value *LoopInfo64) error {
return ioctlPtr(fd, LOOP_SET_STATUS64, unsafe.Pointer(value))
}

View File

@ -73,12 +73,12 @@ aix_ppc64)
darwin_amd64) darwin_amd64)
mkerrors="$mkerrors -m64" mkerrors="$mkerrors -m64"
mktypes="GOARCH=$GOARCH go tool cgo -godefs" mktypes="GOARCH=$GOARCH go tool cgo -godefs"
mkasm="go run mkasm_darwin.go" mkasm="go run mkasm.go"
;; ;;
darwin_arm64) darwin_arm64)
mkerrors="$mkerrors -m64" mkerrors="$mkerrors -m64"
mktypes="GOARCH=$GOARCH go tool cgo -godefs" mktypes="GOARCH=$GOARCH go tool cgo -godefs"
mkasm="go run mkasm_darwin.go" mkasm="go run mkasm.go"
;; ;;
dragonfly_amd64) dragonfly_amd64)
mkerrors="$mkerrors -m64" mkerrors="$mkerrors -m64"
@ -142,33 +142,33 @@ netbsd_arm64)
mktypes="GOARCH=$GOARCH go tool cgo -godefs" mktypes="GOARCH=$GOARCH go tool cgo -godefs"
;; ;;
openbsd_386) openbsd_386)
mkasm="go run mkasm.go"
mkerrors="$mkerrors -m32" mkerrors="$mkerrors -m32"
mksyscall="go run mksyscall.go -l32 -openbsd" mksyscall="go run mksyscall.go -l32 -openbsd -libc"
mksysctl="go run mksysctl_openbsd.go" mksysctl="go run mksysctl_openbsd.go"
mksysnum="go run mksysnum.go 'https://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master'"
mktypes="GOARCH=$GOARCH go tool cgo -godefs" mktypes="GOARCH=$GOARCH go tool cgo -godefs"
;; ;;
openbsd_amd64) openbsd_amd64)
mkasm="go run mkasm.go"
mkerrors="$mkerrors -m64" mkerrors="$mkerrors -m64"
mksyscall="go run mksyscall.go -openbsd" mksyscall="go run mksyscall.go -openbsd -libc"
mksysctl="go run mksysctl_openbsd.go" mksysctl="go run mksysctl_openbsd.go"
mksysnum="go run mksysnum.go 'https://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master'"
mktypes="GOARCH=$GOARCH go tool cgo -godefs" mktypes="GOARCH=$GOARCH go tool cgo -godefs"
;; ;;
openbsd_arm) openbsd_arm)
mkasm="go run mkasm.go"
mkerrors="$mkerrors" mkerrors="$mkerrors"
mksyscall="go run mksyscall.go -l32 -openbsd -arm" mksyscall="go run mksyscall.go -l32 -openbsd -arm -libc"
mksysctl="go run mksysctl_openbsd.go" mksysctl="go run mksysctl_openbsd.go"
mksysnum="go run mksysnum.go 'https://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master'"
# Let the type of C char be signed for making the bare syscall # Let the type of C char be signed for making the bare syscall
# API consistent across platforms. # API consistent across platforms.
mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char" mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char"
;; ;;
openbsd_arm64) openbsd_arm64)
mkasm="go run mkasm.go"
mkerrors="$mkerrors -m64" mkerrors="$mkerrors -m64"
mksyscall="go run mksyscall.go -openbsd" mksyscall="go run mksyscall.go -openbsd -libc"
mksysctl="go run mksysctl_openbsd.go" mksysctl="go run mksysctl_openbsd.go"
mksysnum="go run mksysnum.go 'https://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master'"
# Let the type of C char be signed for making the bare syscall # Let the type of C char be signed for making the bare syscall
# API consistent across platforms. # API consistent across platforms.
mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char" mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char"
@ -214,11 +214,6 @@ esac
if [ "$GOOSARCH" == "aix_ppc64" ]; then if [ "$GOOSARCH" == "aix_ppc64" ]; then
# aix/ppc64 script generates files instead of writing to stdin. # aix/ppc64 script generates files instead of writing to stdin.
echo "$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in && gofmt -w zsyscall_$GOOSARCH.go && gofmt -w zsyscall_"$GOOSARCH"_gccgo.go && gofmt -w zsyscall_"$GOOSARCH"_gc.go " ; echo "$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in && gofmt -w zsyscall_$GOOSARCH.go && gofmt -w zsyscall_"$GOOSARCH"_gccgo.go && gofmt -w zsyscall_"$GOOSARCH"_gc.go " ;
elif [ "$GOOS" == "darwin" ]; then
# 1.12 and later, syscalls via libSystem
echo "$mksyscall -tags $GOOS,$GOARCH,go1.12 $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.go";
# 1.13 and later, syscalls via libSystem (including syscallPtr)
echo "$mksyscall -tags $GOOS,$GOARCH,go1.13 syscall_darwin.1_13.go |gofmt >zsyscall_$GOOSARCH.1_13.go";
elif [ "$GOOS" == "illumos" ]; then elif [ "$GOOS" == "illumos" ]; then
# illumos code generation requires a --illumos switch # illumos code generation requires a --illumos switch
echo "$mksyscall -illumos -tags illumos,$GOARCH syscall_illumos.go |gofmt > zsyscall_illumos_$GOARCH.go"; echo "$mksyscall -illumos -tags illumos,$GOARCH syscall_illumos.go |gofmt > zsyscall_illumos_$GOARCH.go";
@ -232,5 +227,5 @@ esac
if [ -n "$mksysctl" ]; then echo "$mksysctl |gofmt >$zsysctl"; fi if [ -n "$mksysctl" ]; then echo "$mksysctl |gofmt >$zsysctl"; fi
if [ -n "$mksysnum" ]; then echo "$mksysnum |gofmt >zsysnum_$GOOSARCH.go"; fi if [ -n "$mksysnum" ]; then echo "$mksysnum |gofmt >zsysnum_$GOOSARCH.go"; fi
if [ -n "$mktypes" ]; then echo "$mktypes types_$GOOS.go | go run mkpost.go > ztypes_$GOOSARCH.go"; fi if [ -n "$mktypes" ]; then echo "$mktypes types_$GOOS.go | go run mkpost.go > ztypes_$GOOSARCH.go"; fi
if [ -n "$mkasm" ]; then echo "$mkasm $GOARCH"; fi if [ -n "$mkasm" ]; then echo "$mkasm $GOOS $GOARCH"; fi
) | $run ) | $run

27
vendor/golang.org/x/sys/unix/str.go generated vendored
View File

@ -1,27 +0,0 @@
// Copyright 2009 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 aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris
// +build aix darwin dragonfly freebsd linux netbsd openbsd solaris
package unix
func itoa(val int) string { // do it here rather than with fmt to avoid dependency
if val < 0 {
return "-" + uitoa(uint(-val))
}
return uitoa(uint(val))
}
func uitoa(val uint) string {
var buf [32]byte // big enough for int64
i := len(buf) - 1
for val >= 10 {
buf[i] = byte(val%10 + '0')
i--
val /= 10
}
buf[i] = byte(val + '0')
return string(buf[i:])
}

View File

@ -29,8 +29,6 @@ import (
"bytes" "bytes"
"strings" "strings"
"unsafe" "unsafe"
"golang.org/x/sys/internal/unsafeheader"
) )
// ByteSliceFromString returns a NUL-terminated slice of bytes // ByteSliceFromString returns a NUL-terminated slice of bytes
@ -82,13 +80,7 @@ func BytePtrToString(p *byte) string {
ptr = unsafe.Pointer(uintptr(ptr) + 1) ptr = unsafe.Pointer(uintptr(ptr) + 1)
} }
var s []byte return string(unsafe.Slice(p, n))
h := (*unsafeheader.Slice)(unsafe.Pointer(&s))
h.Data = unsafe.Pointer(p)
h.Len = n
h.Cap = n
return string(s)
} }
// Single-word zero for use when we need a valid pointer to 0 bytes. // Single-word zero for use when we need a valid pointer to 0 bytes.

View File

@ -218,13 +218,62 @@ func Accept(fd int) (nfd int, sa Sockaddr, err error) {
} }
func recvmsgRaw(fd int, iov []Iovec, oob []byte, flags int, rsa *RawSockaddrAny) (n, oobn int, recvflags int, err error) { func recvmsgRaw(fd int, iov []Iovec, oob []byte, flags int, rsa *RawSockaddrAny) (n, oobn int, recvflags int, err error) {
// Recvmsg not implemented on AIX var msg Msghdr
return -1, -1, -1, ENOSYS msg.Name = (*byte)(unsafe.Pointer(rsa))
msg.Namelen = uint32(SizeofSockaddrAny)
var dummy byte
if len(oob) > 0 {
// receive at least one normal byte
if emptyIovecs(iov) {
var iova [1]Iovec
iova[0].Base = &dummy
iova[0].SetLen(1)
iov = iova[:]
}
msg.Control = (*byte)(unsafe.Pointer(&oob[0]))
msg.SetControllen(len(oob))
}
if len(iov) > 0 {
msg.Iov = &iov[0]
msg.SetIovlen(len(iov))
}
if n, err = recvmsg(fd, &msg, flags); n == -1 {
return
}
oobn = int(msg.Controllen)
recvflags = int(msg.Flags)
return
} }
func sendmsgN(fd int, iov []Iovec, oob []byte, ptr unsafe.Pointer, salen _Socklen, flags int) (n int, err error) { func sendmsgN(fd int, iov []Iovec, oob []byte, ptr unsafe.Pointer, salen _Socklen, flags int) (n int, err error) {
// SendmsgN not implemented on AIX var msg Msghdr
return -1, ENOSYS msg.Name = (*byte)(unsafe.Pointer(ptr))
msg.Namelen = uint32(salen)
var dummy byte
var empty bool
if len(oob) > 0 {
// send at least one normal byte
empty = emptyIovecs(iov)
if empty {
var iova [1]Iovec
iova[0].Base = &dummy
iova[0].SetLen(1)
iov = iova[:]
}
msg.Control = (*byte)(unsafe.Pointer(&oob[0]))
msg.SetControllen(len(oob))
}
if len(iov) > 0 {
msg.Iov = &iov[0]
msg.SetIovlen(len(iov))
}
if n, err = sendmsg(fd, &msg, flags); err != nil {
return 0, err
}
if len(oob) > 0 && empty {
n = 0
}
return n, nil
} }
func anyToSockaddr(fd int, rsa *RawSockaddrAny) (Sockaddr, error) { func anyToSockaddr(fd int, rsa *RawSockaddrAny) (Sockaddr, error) {

View File

@ -363,7 +363,7 @@ func sendmsgN(fd int, iov []Iovec, oob []byte, ptr unsafe.Pointer, salen _Sockle
var empty bool var empty bool
if len(oob) > 0 { if len(oob) > 0 {
// send at least one normal byte // send at least one normal byte
empty := emptyIovecs(iov) empty = emptyIovecs(iov)
if empty { if empty {
var iova [1]Iovec var iova [1]Iovec
iova[0].Base = &dummy iova[0].Base = &dummy

View File

@ -1,32 +0,0 @@
// Copyright 2019 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 && go1.12 && !go1.13
// +build darwin,go1.12,!go1.13
package unix
import (
"unsafe"
)
const _SYS_GETDIRENTRIES64 = 344
func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) {
// To implement this using libSystem we'd need syscall_syscallPtr for
// fdopendir. However, syscallPtr was only added in Go 1.13, so we fall
// back to raw syscalls for this func on Go 1.12.
var p unsafe.Pointer
if len(buf) > 0 {
p = unsafe.Pointer(&buf[0])
} else {
p = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall6(_SYS_GETDIRENTRIES64, uintptr(fd), uintptr(p), uintptr(len(buf)), uintptr(unsafe.Pointer(basep)), 0, 0)
n = int(r0)
if e1 != 0 {
return n, errnoErr(e1)
}
return n, nil
}

View File

@ -1,108 +0,0 @@
// Copyright 2019 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 && go1.13
// +build darwin,go1.13
package unix
import (
"unsafe"
"golang.org/x/sys/internal/unsafeheader"
)
//sys closedir(dir uintptr) (err error)
//sys readdir_r(dir uintptr, entry *Dirent, result **Dirent) (res Errno)
func fdopendir(fd int) (dir uintptr, err error) {
r0, _, e1 := syscall_syscallPtr(libc_fdopendir_trampoline_addr, uintptr(fd), 0, 0)
dir = uintptr(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
var libc_fdopendir_trampoline_addr uintptr
//go:cgo_import_dynamic libc_fdopendir fdopendir "/usr/lib/libSystem.B.dylib"
func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) {
// Simulate Getdirentries using fdopendir/readdir_r/closedir.
// We store the number of entries to skip in the seek
// offset of fd. See issue #31368.
// It's not the full required semantics, but should handle the case
// of calling Getdirentries or ReadDirent repeatedly.
// It won't handle assigning the results of lseek to *basep, or handle
// the directory being edited underfoot.
skip, err := Seek(fd, 0, 1 /* SEEK_CUR */)
if err != nil {
return 0, err
}
// We need to duplicate the incoming file descriptor
// because the caller expects to retain control of it, but
// fdopendir expects to take control of its argument.
// Just Dup'ing the file descriptor is not enough, as the
// result shares underlying state. Use Openat to make a really
// new file descriptor referring to the same directory.
fd2, err := Openat(fd, ".", O_RDONLY, 0)
if err != nil {
return 0, err
}
d, err := fdopendir(fd2)
if err != nil {
Close(fd2)
return 0, err
}
defer closedir(d)
var cnt int64
for {
var entry Dirent
var entryp *Dirent
e := readdir_r(d, &entry, &entryp)
if e != 0 {
return n, errnoErr(e)
}
if entryp == nil {
break
}
if skip > 0 {
skip--
cnt++
continue
}
reclen := int(entry.Reclen)
if reclen > len(buf) {
// Not enough room. Return for now.
// The counter will let us know where we should start up again.
// Note: this strategy for suspending in the middle and
// restarting is O(n^2) in the length of the directory. Oh well.
break
}
// Copy entry into return buffer.
var s []byte
hdr := (*unsafeheader.Slice)(unsafe.Pointer(&s))
hdr.Data = unsafe.Pointer(&entry)
hdr.Cap = reclen
hdr.Len = reclen
copy(buf, s)
buf = buf[reclen:]
n += reclen
cnt++
}
// Set the seek offset of the input fd to record
// how many files we've already returned.
_, err = Seek(fd, cnt, 0 /* SEEK_SET */)
if err != nil {
return n, err
}
return n, nil
}

View File

@ -19,6 +19,96 @@ import (
"unsafe" "unsafe"
) )
//sys closedir(dir uintptr) (err error)
//sys readdir_r(dir uintptr, entry *Dirent, result **Dirent) (res Errno)
func fdopendir(fd int) (dir uintptr, err error) {
r0, _, e1 := syscall_syscallPtr(libc_fdopendir_trampoline_addr, uintptr(fd), 0, 0)
dir = uintptr(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
var libc_fdopendir_trampoline_addr uintptr
//go:cgo_import_dynamic libc_fdopendir fdopendir "/usr/lib/libSystem.B.dylib"
func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) {
// Simulate Getdirentries using fdopendir/readdir_r/closedir.
// We store the number of entries to skip in the seek
// offset of fd. See issue #31368.
// It's not the full required semantics, but should handle the case
// of calling Getdirentries or ReadDirent repeatedly.
// It won't handle assigning the results of lseek to *basep, or handle
// the directory being edited underfoot.
skip, err := Seek(fd, 0, 1 /* SEEK_CUR */)
if err != nil {
return 0, err
}
// We need to duplicate the incoming file descriptor
// because the caller expects to retain control of it, but
// fdopendir expects to take control of its argument.
// Just Dup'ing the file descriptor is not enough, as the
// result shares underlying state. Use Openat to make a really
// new file descriptor referring to the same directory.
fd2, err := Openat(fd, ".", O_RDONLY, 0)
if err != nil {
return 0, err
}
d, err := fdopendir(fd2)
if err != nil {
Close(fd2)
return 0, err
}
defer closedir(d)
var cnt int64
for {
var entry Dirent
var entryp *Dirent
e := readdir_r(d, &entry, &entryp)
if e != 0 {
return n, errnoErr(e)
}
if entryp == nil {
break
}
if skip > 0 {
skip--
cnt++
continue
}
reclen := int(entry.Reclen)
if reclen > len(buf) {
// Not enough room. Return for now.
// The counter will let us know where we should start up again.
// Note: this strategy for suspending in the middle and
// restarting is O(n^2) in the length of the directory. Oh well.
break
}
// Copy entry into return buffer.
s := unsafe.Slice((*byte)(unsafe.Pointer(&entry)), reclen)
copy(buf, s)
buf = buf[reclen:]
n += reclen
cnt++
}
// Set the seek offset of the input fd to record
// how many files we've already returned.
_, err = Seek(fd, cnt, 0 /* SEEK_SET */)
if err != nil {
return n, err
}
return n, nil
}
// SockaddrDatalink implements the Sockaddr interface for AF_LINK type sockets. // SockaddrDatalink implements the Sockaddr interface for AF_LINK type sockets.
type SockaddrDatalink struct { type SockaddrDatalink struct {
Len uint8 Len uint8

View File

@ -61,7 +61,7 @@ func PtraceGetFsBase(pid int, fsbase *int64) (err error) {
} }
func PtraceIO(req int, pid int, addr uintptr, out []byte, countin int) (count int, err error) { func PtraceIO(req int, pid int, addr uintptr, out []byte, countin int) (count int, err error) {
ioDesc := PtraceIoDesc{Op: int32(req), Offs: (*byte)(unsafe.Pointer(addr)), Addr: (*byte)(unsafe.Pointer(&out[0])), Len: uint32(countin)} ioDesc := PtraceIoDesc{Op: int32(req), Offs: uintptr(unsafe.Pointer(addr)), Addr: uintptr(unsafe.Pointer(&out[0])), Len: uint32(countin)}
err = ptrace(PT_IO, pid, uintptr(unsafe.Pointer(&ioDesc)), 0) err = ptrace(PT_IO, pid, uintptr(unsafe.Pointer(&ioDesc)), 0)
return int(ioDesc.Len), err return int(ioDesc.Len), err
} }

View File

@ -61,7 +61,7 @@ func PtraceGetFsBase(pid int, fsbase *int64) (err error) {
} }
func PtraceIO(req int, pid int, addr uintptr, out []byte, countin int) (count int, err error) { func PtraceIO(req int, pid int, addr uintptr, out []byte, countin int) (count int, err error) {
ioDesc := PtraceIoDesc{Op: int32(req), Offs: (*byte)(unsafe.Pointer(addr)), Addr: (*byte)(unsafe.Pointer(&out[0])), Len: uint64(countin)} ioDesc := PtraceIoDesc{Op: int32(req), Offs: uintptr(unsafe.Pointer(addr)), Addr: uintptr(unsafe.Pointer(&out[0])), Len: uint64(countin)}
err = ptrace(PT_IO, pid, uintptr(unsafe.Pointer(&ioDesc)), 0) err = ptrace(PT_IO, pid, uintptr(unsafe.Pointer(&ioDesc)), 0)
return int(ioDesc.Len), err return int(ioDesc.Len), err
} }

View File

@ -57,7 +57,7 @@ func sendfile(outfd int, infd int, offset *int64, count int) (written int, err e
func Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno) func Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno)
func PtraceIO(req int, pid int, addr uintptr, out []byte, countin int) (count int, err error) { func PtraceIO(req int, pid int, addr uintptr, out []byte, countin int) (count int, err error) {
ioDesc := PtraceIoDesc{Op: int32(req), Offs: (*byte)(unsafe.Pointer(addr)), Addr: (*byte)(unsafe.Pointer(&out[0])), Len: uint32(countin)} ioDesc := PtraceIoDesc{Op: int32(req), Offs: uintptr(unsafe.Pointer(addr)), Addr: uintptr(unsafe.Pointer(&out[0])), Len: uint32(countin)}
err = ptrace(PT_IO, pid, uintptr(unsafe.Pointer(&ioDesc)), 0) err = ptrace(PT_IO, pid, uintptr(unsafe.Pointer(&ioDesc)), 0)
return int(ioDesc.Len), err return int(ioDesc.Len), err
} }

View File

@ -57,7 +57,7 @@ func sendfile(outfd int, infd int, offset *int64, count int) (written int, err e
func Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno) func Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno)
func PtraceIO(req int, pid int, addr uintptr, out []byte, countin int) (count int, err error) { func PtraceIO(req int, pid int, addr uintptr, out []byte, countin int) (count int, err error) {
ioDesc := PtraceIoDesc{Op: int32(req), Offs: (*byte)(unsafe.Pointer(addr)), Addr: (*byte)(unsafe.Pointer(&out[0])), Len: uint64(countin)} ioDesc := PtraceIoDesc{Op: int32(req), Offs: uintptr(unsafe.Pointer(addr)), Addr: uintptr(unsafe.Pointer(&out[0])), Len: uint64(countin)}
err = ptrace(PT_IO, pid, uintptr(unsafe.Pointer(&ioDesc)), 0) err = ptrace(PT_IO, pid, uintptr(unsafe.Pointer(&ioDesc)), 0)
return int(ioDesc.Len), err return int(ioDesc.Len), err
} }

View File

@ -57,7 +57,7 @@ func sendfile(outfd int, infd int, offset *int64, count int) (written int, err e
func Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno) func Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno)
func PtraceIO(req int, pid int, addr uintptr, out []byte, countin int) (count int, err error) { func PtraceIO(req int, pid int, addr uintptr, out []byte, countin int) (count int, err error) {
ioDesc := PtraceIoDesc{Op: int32(req), Offs: (*byte)(unsafe.Pointer(addr)), Addr: (*byte)(unsafe.Pointer(&out[0])), Len: uint64(countin)} ioDesc := PtraceIoDesc{Op: int32(req), Offs: uintptr(unsafe.Pointer(addr)), Addr: uintptr(unsafe.Pointer(&out[0])), Len: uint64(countin)}
err = ptrace(PT_IO, pid, uintptr(unsafe.Pointer(&ioDesc)), 0) err = ptrace(PT_IO, pid, uintptr(unsafe.Pointer(&ioDesc)), 0)
return int(ioDesc.Len), err return int(ioDesc.Len), err
} }

View File

@ -13,6 +13,7 @@ package unix
import ( import (
"encoding/binary" "encoding/binary"
"strconv"
"syscall" "syscall"
"time" "time"
"unsafe" "unsafe"
@ -233,7 +234,7 @@ func Futimesat(dirfd int, path string, tv []Timeval) error {
func Futimes(fd int, tv []Timeval) (err error) { func Futimes(fd int, tv []Timeval) (err error) {
// Believe it or not, this is the best we can do on Linux // Believe it or not, this is the best we can do on Linux
// (and is what glibc does). // (and is what glibc does).
return Utimes("/proc/self/fd/"+itoa(fd), tv) return Utimes("/proc/self/fd/"+strconv.Itoa(fd), tv)
} }
const ImplementsGetwd = true const ImplementsGetwd = true
@ -1541,7 +1542,7 @@ func sendmsgN(fd int, iov []Iovec, oob []byte, ptr unsafe.Pointer, salen _Sockle
var dummy byte var dummy byte
var empty bool var empty bool
if len(oob) > 0 { if len(oob) > 0 {
empty := emptyIovecs(iov) empty = emptyIovecs(iov)
if empty { if empty {
var sockType int var sockType int
sockType, err = GetsockoptInt(fd, SOL_SOCKET, SO_TYPE) sockType, err = GetsockoptInt(fd, SOL_SOCKET, SO_TYPE)
@ -1891,17 +1892,28 @@ func PrctlRetInt(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uint
return int(ret), nil return int(ret), nil
} }
// issue 1435.
// On linux Setuid and Setgid only affects the current thread, not the process.
// This does not match what most callers expect so we must return an error
// here rather than letting the caller think that the call succeeded.
func Setuid(uid int) (err error) { func Setuid(uid int) (err error) {
return EOPNOTSUPP return syscall.Setuid(uid)
} }
func Setgid(uid int) (err error) { func Setgid(gid int) (err error) {
return EOPNOTSUPP return syscall.Setgid(gid)
}
func Setreuid(ruid, euid int) (err error) {
return syscall.Setreuid(ruid, euid)
}
func Setregid(rgid, egid int) (err error) {
return syscall.Setregid(rgid, egid)
}
func Setresuid(ruid, euid, suid int) (err error) {
return syscall.Setresuid(ruid, euid, suid)
}
func Setresgid(rgid, egid, sgid int) (err error) {
return syscall.Setresgid(rgid, egid, sgid)
} }
// SetfsgidRetGid sets fsgid for current thread and returns previous fsgid set. // SetfsgidRetGid sets fsgid for current thread and returns previous fsgid set.
@ -2240,7 +2252,7 @@ func (fh *FileHandle) Bytes() []byte {
if n == 0 { if n == 0 {
return nil return nil
} }
return (*[1 << 30]byte)(unsafe.Pointer(uintptr(unsafe.Pointer(&fh.fileHandle.Type)) + 4))[:n:n] return unsafe.Slice((*byte)(unsafe.Pointer(uintptr(unsafe.Pointer(&fh.fileHandle.Type))+4)), n)
} }
// NameToHandleAt wraps the name_to_handle_at system call; it obtains // NameToHandleAt wraps the name_to_handle_at system call; it obtains
@ -2356,6 +2368,16 @@ func Setitimer(which ItimerWhich, it Itimerval) (Itimerval, error) {
return prev, nil return prev, nil
} }
//sysnb rtSigprocmask(how int, set *Sigset_t, oldset *Sigset_t, sigsetsize uintptr) (err error) = SYS_RT_SIGPROCMASK
func PthreadSigmask(how int, set, oldset *Sigset_t) error {
if oldset != nil {
// Explicitly clear in case Sigset_t is larger than _C__NSIG.
*oldset = Sigset_t{}
}
return rtSigprocmask(how, set, oldset, _C__NSIG/8)
}
/* /*
* Unimplemented * Unimplemented
*/ */
@ -2414,7 +2436,6 @@ func Setitimer(which ItimerWhich, it Itimerval) (Itimerval, error) {
// RestartSyscall // RestartSyscall
// RtSigaction // RtSigaction
// RtSigpending // RtSigpending
// RtSigprocmask
// RtSigqueueinfo // RtSigqueueinfo
// RtSigreturn // RtSigreturn
// RtSigsuspend // RtSigsuspend

View File

@ -41,10 +41,6 @@ func setTimeval(sec, usec int64) Timeval {
//sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) = SYS_SENDFILE64 //sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) = SYS_SENDFILE64
//sys setfsgid(gid int) (prev int, err error) = SYS_SETFSGID32 //sys setfsgid(gid int) (prev int, err error) = SYS_SETFSGID32
//sys setfsuid(uid int) (prev int, err error) = SYS_SETFSUID32 //sys setfsuid(uid int) (prev int, err error) = SYS_SETFSUID32
//sysnb Setregid(rgid int, egid int) (err error) = SYS_SETREGID32
//sysnb Setresgid(rgid int, egid int, sgid int) (err error) = SYS_SETRESGID32
//sysnb Setresuid(ruid int, euid int, suid int) (err error) = SYS_SETRESUID32
//sysnb Setreuid(ruid int, euid int) (err error) = SYS_SETREUID32
//sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error) //sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error)
//sys Stat(path string, stat *Stat_t) (err error) = SYS_STAT64 //sys Stat(path string, stat *Stat_t) (err error) = SYS_STAT64
//sys SyncFileRange(fd int, off int64, n int64, flags int) (err error) //sys SyncFileRange(fd int, off int64, n int64, flags int) (err error)

View File

@ -46,11 +46,7 @@ func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err
//sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) //sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error)
//sys setfsgid(gid int) (prev int, err error) //sys setfsgid(gid int) (prev int, err error)
//sys setfsuid(uid int) (prev int, err error) //sys setfsuid(uid int) (prev int, err error)
//sysnb Setregid(rgid int, egid int) (err error)
//sysnb Setresgid(rgid int, egid int, sgid int) (err error)
//sysnb Setresuid(ruid int, euid int, suid int) (err error)
//sysnb Setrlimit(resource int, rlim *Rlimit) (err error) //sysnb Setrlimit(resource int, rlim *Rlimit) (err error)
//sysnb Setreuid(ruid int, euid int) (err error)
//sys Shutdown(fd int, how int) (err error) //sys Shutdown(fd int, how int) (err error)
//sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error) //sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error)

View File

@ -62,10 +62,6 @@ func Seek(fd int, offset int64, whence int) (newoffset int64, err error) {
//sys Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) = SYS__NEWSELECT //sys Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) = SYS__NEWSELECT
//sys setfsgid(gid int) (prev int, err error) = SYS_SETFSGID32 //sys setfsgid(gid int) (prev int, err error) = SYS_SETFSGID32
//sys setfsuid(uid int) (prev int, err error) = SYS_SETFSUID32 //sys setfsuid(uid int) (prev int, err error) = SYS_SETFSUID32
//sysnb Setregid(rgid int, egid int) (err error) = SYS_SETREGID32
//sysnb Setresgid(rgid int, egid int, sgid int) (err error) = SYS_SETRESGID32
//sysnb Setresuid(ruid int, euid int, suid int) (err error) = SYS_SETRESUID32
//sysnb Setreuid(ruid int, euid int) (err error) = SYS_SETREUID32
//sys Shutdown(fd int, how int) (err error) //sys Shutdown(fd int, how int) (err error)
//sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error) //sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error)
//sys Stat(path string, stat *Stat_t) (err error) = SYS_STAT64 //sys Stat(path string, stat *Stat_t) (err error) = SYS_STAT64

View File

@ -39,11 +39,7 @@ func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err
//sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) //sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error)
//sys setfsgid(gid int) (prev int, err error) //sys setfsgid(gid int) (prev int, err error)
//sys setfsuid(uid int) (prev int, err error) //sys setfsuid(uid int) (prev int, err error)
//sysnb Setregid(rgid int, egid int) (err error)
//sysnb Setresgid(rgid int, egid int, sgid int) (err error)
//sysnb Setresuid(ruid int, euid int, suid int) (err error)
//sysnb setrlimit(resource int, rlim *Rlimit) (err error) //sysnb setrlimit(resource int, rlim *Rlimit) (err error)
//sysnb Setreuid(ruid int, euid int) (err error)
//sys Shutdown(fd int, how int) (err error) //sys Shutdown(fd int, how int) (err error)
//sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error) //sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error)

View File

@ -34,10 +34,6 @@ func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err
//sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) //sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error)
//sys setfsgid(gid int) (prev int, err error) //sys setfsgid(gid int) (prev int, err error)
//sys setfsuid(uid int) (prev int, err error) //sys setfsuid(uid int) (prev int, err error)
//sysnb Setregid(rgid int, egid int) (err error)
//sysnb Setresgid(rgid int, egid int, sgid int) (err error)
//sysnb Setresuid(ruid int, euid int, suid int) (err error)
//sysnb Setreuid(ruid int, euid int) (err error)
//sys Shutdown(fd int, how int) (err error) //sys Shutdown(fd int, how int) (err error)
//sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error) //sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error)

View File

@ -37,11 +37,7 @@ func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err
//sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) //sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error)
//sys setfsgid(gid int) (prev int, err error) //sys setfsgid(gid int) (prev int, err error)
//sys setfsuid(uid int) (prev int, err error) //sys setfsuid(uid int) (prev int, err error)
//sysnb Setregid(rgid int, egid int) (err error)
//sysnb Setresgid(rgid int, egid int, sgid int) (err error)
//sysnb Setresuid(ruid int, euid int, suid int) (err error)
//sysnb Setrlimit(resource int, rlim *Rlimit) (err error) //sysnb Setrlimit(resource int, rlim *Rlimit) (err error)
//sysnb Setreuid(ruid int, euid int) (err error)
//sys Shutdown(fd int, how int) (err error) //sys Shutdown(fd int, how int) (err error)
//sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error) //sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error)
//sys Statfs(path string, buf *Statfs_t) (err error) //sys Statfs(path string, buf *Statfs_t) (err error)

View File

@ -32,10 +32,6 @@ func Syscall9(trap, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr,
//sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) = SYS_SENDFILE64 //sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) = SYS_SENDFILE64
//sys setfsgid(gid int) (prev int, err error) //sys setfsgid(gid int) (prev int, err error)
//sys setfsuid(uid int) (prev int, err error) //sys setfsuid(uid int) (prev int, err error)
//sysnb Setregid(rgid int, egid int) (err error)
//sysnb Setresgid(rgid int, egid int, sgid int) (err error)
//sysnb Setresuid(ruid int, euid int, suid int) (err error)
//sysnb Setreuid(ruid int, euid int) (err error)
//sys Shutdown(fd int, how int) (err error) //sys Shutdown(fd int, how int) (err error)
//sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error) //sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error)
//sys SyncFileRange(fd int, off int64, n int64, flags int) (err error) //sys SyncFileRange(fd int, off int64, n int64, flags int) (err error)

View File

@ -34,10 +34,6 @@ import (
//sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) = SYS_SENDFILE64 //sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) = SYS_SENDFILE64
//sys setfsgid(gid int) (prev int, err error) //sys setfsgid(gid int) (prev int, err error)
//sys setfsuid(uid int) (prev int, err error) //sys setfsuid(uid int) (prev int, err error)
//sysnb Setregid(rgid int, egid int) (err error)
//sysnb Setresgid(rgid int, egid int, sgid int) (err error)
//sysnb Setresuid(ruid int, euid int, suid int) (err error)
//sysnb Setreuid(ruid int, euid int) (err error)
//sys Shutdown(fd int, how int) (err error) //sys Shutdown(fd int, how int) (err error)
//sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error) //sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error)
//sys Stat(path string, stat *Stat_t) (err error) = SYS_STAT64 //sys Stat(path string, stat *Stat_t) (err error) = SYS_STAT64

View File

@ -34,11 +34,7 @@ package unix
//sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) //sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error)
//sys setfsgid(gid int) (prev int, err error) //sys setfsgid(gid int) (prev int, err error)
//sys setfsuid(uid int) (prev int, err error) //sys setfsuid(uid int) (prev int, err error)
//sysnb Setregid(rgid int, egid int) (err error)
//sysnb Setresgid(rgid int, egid int, sgid int) (err error)
//sysnb Setresuid(ruid int, euid int, suid int) (err error)
//sysnb Setrlimit(resource int, rlim *Rlimit) (err error) //sysnb Setrlimit(resource int, rlim *Rlimit) (err error)
//sysnb Setreuid(ruid int, euid int) (err error)
//sys Shutdown(fd int, how int) (err error) //sys Shutdown(fd int, how int) (err error)
//sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error) //sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error)
//sys Stat(path string, stat *Stat_t) (err error) //sys Stat(path string, stat *Stat_t) (err error)

View File

@ -38,11 +38,7 @@ func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err
//sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) //sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error)
//sys setfsgid(gid int) (prev int, err error) //sys setfsgid(gid int) (prev int, err error)
//sys setfsuid(uid int) (prev int, err error) //sys setfsuid(uid int) (prev int, err error)
//sysnb Setregid(rgid int, egid int) (err error)
//sysnb Setresgid(rgid int, egid int, sgid int) (err error)
//sysnb Setresuid(ruid int, euid int, suid int) (err error)
//sysnb Setrlimit(resource int, rlim *Rlimit) (err error) //sysnb Setrlimit(resource int, rlim *Rlimit) (err error)
//sysnb Setreuid(ruid int, euid int) (err error)
//sys Shutdown(fd int, how int) (err error) //sys Shutdown(fd int, how int) (err error)
//sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error) //sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error)

View File

@ -34,11 +34,7 @@ import (
//sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) //sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error)
//sys setfsgid(gid int) (prev int, err error) //sys setfsgid(gid int) (prev int, err error)
//sys setfsuid(uid int) (prev int, err error) //sys setfsuid(uid int) (prev int, err error)
//sysnb Setregid(rgid int, egid int) (err error)
//sysnb Setresgid(rgid int, egid int, sgid int) (err error)
//sysnb Setresuid(ruid int, euid int, suid int) (err error)
//sysnb Setrlimit(resource int, rlim *Rlimit) (err error) //sysnb Setrlimit(resource int, rlim *Rlimit) (err error)
//sysnb Setreuid(ruid int, euid int) (err error)
//sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error) //sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error)
//sys Stat(path string, stat *Stat_t) (err error) //sys Stat(path string, stat *Stat_t) (err error)
//sys Statfs(path string, buf *Statfs_t) (err error) //sys Statfs(path string, buf *Statfs_t) (err error)

View File

@ -31,11 +31,7 @@ package unix
//sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) //sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error)
//sys setfsgid(gid int) (prev int, err error) //sys setfsgid(gid int) (prev int, err error)
//sys setfsuid(uid int) (prev int, err error) //sys setfsuid(uid int) (prev int, err error)
//sysnb Setregid(rgid int, egid int) (err error)
//sysnb Setresgid(rgid int, egid int, sgid int) (err error)
//sysnb Setresuid(ruid int, euid int, suid int) (err error)
//sysnb Setrlimit(resource int, rlim *Rlimit) (err error) //sysnb Setrlimit(resource int, rlim *Rlimit) (err error)
//sysnb Setreuid(ruid int, euid int) (err error)
//sys Shutdown(fd int, how int) (err error) //sys Shutdown(fd int, how int) (err error)
//sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error) //sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error)
//sys Stat(path string, stat *Stat_t) (err error) //sys Stat(path string, stat *Stat_t) (err error)

27
vendor/golang.org/x/sys/unix/syscall_openbsd_libc.go generated vendored Normal file
View File

@ -0,0 +1,27 @@
// Copyright 2022 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 (openbsd && 386) || (openbsd && amd64) || (openbsd && arm) || (openbsd && arm64)
// +build openbsd,386 openbsd,amd64 openbsd,arm openbsd,arm64
package unix
import _ "unsafe"
// Implemented in the runtime package (runtime/sys_openbsd3.go)
func syscall_syscall(fn, a1, a2, a3 uintptr) (r1, r2 uintptr, err Errno)
func syscall_syscall6(fn, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err Errno)
func syscall_syscall10(fn, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10 uintptr) (r1, r2 uintptr, err Errno)
func syscall_rawSyscall(fn, a1, a2, a3 uintptr) (r1, r2 uintptr, err Errno)
func syscall_rawSyscall6(fn, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err Errno)
//go:linkname syscall_syscall syscall.syscall
//go:linkname syscall_syscall6 syscall.syscall6
//go:linkname syscall_syscall10 syscall.syscall10
//go:linkname syscall_rawSyscall syscall.rawSyscall
//go:linkname syscall_rawSyscall6 syscall.rawSyscall6
func syscall_syscall9(fn, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err Errno) {
return syscall_syscall10(fn, a1, a2, a3, a4, a5, a6, a7, a8, a9, 0)
}

View File

@ -750,8 +750,8 @@ type EventPort struct {
// we should handle things gracefully. To do so, we need to keep an extra // we should handle things gracefully. To do so, we need to keep an extra
// reference to the cookie around until the event is processed // reference to the cookie around until the event is processed
// thus the otherwise seemingly extraneous "cookies" map // thus the otherwise seemingly extraneous "cookies" map
// The key of this map is a pointer to the corresponding &fCookie.cookie // The key of this map is a pointer to the corresponding fCookie
cookies map[*interface{}]*fileObjCookie cookies map[*fileObjCookie]struct{}
} }
// PortEvent is an abstraction of the port_event C struct. // PortEvent is an abstraction of the port_event C struct.
@ -778,7 +778,7 @@ func NewEventPort() (*EventPort, error) {
port: port, port: port,
fds: make(map[uintptr]*fileObjCookie), fds: make(map[uintptr]*fileObjCookie),
paths: make(map[string]*fileObjCookie), paths: make(map[string]*fileObjCookie),
cookies: make(map[*interface{}]*fileObjCookie), cookies: make(map[*fileObjCookie]struct{}),
} }
return e, nil return e, nil
} }
@ -799,6 +799,7 @@ func (e *EventPort) Close() error {
} }
e.fds = nil e.fds = nil
e.paths = nil e.paths = nil
e.cookies = nil
return nil return nil
} }
@ -826,17 +827,16 @@ func (e *EventPort) AssociatePath(path string, stat os.FileInfo, events int, coo
if _, found := e.paths[path]; found { if _, found := e.paths[path]; found {
return fmt.Errorf("%v is already associated with this Event Port", path) return fmt.Errorf("%v is already associated with this Event Port", path)
} }
fobj, err := createFileObj(path, stat) fCookie, err := createFileObjCookie(path, stat, cookie)
if err != nil { if err != nil {
return err return err
} }
fCookie := &fileObjCookie{fobj, cookie} _, err = port_associate(e.port, PORT_SOURCE_FILE, uintptr(unsafe.Pointer(fCookie.fobj)), events, (*byte)(unsafe.Pointer(fCookie)))
_, err = port_associate(e.port, PORT_SOURCE_FILE, uintptr(unsafe.Pointer(fobj)), events, (*byte)(unsafe.Pointer(&fCookie.cookie)))
if err != nil { if err != nil {
return err return err
} }
e.paths[path] = fCookie e.paths[path] = fCookie
e.cookies[&fCookie.cookie] = fCookie e.cookies[fCookie] = struct{}{}
return nil return nil
} }
@ -858,7 +858,7 @@ func (e *EventPort) DissociatePath(path string) error {
if err == nil { if err == nil {
// dissociate was successful, safe to delete the cookie // dissociate was successful, safe to delete the cookie
fCookie := e.paths[path] fCookie := e.paths[path]
delete(e.cookies, &fCookie.cookie) delete(e.cookies, fCookie)
} }
delete(e.paths, path) delete(e.paths, path)
return err return err
@ -871,13 +871,16 @@ func (e *EventPort) AssociateFd(fd uintptr, events int, cookie interface{}) erro
if _, found := e.fds[fd]; found { if _, found := e.fds[fd]; found {
return fmt.Errorf("%v is already associated with this Event Port", fd) return fmt.Errorf("%v is already associated with this Event Port", fd)
} }
fCookie := &fileObjCookie{nil, cookie} fCookie, err := createFileObjCookie("", nil, cookie)
_, err := port_associate(e.port, PORT_SOURCE_FD, fd, events, (*byte)(unsafe.Pointer(&fCookie.cookie))) if err != nil {
return err
}
_, err = port_associate(e.port, PORT_SOURCE_FD, fd, events, (*byte)(unsafe.Pointer(fCookie)))
if err != nil { if err != nil {
return err return err
} }
e.fds[fd] = fCookie e.fds[fd] = fCookie
e.cookies[&fCookie.cookie] = fCookie e.cookies[fCookie] = struct{}{}
return nil return nil
} }
@ -896,27 +899,31 @@ func (e *EventPort) DissociateFd(fd uintptr) error {
if err == nil { if err == nil {
// dissociate was successful, safe to delete the cookie // dissociate was successful, safe to delete the cookie
fCookie := e.fds[fd] fCookie := e.fds[fd]
delete(e.cookies, &fCookie.cookie) delete(e.cookies, fCookie)
} }
delete(e.fds, fd) delete(e.fds, fd)
return err return err
} }
func createFileObj(name string, stat os.FileInfo) (*fileObj, error) { func createFileObjCookie(name string, stat os.FileInfo, cookie interface{}) (*fileObjCookie, error) {
fobj := new(fileObj) fCookie := new(fileObjCookie)
fCookie.cookie = cookie
if name != "" && stat != nil {
fCookie.fobj = new(fileObj)
bs, err := ByteSliceFromString(name) bs, err := ByteSliceFromString(name)
if err != nil { if err != nil {
return nil, err return nil, err
} }
fobj.Name = (*int8)(unsafe.Pointer(&bs[0])) fCookie.fobj.Name = (*int8)(unsafe.Pointer(&bs[0]))
s := stat.Sys().(*syscall.Stat_t) s := stat.Sys().(*syscall.Stat_t)
fobj.Atim.Sec = s.Atim.Sec fCookie.fobj.Atim.Sec = s.Atim.Sec
fobj.Atim.Nsec = s.Atim.Nsec fCookie.fobj.Atim.Nsec = s.Atim.Nsec
fobj.Mtim.Sec = s.Mtim.Sec fCookie.fobj.Mtim.Sec = s.Mtim.Sec
fobj.Mtim.Nsec = s.Mtim.Nsec fCookie.fobj.Mtim.Nsec = s.Mtim.Nsec
fobj.Ctim.Sec = s.Ctim.Sec fCookie.fobj.Ctim.Sec = s.Ctim.Sec
fobj.Ctim.Nsec = s.Ctim.Nsec fCookie.fobj.Ctim.Nsec = s.Ctim.Nsec
return fobj, nil }
return fCookie, nil
} }
// GetOne wraps port_get(3c) and returns a single PortEvent. // GetOne wraps port_get(3c) and returns a single PortEvent.
@ -929,44 +936,50 @@ func (e *EventPort) GetOne(t *Timespec) (*PortEvent, error) {
p := new(PortEvent) p := new(PortEvent)
e.mu.Lock() e.mu.Lock()
defer e.mu.Unlock() defer e.mu.Unlock()
e.peIntToExt(pe, p) err = e.peIntToExt(pe, p)
if err != nil {
return nil, err
}
return p, nil return p, nil
} }
// peIntToExt converts a cgo portEvent struct into the friendlier PortEvent // peIntToExt converts a cgo portEvent struct into the friendlier PortEvent
// NOTE: Always call this function while holding the e.mu mutex // NOTE: Always call this function while holding the e.mu mutex
func (e *EventPort) peIntToExt(peInt *portEvent, peExt *PortEvent) { func (e *EventPort) peIntToExt(peInt *portEvent, peExt *PortEvent) error {
if e.cookies == nil {
return fmt.Errorf("this EventPort is already closed")
}
peExt.Events = peInt.Events peExt.Events = peInt.Events
peExt.Source = peInt.Source peExt.Source = peInt.Source
cookie := (*interface{})(unsafe.Pointer(peInt.User)) fCookie := (*fileObjCookie)(unsafe.Pointer(peInt.User))
peExt.Cookie = *cookie _, found := e.cookies[fCookie]
if !found {
panic("unexpected event port address; may be due to kernel bug; see https://go.dev/issue/54254")
}
peExt.Cookie = fCookie.cookie
delete(e.cookies, fCookie)
switch peInt.Source { switch peInt.Source {
case PORT_SOURCE_FD: case PORT_SOURCE_FD:
delete(e.cookies, cookie)
peExt.Fd = uintptr(peInt.Object) peExt.Fd = uintptr(peInt.Object)
// Only remove the fds entry if it exists and this cookie matches // Only remove the fds entry if it exists and this cookie matches
if fobj, ok := e.fds[peExt.Fd]; ok { if fobj, ok := e.fds[peExt.Fd]; ok {
if &fobj.cookie == cookie { if fobj == fCookie {
delete(e.fds, peExt.Fd) delete(e.fds, peExt.Fd)
} }
} }
case PORT_SOURCE_FILE: case PORT_SOURCE_FILE:
if fCookie, ok := e.cookies[cookie]; ok && uintptr(unsafe.Pointer(fCookie.fobj)) == uintptr(peInt.Object) {
// Use our stashed reference rather than using unsafe on what we got back
// the unsafe version would be (*fileObj)(unsafe.Pointer(uintptr(peInt.Object)))
peExt.fobj = fCookie.fobj peExt.fobj = fCookie.fobj
} else {
panic("mismanaged memory")
}
delete(e.cookies, cookie)
peExt.Path = BytePtrToString((*byte)(unsafe.Pointer(peExt.fobj.Name))) peExt.Path = BytePtrToString((*byte)(unsafe.Pointer(peExt.fobj.Name)))
// Only remove the paths entry if it exists and this cookie matches // Only remove the paths entry if it exists and this cookie matches
if fobj, ok := e.paths[peExt.Path]; ok { if fobj, ok := e.paths[peExt.Path]; ok {
if &fobj.cookie == cookie { if fobj == fCookie {
delete(e.paths, peExt.Path) delete(e.paths, peExt.Path)
} }
} }
} }
return nil
} }
// Pending wraps port_getn(3c) and returns how many events are pending. // Pending wraps port_getn(3c) and returns how many events are pending.
@ -990,7 +1003,7 @@ func (e *EventPort) Get(s []PortEvent, min int, timeout *Timespec) (int, error)
got := uint32(min) got := uint32(min)
max := uint32(len(s)) max := uint32(len(s))
var err error var err error
ps := make([]portEvent, max, max) ps := make([]portEvent, max)
_, err = port_getn(e.port, &ps[0], max, &got, timeout) _, err = port_getn(e.port, &ps[0], max, &got, timeout)
// got will be trustworthy with ETIME, but not any other error. // got will be trustworthy with ETIME, but not any other error.
if err != nil && err != ETIME { if err != nil && err != ETIME {
@ -998,8 +1011,18 @@ func (e *EventPort) Get(s []PortEvent, min int, timeout *Timespec) (int, error)
} }
e.mu.Lock() e.mu.Lock()
defer e.mu.Unlock() defer e.mu.Unlock()
valid := 0
for i := 0; i < int(got); i++ { for i := 0; i < int(got); i++ {
e.peIntToExt(&ps[i], &s[i]) err2 := e.peIntToExt(&ps[i], &s[i])
if err2 != nil {
if valid == 0 && err == nil {
// If err2 is the only error and there are no valid events
// to return, return it to the caller.
err = err2
} }
return int(got), err break
}
valid = i + 1
}
return valid, err
} }

View File

@ -13,8 +13,6 @@ import (
"sync" "sync"
"syscall" "syscall"
"unsafe" "unsafe"
"golang.org/x/sys/internal/unsafeheader"
) )
var ( var (
@ -117,11 +115,7 @@ func (m *mmapper) Mmap(fd int, offset int64, length int, prot int, flags int) (d
} }
// Use unsafe to convert addr into a []byte. // Use unsafe to convert addr into a []byte.
var b []byte b := unsafe.Slice((*byte)(unsafe.Pointer(addr)), length)
hdr := (*unsafeheader.Slice)(unsafe.Pointer(&b))
hdr.Data = unsafe.Pointer(addr)
hdr.Cap = length
hdr.Len = length
// Register mapping in m and return it. // Register mapping in m and return it.
p := &b[cap(b)-1] p := &b[cap(b)-1]
@ -429,11 +423,15 @@ func Send(s int, buf []byte, flags int) (err error) {
} }
func Sendto(fd int, p []byte, flags int, to Sockaddr) (err error) { func Sendto(fd int, p []byte, flags int, to Sockaddr) (err error) {
ptr, n, err := to.sockaddr() var ptr unsafe.Pointer
var salen _Socklen
if to != nil {
ptr, salen, err = to.sockaddr()
if err != nil { if err != nil {
return err return err
} }
return sendto(fd, p, flags, ptr, n) }
return sendto(fd, p, flags, ptr, salen)
} }
func SetsockoptByte(fd, level, opt int, value byte) (err error) { func SetsockoptByte(fd, level, opt int, value byte) (err error) {

View File

@ -7,11 +7,7 @@
package unix package unix
import ( import "unsafe"
"unsafe"
"golang.org/x/sys/internal/unsafeheader"
)
// SysvShmAttach attaches the Sysv shared memory segment associated with the // SysvShmAttach attaches the Sysv shared memory segment associated with the
// shared memory identifier id. // shared memory identifier id.
@ -34,12 +30,7 @@ func SysvShmAttach(id int, addr uintptr, flag int) ([]byte, error) {
} }
// Use unsafe to convert addr into a []byte. // Use unsafe to convert addr into a []byte.
// TODO: convert to unsafe.Slice once we can assume Go 1.17 b := unsafe.Slice((*byte)(unsafe.Pointer(addr)), int(info.Segsz))
var b []byte
hdr := (*unsafeheader.Slice)(unsafe.Pointer(&b))
hdr.Data = unsafe.Pointer(addr)
hdr.Cap = int(info.Segsz)
hdr.Len = int(info.Segsz)
return b, nil return b, nil
} }

View File

@ -160,13 +160,12 @@ func Lremovexattr(link string, attr string) (err error) {
} }
func Listxattr(file string, dest []byte) (sz int, err error) { func Listxattr(file string, dest []byte) (sz int, err error) {
d := initxattrdest(dest, 0)
destsiz := len(dest) destsiz := len(dest)
// FreeBSD won't allow you to list xattrs from multiple namespaces // FreeBSD won't allow you to list xattrs from multiple namespaces
s := 0 s, pos := 0, 0
for _, nsid := range [...]int{EXTATTR_NAMESPACE_USER, EXTATTR_NAMESPACE_SYSTEM} { for _, nsid := range [...]int{EXTATTR_NAMESPACE_USER, EXTATTR_NAMESPACE_SYSTEM} {
stmp, e := ExtattrListFile(file, nsid, uintptr(d), destsiz) stmp, e := ListxattrNS(file, nsid, dest[pos:])
/* Errors accessing system attrs are ignored so that /* Errors accessing system attrs are ignored so that
* we can implement the Linux-like behavior of omitting errors that * we can implement the Linux-like behavior of omitting errors that
@ -175,66 +174,102 @@ func Listxattr(file string, dest []byte) (sz int, err error) {
* Linux will still error if we ask for user attributes on a file that * Linux will still error if we ask for user attributes on a file that
* we don't have read permissions on, so don't ignore those errors * we don't have read permissions on, so don't ignore those errors
*/ */
if e != nil && e == EPERM && nsid != EXTATTR_NAMESPACE_USER { if e != nil {
if e == EPERM && nsid != EXTATTR_NAMESPACE_USER {
continue continue
} else if e != nil { }
return s, e return s, e
} }
s += stmp s += stmp
destsiz -= s pos = s
if destsiz < 0 { if pos > destsiz {
destsiz = 0 pos = destsiz
} }
d = initxattrdest(dest, s) }
return s, nil
}
func ListxattrNS(file string, nsid int, dest []byte) (sz int, err error) {
d := initxattrdest(dest, 0)
destsiz := len(dest)
s, e := ExtattrListFile(file, nsid, uintptr(d), destsiz)
if e != nil {
return 0, err
} }
return s, nil return s, nil
} }
func Flistxattr(fd int, dest []byte) (sz int, err error) { func Flistxattr(fd int, dest []byte) (sz int, err error) {
d := initxattrdest(dest, 0)
destsiz := len(dest) destsiz := len(dest)
s := 0 s, pos := 0, 0
for _, nsid := range [...]int{EXTATTR_NAMESPACE_USER, EXTATTR_NAMESPACE_SYSTEM} { for _, nsid := range [...]int{EXTATTR_NAMESPACE_USER, EXTATTR_NAMESPACE_SYSTEM} {
stmp, e := ExtattrListFd(fd, nsid, uintptr(d), destsiz) stmp, e := FlistxattrNS(fd, nsid, dest[pos:])
if e != nil && e == EPERM && nsid != EXTATTR_NAMESPACE_USER {
if e != nil {
if e == EPERM && nsid != EXTATTR_NAMESPACE_USER {
continue continue
} else if e != nil { }
return s, e return s, e
} }
s += stmp s += stmp
destsiz -= s pos = s
if destsiz < 0 { if pos > destsiz {
destsiz = 0 pos = destsiz
} }
d = initxattrdest(dest, s) }
return s, nil
}
func FlistxattrNS(fd int, nsid int, dest []byte) (sz int, err error) {
d := initxattrdest(dest, 0)
destsiz := len(dest)
s, e := ExtattrListFd(fd, nsid, uintptr(d), destsiz)
if e != nil {
return 0, err
} }
return s, nil return s, nil
} }
func Llistxattr(link string, dest []byte) (sz int, err error) { func Llistxattr(link string, dest []byte) (sz int, err error) {
d := initxattrdest(dest, 0)
destsiz := len(dest) destsiz := len(dest)
s := 0 s, pos := 0, 0
for _, nsid := range [...]int{EXTATTR_NAMESPACE_USER, EXTATTR_NAMESPACE_SYSTEM} { for _, nsid := range [...]int{EXTATTR_NAMESPACE_USER, EXTATTR_NAMESPACE_SYSTEM} {
stmp, e := ExtattrListLink(link, nsid, uintptr(d), destsiz) stmp, e := LlistxattrNS(link, nsid, dest[pos:])
if e != nil && e == EPERM && nsid != EXTATTR_NAMESPACE_USER {
if e != nil {
if e == EPERM && nsid != EXTATTR_NAMESPACE_USER {
continue continue
} else if e != nil { }
return s, e return s, e
} }
s += stmp s += stmp
destsiz -= s pos = s
if destsiz < 0 { if pos > destsiz {
destsiz = 0 pos = destsiz
} }
d = initxattrdest(dest, s) }
return s, nil
}
func LlistxattrNS(link string, nsid int, dest []byte) (sz int, err error) {
d := initxattrdest(dest, 0)
destsiz := len(dest)
s, e := ExtattrListLink(link, nsid, uintptr(d), destsiz)
if e != nil {
return 0, err
} }
return s, nil return s, nil

View File

@ -1,11 +1,11 @@
// mkerrors.sh -Wall -Werror -static -I/tmp/include -m32 // mkerrors.sh -Wall -Werror -static -I/tmp/386/include -m32
// Code generated by the command above; see README.md. DO NOT EDIT. // Code generated by the command above; see README.md. DO NOT EDIT.
//go:build 386 && linux //go:build 386 && linux
// +build 386,linux // +build 386,linux
// Code generated by cmd/cgo -godefs; DO NOT EDIT. // Code generated by cmd/cgo -godefs; DO NOT EDIT.
// cgo -godefs -- -Wall -Werror -static -I/tmp/include -m32 _const.go // cgo -godefs -- -Wall -Werror -static -I/tmp/386/include -m32 _const.go
package unix package unix

View File

@ -1,11 +1,11 @@
// mkerrors.sh -Wall -Werror -static -I/tmp/include -m64 // mkerrors.sh -Wall -Werror -static -I/tmp/amd64/include -m64
// Code generated by the command above; see README.md. DO NOT EDIT. // Code generated by the command above; see README.md. DO NOT EDIT.
//go:build amd64 && linux //go:build amd64 && linux
// +build amd64,linux // +build amd64,linux
// Code generated by cmd/cgo -godefs; DO NOT EDIT. // Code generated by cmd/cgo -godefs; DO NOT EDIT.
// cgo -godefs -- -Wall -Werror -static -I/tmp/include -m64 _const.go // cgo -godefs -- -Wall -Werror -static -I/tmp/amd64/include -m64 _const.go
package unix package unix

View File

@ -1,11 +1,11 @@
// mkerrors.sh -Wall -Werror -static -I/tmp/include // mkerrors.sh -Wall -Werror -static -I/tmp/arm/include
// Code generated by the command above; see README.md. DO NOT EDIT. // Code generated by the command above; see README.md. DO NOT EDIT.
//go:build arm && linux //go:build arm && linux
// +build arm,linux // +build arm,linux
// Code generated by cmd/cgo -godefs; DO NOT EDIT. // Code generated by cmd/cgo -godefs; DO NOT EDIT.
// cgo -godefs -- -Wall -Werror -static -I/tmp/include _const.go // cgo -godefs -- -Wall -Werror -static -I/tmp/arm/include _const.go
package unix package unix

View File

@ -1,11 +1,11 @@
// mkerrors.sh -Wall -Werror -static -I/tmp/include -fsigned-char // mkerrors.sh -Wall -Werror -static -I/tmp/arm64/include -fsigned-char
// Code generated by the command above; see README.md. DO NOT EDIT. // Code generated by the command above; see README.md. DO NOT EDIT.
//go:build arm64 && linux //go:build arm64 && linux
// +build arm64,linux // +build arm64,linux
// Code generated by cmd/cgo -godefs; DO NOT EDIT. // Code generated by cmd/cgo -godefs; DO NOT EDIT.
// cgo -godefs -- -Wall -Werror -static -I/tmp/include -fsigned-char _const.go // cgo -godefs -- -Wall -Werror -static -I/tmp/arm64/include -fsigned-char _const.go
package unix package unix

View File

@ -1,11 +1,11 @@
// mkerrors.sh -Wall -Werror -static -I/tmp/include // mkerrors.sh -Wall -Werror -static -I/tmp/loong64/include
// Code generated by the command above; see README.md. DO NOT EDIT. // Code generated by the command above; see README.md. DO NOT EDIT.
//go:build loong64 && linux //go:build loong64 && linux
// +build loong64,linux // +build loong64,linux
// Code generated by cmd/cgo -godefs; DO NOT EDIT. // Code generated by cmd/cgo -godefs; DO NOT EDIT.
// cgo -godefs -- -Wall -Werror -static -I/tmp/include _const.go // cgo -godefs -- -Wall -Werror -static -I/tmp/loong64/include _const.go
package unix package unix

View File

@ -1,11 +1,11 @@
// mkerrors.sh -Wall -Werror -static -I/tmp/include // mkerrors.sh -Wall -Werror -static -I/tmp/mips/include
// Code generated by the command above; see README.md. DO NOT EDIT. // Code generated by the command above; see README.md. DO NOT EDIT.
//go:build mips && linux //go:build mips && linux
// +build mips,linux // +build mips,linux
// Code generated by cmd/cgo -godefs; DO NOT EDIT. // Code generated by cmd/cgo -godefs; DO NOT EDIT.
// cgo -godefs -- -Wall -Werror -static -I/tmp/include _const.go // cgo -godefs -- -Wall -Werror -static -I/tmp/mips/include _const.go
package unix package unix

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