diff --git a/go.mod b/go.mod index c3cf6a4..bb8f407 100644 --- a/go.mod +++ b/go.mod @@ -8,11 +8,11 @@ require ( github.com/iancoleman/strcase v0.3.0 github.com/stretchr/testify v1.12.1 github.com/txix-open/bgjob v1.6.0 - github.com/txix-open/isp-kit v1.74.1 + github.com/txix-open/isp-kit v1.76.0 github.com/txix-open/jsonschema v1.3.0 - golang.org/x/crypto v0.55.0 - golang.org/x/sync v0.22.0 - google.golang.org/grpc v1.83.2 + golang.org/x/crypto v0.59.0 + golang.org/x/sync v0.25.0 + google.golang.org/grpc v1.85.0 ) require ( @@ -22,61 +22,63 @@ require ( github.com/cenkalti/backoff/v5 v5.0.3 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/coder/websocket v1.8.15 // indirect - github.com/gabriel-vasile/mimetype v1.4.15 // indirect - github.com/getsentry/sentry-go v0.49.0 // indirect - github.com/go-faker/faker/v4 v4.11.0 // indirect + github.com/gabriel-vasile/mimetype v1.4.16 // indirect + github.com/getsentry/sentry-go v0.50.0 // indirect + github.com/go-faker/faker/v4 v4.12.0 // indirect github.com/go-logr/logr v1.4.4 // indirect github.com/go-logr/stdr v1.2.2 // indirect - github.com/go-playground/locales v0.14.1 // indirect - github.com/go-playground/universal-translator v0.18.1 // indirect - github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0 // indirect + github.com/go-playground/locales v0.14.2 // indirect + github.com/go-playground/universal-translator v0.18.2 // indirect + github.com/grpc-ecosystem/grpc-gateway/v2 v2.34.0 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect - github.com/jackc/pgx/v5 v5.10.0 // indirect - github.com/jackc/puddle/v2 v2.2.2 // indirect + github.com/jackc/pgx/v5 v5.13.0 // indirect + github.com/jackc/puddle/v2 v2.2.4 // indirect github.com/jmoiron/sqlx v1.4.0 // indirect github.com/json-iterator/go v1.1.12 // indirect - github.com/klauspost/compress v1.19.2 // indirect + github.com/klauspost/compress v1.20.4 // indirect github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 // indirect github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 // indirect github.com/leodido/go-urn v1.5.0 // indirect github.com/mailru/easyjson v0.9.2 // indirect - github.com/mfridman/interpolate v0.0.2 // indirect + github.com/mfridman/interpolate v0.2.0 // indirect github.com/mitchellh/mapstructure v1.5.0 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect - github.com/pressly/goose/v3 v3.27.3 // indirect - github.com/prometheus/client_golang v1.24.1 // indirect - github.com/prometheus/client_model v0.6.2 // indirect - github.com/prometheus/common v0.70.1 // indirect - github.com/prometheus/procfs v0.21.1 // indirect + github.com/pandatix/go-abnf v0.5.5 // indirect + github.com/pressly/goose/v3 v3.30.1 // indirect + github.com/prometheus/client_golang v1.25.0 // indirect + github.com/prometheus/client_model v0.6.3 // indirect + github.com/prometheus/common v0.74.0 // indirect + github.com/prometheus/procfs v0.23.0 // indirect github.com/robfig/cron/v3 v3.0.1 // indirect - github.com/sethvargo/go-retry v0.4.0 // indirect + github.com/sethvargo/go-retry v0.5.0 // indirect github.com/txix-open/bellows v1.2.0 // indirect github.com/txix-open/etp/v4 v4.1.3 // indirect - github.com/txix-open/validator/v10 v10.0.0-20250506161033-f8ce404fffdb // indirect + github.com/txix-open/validator/v10 v10.0.0-20261027072444-85f3391fc5c3 // indirect github.com/wk8/go-ordered-map/v2 v2.1.8 // indirect github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect github.com/xeipuuv/gojsonschema v1.2.0 // indirect go.opentelemetry.io/auto/sdk v1.2.1 // indirect - go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.71.0 // indirect - go.opentelemetry.io/otel v1.46.0 // indirect - go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.46.0 // indirect - go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.46.0 // indirect - go.opentelemetry.io/otel/metric v1.46.0 // indirect - go.opentelemetry.io/otel/sdk v1.46.0 // indirect - go.opentelemetry.io/otel/trace v1.46.0 // indirect - go.opentelemetry.io/proto/otlp v1.11.0 // indirect + go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.72.0 // indirect + go.opentelemetry.io/otel v1.47.0 // indirect + go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0 // indirect + go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0 // indirect + go.opentelemetry.io/otel/log v1.47.0 // indirect + go.opentelemetry.io/otel/metric v1.47.0 // indirect + go.opentelemetry.io/otel/sdk v1.47.0 // indirect + go.opentelemetry.io/otel/trace v1.47.0 // indirect + go.opentelemetry.io/proto/otlp v1.11.1 // indirect go.uber.org/multierr v1.11.0 // indirect go.uber.org/zap v1.28.0 // indirect - go.yaml.in/yaml/v3 v3.0.5 // indirect - golang.org/x/net v0.58.0 // indirect - golang.org/x/sys v0.47.0 // indirect - golang.org/x/text v0.41.0 // indirect - google.golang.org/genproto/googleapis/api v0.0.0-20260825221802-da73d73af1c5 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20260825221802-da73d73af1c5 // indirect + go.yaml.in/yaml/v3 v3.0.6 // indirect + golang.org/x/net v0.63.0 // indirect + golang.org/x/sys v0.50.0 // indirect + golang.org/x/text v0.44.0 // indirect + google.golang.org/genproto/googleapis/api v0.0.0-20261118221215-c8830f628b3f // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20261118221215-c8830f628b3f // indirect google.golang.org/protobuf v1.36.12 // indirect gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect diff --git a/go.sum b/go.sum index bfab8b8..8cb1bed 100644 --- a/go.sum +++ b/go.sum @@ -21,16 +21,23 @@ github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSs github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= +github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2xWg= github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc= github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE= github.com/gabriel-vasile/mimetype v1.4.15 h1:05iP/CYtZ/w455R/KZM6rZ5ieAdh99UPtd+d3YzLmaI= github.com/gabriel-vasile/mimetype v1.4.15/go.mod h1:azpTcoLcDZRNgFou5j+APrqQx9HqVPWa6ijYQIIVswQ= +github.com/gabriel-vasile/mimetype v1.4.16 h1:5izNFuvA37st1dDRAcA7TtmngBmRgiIPDmTtiEvjx1E= +github.com/gabriel-vasile/mimetype v1.4.16/go.mod h1:3oFFwxX8kTklZwzIl2aQEDZT0lKY8xH92ST88bAwba4= github.com/getsentry/sentry-go v0.49.0 h1:Ehejknu1l023Ub7QoRBVLAI7g3Jnhqku4oWx4B4Sh5s= github.com/getsentry/sentry-go v0.49.0/go.mod h1:nuMJAoCfe1u0Bts2ocyNI+TW8HT84vRMqwA5Qq/SKUI= +github.com/getsentry/sentry-go v0.50.0 h1:gkO59rn/i0RCAXUUTflC5QVbTQGPXbaFabs2olVzc9g= +github.com/getsentry/sentry-go v0.50.0/go.mod h1:+xsDuN+SoRN/xfs1hdq78wnrE3omIZf+FCuh9FOW1C8= github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA= github.com/go-errors/errors v1.4.2/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og= github.com/go-faker/faker/v4 v4.11.0 h1:HeIFTzafXsgrlxKE2QySGGTQocfGdQ8sGqU2CXvs120= github.com/go-faker/faker/v4 v4.11.0/go.mod h1:VFIEwWDd16EdYDLF6NJ5gAAzEp7vz5LgKgJ2iZ17Tdg= +github.com/go-faker/faker/v4 v4.12.0 h1:yZXxuoQjxN+C2PVgYoDSHGiD9wj6dX1/Ful4p7QQV0k= +github.com/go-faker/faker/v4 v4.12.0/go.mod h1:VFIEwWDd16EdYDLF6NJ5gAAzEp7vz5LgKgJ2iZ17Tdg= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8= github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= @@ -40,13 +47,18 @@ github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lY github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= +github.com/go-playground/locales v0.14.2 h1:d8UmcrM6Nip0hfGZKLGpAvZH37XB4TS0xzK9B56YNCY= +github.com/go-playground/locales v0.14.2/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= +github.com/go-playground/universal-translator v0.18.2 h1:LCsMLC9RzmbUMNUPVYD15dmcjwYAJhmX8mPZRW4rAVU= +github.com/go-playground/universal-translator v0.18.2/go.mod h1:67VZIMp5lQpDWlnStOct22q1bkdJGJqHghbOtmkawxk= github.com/go-resty/resty/v2 v2.17.2 h1:FQW5oHYcIlkCNrMD2lloGScxcHJ0gkjshV3qcQAyHQk= github.com/go-resty/resty/v2 v2.17.2/go.mod h1:kCKZ3wWmwJaNc7S29BRtUhJwy7iqmn+2mLtQrOyQlVA= github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg= github.com/go-sql-driver/mysql v1.10.0 h1:Q+1LV8DkHJvSYAdR83XzuhDaTykuDx0l6fkXxoWCWfw= github.com/go-sql-driver/mysql v1.10.0/go.mod h1:M+cqaI7+xxXGG9swrdeUIoPG3Y3KCkF0pZej+SK+nWk= +github.com/go-sql-driver/mysql v1.10.1 h1:arlSnNLq6a5yxGxV7qg9lF4j0C+KwD6NbQyKr9QL6ME= github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= @@ -56,6 +68,8 @@ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0 h1:/Tnpcb2E0Pz/tN9s3bfEY2Q8ePCEX9iuS+cneUwncnw= github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0/go.mod h1:zOBXOsUaBSjKgmH4OGzV1esUpR3oUSCPYVd2cUBjKYY= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.34.0 h1:vzlTzzi4tHLa/JQdIE5LeXw6SEX5EVVhq/VPqKHnKOk= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.34.0/go.mod h1:FHXQZnW5pA0txiMr3jApv9uNJzZ+7mYZd+u+PPenCFU= github.com/iancoleman/strcase v0.3.0 h1:nTXanmYxhfFAMjZL34Ov6gkzEsSJZ5DbhxWjvSASxEI= github.com/iancoleman/strcase v0.3.0/go.mod h1:iwCmte+B7n89clKwxIoIXy/HfoL7AsD47ZCWhYzw7ho= github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= @@ -64,8 +78,12 @@ github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7Ulw github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= github.com/jackc/pgx/v5 v5.10.0 h1:VhSvgU2jSli8o3AqIEOTJr7rZwAEUVo4E4XhR94Zfr0= github.com/jackc/pgx/v5 v5.10.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4= +github.com/jackc/pgx/v5 v5.13.0 h1:Hl08k64maU0nrRyVUEbwCnK6/gT0EhMrtAqBHz9/gA4= +github.com/jackc/pgx/v5 v5.13.0/go.mod h1:u2Fi6no03HCSBYE+ZVdLxbwdu3xyi2vU+K/YNJioSds= github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= +github.com/jackc/puddle/v2 v2.2.4 h1:N6Mz6EGB9DL0bz3OEfxJ7eoOpjRHnnjpOh+G8kbLoG8= +github.com/jackc/puddle/v2 v2.2.4/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= github.com/jmoiron/sqlx v1.4.0 h1:1PLqN7S1UYp5t4SrVVnt4nUVNemrDAtxlulVe+Qgm3o= github.com/jmoiron/sqlx v1.4.0/go.mod h1:ZrZ7UsYB/weZdl2Bxg6jCRO9c3YHl8r3ahlKmRT4JLY= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= @@ -74,6 +92,8 @@ github.com/julienschmidt/httprouter v1.3.0 h1:U0609e9tgbseu3rBINet9P48AI/D3oJs4d github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM= github.com/klauspost/compress v1.19.2 h1:hMRETovs/pu/dVWN7zIT1PGG8t509MwT6bO7XSi26R8= github.com/klauspost/compress v1.19.2/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ= +github.com/klauspost/compress v1.20.4 h1:dD0v/bvxtjCBqQu6sx1TNWkalEY5lNTIe+HY9w8TeNI= +github.com/klauspost/compress v1.20.4/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= @@ -92,10 +112,13 @@ github.com/mailru/easyjson v0.9.2 h1:dX8U45hQsZpxd80nLvDGihsQ/OxlvTkVUXH2r/8cb2M github.com/mailru/easyjson v0.9.2/go.mod h1:1+xMtQp2MRNVL/V1bOzuP3aP8VNwRW55fQUto+XFtTU= github.com/mattn/go-isatty v0.0.23 h1:cYwCQTQf3HB6xUC+BtyCLZNr7IzbOmoZbmssVNzSyiQ= github.com/mattn/go-isatty v0.0.23/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A= +github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI= github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU= github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y= github.com/mfridman/interpolate v0.0.2 h1:pnuTK7MQIxxFz1Gr+rjSIx9u7qVjf5VOoM/u6BbAxPY= github.com/mfridman/interpolate v0.0.2/go.mod h1:p+7uk6oE07mpE/Ik1b8EckO0O4ZXiGAfshKBWLUM9Xg= +github.com/mfridman/interpolate v0.2.0 h1:HM9ID8p6CUxoMJX+fECOtGQ2Mu7TW/GIMPyu48nnvUg= +github.com/mfridman/interpolate v0.2.0/go.mod h1:8SfDy95IaPNnIokZh9mvIppmc3fGl8fx+Gu7uusuO9Q= github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= @@ -107,6 +130,9 @@ github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w= github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= +github.com/ncruces/go-strftime v1.1.0 h1:vtPmPWMkb539RGV9WpWT9EwJGvrOCKvMNI4obWL47Hk= +github.com/pandatix/go-abnf v0.5.5 h1:EXex5KkRQx4Dm6GnpAcQnIMBs9KiK0uf8p/wq+4t9PM= +github.com/pandatix/go-abnf v0.5.5/go.mod h1:AE0KD3/VNoCjGzc1gqetRKshbI4SYErXQ/8kPenR5mc= github.com/pingcap/errors v0.11.4 h1:lFuQV/oaUMGcD2tqt+01ROSmJs75VG1ToEOkZIZ4nE4= github.com/pingcap/errors v0.11.4/go.mod h1:Oi8TUi2kEtXXLMJk9l1cGmz20kV3TaQ0usTwv5KuLY8= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= @@ -114,16 +140,27 @@ github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINE github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pressly/goose/v3 v3.27.3 h1:pIglVHjw99r4e/hDHHwbl9vfOsDMqUokfkXo6+n/RxA= github.com/pressly/goose/v3 v3.27.3/go.mod h1:Dag+xpV6o20HR2LFY1j0q6MDwc3f7vPUFDA77R+0yGY= +github.com/pressly/goose/v3 v3.30.1 h1:KO28meBdbAUIdMbTP7bl9dp1FYZGXcYWb2O7miT09lE= +github.com/pressly/goose/v3 v3.30.1/go.mod h1:CHGwuG2acDerUaXwz2i5T18VSauXpYDiL4WxzDvcOIM= github.com/prometheus/client_golang v1.24.1 h1:JnJkREXzWxUdCuPFpIWZiPispT9xVV59uiuyR2bPlnU= github.com/prometheus/client_golang v1.24.1/go.mod h1:F+oSRECHg4sse5ucfYpYDeIv/hu68Zo0uoHKetWnzcE= +github.com/prometheus/client_golang v1.25.0 h1:cDtW1TcFsMi1RJc8khwCKB4VhzwV04aKqbYtNOXuiK0= +github.com/prometheus/client_golang v1.25.0/go.mod h1:j2X/4/kaQHLPnmyEU8zjmkndo1T317VpCIQEml8LTKk= github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk= github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE= +github.com/prometheus/client_model v0.6.3 h1:O0jaTVAYNxTHYInEPFJt5I3+sN8zqBtVMPTB1qyxiEo= +github.com/prometheus/client_model v0.6.3/go.mod h1:gpN5P9S7Rr6Yr92PiQ+Ixvhf6JZEkF1dnxsYL2aPBEM= github.com/prometheus/common v0.70.1 h1:1HvjP4D5oL3t8RsPlwxA9onvvStjtIHYE5XuuwOi/PY= github.com/prometheus/common v0.70.1/go.mod h1:VdFUQDMZK3VLkurFUVhia6uys/0suUp86TJz5qbJRhc= +github.com/prometheus/common v0.74.0 h1:6iYW8MsYvmEnXFD9zLGgF0qmReaRhs3OMONu1c/nrLI= +github.com/prometheus/common v0.74.0/go.mod h1:i/02C+FCst5B1etKgWesNrD49n+onplJCqUCtUKkOeA= github.com/prometheus/procfs v0.21.1 h1:GljZCt+zSTS+NZq88cyQ1LjZ+RCHp3uVuabBWA5+OJI= github.com/prometheus/procfs v0.21.1/go.mod h1:aB55Cww9pdSJVHk0hUf0inxWyyjPogFIjmHKYgMKmtY= +github.com/prometheus/procfs v0.23.0 h1:ad+S6FTkzwaMgacKLM5h6bNKExS+DMH0YiUwXItH/o4= +github.com/prometheus/procfs v0.23.0/go.mod h1:3AVXO0FqLafyYFU/V/IQRZlC8Rgqz8Dm/x6pKLK+RIk= github.com/rabbitmq/amqp091-go v1.14.0 h1:RSaT7aOKt/OrkVUyswPDW29lnRz9psuGmfZFBmLqLek= github.com/rabbitmq/amqp091-go v1.14.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o= +github.com/rabbitmq/amqp091-go v1.17.0 h1:6KmTqrnJq93cGIE3Q3UnXgsqw6NtLu8MNfFoIbfBAIQ= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs= @@ -132,6 +169,8 @@ github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0t github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= github.com/sethvargo/go-retry v0.4.0 h1:9qy1OoIAxBL+gBYnkTnTnWle5wlfsXQlwRzIbbpdqPw= github.com/sethvargo/go-retry v0.4.0/go.mod h1:tvsjdKG6xfiCx4LSiUZ06kcv38xvdVQwv8R6/VnnVWg= +github.com/sethvargo/go-retry v0.5.0 h1:JYfFKmVJ8ER06GReN1efzc5cm52BrVsFVzmcHiKJwfY= +github.com/sethvargo/go-retry v0.5.0/go.mod h1:tvsjdKG6xfiCx4LSiUZ06kcv38xvdVQwv8R6/VnnVWg= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= @@ -155,10 +194,14 @@ github.com/txix-open/grmq v1.12.0 h1:lSPYvwLfTL0+b0xDQmuuN6RaKS3NCEJNK9ccWpOWa8Y github.com/txix-open/grmq v1.12.0/go.mod h1:6m9CCTQao/HAFalu5rFOZGJ5KLEP6WzzIwj80Ml3KGE= github.com/txix-open/isp-kit v1.74.1 h1:2WQl1+e6E1TXcgkm554kYpiyORgZiyJa/zQIks4cUCw= github.com/txix-open/isp-kit v1.74.1/go.mod h1:i4g+hgfVQAXa02kHqr104TqYEsiW2em17RZF0KjkB78= +github.com/txix-open/isp-kit v1.76.0 h1:kqhX2DuoTfeW7BIshedG26TRIfOgX0QOInm606ssGVg= +github.com/txix-open/isp-kit v1.76.0/go.mod h1:hR9iAlh3x9gEg5GfALrrkN/2SbGkgZQCmwO2GZWjC1M= github.com/txix-open/jsonschema v1.3.0 h1:XGuOTg22G7PdqfKypjajM20/i5FyGfFYsJKmheebKi4= github.com/txix-open/jsonschema v1.3.0/go.mod h1:l8YDZ1nvJrw6uxWowSVOxCV/ebiMJyapffW87ZEqH00= github.com/txix-open/validator/v10 v10.0.0-20250506161033-f8ce404fffdb h1:UJgT4u/QMv5QHKOQeJ7igShHa36c2/vIRqJiRLdDlf0= github.com/txix-open/validator/v10 v10.0.0-20250506161033-f8ce404fffdb/go.mod h1:0biAFE0bgbcKeBBAwgEDhbZz6uT1vuSETCrFQlv2RiA= +github.com/txix-open/validator/v10 v10.0.0-20261027072444-85f3391fc5c3 h1:1jE11HLmMHDYYAcE+UmQ5VHgz4stzz0+daJbDWS+sEs= +github.com/txix-open/validator/v10 v10.0.0-20261027072444-85f3391fc5c3/go.mod h1:Yf41v210LFyYAj+tGmDh7PHdGsTaZjdBzHG0ptUvihw= github.com/wk8/go-ordered-map/v2 v2.1.8 h1:5h/BUHu93oj4gIdvHHHGsScSTMijfx5PeYkE/fJgbpc= github.com/wk8/go-ordered-map/v2 v2.1.8/go.mod h1:5nJHM5DyteebpVlHnWMV0rPz6Zp7+xBAnxjb1X5vnTw= github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= @@ -172,24 +215,44 @@ go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.71.0 h1:oFNJW32h2SXnET7XXstgT7pVh4vN+jW+GfiIaBguIZE= go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.71.0/go.mod h1:+H3sPOFwag14eMHTPMElZtV0e4YfVZ/85KgrKUCB5FI= +go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.72.0 h1:jva1c3z2ZFEQ5sTvnLG2tBALNehO+QvdXKQii6eKRoo= +go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.72.0/go.mod h1:3pjFS5EnOVfjvYO6/NMdtJFHFQR+8uiGtrZ965nZP4w= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0 h1:3g7B90UzBltIDKq1/5mrTGxTnOFDV0ICOhLoxiZ8jlg= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0/go.mod h1:Ef8SuTh59BT7+ofpDxN9z+yOlc4t2GjLmKDgYNJL/NU= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0 h1:LxwW/9ctSCv+QkE/cLR7M91ZIkXNMqJtEMi1vCw9U8s= go.opentelemetry.io/otel v1.46.0 h1:FHt5/CDyVxi/8IM1CH7VE/rRgq3kLHa2mSTVMO8AWyc= go.opentelemetry.io/otel v1.46.0/go.mod h1:Gj3SEScelsNC45tp4nSxRYlS+f5iez7W8XPMCt905kE= +go.opentelemetry.io/otel v1.47.0 h1:j7ALJ/zgkS7Z6aeJW09p8VC9804bC+PpeTfCD4XPnOM= +go.opentelemetry.io/otel v1.47.0/go.mod h1:8wS9O2qfXrYrzp6hIF/HOYJJf/wIhFPhR2xLuP+iXQU= go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.46.0 h1:OFnwLJr+pF3iHrlGSzbxyuo6/6HyBlnlN1CWEJmBVcw= go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.46.0/go.mod h1:716wFneO0ov19A2beH5hjfh9AK5z/VWNAtDijp1Y0/g= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0 h1:julhjPeUH/q/7hinbSdDdqt5h7Zw9YWmRlWRhI0jd54= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0/go.mod h1:Ao2mz688LH/tFf0yMAenidq6k2YNSx6SIY2q6jDACck= go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.46.0 h1:KrC1YrQeSt46ITMWAbgQx1M1eV1/1TKzttrBzymPmss= go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.46.0/go.mod h1:zDSEzoEqsOrgBeGvH66KRgxh90VonFyJqBHA0Pk3+rM= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0 h1:aXZXsZ012wOgVkqaiQv+Z/d8V0xKjmg70F6m4CE94lc= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0/go.mod h1:ziu1gUIJhAaxM3EV1e3Ralk5AAyL1UOYz3lJJ4VSI38= +go.opentelemetry.io/otel/log v1.47.0 h1:cOTS1CcLbSQeZKanGJ+0JpF/+t4PELi3O3bbl2lqCcI= +go.opentelemetry.io/otel/log v1.47.0/go.mod h1:9byitSQ5pLC6PpqwGXjqdMKya6ZTswHRZh2vvXT33nw= go.opentelemetry.io/otel/metric v1.46.0 h1:yBnkXvgV7AXFILZc5K6IZe/CBFF3OS7BJ8ov6/lj0K8= go.opentelemetry.io/otel/metric v1.46.0/go.mod h1:iPmdWqifKUdzziPkvvzIJXITl56fQx2mGM/DHLB3/2o= +go.opentelemetry.io/otel/metric v1.47.0 h1:4PptaldXx3Eat1XjMZ68pPJEs5wrhlemctZE9a3UdWY= +go.opentelemetry.io/otel/metric v1.47.0/go.mod h1:ADGSXxRrXM6bjbvLo535EstVFlPpPYZm4LBKixjDHwU= go.opentelemetry.io/otel/sdk v1.46.0 h1:h5CNQQjEbuQXY/JfZtgt3i7HVFV3aHPO2OAwO2eTYPI= go.opentelemetry.io/otel/sdk v1.46.0/go.mod h1:GAERFXFt5SYCEB+YiKUbMBeza6UaDH7GmGOZEfh2gSM= +go.opentelemetry.io/otel/sdk v1.47.0 h1:zWXEr4j2lFefG87TU6Yg8a7ngfohIKFZHKp0Hf5hC6I= +go.opentelemetry.io/otel/sdk v1.47.0/go.mod h1:VUc24kiOeoGsxG8G9ULx3fWKvB7jMhnGE8Oi607lgR0= go.opentelemetry.io/otel/sdk/metric v1.46.0 h1:0piZ26EG4RBfebb2jhDH6ERCYHoVWduc3kLgPCwSnSE= go.opentelemetry.io/otel/sdk/metric v1.46.0/go.mod h1:I1PbKrdVc8Qu8HYVDNtqVIwLwjNrhsV/uFuxfwg8mO4= +go.opentelemetry.io/otel/sdk/metric v1.47.0 h1:lfISg2j93VT6yqdk9OfUaZmw/GfcZqCCV3jdXtsPnKw= go.opentelemetry.io/otel/trace v1.46.0 h1:OULy7ccdJnZtJ0UDYFOIGaCmiWzJ8Vi2G/Rsu60qs1c= go.opentelemetry.io/otel/trace v1.46.0/go.mod h1:J7GAXweO77XSFkB/rmAqk9D6ihszhFjLU+d9WuUxDLI= +go.opentelemetry.io/otel/trace v1.47.0 h1:JOjX/Oci8K94QHddo+bbfya/Ai/nf6/dt9ZfrFNWSrM= +go.opentelemetry.io/otel/trace v1.47.0/go.mod h1:jNaSLa2PZEYFG6fRjJABAu+bw4FS08uDmPg28lTghu0= go.opentelemetry.io/proto/otlp v1.11.0 h1:5rrYs0Ykyj50sdU/JU0x8etU+LubXWb+gED6TbEdMIk= go.opentelemetry.io/proto/otlp v1.11.0/go.mod h1:SmVizdCOAm3XBtG1g1NnOdhW6jtddT72hLMhv8VwA8E= +go.opentelemetry.io/proto/otlp v1.11.1 h1:SCrPqH9NE5CmBrOqpjNCiT0X5mGwMyGERXdogfR7Yjw= +go.opentelemetry.io/proto/otlp v1.11.1/go.mod h1:wq8W4aSf6bOy8RZyESOeQFr9Pu7wydWX/TY4sgvrTPg= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= @@ -198,26 +261,45 @@ go.uber.org/zap v1.28.0 h1:IZzaP1Fv73/T/pBMLk4VutPl36uNC+OSUh3JLG3FIjo= go.uber.org/zap v1.28.0/go.mod h1:rDLpOi171uODNm/mxFcuYWxDsqWSAVkFdX4XojSKg/Q= go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ= go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ= +go.yaml.in/yaml/v2 v2.4.5 h1:a5nxWvYi94DRl6QSLlTbLpVmutgx2qg8EVjnJtuFpwI= go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw= go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= +go.yaml.in/yaml/v3 v3.0.6 h1:zcDfvjXEqTQmpjniUBLc91xYJMB2c4QOFxEF/LCEckM= +go.yaml.in/yaml/v3 v3.0.6/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= golang.org/x/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M= golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis= +golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c= +golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U= golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To= golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU= +golang.org/x/net v0.63.0 h1:HCoTmNh9EpD1PpK8gBNFY4gcTY4N+KQEO8ylfIKqFJ0= +golang.org/x/net v0.63.0/go.mod h1:15JLg3IX1bLjHK264EZQEbIpTiR/KVLuo9CTRWd0pig= golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= +golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs= +golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs= golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs= +golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8= golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M= +golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo= +golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY= gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4= gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E= google.golang.org/genproto/googleapis/api v0.0.0-20260825221802-da73d73af1c5 h1:izFU9hz7aeLI/Mi1J0991ae+xcwRLr7hTqWnB/9aIIU= google.golang.org/genproto/googleapis/api v0.0.0-20260825221802-da73d73af1c5/go.mod h1:3LhxRw4YYkf+ylAfgaY9JlVLFKhokkCV8duhLLe7+t0= +google.golang.org/genproto/googleapis/api v0.0.0-20261118221215-c8830f628b3f h1:7CbYDSDM5xqpq8v2tNm+Q057COf1lvA0gorVk+304tY= +google.golang.org/genproto/googleapis/api v0.0.0-20261118221215-c8830f628b3f/go.mod h1:CPxXEEQ1S9iJmInAF/8MNc8tKWnya8I8Kni9Zh2hV0M= google.golang.org/genproto/googleapis/rpc v0.0.0-20260825221802-da73d73af1c5 h1:1VUiZAXyC+zmiFYi+WLtBzr68Cj8wOofHjjrA/kkizc= google.golang.org/genproto/googleapis/rpc v0.0.0-20260825221802-da73d73af1c5/go.mod h1:DjtHYE8FKJLivXcBEjGwndXfIC23G0VpXiXKqG179uA= +google.golang.org/genproto/googleapis/rpc v0.0.0-20261118221215-c8830f628b3f h1:aDW6Vb2T1K0xbAgW+ED8iz39WlgjjX/OKiNh6tXv/+g= +google.golang.org/genproto/googleapis/rpc v0.0.0-20261118221215-c8830f628b3f/go.mod h1:OaIUM3+LpYcK2GXM4FTmhWoIq371Owdr+Cc7/BsYHHc= google.golang.org/grpc v1.83.2 h1:EManeRomTObA0BU7I8vXgg/78uE5MJ9M8B39EX2WscU= google.golang.org/grpc v1.83.2/go.mod h1:YPI1hK3kDked6iHvgX3tR0y+nX/qpMFKhPgFsokw1S8= +google.golang.org/grpc v1.85.0 h1:BPBCfuVRQ1qvBhKDOq9uvQllMvO59rKsYhXpp7Dd8vw= +google.golang.org/grpc v1.85.0/go.mod h1:0rQrOD58yjal/0EaVbGBANindixsCZNQPDV3VKtaKuQ= google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc= google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= @@ -230,9 +312,12 @@ gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= modernc.org/libc v1.74.3 h1:a4J+Z8aVaxPyjyxRAdJzw246PqpcFGvVPnfT/AuM5Ws= modernc.org/libc v1.74.3/go.mod h1:4H7h/MJ8wnjL8RAbp9v3OXgnk22X7MouHIhDbvP3gj4= +modernc.org/libc v1.80.2 h1:3+a4fJZvvzg920ZC0mOepnKPGn7cqCaVeDxm/UnrM1A= modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU= modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg= modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI= modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw= +modernc.org/memory v1.12.1 h1:nFMiWrpStgZczNl6XI9GnIk/rWhYIyHGUaR04pGbp9g= modernc.org/sqlite v1.54.0 h1:JCxR4qwkJvOaqAoYcgDoO25Nc+ROg6EJ2LfBVzdrgog= modernc.org/sqlite v1.54.0/go.mod h1:4ntCLuNmnH8+GNqjka1wNg7KJd5/Hi5FYp8K+XQ7GZw= +modernc.org/sqlite v1.62.0 h1:gMaCjSM1qpl+iOjiWhR1LYP3zqrYDI+5GYLGt6veP2g= diff --git a/vendor/github.com/gabriel-vasile/mimetype/README.md b/vendor/github.com/gabriel-vasile/mimetype/README.md index b024316..bb2dece 100644 --- a/vendor/github.com/gabriel-vasile/mimetype/README.md +++ b/vendor/github.com/gabriel-vasile/mimetype/README.md @@ -13,6 +13,9 @@ Go Reference + + Tests + Code coverage diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/cdf/cdf.go b/vendor/github.com/gabriel-vasile/mimetype/internal/cdf/cdf.go index 926cef7..574c2ea 100644 --- a/vendor/github.com/gabriel-vasile/mimetype/internal/cdf/cdf.go +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/cdf/cdf.go @@ -46,12 +46,14 @@ type cdf struct { satSecs int32s // list of SAT sector ids; usually a sub-slice of raw input satEntries int // number of valid SAT entries reachable through satSecs firstSSAT int32 + ssatSecs int32s // list of SSAT sector ids, precomputed from the firstSSAT chain dirRaw []byte // directory stream bytes (entries are decoded on demand) sst []byte // short-stream pool (root storage's stream) sstBuilt bool // whether sst was already loaded (it is loaded lazily) rootStreamFirst int32 // first sector of the root storage short-stream pool rootStreamSize uint32 // size of the root storage short-stream pool - rootStorageUUID []byte + rootChild int32 // directory id of the root storage's child tree + rootStorageUUID [16]byte } // parse reads the entire on-disk structure required for type detection. It @@ -81,35 +83,108 @@ func parse(raw []byte, c *cdf) bool { masterSAT := int32s{b: raw[76 : 76+4*masterSATSize]} c.buildSAT(masterSAT, firstMSAT, nMSAT) + c.buildSSAT() c.dirRaw = c.readLong(firstDirSec, 0) c.rootStreamFirst = -1 + c.rootChild = -1 var d dirEntry for i, n := 0, c.dirLen(); i < n; i++ { c.dirAt(i, &d) - if d.typ != dirTypeRootStorage || d.streamFirst < 0 { + if d.typ != dirTypeRootStorage { continue } - c.rootStorageUUID = d.storageUUID[:] + copy(c.rootStorageUUID[:], d.storageUUID[:]) + c.rootChild = d.child // Record where the short-stream pool lives; it is loaded lazily by // shortStream the first time a short stream is actually read. - c.rootStreamFirst = d.streamFirst - c.rootStreamSize = d.size + if d.streamFirst >= 0 { + c.rootStreamFirst = d.streamFirst + c.rootStreamSize = d.size + } break } return true } +// rootChildIter iterates over the directory entries that are direct children +// of the root storage, walking the red-black sibling tree hanging off the root +// entry's child pointer. Restricting detection to root-level entries matters: +// embedded OLE objects (e.g. an Excel sheet inside a Word document) carry +// their own SummaryInformation streams deeper in the hierarchy, and a flat +// directory scan can pick those up instead of the document's own. +// If the tree is unusable (no valid root child) iteration degrades to a flat +// scan of all entries so truncated or malformed files still get best-effort +// detection. The iterator lives entirely on the caller's stack: it allocates +// nothing and decodes each visited entry into its inline d field. +type rootChildIter struct { + c *cdf + d dirEntry // entry decoded by the latest successful next call + n int // total directory entries + i int // next index for the flat fallback scan + flat bool // no usable tree; scan all entries instead + visited int // entries visited so far; guards against cyclic trees + sp int // number of ids on stack + stack [64]int32 +} + +// rootChildren returns an iterator over the root storage's direct children. +// Usage: for it := c.rootChildren(); it.next(); { ... use it.d ... } +func (c *cdf) rootChildren() rootChildIter { + it := rootChildIter{c: c, n: c.dirLen()} + if c.rootChild >= 0 && int(c.rootChild) < it.n { + it.stack[0] = c.rootChild + it.sp = 1 + } else { + it.flat = true + } + return it +} + +// next advances to the next entry, decoding it into it.d. It reports false +// when iteration is done. +func (it *rootChildIter) next() bool { + if it.flat { + if it.i >= it.n { + return false + } + it.c.dirAt(it.i, &it.d) + it.i++ + return true + } + for it.sp > 0 { + it.sp-- + id := it.stack[it.sp] + if id < 0 || int(id) >= it.n { + continue + } + if it.visited++; it.visited > it.n { + return false // cyclic sibling pointers in a malformed directory + } + it.c.dirAt(int(id), &it.d) + // Push the siblings. A valid red-black tree of n entries is at most + // 2*log2(n) deep, so the fixed-size stack cannot overflow for any + // real directory; if a malformed tree overflows it, the excess + // branches are dropped and detection degrades gracefully. + for _, sib := range [2]int32{it.d.left, it.d.right} { + if sib >= 0 && it.sp < len(it.stack) { + it.stack[it.sp] = sib + it.sp++ + } + } + return true + } + return false +} + func (c *cdf) detect() CDFType { for _, name := range []string{"\x05SummaryInformation", "\x05DocumentSummaryInformation"} { if t, ok := c.detectFromSummary(name); ok { return t } } - var d dirEntry - for i, n := 0, c.dirLen(); i < n; i++ { - c.dirAt(i, &d) - if t, ok := lookupSection(d.nameBytes(), d.typ); ok { + for it := c.rootChildren(); it.next(); { + if t, ok := lookupSection(it.d.nameBytes(), it.d.typ); ok { return t } } @@ -120,7 +195,7 @@ func (c *cdf) detect() CDFType { // derive a CDFType from the root-storage CLSID, the property NameOfApplication, // and finally the names of sibling user streams. func (c *cdf) detectFromSummary(streamName string) (CDFType, bool) { - if c.rootStorageUUID != nil && bytes.Equal(c.rootStorageUUID, msiCLSID) { + if bytes.Equal(c.rootStorageUUID[:], msiCLSID) { return CDFTypeInstaller, true } raw, ok := c.userStream(streamName) @@ -132,13 +207,11 @@ func (c *cdf) detectFromSummary(streamName string) (CDFType, bool) { return t, true } } - for i, n := 0, c.dirLen(); i < n; i++ { - var d dirEntry - c.dirAt(i, &d) - if d.nameLen == 0 { + for it := c.rootChildren(); it.next(); { + if it.d.nameLen == 0 { continue } - if t, ok := lookupSubstring(d.nameBytes(), name2type); ok { + if t, ok := lookupSubstring(it.d.nameBytes(), name2type); ok { return t, true } } @@ -164,6 +237,9 @@ type dirEntry struct { name [32]byte nameLen uint8 typ uint8 + left int32 // left sibling directory id + right int32 // right sibling directory id + child int32 // first child directory id (for storages) streamFirst int32 size uint32 storageUUID [16]byte @@ -172,23 +248,56 @@ type dirEntry struct { // nameBytes returns the decoded ASCII name without copying. func (d *dirEntry) nameBytes() []byte { return d.name[:d.nameLen] } -func (c *cdf) ssatAt(i int32) int32 { +// buildSSAT records the list of SSAT sector ids by walking the firstSSAT chain +// through the SAT once. The SSAT contents are not materialized; ssatAt computes +// the requested entry directly from c.data via ssatSecs, mirroring satSecs/satAt. +// The walk is bounded by the number of sectors in the file so a cyclic SAT +// (a self-looping sector) cannot spin forever. +func (c *cdf) buildSSAT() { + maxIDs := len(c.data)/c.secSize + 1 + buf := make([]byte, 0, 4*8) + var tmp [4]byte for sid := c.firstSSAT; sid >= 0; { if int(sid) >= c.satLen() { break // SAT is truncated; stop collecting } - buf, ok := c.sector(sid) - if !ok { + if _, ok := c.sector(sid); !ok { break } - lbuf := int32(len(buf) / 4) //nolint:gosec // anything divided by 4 fits int32 - if i < lbuf { - return int32(binary.LittleEndian.Uint32(buf[4*i:])) //nolint:gosec // intentional two's-complement reinterpretation of a sector id + binary.LittleEndian.PutUint32(tmp[:], uint32(sid)) //nolint:gosec // reinterpret sector id + buf = append(buf, tmp[:]...) + if len(buf)/4 > maxIDs { + break // cyclic SAT chain; stop allocating } - i -= lbuf sid = c.satAt(sid) } - return -1 + c.ssatSecs = int32s{b: buf} +} + +// ssatAt returns the i-th SSAT entry (a short-sector id) by indexing directly +// into the precomputed ssatSecs, the same way satAt indexes satSecs. It returns +// -1 when i is past the end of the SSAT or the backing sector is truncated. +func (c *cdf) ssatAt(i int32) int32 { + if i < 0 { + return -1 + } + perSec := int32(c.secSize / 4) //nolint:gosec // secSize is a small power of two + secIdx := int(i / perSec) + if secIdx >= c.ssatSecs.len() { + return -1 + } + sid := c.ssatSecs.at(secIdx) + buf, ok := c.sector(sid) + if !ok { + return -1 + } + entryIdx := i % perSec + //nolint:gosec // anything divided by 4 fits int32 + if entryIdx >= int32(len(buf)/4) { + return -1 // sector truncated short of this entry + } + //nolint:gosec // intentional two's-complement reinterpretation of a sector id + return int32(binary.LittleEndian.Uint32(buf[4*entryIdx:])) } // shortStream returns the root storage short-stream pool, loading it on first @@ -435,6 +544,9 @@ func (c *cdf) readShort(sid int32, length uint32) []byte { } off := int(off64) out = append(out, sst[off:off+c.shortSecSize]...) + if length > 0 && int64(len(out)) >= int64(length) { + break // read enough to satisfy the stream's declared length + } if len(out) >= len(sst) { break // chain longer than the pool: cyclic SSAT, stop } @@ -476,18 +588,19 @@ func (c *cdf) dirAt(i int, out *dirEntry) { } out.nameLen = k out.typ = raw[66] + out.left = readSecID(raw[68:72]) + out.right = readSecID(raw[72:76]) + out.child = readSecID(raw[76:80]) out.streamFirst = readSecID(raw[116:120]) out.size = binary.LittleEndian.Uint32(raw[120:]) copy(out.storageUUID[:], raw[80:96]) } -// userStream finds a user stream by name and returns its bytes. +// userStream finds a root-level user stream by name and returns its bytes. func (c *cdf) userStream(name string) ([]byte, bool) { - var d dirEntry - for i, n := 0, c.dirLen(); i < n; i++ { - c.dirAt(i, &d) - if d.typ == dirTypeUserStream && string(d.nameBytes()) == name { - buf := c.readChain(d.streamFirst, d.size) + for it := c.rootChildren(); it.next(); { + if it.d.typ == dirTypeUserStream && string(it.d.nameBytes()) == name { + buf := c.readChain(it.d.streamFirst, it.d.size) if buf == nil { return nil, false } diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/audio.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/audio.go index ad48d8f..7ef9975 100644 --- a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/audio.go +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/audio.go @@ -50,7 +50,7 @@ func M3U(raw []byte, _ uint32) bool { // AAC matches an Advanced Audio Coding file. func AAC(raw []byte, _ uint32) bool { - return len(raw) > 1 && ((raw[0] == 0xFF && raw[1] == 0xF1) || (raw[0] == 0xFF && raw[1] == 0xF9)) + return len(raw) > 1 && raw[0] == 0xFF && (raw[1] == 0xF1 || raw[1] == 0xF9) } // MP3 matches a .mp3 file. @@ -128,27 +128,30 @@ func id3v2(raw []byte) bool { } size := uint32(raw[6])<<21 | uint32(raw[7])<<14 | uint32(raw[8])<<7 | uint32(raw[9]) - // Disallow too big frames, let's say 10MB. - return size > 0 && size < 10*1024*1024 + // The synchsafe integer is already bounded to 28 bits (~256MB). A 10MB + // cap rejected legitimate files with large ID3v2 album art. #839 + return size > 0 +} + +// iff checks for an Interchange File Format layout: 4-byte container tag, +// 4-byte size, 4-byte format tag. +func iff(raw []byte, container, format []byte) bool { + return len(raw) > 12 && + bytes.Equal(raw[:4], container) && + bytes.Equal(raw[8:12], format) } // Wav matches a Waveform Audio File Format file. func Wav(raw []byte, limit uint32) bool { - return len(raw) > 12 && - bytes.Equal(raw[:4], []byte("RIFF")) && - bytes.Equal(raw[8:12], []byte{0x57, 0x41, 0x56, 0x45}) + return iff(raw, []byte("RIFF"), []byte("WAVE")) } // Aiff matches Audio Interchange File Format file. func Aiff(raw []byte, limit uint32) bool { - return len(raw) > 12 && - bytes.Equal(raw[:4], []byte{0x46, 0x4F, 0x52, 0x4D}) && - bytes.Equal(raw[8:12], []byte{0x41, 0x49, 0x46, 0x46}) + return iff(raw, []byte("FORM"), []byte("AIFF")) } // Qcp matches a Qualcomm Pure Voice file. func Qcp(raw []byte, limit uint32) bool { - return len(raw) > 12 && - bytes.Equal(raw[:4], []byte("RIFF")) && - bytes.Equal(raw[8:12], []byte("QLCM")) + return iff(raw, []byte("RIFF"), []byte("QLCM")) } diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/binary.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/binary.go index d217968..9e14b6f 100644 --- a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/binary.go +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/binary.go @@ -121,29 +121,22 @@ func Dbf(raw []byte, limit uint32) bool { return slices.Contains(dbfTypes, raw[0]) } -// ElfObj matches an object file. -func ElfObj(raw []byte, limit uint32) bool { - return len(raw) > 17 && ((raw[16] == 0x01 && raw[17] == 0x00) || - (raw[16] == 0x00 && raw[17] == 0x01)) +func elfType(raw []byte, t byte) bool { + return len(raw) > 17 && + ((raw[16] == t && raw[17] == 0x00) || (raw[16] == 0x00 && raw[17] == t)) } +// ElfObj matches an object file. +func ElfObj(raw []byte, limit uint32) bool { return elfType(raw, 0x01) } + // ElfExe matches an executable file. -func ElfExe(raw []byte, limit uint32) bool { - return len(raw) > 17 && ((raw[16] == 0x02 && raw[17] == 0x00) || - (raw[16] == 0x00 && raw[17] == 0x02)) -} +func ElfExe(raw []byte, limit uint32) bool { return elfType(raw, 0x02) } // ElfLib matches a shared library file. -func ElfLib(raw []byte, limit uint32) bool { - return len(raw) > 17 && ((raw[16] == 0x03 && raw[17] == 0x00) || - (raw[16] == 0x00 && raw[17] == 0x03)) -} +func ElfLib(raw []byte, limit uint32) bool { return elfType(raw, 0x03) } // ElfDump matches a core dump file. -func ElfDump(raw []byte, limit uint32) bool { - return len(raw) > 17 && ((raw[16] == 0x04 && raw[17] == 0x00) || - (raw[16] == 0x00 && raw[17] == 0x04)) -} +func ElfDump(raw []byte, limit uint32) bool { return elfType(raw, 0x04) } // Dcm matches a DICOM medical format file. func Dcm(raw []byte, limit uint32) bool { diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/image.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/image.go index d46faca..1f4164e 100644 --- a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/image.go +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/image.go @@ -178,9 +178,7 @@ func jpeg2k(raw []byte, sig []byte) bool { // Webp matches a WebP file. func Webp(raw []byte, _ uint32) bool { - return len(raw) > 12 && - bytes.Equal(raw[0:4], []byte("RIFF")) && - bytes.Equal(raw[8:12], []byte{0x57, 0x45, 0x42, 0x50}) + return iff(raw, []byte("RIFF"), []byte("WEBP")) } // Dwg matches a CAD drawing file. diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/magic.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/magic.go index f078ff3..802515b 100644 --- a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/magic.go +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/magic.go @@ -101,25 +101,13 @@ func markup(b scan.Bytes, sigs ...[]byte) bool { return false } func markupCheck(sig, raw []byte) bool { - if len(raw) < len(sig)+1 { + if !ciCheck(sig, raw) { return false } - - // perform case insensitive check - for i, b := range sig { - db := raw[i] - if 'A' <= b && b <= 'Z' { - db &= 0xDF - } - if b != db { - return false - } - } // Next byte must be space or right angle bracket. if db := raw[len(sig)]; !scan.ByteIsWS(db) && db != '>' { return false } - return true } diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/ms_office.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/ms_office.go index 62cced0..27b63b2 100644 --- a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/ms_office.go +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/ms_office.go @@ -46,26 +46,16 @@ func Ole(raw []byte, limit uint32) bool { return bytes.HasPrefix(raw, []byte{0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1}) } -// Doc matches a Microsoft Word 97-2003 file. -// See: https://github.com/decalage2/oletools/blob/412ee36ae45e70f42123e835871bac956d958461/oletools/common/clsid.py -func Doc(raw []byte, _ uint32) bool { +// cdfOrClsid checks if the raw input is detected as the given CDF type, and if +// the CDF parser returns a generic result, falls back to matching root storage CLSIDs. +func cdfOrClsid(raw []byte, want cdf.CDFType, clsids ...[]byte) bool { fromParsing := cdf.Detect(raw) - if fromParsing == cdf.CDFTypeDoc { + if fromParsing == want { return true } if fromParsing != cdf.CDFTypeGeneric { return false } - // Fallback for inputs where the CDF directory is past the read limit: match - // the root storage CLSID, which often lies within the first sectors. - clsids := [][]byte{ - // Microsoft Word 97-2003 Document (Word.Document.8) - {0x06, 0x09, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}, - // Microsoft Word 6.0-7.0 Document (Word.Document.6) - {0x00, 0x09, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}, - // Microsoft Word Picture (Word.Picture.8) - {0x07, 0x09, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}, - } for _, clsid := range clsids { if matchOleClsid(raw, clsid) { return true @@ -74,25 +64,27 @@ func Doc(raw []byte, _ uint32) bool { return false } +// Doc matches a Microsoft Word 97-2003 file. +// See: https://github.com/decalage2/oletools/blob/412ee36ae45e70f42123e835871bac956d958461/oletools/common/clsid.py +func Doc(raw []byte, _ uint32) bool { + return cdfOrClsid(raw, cdf.CDFTypeDoc, + // Microsoft Word 97-2003 Document (Word.Document.8) + []byte{0x06, 0x09, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}, + // Microsoft Word 6.0-7.0 Document (Word.Document.6) + []byte{0x00, 0x09, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}, + // Microsoft Word Picture (Word.Picture.8) + []byte{0x07, 0x09, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}, + ) +} + // Ppt matches a Microsoft PowerPoint 97-2003 file or a PowerPoint 95 presentation. func Ppt(raw []byte, limit uint32) bool { - fromParsing := cdf.Detect(raw) - if fromParsing == cdf.CDFTypePpt { - return true - } - if fromParsing != cdf.CDFTypeGeneric { - return false - } - // Fallback for inputs where the CDF directory is past the read limit. - // Root CLSID test is the safest way to identify the OLE, however, the format - // often places the root CLSID at the end of the file. - if matchOleClsid(raw, []byte{ - 0x10, 0x8d, 0x81, 0x64, 0x9b, 0x4f, 0xcf, 0x11, - 0x86, 0xea, 0x00, 0xaa, 0x00, 0xb9, 0x29, 0xe8, - }) || matchOleClsid(raw, []byte{ - 0x70, 0xae, 0x7b, 0xea, 0x3b, 0xfb, 0xcd, 0x11, - 0xa9, 0x03, 0x00, 0xaa, 0x00, 0x51, 0x0e, 0xa3, - }) { + if cdfOrClsid(raw, cdf.CDFTypePpt, + []byte{0x10, 0x8d, 0x81, 0x64, 0x9b, 0x4f, 0xcf, 0x11, + 0x86, 0xea, 0x00, 0xaa, 0x00, 0xb9, 0x29, 0xe8}, + []byte{0x70, 0xae, 0x7b, 0xea, 0x3b, 0xfb, 0xcd, 0x11, + 0xa9, 0x03, 0x00, 0xaa, 0x00, 0x51, 0x0e, 0xa3}, + ) { return true } @@ -117,21 +109,10 @@ func Ppt(raw []byte, limit uint32) bool { // Xls matches a Microsoft Excel 97-2003 file. func Xls(raw []byte, limit uint32) bool { - fromParsing := cdf.Detect(raw) - if fromParsing == cdf.CDFTypeXls { - return true - } - if fromParsing != cdf.CDFTypeGeneric { - return false - } - // Fallback for inputs where the CDF directory is past the read limit. - // Root CLSID test is the safest way to identify the OLE, however, the format - // often places the root CLSID at the end of the file. - if matchOleClsid(raw, []byte{ - 0x10, 0x08, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, - }) || matchOleClsid(raw, []byte{ - 0x20, 0x08, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, - }) { + if cdfOrClsid(raw, cdf.CDFTypeXls, + []byte{0x10, 0x08, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00}, + []byte{0x20, 0x08, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00}, + ) { return true } @@ -168,19 +149,10 @@ func Pub(raw []byte, limit uint32) bool { // Msg matches a Microsoft Outlook email file. func Msg(raw []byte, limit uint32) bool { - fromParsing := cdf.Detect(raw) - if fromParsing == cdf.CDFTypeMsg { - return true - } - if fromParsing != cdf.CDFTypeGeneric { - return false - } - // Fallback for inputs where the CDF directory does not carry the streams the - // parser keys on: match the root storage CLSID instead. - return matchOleClsid(raw, []byte{ - 0x0B, 0x0D, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, - 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46, - }) + return cdfOrClsid(raw, cdf.CDFTypeMsg, + []byte{0x0B, 0x0D, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, + 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}, + ) } // Msi matches a Microsoft Windows Installer file. diff --git a/vendor/github.com/getsentry/sentry-go/.craft.yml b/vendor/github.com/getsentry/sentry-go/.craft.yml index 6c923e3..d65a4b9 100644 --- a/vendor/github.com/getsentry/sentry-go/.craft.yml +++ b/vendor/github.com/getsentry/sentry-go/.craft.yml @@ -15,6 +15,9 @@ targets: - name: github tagPrefix: otel/otlp/v tagOnly: true + - name: github + tagPrefix: cron/v + tagOnly: true - name: github tagPrefix: echo/v tagOnly: true diff --git a/vendor/github.com/getsentry/sentry-go/CHANGELOG.md b/vendor/github.com/getsentry/sentry-go/CHANGELOG.md index 8da887e..b4db12a 100644 --- a/vendor/github.com/getsentry/sentry-go/CHANGELOG.md +++ b/vendor/github.com/getsentry/sentry-go/CHANGELOG.md @@ -1,5 +1,40 @@ # Changelog +## 0.50.0 + +### Breaking Changes 🛠 + +- adds NoopClient implementation. The SDK now returns a non-nil noop client and handles the previous nil checks with checking for a disabled client. Code paths that were using nil checks now need to check for `client.IsEnabled`. by @giortzisg in [#1365](https://github.com/getsentry/sentry-go/pull/1365) + +### New Features ✨ + +#### Crons + +- Add `sentry.WithMonitor` and `Hub.WithMonitor` to wrap a job in cron check-ins and create or update the monitor from code. by @wedamija in [#1443](https://github.com/getsentry/sentry-go/pull/1443) +- Add `sentrycron.AddFunc` to report robfig/cron jobs to Sentry Crons, using the job's spec as the monitor schedule. by @wedamija in [#1443](https://github.com/getsentry/sentry-go/pull/1443) +- Docs: https://github.com/getsentry/sentry-docs/pull/19778 by @wedamija in [#1443](https://github.com/getsentry/sentry-go/pull/1443) + +### Bug Fixes 🐛 + +- (dsn) Build envelope URL without re-parsing by @giortzisg in [#1436](https://github.com/getsentry/sentry-go/pull/1436) +- (httpclient) Decouple span creation from trace propagation by @giortzisg in [#1421](https://github.com/getsentry/sentry-go/pull/1421) +- (slog) Stop replaceAttrs from mutating the handler's grouped attrs by @breken-ai in [#1439](https://github.com/getsentry/sentry-go/pull/1439) +- (zerolog) Unescape JSON string values before sending to Sentry by @breken-ai in [#1440](https://github.com/getsentry/sentry-go/pull/1440) +- Guard concurrent flushes by @giortzisg in [#1449](https://github.com/getsentry/sentry-go/pull/1449) +- Keep http.Hijacker when wrapping a response writer by @knQzx in [#1387](https://github.com/getsentry/sentry-go/pull/1387) + +### Internal Changes 🔧 + +#### Deps + +- Bump getsentry/craft from 2.30.1 to 2.31.2 by @dependabot in [#1441](https://github.com/getsentry/sentry-go/pull/1441) +- Bump getsentry/github-workflows/validate-pr from 4013fc6e1aeb1be1f9d3b4d232624f0ec1afa613 to 36c729264d2edc29ebae61950c50e1e9f043ad7e by @dependabot in [#1442](https://github.com/getsentry/sentry-go/pull/1442) +- Bump go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp from 1.43.0 to 1.45.0 in /otel/otlp by @dependabot in [#1430](https://github.com/getsentry/sentry-go/pull/1430) +- Bump go.opentelemetry.io/otel/sdk from 1.44.0 to 1.45.0 by @dependabot in [#1431](https://github.com/getsentry/sentry-go/pull/1431) +- Bump google.golang.org/grpc from 1.83.1 to 1.83.2 by @dependabot in [#1422](https://github.com/getsentry/sentry-go/pull/1422) +- Bump getsentry/craft from 2.27.2 to 2.30.1 by @dependabot in [#1411](https://github.com/getsentry/sentry-go/pull/1411) +- Bump google.golang.org/grpc from 1.82.1 to 1.83.1 by @dependabot in [#1413](https://github.com/getsentry/sentry-go/pull/1413) + ## 0.49.0 ### Breaking Changes 🛠 diff --git a/vendor/github.com/getsentry/sentry-go/attribute/value.go b/vendor/github.com/getsentry/sentry-go/attribute/value.go index 872a04a..4e00c04 100644 --- a/vendor/github.com/getsentry/sentry-go/attribute/value.go +++ b/vendor/github.com/getsentry/sentry-go/attribute/value.go @@ -305,6 +305,8 @@ func (t Type) String() string { return "invalid" } +const arrayType = "array" + // mapTypesToStr is a map from attribute.Type to the primitive types the server understands. // https://develop.sentry.dev/sdk/foundations/data-model/attributes/#primitive-types var mapTypesToStr = map[Type]string{ @@ -313,9 +315,9 @@ var mapTypesToStr = map[Type]string{ INT64: "integer", FLOAT64: "double", STRING: "string", - BOOLSLICE: "array", - INT64SLICE: "array", - FLOAT64SLICE: "array", - STRINGSLICE: "array", + BOOLSLICE: arrayType, + INT64SLICE: arrayType, + FLOAT64SLICE: arrayType, + STRINGSLICE: arrayType, UINT64: "integer", // wire format: same "integer" type } diff --git a/vendor/github.com/getsentry/sentry-go/client.go b/vendor/github.com/getsentry/sentry-go/client.go index dd6f13b..c4e8750 100644 --- a/vendor/github.com/getsentry/sentry-go/client.go +++ b/vendor/github.com/getsentry/sentry-go/client.go @@ -133,8 +133,8 @@ type ClientOptions struct { // The DSN to use. If the DSN is not set, the client is effectively // disabled. Dsn string - // In debug mode, the debug information is printed to stdout to help you - // understand what sentry is doing. + // In debug mode, diagnostic information is written to DebugWriter, which + // defaults to stderr. Debug bool // Configures whether SDK should generate and attach stacktraces to pure // capture message calls. @@ -298,6 +298,7 @@ type ClientOptions struct { // instances. It must be created with NewClient. type Client struct { mu sync.RWMutex + disabled bool options ClientOptions dsn *protocol.Dsn eventProcessors []EventProcessor @@ -450,6 +451,45 @@ func NewClient(options ClientOptions) (*Client, error) { return &client, nil } +var noopClient = &Client{ + disabled: true, + options: ClientOptions{ + DisableTelemetryBuffer: true, + MaxErrorDepth: maxErrorDepth, + MaxSpans: defaultMaxSpans, + TraceIgnoreStatusCodes: [][]int{{404}}, + }, + sdkIdentifier: sdkIdentifier, + sdkVersion: SDKVersion, + Transport: new(noopTransport), + reportRecorder: report.NoopRecorder(), + reportProvider: report.NoopProvider(), +} + +// NewNoopClient returns the shared client that safely discards telemetry. +// Its mutating methods have no effect. +func NewNoopClient() *Client { + return noopClient +} + +// IsEnabled reports whether the client processes captured telemetry. +// +// It returns false for a nil receiver and for clients returned by +// NewNoopClient. A client can be enabled while using a transport that discards +// telemetry, such as a client configured with an empty DSN. +func (client *Client) IsEnabled() bool { + return client != nil && !client.disabled +} + +// normalizeClient returns client, or the shared no-op client when client is +// nil. +func normalizeClient(client *Client) *Client { + if client == nil { + return noopClient + } + return client +} + func (client *Client) setupTransport() { opts := client.options transport := opts.Transport @@ -555,6 +595,9 @@ func (client *Client) setupIntegrations() { // client is shared among multiple hubs, one per goroutine, such that adding an // event processor to the client affects all hubs that share the client. func (client *Client) AddEventProcessor(processor EventProcessor) { + if !client.IsEnabled() { + return + } client.eventProcessors = append(client.eventProcessors, processor) } @@ -563,6 +606,9 @@ func (client *Client) AddEventProcessor(processor EventProcessor) { // // This is intended for integrations such as OpenTelemetry. func (client *Client) SetExternalContextTraceResolver(resolver func(ctx context.Context) (TraceID, SpanID, bool)) { + if !client.IsEnabled() { + return + } client.mu.Lock() defer client.mu.Unlock() @@ -596,7 +642,7 @@ func (client *Client) Options() ClientOptions { // GetDataCollection returns a copy of the resolved data collection // configuration used by the client. func (client *Client) GetDataCollection() DataCollection { - if client == nil || client.options.DataCollection == nil { + if !client.IsEnabled() || client.options.DataCollection == nil { return DataCollection{} } return *cloneDataCollection(client.options.DataCollection) @@ -604,22 +650,32 @@ func (client *Client) GetDataCollection() DataCollection { // CaptureMessage captures an arbitrary message. func (client *Client) CaptureMessage(message string, hint *EventHint, scope EventModifier) *EventID { + if !client.IsEnabled() { + return nil + } event := client.EventFromMessage(message, LevelInfo) return client.CaptureEvent(event, hint, scope) } // CaptureException captures an error. func (client *Client) CaptureException(exception error, hint *EventHint, scope EventModifier) *EventID { + if !client.IsEnabled() { + return nil + } event := client.EventFromException(exception, LevelError) return client.CaptureEvent(event, hint, scope) } // CaptureCheckIn captures a check in. func (client *Client) CaptureCheckIn(checkIn *CheckIn, monitorConfig *MonitorConfig, scope EventModifier) *EventID { + if !client.IsEnabled() { + return nil + } event := client.EventFromCheckIn(checkIn, monitorConfig) if event != nil && event.CheckIn != nil { - client.CaptureEvent(event, nil, scope) - return &event.CheckIn.ID + if client.CaptureEvent(event, nil, scope) != nil { + return &event.CheckIn.ID + } } return nil } @@ -630,6 +686,9 @@ func (client *Client) CaptureCheckIn(checkIn *CheckIn, monitorConfig *MonitorCon // the utility methods like CaptureException. The return value is the // event ID. In case Sentry is disabled or event was dropped, the return value will be nil. func (client *Client) CaptureEvent(event *Event, hint *EventHint, scope EventModifier) *EventID { + if !client.IsEnabled() { + return nil + } return client.processEvent(event, hint, scope) } @@ -727,6 +786,9 @@ func (client *Client) RecoverWithContext( if err == nil { return nil } + if !client.IsEnabled() { + return nil + } if ctx != nil { if hint == nil { @@ -751,7 +813,8 @@ func (client *Client) RecoverWithContext( // Flush waits until the underlying Transport sends any buffered events to the // Sentry server, blocking for at most the given timeout. It returns false if -// the timeout was reached. In that case, some events may not have been sent. +// the client is disabled or the timeout was reached. In the latter case, some +// events may not have been sent. // // Flush should be called before terminating the program to avoid // unintentionally dropping events. @@ -761,6 +824,9 @@ func (client *Client) RecoverWithContext( // the network synchronously, configure it to use the HTTPSyncTransport in the // call to Init. func (client *Client) Flush(timeout time.Duration) bool { + if !client.IsEnabled() { + return false + } if client.batchLogger != nil || client.batchMeter != nil || client.telemetryProcessor != nil { ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() @@ -770,9 +836,10 @@ func (client *Client) Flush(timeout time.Duration) bool { } // FlushWithContext waits until the underlying Transport sends any buffered events -// to the Sentry server, blocking for at most the duration specified by the context. -// It returns false if the context is canceled before the events are sent. In such a case, -// some events may not be delivered. +// to the Sentry server, blocking for at most the duration specified by the +// context. It returns false if the client is disabled or the context is +// canceled before the events are sent. In the latter case, some events may not +// be delivered. // // FlushWithContext should be called before terminating the program to ensure no // events are unintentionally dropped. @@ -782,6 +849,9 @@ func (client *Client) Flush(timeout time.Duration) bool { // configure the SDK to use HTTPSyncTransport during initialization with Init. func (client *Client) FlushWithContext(ctx context.Context) bool { + if !client.IsEnabled() { + return false + } if client.batchLogger != nil { client.batchLogger.Flush(ctx.Done()) } @@ -799,6 +869,9 @@ func (client *Client) FlushWithContext(ctx context.Context) bool { // Close should be called after Flush and before terminating the program // otherwise some events may be lost. func (client *Client) Close() { + if !client.IsEnabled() { + return + } if client.telemetryProcessor != nil { client.telemetryProcessor.Close(5 * time.Second) } @@ -875,6 +948,9 @@ func (client *Client) EventFromCheckIn(checkIn *CheckIn, monitorConfig *MonitorC } func (client *Client) SetSDKIdentifier(identifier string) { + if !client.IsEnabled() { + return + } client.mu.Lock() defer client.mu.Unlock() diff --git a/vendor/github.com/getsentry/sentry-go/dynamic_sampling_context.go b/vendor/github.com/getsentry/sentry-go/dynamic_sampling_context.go index a257f6f..64bdd4d 100644 --- a/vendor/github.com/getsentry/sentry-go/dynamic_sampling_context.go +++ b/vendor/github.com/getsentry/sentry-go/dynamic_sampling_context.go @@ -43,7 +43,7 @@ func DynamicSamplingContextFromTransaction(span *Span) DynamicSamplingContext { scope := hub.Scope() client := hub.Client() - if client == nil || scope == nil { + if !client.IsEnabled() || scope == nil { return DynamicSamplingContext{ Entries: map[string]string{}, Frozen: false, @@ -53,7 +53,7 @@ func DynamicSamplingContextFromTransaction(span *Span) DynamicSamplingContext { entries := make(map[string]string) if traceID := span.TraceID.String(); traceID != "" { - entries["trace_id"] = traceID + entries[traceIDContextKey] = traceID } if sampleRate := span.sampleRate; sampleRate != 0 { entries["sample_rate"] = strconv.FormatFloat(sampleRate, 'f', -1, 64) @@ -122,7 +122,7 @@ func (d DynamicSamplingContext) String() string { func DynamicSamplingContextFromScope(scope *Scope, client *Client) DynamicSamplingContext { entries := map[string]string{} - if client == nil || scope == nil { + if !client.IsEnabled() || scope == nil { return DynamicSamplingContext{ Entries: entries, Frozen: false, @@ -132,7 +132,7 @@ func DynamicSamplingContextFromScope(scope *Scope, client *Client) DynamicSampli propagationContext := scope.propagationContext if traceID := propagationContext.TraceID.String(); traceID != "" { - entries["trace_id"] = traceID + entries[traceIDContextKey] = traceID } if sampleRate := client.options.TracesSampleRate; sampleRate != 0 { entries["sample_rate"] = strconv.FormatFloat(sampleRate, 'f', -1, 64) diff --git a/vendor/github.com/getsentry/sentry-go/exception.go b/vendor/github.com/getsentry/sentry-go/exception.go index f7ef4a0..e3e8566 100644 --- a/vendor/github.com/getsentry/sentry-go/exception.go +++ b/vendor/github.com/getsentry/sentry-go/exception.go @@ -20,7 +20,7 @@ type visited struct { func (v *visited) seenError(err error) bool { t := reflect.ValueOf(err) - if t.Kind() == reflect.Ptr && !t.IsNil() { + if t.Kind() == reflect.Pointer && !t.IsNil() { ptr := t.Pointer() if _, ok := v.ptrs[ptr]; ok { return true diff --git a/vendor/github.com/getsentry/sentry-go/go.work b/vendor/github.com/getsentry/sentry-go/go.work index a1a4f91..efd675c 100644 --- a/vendor/github.com/getsentry/sentry-go/go.work +++ b/vendor/github.com/getsentry/sentry-go/go.work @@ -2,6 +2,7 @@ go 1.25.0 use ( . + ./cron ./crosstest ./echo ./fasthttp diff --git a/vendor/github.com/getsentry/sentry-go/go.work.sum b/vendor/github.com/getsentry/sentry-go/go.work.sum index f27f5dd..cb2a631 100644 --- a/vendor/github.com/getsentry/sentry-go/go.work.sum +++ b/vendor/github.com/getsentry/sentry-go/go.work.sum @@ -1,5 +1,7 @@ cel.dev/expr v0.25.1 h1:1KrZg61W6TWSxuNZ37Xy49ps13NUovb66QLprthtwi4= cel.dev/expr v0.25.1/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4= +cel.dev/expr v0.25.2/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4= +cloud.google.com/go/auth v0.18.2/go.mod h1:xD+oY7gcahcu7G2SG2DsBerfFxgPAJz17zz2joOFF3M= cloud.google.com/go/compute/metadata v0.3.0/go.mod h1:zFmK7XCadkQkj6TtorcaGlCW1hT1fIilQDwofLpJ20k= cloud.google.com/go/compute/metadata v0.9.0 h1:pDUj4QMoPejqq20dK0Pg2N4yG9zIkYGdBtwLoEkH9Zs= cloud.google.com/go/compute/metadata v0.9.0/go.mod h1:E0bWwX5wTnLPedCKqk3pJmVgCBSM6qQI1yTBdEb3C10= @@ -14,6 +16,7 @@ git.sr.ht/~sbinet/gg v0.6.0/go.mod h1:uucygbfC9wVPQIfrmwM2et0imr8L7KQWywX0xpFMm9 github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.31.0 h1:DHa2U07rk8syqvCge0QIGMCE1WxGj9njT44GH7zNJLQ= github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.31.0/go.mod h1:P4WPRUkOhJC13W//jWpyfJNDAIpvRbAUIYLX/4jtlE0= github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.32.0/go.mod h1:RD2SsorTmYhF6HkTmDw7KmPYQk8OBYwTkuasChwv7R4= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.33.0/go.mod h1:pJTkW8hEUIIi3Pf65lPZOnn4Y81yCllX6IWk2jNXdkM= github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY= github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU= github.com/PuerkitoBio/goquery v1.8.1 h1:uQxhNlArOIdbrH1tr0UXwdVFgDcZDrZVdcpygAcwmWM= @@ -60,6 +63,7 @@ github.com/envoyproxy/go-control-plane/ratelimit v0.1.0/go.mod h1:Wk+tMFAFbCXaJP github.com/envoyproxy/protoc-gen-validate v1.3.0 h1:TvGH1wof4H33rezVKWSpqKz5NXWg5VPuZ0uONDT6eb4= github.com/envoyproxy/protoc-gen-validate v1.3.0/go.mod h1:HvYl7zwPa5mffgyeTUHA9zHIH36nmrm7oCbo4YKoSWA= github.com/envoyproxy/protoc-gen-validate v1.3.3/go.mod h1:TsndJ/ngyIdQRhMcVVGDDHINPLWB7C82oDArY51KfB0= +github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= github.com/go-jose/go-jose/v4 v4.1.3 h1:CVLmWDhDVRa6Mi/IgCgaopNosCaHz7zrMeF9MlZRkrs= github.com/go-jose/go-jose/v4 v4.1.3/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08= github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08= @@ -85,6 +89,9 @@ github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/ github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/gofuzz v1.0.0 h1:A8PeW59pxE9IoFRqBp37U+mSNaQoZ46F1f0f863XSXw= +github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM= +github.com/googleapis/enterprise-certificate-proxy v0.3.11/go.mod h1:RFV7MUdlb7AgEq2v7FmMCfeSMCllAzWxFgRdusoGks8= +github.com/googleapis/gax-go/v2 v2.17.0/go.mod h1:mzaqghpQp4JDh3HvADwrat+6M3MOIDp5YKHhb9PAgDY= github.com/gorilla/securecookie v1.1.1 h1:miw7JPhV+b/lAHSXz4qd/nN9jRiAFV5FwjeKyCS8BvQ= github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4= github.com/iancoleman/strcase v0.3.0 h1:nTXanmYxhfFAMjZL34Ov6gkzEsSJZ5DbhxWjvSASxEI= @@ -138,6 +145,7 @@ github.com/spf13/afero v1.10.0 h1:EaGW2JJh15aKOejeuJ+wpFSHnbd7GE6Wvp3TsNhb6LY= github.com/spf13/afero v1.10.0/go.mod h1:UBogFpq8E9Hx+xc5CNTTEpTnuHVmXDwZcZcE1eb/UhQ= github.com/spiffe/go-spiffe/v2 v2.6.0 h1:l+DolpxNWYgruGQVV0xsfeya3CsC7m8iBzDnMpsbLuo= github.com/spiffe/go-spiffe/v2 v2.6.0/go.mod h1:gm2SeUoMZEtpnzPNs2Csc0D/gX33k1xIx7lEzqblHEs= +github.com/spiffe/go-spiffe/v2 v2.7.0/go.mod h1:47Q0Q9/AqGha8QLHp+kxpH4Wca7X7EnOtlIJy3mxZ3U= github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= github.com/tailscale/depaware v0.0.0-20210622194025-720c4b409502 h1:34icjjmqJ2HPjrSuJYEkdZ+0ItmGQAQ75cRHIiftIyE= github.com/tdewolff/argp v0.0.0-20240126212256-acdb2fb50090 h1:ok0U1tNDp9ICD93bMrZuFtHLwDoW+5nfSfF8e/x36Y0= @@ -161,9 +169,13 @@ go.etcd.io/bbolt v1.3.7/go.mod h1:N9Mkw9X8x5fupy0IKsmuqVtoGDyxsaDlbk4Rd05IAQw= go.opentelemetry.io/contrib/detectors/gcp v1.39.0 h1:kWRNZMsfBHZ+uHjiH4y7Etn2FK26LAGkNFw7RHv1DhE= go.opentelemetry.io/contrib/detectors/gcp v1.39.0/go.mod h1:t/OGqzHBa5v6RHZwrDBJ2OirWc+4q/w2fTbLZwAKjTk= go.opentelemetry.io/contrib/detectors/gcp v1.43.0/go.mod h1:RyaZMFY7yi1kAs45S6mbFGz8O8rqB0dTY14uzvG4LCs= +go.opentelemetry.io/contrib/detectors/gcp v1.44.0/go.mod h1:tNAsgd8avTGke1+MndXlU5Cru4PQ9Ai/cCNWQv/ZJ/s= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0/go.mod h1:UHB22Z8QsdRDrnAtX4PntOl36ajSxcdUMt1sF7Y6E7Q= go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= golang.org/x/crypto v0.28.0/go.mod h1:rmgy+3RHxRZMyY0jjAJShp2zgEdOqj2AO7U0pYmeQ7U= +golang.org/x/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M= +golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis= golang.org/x/image v0.25.0 h1:Y6uW6rH1y5y/LK1J8BPWZtr6yZ7hrsy6hFrXjgsc2fQ= golang.org/x/image v0.25.0/go.mod h1:tCAmOEGthTtkalusGp1g3xa2gke8J6c2N565dTyl9Rs= golang.org/x/mod v0.21.0/go.mod h1:6SkKJ3Xj0I0BrPOZoBy3bdMptDDU9oJrpohJ3eWZ1fY= @@ -172,10 +184,12 @@ golang.org/x/mod v0.33.0/go.mod h1:swjeQEj+6r7fODbD2cqrnje9PnziFuw4bmLbBZFrQ5w= golang.org/x/mod v0.35.0 h1:Ww1D637e6Pg+Zb2KrWfHQUnH2dQRLBQyAtpr/haaJeM= golang.org/x/mod v0.35.0/go.mod h1:+GwiRhIInF8wPm+4AoT6L0FA1QWAad3OMdTRx4tFYlU= golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0= +golang.org/x/mod v0.38.0/go.mod h1:V6Xz0pq8TQ3dGqVQ1FVHuelZpAL0uNhSkk9ogYP3c40= golang.org/x/net v0.30.0/go.mod h1:2wGyMJ5iFasEhkwi13ChkO/t1ECNC4X4eBKkVFyYFlU= golang.org/x/net v0.49.0/go.mod h1:/ysNB2EvaqvesRkuLAyjI1ycPZlQHM3q01F02UY/MV8= golang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y= golang.org/x/net v0.53.0/go.mod h1:JvMuJH7rrdiCfbeHoo3fCQU24Lf5JJwT9W3sJFulfgs= +golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU= golang.org/x/oauth2 v0.34.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA= golang.org/x/oauth2 v0.35.0 h1:Mv2mzuHuZuY2+bkyWXIHMfhNdJAdwW3FuWeCPYN5GVQ= golang.org/x/oauth2 v0.35.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA= @@ -184,6 +198,7 @@ golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4= golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= +golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.26.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= @@ -199,6 +214,7 @@ golang.org/x/term v0.41.0/go.mod h1:3pfBgksrReYfZ5lvYM0kSO0LIkAl4Yl2bXOkKP7Ec2A= golang.org/x/term v0.43.0 h1:S4RLU2sB31O/NCl+zFN9Aru9A/Cq2aqKpTZJ6B+DwT4= golang.org/x/term v0.43.0/go.mod h1:lrhlHNdQJHO+1qVYiHfFKVuVioJIheAc3fBSMFYEIsk= golang.org/x/term v0.44.0/go.mod h1:7ze4MdzUzLXpSAoFP1H0bOI9aXDqveSvatT5vKcFh2Y= +golang.org/x/term v0.45.0/go.mod h1:9aqxs0blBcrm/n0L9QW0aRVD+ktan8ssZromtqJC43w= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= golang.org/x/text v0.19.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY= golang.org/x/text v0.33.0/go.mod h1:LuMebE6+rBincTi9+xWTY8TztLzKHc/9C1uBCG27+q8= @@ -212,11 +228,13 @@ golang.org/x/tools v0.43.0/go.mod h1:uHkMso649BX2cZK6+RpuIPXS3ho2hZo4FVwfoy1vIk0 golang.org/x/tools v0.44.0 h1:UP4ajHPIcuMjT1GqzDWRlalUEoY+uzoZKnhOjbIPD2c= golang.org/x/tools v0.44.0/go.mod h1:KA0AfVErSdxRZIsOVipbv3rQhVXTnlU6UhKxHd1seDI= golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA= +golang.org/x/tools v0.48.0/go.mod h1:08xX0orndb/F7jJxGDicx061tyd5pcMto75YMAXr6lk= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= gonum.org/v1/plot v0.15.2 h1:Tlfh/jBk2tqjLZ4/P8ZIwGrLEWQSPDLRm/SNWKNXiGI= gonum.org/v1/plot v0.15.2/go.mod h1:DX+x+DWso3LTha+AdkJEv5Txvi+Tql3KAGkehP0/Ubg= gonum.org/v1/tools v0.0.0-20200318103217-c168b003ce8c h1:cJWOvXtcaFSGXz2F4z2AMM0VV7edDDGrxb5GLQH7ayQ= gonum.org/v1/tools v0.0.0-20200318103217-c168b003ce8c/go.mod h1:fy6Otjqbk477ELp8IXTpw1cObQtLbRCBVonY+bTTfcM= +google.golang.org/genproto v0.0.0-20260128011058-8636f8732409 h1:VQZ/yAbAtjkHgH80teYd2em3xtIkkHd7ZhqfH2N9CsM= google.golang.org/genproto/googleapis/api v0.0.0-20260120221211-b8f7ae30c516/go.mod h1:p3MLuOwURrGBRoEyFHBT3GjUwaCQVKeNqqWxlcISGdw= google.golang.org/genproto/googleapis/rpc v0.0.0-20260120221211-b8f7ae30c516/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ= google.golang.org/genproto/googleapis/rpc v0.0.0-20260401001100-f93e5f3e9f0f/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= diff --git a/vendor/github.com/getsentry/sentry-go/hub.go b/vendor/github.com/getsentry/sentry-go/hub.go index 15420a6..72dd116 100644 --- a/vendor/github.com/getsentry/sentry-go/hub.go +++ b/vendor/github.com/getsentry/sentry-go/hub.go @@ -20,7 +20,7 @@ const ( RequestContextKey = contextKey(2) ) -// currentHub is the initial Hub with no Client bound and an empty Scope. +// currentHub is the initial Hub with a no-op Client and an empty Scope. var currentHub = NewHub(nil, NewScope()) // Hub is the central object that manages scopes and clients. @@ -58,7 +58,7 @@ func (l *layer) Client() *Client { func (l *layer) SetClient(c *Client) { l.mu.Lock() defer l.mu.Unlock() - l.client = c + l.client = normalizeClient(c) } type stack []*layer @@ -67,7 +67,7 @@ type stack []*layer func NewHub(client *Client, scope *Scope) *Hub { hub := Hub{ stack: &stack{{ - client: client, + client: normalizeClient(client), scope: scope, }}, } @@ -218,12 +218,12 @@ func (hub *Hub) CaptureEvent(event *Event) *EventID { // CaptureEventWithHint is like CaptureEvent but additionally accepts an EventHint. func (hub *Hub) CaptureEventWithHint(event *Event, hint *EventHint) *EventID { client, scope := hub.Client(), hub.Scope() - if client == nil || scope == nil { + if scope == nil { return nil } eventID := client.CaptureEvent(event, hint, scope) - if event.Type != transactionType && eventID != nil { + if event != nil && event.Type != transactionType && eventID != nil { hub.mu.Lock() hub.lastEventID = *eventID hub.mu.Unlock() @@ -236,7 +236,7 @@ func (hub *Hub) CaptureEventWithHint(event *Event, hint *EventHint) *EventID { // Returns EventID if successfully, or nil if there's no Scope or Client available. func (hub *Hub) CaptureMessage(message string) *EventID { client, scope := hub.Client(), hub.Scope() - if client == nil || scope == nil { + if scope == nil { return nil } eventID := client.CaptureMessage(message, nil, scope) @@ -254,7 +254,7 @@ func (hub *Hub) CaptureMessage(message string) *EventID { // Returns EventID if successfully, or nil if there's no Scope or Client available. func (hub *Hub) CaptureException(exception error) *EventID { client, scope := hub.Client(), hub.Scope() - if client == nil || scope == nil { + if scope == nil { return nil } eventID := client.CaptureException(exception, &EventHint{OriginalException: exception}, scope) @@ -272,13 +272,46 @@ func (hub *Hub) CaptureException(exception error) *EventID { // Returns CheckInID if the check-in was captured successfully, or nil otherwise. func (hub *Hub) CaptureCheckIn(checkIn *CheckIn, monitorConfig *MonitorConfig) *EventID { client, scope := hub.Client(), hub.Scope() - if client == nil { - return nil - } - return client.CaptureCheckIn(checkIn, monitorConfig, scope) } +// WithMonitor runs fn and reports its outcome as check-ins for the cron +// monitor identified by monitorSlug. +// +// An in_progress check-in carrying monitorConfig is sent before fn runs. When +// monitorConfig is not nil, Sentry creates the monitor if it does not exist, +// or updates its configuration. After fn returns, an ok check-in is sent if +// it returned nil, or an error check-in otherwise, along with the measured +// duration. If fn panics, an error check-in is sent and the panic continues. +// +// The error returned by fn is returned unchanged. +func (hub *Hub) WithMonitor(monitorSlug string, monitorConfig *MonitorConfig, fn func() error) error { + checkInID := hub.CaptureCheckIn(&CheckIn{ + MonitorSlug: monitorSlug, + Status: CheckInStatusInProgress, + }, monitorConfig) + start := time.Now() + + status := CheckInStatusError + defer func() { + checkIn := &CheckIn{ + MonitorSlug: monitorSlug, + Status: status, + Duration: time.Since(start), + } + if checkInID != nil { + checkIn.ID = *checkInID + } + hub.CaptureCheckIn(checkIn, nil) + }() + + err := fn() + if err == nil { + status = CheckInStatusOK + } + return err +} + // AddBreadcrumb records a new breadcrumb. // // The total number of breadcrumbs that can be recorded are limited by the @@ -286,12 +319,6 @@ func (hub *Hub) CaptureCheckIn(checkIn *CheckIn, monitorConfig *MonitorConfig) * func (hub *Hub) AddBreadcrumb(breadcrumb *Breadcrumb, hint *BreadcrumbHint) { client := hub.Client() - // If there's no client, just store it on the scope straight away - if client == nil { - hub.Scope().AddBreadcrumb(breadcrumb, defaultMaxBreadcrumbs) - return - } - limit := client.options.MaxBreadcrumbs switch { case limit < 0: @@ -321,7 +348,7 @@ func (hub *Hub) Recover(err interface{}) *EventID { err = recover() } client, scope := hub.Client(), hub.Scope() - if client == nil || scope == nil { + if scope == nil { return nil } return client.Recover(err, &EventHint{RecoveredException: err}, scope) @@ -335,7 +362,7 @@ func (hub *Hub) RecoverWithContext(ctx context.Context, err interface{}) *EventI err = recover() } client, scope := hub.Client(), hub.Scope() - if client == nil || scope == nil { + if scope == nil { return nil } return client.RecoverWithContext(ctx, err, &EventHint{RecoveredException: err}, scope) @@ -353,19 +380,14 @@ func (hub *Hub) RecoverWithContext(ctx context.Context, err interface{}) *EventI // the network synchronously, configure it to use the HTTPSyncTransport in the // call to Init. func (hub *Hub) Flush(timeout time.Duration) bool { - client := hub.Client() - - if client == nil { - return false - } - - return client.Flush(timeout) + return hub.Client().Flush(timeout) } // FlushWithContext waits until the underlying Transport sends any buffered events -// to the Sentry server, blocking for at most the duration specified by the context. -// It returns false if the context is canceled before the events are sent. In such a case, -// some events may not be delivered. +// to the Sentry server, blocking for at most the duration specified by the +// context. It returns false if capture is disabled or the context is canceled +// before the events are sent. In the latter case, some events may not be +// delivered. // // FlushWithContext should be called before terminating the program to ensure no // events are unintentionally dropped. @@ -375,13 +397,7 @@ func (hub *Hub) Flush(timeout time.Duration) bool { // configure the SDK to use HTTPSyncTransport during initialization with Init. func (hub *Hub) FlushWithContext(ctx context.Context) bool { - client := hub.Client() - - if client == nil { - return false - } - - return client.FlushWithContext(ctx) + return hub.Client().FlushWithContext(ctx) } // GetTraceparent returns the current Sentry traceparent string, to be used as a HTTP header value diff --git a/vendor/github.com/getsentry/sentry-go/internal/httputils/wrap_writer.go b/vendor/github.com/getsentry/sentry-go/internal/httputils/wrap_writer.go index 51bf910..caa91a7 100644 --- a/vendor/github.com/getsentry/sentry-go/internal/httputils/wrap_writer.go +++ b/vendor/github.com/getsentry/sentry-go/internal/httputils/wrap_writer.go @@ -48,6 +48,12 @@ func NewWrapResponseWriter(w http.ResponseWriter, protoMajor int) WrapResponseWr if fl && hj && rf { return &httpFancyWriter{bw} } + if fl && hj { + return &flushHijackWriter{bw} + } + if hj { + return &hijackWriter{bw} + } } if fl { return &flushWriter{bw} @@ -143,6 +149,36 @@ func (f *flushWriter) Flush() { var _ http.Flusher = &flushWriter{} +// flushHijackWriter is a HTTP writer that additionally satisfies http.Flusher +// and http.Hijacker, for writers that do not implement io.ReaderFrom. +type flushHijackWriter struct { + basicWriter +} + +func (f *flushHijackWriter) Flush() { + f.wroteHeader = true + f.ResponseWriter.(http.Flusher).Flush() +} + +func (f *flushHijackWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { + return f.ResponseWriter.(http.Hijacker).Hijack() +} + +var _ http.Flusher = &flushHijackWriter{} +var _ http.Hijacker = &flushHijackWriter{} + +// hijackWriter is a HTTP writer that additionally satisfies http.Hijacker, for +// writers that implement neither http.Flusher nor io.ReaderFrom. +type hijackWriter struct { + basicWriter +} + +func (f *hijackWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { + return f.ResponseWriter.(http.Hijacker).Hijack() +} + +var _ http.Hijacker = &hijackWriter{} + // httpFancyWriter is a HTTP writer that additionally satisfies // http.Flusher, http.Hijacker, and io.ReaderFrom. It exists for the common case // of wrapping the http.ResponseWriter that package http gives you, in order to diff --git a/vendor/github.com/getsentry/sentry-go/internal/protocol/dsn.go b/vendor/github.com/getsentry/sentry-go/internal/protocol/dsn.go index b49e88c..3f2f5ba 100644 --- a/vendor/github.com/getsentry/sentry-go/internal/protocol/dsn.go +++ b/vendor/github.com/getsentry/sentry-go/internal/protocol/dsn.go @@ -3,6 +3,7 @@ package protocol import ( "encoding/json" "fmt" + "net" "net/url" "strconv" "strings" @@ -210,17 +211,20 @@ func (dsn *Dsn) SetOrgID(orgID uint64) { // GetAPIURL returns the URL of the envelope endpoint of the project // associated with the DSN. func (dsn Dsn) GetAPIURL() *url.URL { - var rawURL string - rawURL += fmt.Sprintf("%s://%s", dsn.scheme, dsn.host) + host := dsn.host + port := "" if dsn.port != dsn.scheme.defaultPort() { - rawURL += fmt.Sprintf(":%d", dsn.port) + port = strconv.Itoa(dsn.port) } - if dsn.path != "" { - rawURL += dsn.path + // JoinHostPort correctly adds brackets for IPv6 hosts. However with an + // empty port it leaves a trailing ":", which we trim to omit the default port. + host = net.JoinHostPort(host, port) + host = strings.TrimSuffix(host, ":") + return &url.URL{ + Scheme: string(dsn.scheme), + Host: host, + Path: dsn.path + "/api/" + dsn.projectID + "/envelope/", } - rawURL += fmt.Sprintf("/api/%s/%s/", dsn.projectID, "envelope") - parsedURL, _ := url.Parse(rawURL) - return parsedURL } // RequestHeaders returns all the necessary headers that have to be used in the transport when sending events diff --git a/vendor/github.com/getsentry/sentry-go/internal/telemetry/scheduler.go b/vendor/github.com/getsentry/sentry-go/internal/telemetry/scheduler.go index f1bdc1e..e333cf0 100644 --- a/vendor/github.com/getsentry/sentry-go/internal/telemetry/scheduler.go +++ b/vendor/github.com/getsentry/sentry-go/internal/telemetry/scheduler.go @@ -26,6 +26,9 @@ type Scheduler struct { cancel context.CancelFunc processingWg sync.WaitGroup + // processing serializes buffer-to-transport handoffs and allows cancelable waits. + processing chan struct{} + mu sync.Mutex cond *sync.Cond startOnce sync.Once @@ -79,6 +82,7 @@ func NewScheduler( currentCycle: currentCycle, ctx: ctx, cancel: cancel, + processing: make(chan struct{}, 1), } s.cond = sync.NewCond(&s.mu) @@ -145,7 +149,9 @@ func (s *Scheduler) Flush(timeout time.Duration) bool { } func (s *Scheduler) FlushWithContext(ctx context.Context) bool { - s.flushBuffers() + if !s.flushBuffers(ctx) { + return false + } return s.transport.FlushWithContext(ctx) } @@ -193,6 +199,13 @@ func (s *Scheduler) hasWork() bool { } func (s *Scheduler) processNextBatch() { + select { + case s.processing <- struct{}{}: + defer func() { <-s.processing }() + case <-s.ctx.Done(): + return + } + if len(s.currentCycle) == 0 { return } @@ -290,12 +303,23 @@ func (s *Scheduler) sendItem(item protocol.EnvelopeConvertible) { } } -func (s *Scheduler) flushBuffers() { +func (s *Scheduler) flushBuffers(ctx context.Context) bool { + select { + case s.processing <- struct{}{}: + defer func() { <-s.processing }() + case <-ctx.Done(): + return false + } + for category, buffer := range s.buffers { + if ctx.Err() != nil { + return false + } if !buffer.IsEmpty() { s.processItems(buffer, category, true) } } + return ctx.Err() == nil } func (s *Scheduler) isRateLimited(category ratelimit.Category) bool { diff --git a/vendor/github.com/getsentry/sentry-go/log.go b/vendor/github.com/getsentry/sentry-go/log.go index 72a2b97..e1950c1 100644 --- a/vendor/github.com/getsentry/sentry-go/log.go +++ b/vendor/github.com/getsentry/sentry-go/log.go @@ -60,7 +60,7 @@ func NewLogger(ctx context.Context) Logger { // nolint: dupl } client := hub.Client() - if client != nil { + if client.IsEnabled() { // Build default attrs serverAddr := client.options.ServerName if serverAddr == "" { @@ -111,7 +111,7 @@ func (l *sentryLogger) log(ctx context.Context, level LogLevel, severity int, me hub = l.hub } client := hub.Client() - if client == nil { + if !client.IsEnabled() { return } diff --git a/vendor/github.com/getsentry/sentry-go/metrics.go b/vendor/github.com/getsentry/sentry-go/metrics.go index c3dcb03..b6b21e6 100644 --- a/vendor/github.com/getsentry/sentry-go/metrics.go +++ b/vendor/github.com/getsentry/sentry-go/metrics.go @@ -55,7 +55,7 @@ func NewMeter(ctx context.Context) Meter { hub = CurrentHub() } client := hub.Client() - if client != nil { + if client.IsEnabled() { // build default attrs serverAddr := client.options.ServerName if serverAddr == "" { @@ -110,7 +110,7 @@ func (m *sentryMeter) emit(ctx context.Context, metricType MetricType, name stri } client := hub.Client() - if client == nil { + if !client.IsEnabled() { return } diff --git a/vendor/github.com/getsentry/sentry-go/propagation_context.go b/vendor/github.com/getsentry/sentry-go/propagation_context.go index 310de72..a8005cd 100644 --- a/vendor/github.com/getsentry/sentry-go/propagation_context.go +++ b/vendor/github.com/getsentry/sentry-go/propagation_context.go @@ -4,6 +4,11 @@ import ( "crypto/rand" ) +const ( + traceIDContextKey = "trace_id" + spanIDContextKey = "span_id" +) + type PropagationContext struct { TraceID TraceID `json:"trace_id"` SpanID SpanID `json:"span_id"` @@ -13,8 +18,8 @@ type PropagationContext struct { func (p PropagationContext) Map() map[string]interface{} { m := map[string]interface{}{ - "trace_id": p.TraceID, - "span_id": p.SpanID, + traceIDContextKey: p.TraceID, + spanIDContextKey: p.SpanID, } if p.ParentSpanID != zeroSpanID { diff --git a/vendor/github.com/getsentry/sentry-go/scope.go b/vendor/github.com/getsentry/sentry-go/scope.go index c7a6067..e99240f 100644 --- a/vendor/github.com/getsentry/sentry-go/scope.go +++ b/vendor/github.com/getsentry/sentry-go/scope.go @@ -30,7 +30,15 @@ import ( // an event for reporting, the current client adds information from the current // scope into the event. type Scope struct { - mu sync.RWMutex + mu sync.RWMutex + // eventProcessors are retained by Clear and inherited by Clone. + eventProcessors []EventProcessor + + // scopeData keeps track of all scope specific data + scopeData +} + +type scopeData struct { attributes map[string]attribute.Value breadcrumbs []*Breadcrumb attachments []*Attachment @@ -49,7 +57,6 @@ type Scope struct { // size. Overflow() bool } - eventProcessors []EventProcessor propagationContext PropagationContext span *Span @@ -57,14 +64,18 @@ type Scope struct { // NewScope creates a new Scope. func NewScope() *Scope { - return &Scope{ + return &Scope{scopeData: newScopeData(NewPropagationContext())} +} + +func newScopeData(propagationContext PropagationContext) scopeData { + return scopeData{ attributes: make(map[string]attribute.Value), breadcrumbs: make([]*Breadcrumb, 0), attachments: make([]*Attachment, 0), tags: make(map[string]string), contexts: make(map[string]Context), fingerprint: make([]string, 0), - propagationContext: NewPropagationContext(), + propagationContext: propagationContext, } } @@ -282,6 +293,7 @@ func (scope *Scope) Clone() *Scope { clone := NewScope() clone.user = scope.user + clone.user.Data = maps.Clone(scope.user.Data) clone.breadcrumbs = make([]*Breadcrumb, len(scope.breadcrumbs)) copy(clone.breadcrumbs, scope.breadcrumbs) clone.attachments = make([]*Attachment, len(scope.attachments)) @@ -300,9 +312,16 @@ func (scope *Scope) Clone() *Scope { return clone } -// Clear removes the data from the current scope. Not safe for concurrent use. +// Clear removes enrichment data while preserving event processors and trace +// correlation. It is safe for concurrent use. func (scope *Scope) Clear() { - *scope = *NewScope() + scope.mu.Lock() + defer scope.mu.Unlock() + + propagationContext := scope.propagationContext + span := scope.span + scope.scopeData = newScopeData(propagationContext) + scope.span = span } // AddEventProcessor adds an event processor to the current scope. @@ -375,7 +394,7 @@ func (scope *Scope) ApplyToEvent(event *Event, hint *EventHint, client *Client) event.Contexts["trace"] = scope.propagationContext.Map() dsc := scope.propagationContext.DynamicSamplingContext - if !dsc.HasEntries() && client != nil { + if !dsc.HasEntries() && client.IsEnabled() { dsc = DynamicSamplingContextFromScope(scope, client) } event.sdkMetaData.dsc = dsc @@ -383,7 +402,7 @@ func (scope *Scope) ApplyToEvent(event *Event, hint *EventHint, client *Client) // If an external trace resolver is registered (e.g. OTel), override // trace/span IDs from the hint context or the scope's request context. - if client != nil { + if client.IsEnabled() { var ctx context.Context if hint != nil { ctx = hint.Context @@ -393,13 +412,14 @@ func (scope *Scope) ApplyToEvent(event *Event, hint *EventHint, client *Client) } if traceID, spanID, ok := client.externalTraceContextFromContext(ctx); event.Type != transactionType && ok { traceCtx := event.Contexts["trace"] - traceCtx["trace_id"] = traceID.String() - traceCtx["span_id"] = spanID.String() + traceCtx[traceIDContextKey] = traceID.String() + traceCtx[spanIDContextKey] = spanID.String() } } if event.User.IsEmpty() { event.User = scope.user + event.User.Data = maps.Clone(scope.user.Data) } if len(event.Fingerprint) == 0 { @@ -434,7 +454,7 @@ func (scope *Scope) ApplyToEvent(event *Event, hint *EventHint, client *Client) event = processor(event, hint) if event == nil { debuglog.Printf("Event dropped by one of the Scope EventProcessors: %s\n", id) - if client != nil { + if client.IsEnabled() { client.reportRecorder.RecordOne(report.ReasonEventProcessor, category) if category == ratelimit.CategoryTransaction { client.reportRecorder.Record(report.ReasonEventProcessor, ratelimit.CategorySpan, int64(spanCountBefore)) @@ -443,7 +463,7 @@ func (scope *Scope) ApplyToEvent(event *Event, hint *EventHint, client *Client) return nil } if droppedSpans := spanCountBefore - event.GetSpanCount(); droppedSpans > 0 { - if client != nil { + if client.IsEnabled() { client.reportRecorder.Record(report.ReasonEventProcessor, ratelimit.CategorySpan, int64(droppedSpans)) } } @@ -524,7 +544,7 @@ func resolveTrace(scope *Scope, client *Client, ctxs ...context.Context) (traceI if ctx == nil { continue } - if client != nil { + if client.IsEnabled() { if traceID, spanID, ok := client.externalTraceContextFromContext(ctx); ok { return traceID, spanID } diff --git a/vendor/github.com/getsentry/sentry-go/sentry.go b/vendor/github.com/getsentry/sentry-go/sentry.go index 0faa11e..cc33107 100644 --- a/vendor/github.com/getsentry/sentry-go/sentry.go +++ b/vendor/github.com/getsentry/sentry-go/sentry.go @@ -6,7 +6,7 @@ import ( ) // The version of the SDK. -const SDKVersion = "0.49.0" +const SDKVersion = "0.50.0" // apiVersion is the minimum version of the Sentry API compatible with the // sentry-go SDK. @@ -54,6 +54,26 @@ func CaptureCheckIn(checkIn *CheckIn, monitorConfig *MonitorConfig) *EventID { return hub.CaptureCheckIn(checkIn, monitorConfig) } +// WithMonitor runs fn and reports its outcome as check-ins for the cron +// monitor identified by monitorSlug, creating or updating the monitor with +// monitorConfig when it is not nil. It is a shorthand for +// CurrentHub().WithMonitor. +// +// Example: +// +// err := sentry.WithMonitor("nightly-cleanup", &sentry.MonitorConfig{ +// Schedule: sentry.CrontabSchedule("0 3 * * *"), +// CheckInMargin: 5, +// MaxRuntime: 30, +// Timezone: "UTC", +// }, func() error { +// return cleanup() +// }) +func WithMonitor(monitorSlug string, monitorConfig *MonitorConfig, fn func() error) error { + hub := CurrentHub() + return hub.WithMonitor(monitorSlug, monitorConfig, fn) +} + // CaptureEvent captures an event on the currently active client if any. // // The event must already be assembled. Typically code would instead use @@ -129,9 +149,10 @@ func Flush(timeout time.Duration) bool { } // FlushWithContext waits until the underlying Transport sends any buffered events -// to the Sentry server, blocking for at most the duration specified by the context. -// It returns false if the context is canceled before the events are sent. In such a case, -// some events may not be delivered. +// to the Sentry server, blocking for at most the duration specified by the +// context. It returns false if capture is disabled or the context is canceled +// before the events are sent. In the latter case, some events may not be +// delivered. // // FlushWithContext should be called before terminating the program to ensure no // events are unintentionally dropped. diff --git a/vendor/github.com/getsentry/sentry-go/span_recorder.go b/vendor/github.com/getsentry/sentry-go/span_recorder.go index ba04101..ac29d6a 100644 --- a/vendor/github.com/getsentry/sentry-go/span_recorder.go +++ b/vendor/github.com/getsentry/sentry-go/span_recorder.go @@ -18,7 +18,7 @@ type spanRecorder struct { // span tree. func (r *spanRecorder) record(s *Span) { maxSpans := defaultMaxSpans - if client := CurrentHub().Client(); client != nil { + if client := CurrentHub().Client(); client.IsEnabled() { maxSpans = client.options.MaxSpans } r.mu.Lock() diff --git a/vendor/github.com/getsentry/sentry-go/tracing.go b/vendor/github.com/getsentry/sentry-go/tracing.go index 475a8a4..bd1a0d9 100644 --- a/vendor/github.com/getsentry/sentry-go/tracing.go +++ b/vendor/github.com/getsentry/sentry-go/tracing.go @@ -551,7 +551,7 @@ func (s *Span) updateFromBaggage(header []byte) { func (s *Span) clientOptions() *ClientOptions { client := hubFromContext(s.ctx).Client() - if client != nil { + if client.IsEnabled() { return &client.options } return &ClientOptions{} @@ -933,8 +933,8 @@ type TraceContext struct { func (tc TraceContext) Map() map[string]interface{} { m := map[string]interface{}{ - "trace_id": tc.TraceID, - "span_id": tc.SpanID, + traceIDContextKey: tc.TraceID, + spanIDContextKey: tc.SpanID, } if tc.ParentSpanID != [8]byte{} { @@ -1202,7 +1202,7 @@ func HTTPtoSpanStatus(code int) SpanStatus { } func shouldContinueTrace(client *Client, dsc DynamicSamplingContext) bool { - if client == nil { + if !client.IsEnabled() { return true } diff --git a/vendor/github.com/go-faker/faker/v4/faker.go b/vendor/github.com/go-faker/faker/v4/faker.go index c0fe47b..5495af0 100644 --- a/vendor/github.com/go-faker/faker/v4/faker.go +++ b/vendor/github.com/go-faker/faker/v4/faker.go @@ -63,6 +63,7 @@ const ( ChineseFirstNameTag = "chinese_first_name" ChineseLastNameTag = "chinese_last_name" ChineseNameTag = "chinese_name" + ChinesePhoneNumberTag = "chinese_phone_number" GENDER = "gender" UnixTimeTag = "unix_time" DATE = "date" @@ -107,7 +108,7 @@ const ( var PriorityTags = []string{ID, HyphenatedID, EmailTag, MacAddressTag, DomainNameTag, UserNameTag, URLTag, IPV4Tag, IPV6Tag, PASSWORD, JWT, CountryInfoTag, LATITUDE, LONGITUDE, CreditCardNumber, CreditCardType, PhoneNumber, TollFreeNumber, E164PhoneNumberTag, TitleMaleTag, TitleFemaleTag, FirstNameTag, FirstNameMaleTag, FirstNameFemaleTag, LastNameTag, - NAME, ChineseFirstNameTag, ChineseLastNameTag, ChineseNameTag, GENDER, UnixTimeTag, DATE, TIME, MonthNameTag, + NAME, ChineseFirstNameTag, ChineseLastNameTag, ChineseNameTag, ChinesePhoneNumberTag, GENDER, UnixTimeTag, DATE, TIME, MonthNameTag, YEAR, DayOfWeekTag, DayOfMonthTag, TIMESTAMP, CENTURY, TIMEZONE, TimePeriodTag, WORD, SENTENCE, PARAGRAPH, CurrencyTag, AmountTag, AmountWithCurrencyTag, SKIP, Length, SliceLength, Language, BoundaryStart, BoundaryEnd, ONEOF, BloodTypeTag, UserAgentTag, @@ -169,6 +170,7 @@ func initDefaultTag() { defaultTag.Store(ChineseFirstNameTag, ChineseFirstNameTag) defaultTag.Store(ChineseLastNameTag, ChineseLastNameTag) defaultTag.Store(ChineseNameTag, ChineseNameTag) + defaultTag.Store(ChinesePhoneNumberTag, ChinesePhoneNumberTag) defaultTag.Store(GENDER, GENDER) defaultTag.Store(UnixTimeTag, UnixTimeTag) defaultTag.Store(DATE, DATE) @@ -220,6 +222,7 @@ func initMapperTagDefault() { mapperTag.Store(ChineseFirstNameTag, GetPerson().ChineseFirstName) mapperTag.Store(ChineseLastNameTag, GetPerson().ChineseLastName) mapperTag.Store(ChineseNameTag, GetPerson().ChineseName) + mapperTag.Store(ChinesePhoneNumberTag, GetPhoner().ChinesePhoneNumber) mapperTag.Store(GENDER, GetPerson().Gender) mapperTag.Store(UnixTimeTag, GetDateTimer().UnixTime) mapperTag.Store(DATE, GetDateTimer().Date) diff --git a/vendor/github.com/go-faker/faker/v4/phone.go b/vendor/github.com/go-faker/faker/v4/phone.go index 87e8bc2..d8ca53f 100644 --- a/vendor/github.com/go-faker/faker/v4/phone.go +++ b/vendor/github.com/go-faker/faker/v4/phone.go @@ -9,6 +9,20 @@ import ( "github.com/go-faker/faker/v4/pkg/slice" ) +// chineseMobilePrefixes holds the 3-digit prefixes of Mainland China mobile +// numbers, allocated to China Mobile, China Unicom, China Telecom and China +// Broadnet (including MVNO & IoT segments). Each prefix is followed by 8 +// subscriber digits to form an 11-digit number. +var chineseMobilePrefixes = []string{ + "130", "131", "132", "133", "134", "135", "136", "137", "138", "139", + "145", "146", "147", "148", "149", + "150", "151", "152", "153", "155", "156", "157", "158", "159", + "162", "165", "166", "167", + "170", "171", "172", "173", "174", "175", "176", "177", "178", + "180", "181", "182", "183", "184", "185", "186", "187", "188", "189", + "190", "191", "192", "193", "195", "196", "197", "198", "199", +} + // GetPhoner serves as a constructor for Phoner interface func GetPhoner() Phoner { phone := &Phone{} @@ -20,6 +34,7 @@ type Phoner interface { PhoneNumber(v reflect.Value) (any, error) TollFreePhoneNumber(v reflect.Value) (any, error) E164PhoneNumber(v reflect.Value) (any, error) + ChinesePhoneNumber(v reflect.Value) (any, error) } // Phone struct @@ -95,3 +110,22 @@ func E164PhoneNumber(opts ...options.OptionFunc) string { return p.e164PhoneNumber() }, opts...).(string) } + +func (p Phone) chinesePhoneNumber() string { + prefix := chineseMobilePrefixes[rand.Intn(len(chineseMobilePrefixes))] + return prefix + randomStringNumber(8) +} + +// ChinesePhoneNumber generates a Mainland-China mobile phone number of the +// form "13812345678" (11 digits, starting with a valid operator prefix) +func (p Phone) ChinesePhoneNumber(v reflect.Value) (any, error) { + return p.chinesePhoneNumber(), nil +} + +// ChinesePhoneNumber get fake Chinese phone number +func ChinesePhoneNumber(opts ...options.OptionFunc) string { + return singleFakeData(ChinesePhoneNumberTag, func() any { + p := Phone{} + return p.chinesePhoneNumber() + }, opts...).(string) +} diff --git a/vendor/github.com/go-playground/locales/README.md b/vendor/github.com/go-playground/locales/README.md index 7b6be2c..ee6fa0e 100644 --- a/vendor/github.com/go-playground/locales/README.md +++ b/vendor/github.com/go-playground/locales/README.md @@ -139,11 +139,13 @@ func main() { fmt.Println(l.CardinalPluralRule(1.0, 1)) fmt.Println(l.CardinalPluralRule(3, 0)) - // Ordinal Plural Rules - fmt.Println(l.OrdinalPluralRule(21, 0)) // 21st - fmt.Println(l.OrdinalPluralRule(22, 0)) // 22nd - fmt.Println(l.OrdinalPluralRule(33, 0)) // 33rd - fmt.Println(l.OrdinalPluralRule(34, 0)) // 34th + // Ordinal Plural Rules. The method returns the locales/plurals.Rule + // (e.g. One, Two, Few, Other) for the number; converting that rule into + // the actual suffix ("st", "nd", "rd", "th") is left to the caller. + fmt.Println(l.OrdinalPluralRule(21, 0)) // One (-> "21st") + fmt.Println(l.OrdinalPluralRule(22, 0)) // Two (-> "22nd") + fmt.Println(l.OrdinalPluralRule(33, 0)) // Few (-> "33rd") + fmt.Println(l.OrdinalPluralRule(34, 0)) // Other (-> "34th") // Range Plural Rules fmt.Println(l.RangePluralRule(1, 0, 1, 0)) // 1-1 diff --git a/vendor/github.com/go-playground/locales/en/en.go b/vendor/github.com/go-playground/locales/en/en.go index baf343d..6aa88f7 100644 --- a/vendor/github.com/go-playground/locales/en/en.go +++ b/vendor/github.com/go-playground/locales/en/en.go @@ -498,10 +498,9 @@ func (en *en) FmtTimeShort(t time.Time) string { b := make([]byte, 0, 32) - h := t.Hour() - - if h > 12 { - h -= 12 + h := t.Hour() % 12 + if h == 0 { + h = 12 } b = strconv.AppendInt(b, int64(h), 10) @@ -528,10 +527,9 @@ func (en *en) FmtTimeMedium(t time.Time) string { b := make([]byte, 0, 32) - h := t.Hour() - - if h > 12 { - h -= 12 + h := t.Hour() % 12 + if h == 0 { + h = 12 } b = strconv.AppendInt(b, int64(h), 10) @@ -565,10 +563,9 @@ func (en *en) FmtTimeLong(t time.Time) string { b := make([]byte, 0, 32) - h := t.Hour() - - if h > 12 { - h -= 12 + h := t.Hour() % 12 + if h == 0 { + h = 12 } b = strconv.AppendInt(b, int64(h), 10) @@ -607,10 +604,9 @@ func (en *en) FmtTimeFull(t time.Time) string { b := make([]byte, 0, 32) - h := t.Hour() - - if h > 12 { - h -= 12 + h := t.Hour() % 12 + if h == 0 { + h = 12 } b = strconv.AppendInt(b, int64(h), 10) diff --git a/vendor/github.com/go-playground/locales/rules.go b/vendor/github.com/go-playground/locales/rules.go index 9202900..6481269 100644 --- a/vendor/github.com/go-playground/locales/rules.go +++ b/vendor/github.com/go-playground/locales/rules.go @@ -98,7 +98,7 @@ type Translator interface { // returns the locales narrow weekday given the 'weekday' provided WeekdayNarrow(weekday time.Weekday) string - // WeekdaysNarrowreturns the locales narrow weekdays + // WeekdaysNarrow returns the locales narrow weekdays WeekdaysNarrow() []string // returns the locales short weekday given the 'weekday' provided @@ -113,7 +113,7 @@ type Translator interface { // returns the locales wide weekdays WeekdaysWide() []string - // The following Functions are common Formatting functionsfor the Translator's Locale + // The following Functions are common Formatting functions for the Translator's Locale // returns 'num' with digits/precision of 'v' for locale and handles both Whole and Real numbers based on 'v' FmtNumber(num float64, v uint64) string @@ -228,14 +228,14 @@ func W(n float64, v uint64) (w int64) { s := strconv.FormatFloat(n-float64(int64(n)), 'f', int(v), 64) - // with either be '0' or '0.xxxx', so if 1 then w will be zero + // will either be '0' or '0.xxxx', so if 1 then w will be zero // otherwise need to parse if len(s) != 1 { s = s[2:] - end := len(s) + 1 + end := 0 - for i := end; i >= 0; i-- { + for i := len(s) - 1; i >= 0; i-- { if s[i] != '0' { end = i + 1 break @@ -253,7 +253,7 @@ func F(n float64, v uint64) (f int64) { s := strconv.FormatFloat(n-float64(int64(n)), 'f', int(v), 64) - // with either be '0' or '0.xxxx', so if 1 then f will be zero + // will either be '0' or '0.xxxx', so if 1 then f will be zero // otherwise need to parse if len(s) != 1 { @@ -270,14 +270,14 @@ func T(n float64, v uint64) (t int64) { s := strconv.FormatFloat(n-float64(int64(n)), 'f', int(v), 64) - // with either be '0' or '0.xxxx', so if 1 then t will be zero + // will either be '0' or '0.xxxx', so if 1 then t will be zero // otherwise need to parse if len(s) != 1 { s = s[2:] - end := len(s) + 1 + end := 0 - for i := end; i >= 0; i-- { + for i := len(s) - 1; i >= 0; i-- { if s[i] != '0' { end = i + 1 break @@ -286,8 +286,11 @@ func T(n float64, v uint64) (t int64) { // ignoring error, because it can't fail as we generated // the string internally from a real number - t, _ = strconv.ParseInt(s[:end], 10, 64) + if end > 0 { + t, _ = strconv.ParseInt(s[:end], 10, 64) + } } return } + diff --git a/vendor/github.com/go-playground/universal-translator/CLAUDE.md b/vendor/github.com/go-playground/universal-translator/CLAUDE.md new file mode 100644 index 0000000..f34c773 --- /dev/null +++ b/vendor/github.com/go-playground/universal-translator/CLAUDE.md @@ -0,0 +1,42 @@ +# CLAUDE.md + +This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. + +## Project + +`universal-translator` (`ut`) is a Go i18n library that wraps `github.com/go-playground/locales` (CLDR locale data) to provide translation registration, plural rule handling (cardinal, ordinal, range), and `{0}`-style parameter substitution. Translations can be registered programmatically or loaded from JSON files. + +## Commands + +```bash +# Run tests with race detection and coverage +make test + +# Run benchmarks +make bench + +# Lint +make lint # or: golangci-lint run + +# Run a single test +go test -run TestTranslatorAdd -race -v ./... +``` + +## Architecture + +Flat package `ut` at the repo root — no sub-packages. + +- **`universal_translator.go`** — `UniversalTranslator` struct: holds a `map[string]Translator` (keyed by lowercased locale) plus a fallback. Constructor: `New(fallback, ...supportedLocales)`. Methods: `FindTranslator`, `GetTranslator`, `AddTranslator`, `VerifyTranslations`. +- **`translator.go`** — `Translator` interface (embeds `locales.Translator`) and private `translator` impl. Registration: `Add`, `AddCardinal`, `AddOrdinal`, `AddRange`. Resolution: `T`, `C`, `O`, `R`. Each translation key is `interface{}` (string or int). Parameter substitution indexes are precomputed at registration time via `transText`. +- **`import_export.go`** — JSON import/export. `Export` writes per-locale JSON files. `Import` reads them (supports recursive directory traversal). `ImportByReader` for streaming. +- **`errors.go`** — Typed error structs: `ErrUnknownTranslation`, `ErrExistingTranslator`, `ErrConflictingTranslation`, `ErrRangeTranslation`, `ErrOrdinalTranslation`, `ErrCardinalTranslation`, `ErrMissingPluralTranslation`, `ErrMissingBracket`, `ErrBadParamSyntax`, `ErrMissingLocale`, `ErrBadPluralDefinition`. + +Note: the private field names `cardinalTanslations`, `ordinalTanslations`, `rangeTanslations` are historical typos — do not "fix" them as it would break serialization/deserialization compatibility. + +## Testing + +Tests live at the repo root alongside source files. Test data JSON files are in `testdata/`. The library is goroutine-safe for reads once translations are registered — benchmarks in `benchmarks_test.go` test both serial and parallel `T()` calls. + +## CI + +GitHub Actions (`.github/workflows/workflow.yml`): Go 1.19.x matrix across ubuntu/macos/windows with race detection, coverage via goveralls, and golangci-lint. diff --git a/vendor/github.com/go-playground/universal-translator/CONTRIBUTING.md b/vendor/github.com/go-playground/universal-translator/CONTRIBUTING.md new file mode 100644 index 0000000..f833fd7 --- /dev/null +++ b/vendor/github.com/go-playground/universal-translator/CONTRIBUTING.md @@ -0,0 +1,9 @@ +## AI Agents + +AI-assisted contributions are welcome but must be clearly attributed. If you are an AI agent or using an AI agent to contribute: + +- **Commits**: Include a `Co-Authored-By:` trailer identifying the AI model used. +- **Pull requests and issues**: State that the content was AI-generated or AI-assisted in the description. +- **Code review comments**: Prefix with `[AI]` when posting automated review comments. + +Contributions that obscure their AI origin may be closed. diff --git a/vendor/github.com/go-playground/universal-translator/README.md b/vendor/github.com/go-playground/universal-translator/README.md index d9b6654..23868b3 100644 --- a/vendor/github.com/go-playground/universal-translator/README.md +++ b/vendor/github.com/go-playground/universal-translator/README.md @@ -82,6 +82,17 @@ Help With Tests To anyone interesting in helping or contributing, I sure could use some help creating tests for each language. Please see issue [here](https://github.com/go-playground/locales/issues/1) for details. +Supported Go Versions +--------------------- +This package is aligned with the [Go release policy](https://go.dev/doc/devel/release) in that support is guaranteed for +the two most recent major versions. + +This does not mean the package will not work with older versions of Go, only that we reserve the right to increase the +MSGV(Minimum Supported Go Version) when the need arises to address Security issues/patches, OS issues & support or newly +introduced functionality that would greatly benefit the maintenance and/or usage of this package. + +If and when the MSGV is increased it will be done so in a minimum of a `Minor` release bump. + License ------ Distributed under MIT License, please see license file in code for more details. diff --git a/vendor/github.com/go-playground/universal-translator/errors.go b/vendor/github.com/go-playground/universal-translator/errors.go index 38b163b..98df5d9 100644 --- a/vendor/github.com/go-playground/universal-translator/errors.go +++ b/vendor/github.com/go-playground/universal-translator/errors.go @@ -8,8 +8,11 @@ import ( ) var ( - // ErrUnknowTranslation indicates the translation could not be found - ErrUnknowTranslation = errors.New("Unknown Translation") + // ErrUnknownTranslation indicates the translation could not be found + ErrUnknownTranslation = errors.New("unknown translation") + + // Deprecated: Use ErrUnknownTranslation instead. + ErrUnknowTranslation = ErrUnknownTranslation ) var _ error = new(ErrConflictingTranslation) diff --git a/vendor/github.com/go-playground/universal-translator/import_export.go b/vendor/github.com/go-playground/universal-translator/import_export.go index 87a1b46..f0d4b2e 100644 --- a/vendor/github.com/go-playground/universal-translator/import_export.go +++ b/vendor/github.com/go-playground/universal-translator/import_export.go @@ -163,7 +163,7 @@ func (t *UniversalTranslator) Import(format ImportExportFormat, dirnameOrFilenam if err != nil { return err } - defer f.Close() + defer func() { _ = f.Close() }() return t.ImportByReader(format, f) } diff --git a/vendor/github.com/go-playground/universal-translator/translator.go b/vendor/github.com/go-playground/universal-translator/translator.go index 24b18db..4272f3a 100644 --- a/vendor/github.com/go-playground/universal-translator/translator.go +++ b/vendor/github.com/go-playground/universal-translator/translator.go @@ -101,35 +101,87 @@ func (t *translator) Add(key interface{}, text string, override bool) error { return &ErrConflictingTranslation{locale: t.Locale(), key: key, text: text} } - lb := strings.Count(text, "{") - rb := strings.Count(text, "}") - - if lb != rb { - return &ErrMissingBracket{locale: t.Locale(), key: key, text: text} + indexes, err := parseParamPlaceholders(text, t.Locale(), key) + if err != nil { + return err } - trans := &transText{ - text: text, - } - - var idx int - - for i := 0; i < lb; i++ { - s := "{" + strconv.Itoa(i) + "}" - idx = strings.Index(text, s) - if idx == -1 { - return &ErrBadParamSyntax{locale: t.Locale(), param: s, key: key, text: text} - } - - trans.indexes = append(trans.indexes, idx) - trans.indexes = append(trans.indexes, idx+len(s)) - } - - t.translations[key] = trans + t.translations[key] = &transText{text: text, indexes: indexes} return nil } +// parseParamPlaceholders scans text for {N} placeholders where N is a canonical +// non-negative integer (no leading zeros). Returns triplets [start, end, paramIdx, ...] +// sorted by text position. Requires consecutive param indices starting from 0. +func parseParamPlaceholders(text string, locale string, key interface{}) ([]int, error) { + var indexes []int + seen := make(map[int]struct{}) + maxParam := -1 + + for i := 0; i < len(text); i++ { + if text[i] != '{' { + continue + } + + j := i + 1 + for j < len(text) && text[j] >= '0' && text[j] <= '9' { + j++ + } + + digitLen := j - i - 1 + if digitLen == 0 { + continue + } + + if j >= len(text) { + return nil, &ErrMissingBracket{locale: locale, key: key, text: text} + } + + if text[j] != '}' { + i = j - 1 + continue + } + + if digitLen > 1 && text[i+1] == '0' { + i = j + continue + } + + if digitLen > 9 { + i = j + continue + } + + n := 0 + for k := i + 1; k < j; k++ { + n = n*10 + int(text[k]-'0') + } + + indexes = append(indexes, i, j+1, n) + seen[n] = struct{}{} + if n > maxParam { + maxParam = n + } + + i = j + } + + if len(seen) == 0 { + return nil, nil + } + + if maxParam != len(seen)-1 { + for i := 0; i <= maxParam; i++ { + if _, ok := seen[i]; !ok { + return nil, &ErrBadParamSyntax{locale: locale, param: "{" + strconv.Itoa(i) + "}", key: key, text: text} + } + } + } + + return indexes, nil +} + // AddCardinal adds a cardinal plural translation for a particular language/locale // {0} is the only replacement type accepted and only one variable is accepted as // multiple cannot be used for a plural rule determination, unless it is a range; @@ -298,20 +350,18 @@ func (t *translator) T(key interface{}, params ...string) (string, error) { trans, ok := t.translations[key] if !ok { - return unknownTranslation, ErrUnknowTranslation + return unknownTranslation, ErrUnknownTranslation } b := make([]byte, 0, 64) - var start, end, count int + var start, end int - for i := 0; i < len(trans.indexes); i++ { + for i := 0; i < len(trans.indexes); i += 3 { end = trans.indexes[i] b = append(b, trans.text[start:end]...) - b = append(b, params[count]...) - i++ - start = trans.indexes[i] - count++ + b = append(b, params[trans.indexes[i+2]]...) + start = trans.indexes[i+1] } b = append(b, trans.text[start:]...) @@ -324,7 +374,7 @@ func (t *translator) C(key interface{}, num float64, digits uint64, param string tarr, ok := t.cardinalTanslations[key] if !ok { - return unknownTranslation, ErrUnknowTranslation + return unknownTranslation, ErrUnknownTranslation } rule := t.CardinalPluralRule(num, digits) @@ -344,7 +394,7 @@ func (t *translator) O(key interface{}, num float64, digits uint64, param string tarr, ok := t.ordinalTanslations[key] if !ok { - return unknownTranslation, ErrUnknowTranslation + return unknownTranslation, ErrUnknownTranslation } rule := t.OrdinalPluralRule(num, digits) @@ -365,7 +415,7 @@ func (t *translator) R(key interface{}, num1 float64, digits1 uint64, num2 float tarr, ok := t.rangeTanslations[key] if !ok { - return unknownTranslation, ErrUnknowTranslation + return unknownTranslation, ErrUnknownTranslation } rule := t.RangePluralRule(num1, digits1, num2, digits2) diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule/parse.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule/parse.go index 65ffcf5..06762fe 100644 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule/parse.go +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule/parse.go @@ -18,6 +18,50 @@ func (e InvalidTemplateError) Error() string { // Parse parses the string representation of path template func Parse(tmpl string) (Compiler, error) { + return parse(tmpl) +} + +// Segment is a top-level segment of a parsed path template. +type Segment struct { + // FieldPath is the field path bound by a variable segment, e.g. "name" + // for "{name=projects/*}". It is empty for literal and wildcard segments. + FieldPath string + // Value is the literal or wildcard ("*" or "**") of a non-variable + // segment, or the pattern of a variable segment, e.g. "projects/*" for + // "{name=projects/*}". A variable without an explicit pattern, such as + // "{name}", has the pattern "*". + Value string +} + +// SplitTemplate parses the string representation of path template and +// returns its top-level segments and its verb. The root template "/" has no +// segments. +func SplitTemplate(tmpl string) (segments []Segment, verb string, err error) { + t, err := parse(tmpl) + if err != nil { + return nil, "", err + } + for _, s := range t.segments { + switch s := s.(type) { + case literal: + if s == eof { + continue + } + segments = append(segments, Segment{Value: string(s)}) + case variable: + pattern := make([]string, 0, len(s.segments)) + for _, vs := range s.segments { + pattern = append(pattern, vs.String()) + } + segments = append(segments, Segment{FieldPath: s.path, Value: strings.Join(pattern, "/")}) + default: + segments = append(segments, Segment{Value: s.String()}) + } + } + return segments, t.verb, nil +} + +func parse(tmpl string) (template, error) { if !strings.HasPrefix(tmpl, "/") { return template{}, InvalidTemplateError{tmpl: tmpl, msg: "no leading /"} } @@ -28,6 +72,9 @@ func Parse(tmpl string) (Compiler, error) { if err != nil { return template{}, InvalidTemplateError{tmpl: tmpl, msg: err.Error()} } + if err := expectPChars(verb); err != nil { + return template{}, InvalidTemplateError{tmpl: tmpl, msg: fmt.Sprintf("invalid verb: %v", err)} + } return template{ segments: segs, diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/BUILD.bazel b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/BUILD.bazel index 04b4beb..691558c 100644 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/BUILD.bazel +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/BUILD.bazel @@ -38,6 +38,7 @@ go_library( "@org_golang_google_protobuf//reflect/protoreflect", "@org_golang_google_protobuf//reflect/protoregistry", "@org_golang_google_protobuf//types/known/durationpb", + "@org_golang_google_protobuf//types/known/emptypb", "@org_golang_google_protobuf//types/known/fieldmaskpb", "@org_golang_google_protobuf//types/known/structpb", "@org_golang_google_protobuf//types/known/timestamppb", @@ -49,13 +50,16 @@ go_test( name = "runtime_test", size = "small", srcs = [ + "context_internal_test.go", "context_test.go", "convert_test.go", "errors_test.go", + "fieldmask_empty_object_test.go", "fieldmask_test.go", "handler_test.go", "marshal_httpbodyproto_test.go", "marshal_json_test.go", + "marshal_jsonpb_bench_test.go", "marshal_jsonpb_test.go", "marshal_proto_test.go", "marshaler_registry_test.go", @@ -63,6 +67,7 @@ go_test( "mux_test.go", "pattern_test.go", "query_fuzz_test.go", + "query_internal_test.go", "query_test.go", ], embed = [":runtime"], @@ -76,6 +81,7 @@ go_test( "@org_golang_google_genproto_googleapis_rpc//status", "@org_golang_google_grpc//:grpc", "@org_golang_google_grpc//codes", + "@org_golang_google_grpc//credentials/insecure", "@org_golang_google_grpc//health/grpc_health_v1", "@org_golang_google_grpc//metadata", "@org_golang_google_grpc//status", diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/context.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/context.go index 00b2228..2f6a1de 100644 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/context.go +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/context.go @@ -4,6 +4,7 @@ import ( "context" "encoding/base64" "fmt" + "math" "net" "net/http" "net/textproto" @@ -36,6 +37,13 @@ const metadataHeaderBinarySuffix = "-Bin" const xForwardedFor = "X-Forwarded-For" const xForwardedHost = "X-Forwarded-Host" +// gRPC metadata keys are lower-case, so these two are appended to the pairs under their +// lower-case spelling. Writing it out as a constant keeps strings.ToLower off the per-request +// path, where it allocated a new string for a compile-time constant on every call, and lets +// metadata.Pairs skip its own lower-casing for these keys as well. +const xForwardedForKey = "x-forwarded-for" +const xForwardedHostKey = "x-forwarded-host" + // DefaultContextTimeout is used for gRPC call context.WithTimeout whenever a Grpc-Timeout inbound // header isn't present. If the value is 0 the sent `context` will not have a timeout. var DefaultContextTimeout = 0 * time.Second @@ -107,6 +115,10 @@ func isValidGRPCMetadataKey(key string) bool { // This means 0-9 a-z _ - . // Only lowercase letters are valid in the wire protocol, but the client library will normalize // uppercase ASCII to lowercase, so uppercase ASCII is also acceptable. + // An empty key is not a valid header name, and gRPC fails the call with one. + if key == "" { + return false + } bytes := []byte(key) // gRPC validates strings on the byte level, not Unicode. for _, ch := range bytes { validLowercaseLetter := ch >= 'a' && ch <= 'z' @@ -146,7 +158,21 @@ func annotateContext(ctx context.Context, mux *ServeMux, req *http.Request, rpcM return nil, nil, status.Errorf(codes.InvalidArgument, "invalid grpc-timeout: %s", tm) } } - var pairs []string + // Each forwarded header contributes a key and a value, and the two X-Forwarded-* pairs the + // gateway derives below add two more. Sizing for that up front replaces the handful of + // reallocations an empty slice goes through while it doubles. + pairs := make([]string, 0, 2*(len(req.Header)+2)) + // For backwards-compatibility, pass through 'authorization' header with no prefix. + // It is added before the header loop so that it is always the first + // "authorization" value: the loop iterates a map, so a header the matcher + // forwards under the same key (Grpc-Metadata-Authorization with the default + // matcher) would otherwise land ahead of it in random order, and a backend + // reading the first value would get the client-forwarded one. + for _, val := range req.Header.Values("Authorization") { + if isValidGRPCMetadataTextValue(val) { + pairs = append(pairs, "authorization", val) + } + } for key, vals := range req.Header { key = textproto.CanonicalMIMEHeaderKey(key) switch key { @@ -156,11 +182,17 @@ func annotateContext(ctx context.Context, mux *ServeMux, req *http.Request, rpcM } for _, val := range vals { - // For backwards-compatibility, pass through 'authorization' header with no prefix. - if key == "Authorization" { - pairs = append(pairs, "authorization", val) - } if h, ok := mux.incomingHeaderMatcher(key); ok { + // The gateway derives x-forwarded-host and x-forwarded-for below from + // the trusted request (Host / X-Forwarded-* / RemoteAddr), and backends + // rely on those metadata keys for client host/IP decisions. Refuse a + // forwarded header that the matcher strips into one of them (e.g. + // Grpc-Metadata-X-Forwarded-For) so a client cannot slip a spoofed value + // in ahead of the gateway-set one. + if strings.EqualFold(h, xForwardedFor) || strings.EqualFold(h, xForwardedHost) { + grpclog.Errorf("HTTP header %q maps to gateway-reserved metadata key %q; skipping", key, h) + continue + } if !isValidGRPCMetadataKey(h) { grpclog.Errorf("HTTP header name %q is not valid as gRPC metadata key; skipping", h) continue @@ -182,28 +214,52 @@ func annotateContext(ctx context.Context, mux *ServeMux, req *http.Request, rpcM } } } - if host := req.Header.Get(xForwardedHost); host != "" { - pairs = append(pairs, strings.ToLower(xForwardedHost), host) - } else if req.Host != "" { - pairs = append(pairs, strings.ToLower(xForwardedHost), req.Host) + if host := req.Header.Get(xForwardedHost); host != "" && isValidGRPCMetadataTextValue(host) { + pairs = append(pairs, xForwardedHostKey, host) + } else if req.Host != "" && isValidGRPCMetadataTextValue(req.Host) { + pairs = append(pairs, xForwardedHostKey, req.Host) } - xff := req.Header.Values(xForwardedFor) + // Validate each X-Forwarded-For value on its own, so that an invalid + // client-supplied value is dropped without also dropping the remote + // address the gateway appends. + var xff []string + for _, value := range req.Header.Values(xForwardedFor) { + if isValidGRPCMetadataTextValue(value) { + xff = append(xff, value) + } + } if addr := req.RemoteAddr; addr != "" { - if remoteIP, _, err := net.SplitHostPort(addr); err == nil { + if remoteIP, _, err := net.SplitHostPort(addr); err == nil && isValidGRPCMetadataTextValue(remoteIP) { xff = append(xff, remoteIP) } } if len(xff) > 0 { - pairs = append(pairs, strings.ToLower(xForwardedFor), strings.Join(xff, ", ")) + pairs = append(pairs, xForwardedForKey, strings.Join(xff, ", ")) } if timeout != 0 { ctx, _ = context.WithTimeout(ctx, timeout) } md := metadata.Pairs(pairs...) + var annotated metadata.MD for _, mda := range mux.metadataAnnotators { - md = metadata.Join(md, mda(ctx, req)) + annotated = metadata.Join(annotated, mda(ctx, req)) + } + // Annotators are the gateway's own code, so their values replace whatever + // the request headers put under the same key. Joining them after the + // header values would let a client send Grpc-Metadata- and have its + // value read first by a backend that trusts the annotator. + // + // With no annotators registered -- the default -- there is nothing to merge, and + // metadata.Join would rebuild the whole map for nothing: it starts from an empty MD and + // appends every key's values into a fresh slice, so the result is an identical copy of md + // bought with one allocation per key. + if len(annotated) > 0 { + for k := range annotated { + delete(md, strings.ToLower(k)) + } + md = metadata.Join(md, annotated) } if len(md) == 0 { return ctx, nil, nil @@ -302,10 +358,16 @@ func timeoutDecode(s string) (time.Duration, error) { if !ok { return 0, fmt.Errorf("timeout unit is not recognized: %q", s) } - t, err := strconv.ParseInt(s[:size-1], 10, 64) + t, err := strconv.ParseUint(s[:size-1], 10, 64) if err != nil { return 0, err } + // Guard against overflowing time.Duration, which is an int64 nanosecond + // count: without this a large value wraps to a bogus (often negative) + // deadline instead of the long timeout the client asked for. + if t > uint64(math.MaxInt64)/uint64(d) { + return time.Duration(math.MaxInt64), nil + } return d * time.Duration(t), nil } diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/convert.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/convert.go index 2e50082..8548f72 100644 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/convert.go +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/convert.go @@ -3,6 +3,7 @@ package runtime import ( "encoding/base64" "fmt" + "math" "strconv" "strings" @@ -44,9 +45,40 @@ func BoolSlice(val, sep string) ([]bool, error) { return values, nil } +// parseFloat parses a floating point value the way the proto3 JSON mapping +// does: a decimal number, or the exact strings "Infinity", "-Infinity" and +// "NaN". strconv.ParseFloat additionally accepts hexadecimal floats ("0x1p4"), +// underscore digit separators ("1_000") and alternate infinity/NaN spellings +// ("Inf", "nan", "infinity"), none of which protojson (and so the request body +// and backend) accept. Reject those so a value bound from a query or path +// parameter can't differ from the same value sent in the body. +func parseFloat(val string, bitSize int) (float64, error) { + switch val { + case "Infinity": + return math.Inf(1), nil + case "-Infinity": + return math.Inf(-1), nil + case "NaN": + return math.NaN(), nil + } + if strings.ContainsAny(val, "xX_") { + return 0, fmt.Errorf("invalid syntax %q", val) + } + f, err := strconv.ParseFloat(val, bitSize) + if err != nil { + return 0, err + } + // ParseFloat only yields Inf/NaN without an error for the alternate + // spellings handled above; overflow returns a range error instead. + if math.IsInf(f, 0) || math.IsNaN(f) { + return 0, fmt.Errorf("invalid syntax %q", val) + } + return f, nil +} + // Float64 converts the given string representation into representation of a floating point number into float64. func Float64(val string) (float64, error) { - return strconv.ParseFloat(val, 64) + return parseFloat(val, 64) } // Float64Slice converts 'val' where individual floating point numbers are separated by @@ -66,7 +98,7 @@ func Float64Slice(val, sep string) ([]float64, error) { // Float32 converts the given string representation of a floating point number into float32. func Float32(val string) (float32, error) { - f, err := strconv.ParseFloat(val, 32) + f, err := parseFloat(val, 32) if err != nil { return 0, err } @@ -90,7 +122,7 @@ func Float32Slice(val, sep string) ([]float32, error) { // Int64 converts the given string representation of an integer into int64. func Int64(val string) (int64, error) { - return strconv.ParseInt(val, 0, 64) + return strconv.ParseInt(val, 10, 64) } // Int64Slice converts 'val' where individual integers are separated by @@ -110,7 +142,7 @@ func Int64Slice(val, sep string) ([]int64, error) { // Int32 converts the given string representation of an integer into int32. func Int32(val string) (int32, error) { - i, err := strconv.ParseInt(val, 0, 32) + i, err := strconv.ParseInt(val, 10, 32) if err != nil { return 0, err } @@ -134,7 +166,7 @@ func Int32Slice(val, sep string) ([]int32, error) { // Uint64 converts the given string representation of an integer into uint64. func Uint64(val string) (uint64, error) { - return strconv.ParseUint(val, 0, 64) + return strconv.ParseUint(val, 10, 64) } // Uint64Slice converts 'val' where individual integers are separated by @@ -154,7 +186,7 @@ func Uint64Slice(val, sep string) ([]uint64, error) { // Uint32 converts the given string representation of an integer into uint32. func Uint32(val string) (uint32, error) { - i, err := strconv.ParseUint(val, 0, 32) + i, err := strconv.ParseUint(val, 10, 32) if err != nil { return 0, err } @@ -176,21 +208,22 @@ func Uint32Slice(val, sep string) ([]uint32, error) { return values, nil } -// Bytes converts the given string representation of a byte sequence into a slice of bytes -// A bytes sequence is encoded in URL-safe base64 without padding +// Bytes converts the given string representation of a byte sequence into a slice of bytes. +// Like the protobuf JSON mapping, it accepts standard or URL-safe base64, with or +// without padding. func Bytes(val string) ([]byte, error) { - b, err := base64.StdEncoding.DecodeString(val) - if err != nil { - b, err = base64.URLEncoding.DecodeString(val) - if err != nil { - return nil, err - } + enc := base64.StdEncoding + if strings.ContainsAny(val, "-_") { + enc = base64.URLEncoding } - return b, nil + if len(val)%4 != 0 { + enc = enc.WithPadding(base64.NoPadding) + } + return enc.DecodeString(val) } -// BytesSlice converts 'val' where individual bytes sequences, encoded in URL-safe -// base64 without padding, are separated by 'sep' into a slice of byte slices. +// BytesSlice converts 'val' where individual bytes sequences, encoded in standard or +// URL-safe base64, are separated by 'sep' into a slice of byte slices. func BytesSlice(val, sep string) ([][]byte, error) { s := strings.Split(val, sep) values := make([][]byte, len(s)) diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/errors.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/errors.go index bbe7dec..7db5d71 100644 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/errors.go +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/errors.go @@ -134,7 +134,8 @@ func DefaultHTTPErrorHandler(ctx context.Context, mux *ServeMux, marshaler Marsh w.Header().Set("Content-Type", contentType) if s.Code() == codes.Unauthenticated { - w.Header().Set("WWW-Authenticate", s.Message()) + // Canonical spelling, so Header.Set does not have to build one. + w.Header().Set("Www-Authenticate", s.Message()) } buf, merr := marshaler.Marshal(respRw) diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/fieldmask.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/fieldmask.go index 2fcd7af..d235ede 100644 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/fieldmask.go +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/fieldmask.go @@ -6,6 +6,7 @@ import ( "fmt" "io" "sort" + "strings" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/reflect/protoreflect" @@ -65,14 +66,16 @@ func FieldMaskFromRequestBody(r io.Reader, msg proto.Message) (*field_mask.Field } if isProtobufAnyMessage(fd.Message()) && !fd.IsList() { - _, hasTypeField := v.(map[string]interface{})["@type"] - if hasTypeField { - queue = append(queue, fieldMaskPathItem{path: k}) - continue - } else { + vm, _ := v.(map[string]interface{}) + if _, hasTypeField := vm["@type"]; !hasTypeField { return nil, fmt.Errorf("could not find field @type in %q in message %q", k, item.msg.Descriptor().FullName()) } - + newPath := string(fd.FullName().Name()) + if item.path != "" { + newPath = item.path + "." + newPath + } + queue = append(queue, fieldMaskPathItem{path: newPath}) + continue } child := fieldMaskPathItem{ @@ -96,10 +99,10 @@ func FieldMaskFromRequestBody(r io.Reader, msg proto.Message) (*field_mask.Field queue = append(queue, child) } } - case ok && len(m) == 0: - fallthrough case len(item.path) > 0: - // otherwise, it's a leaf node so print its path + // otherwise, it's a leaf node (an empty object counts as one) so + // print its path. The root has no path: an empty body such as {} + // sets nothing, and an empty path is not a valid FieldMask path. fm.Paths = append(fm.Paths, item.path) } } @@ -126,30 +129,55 @@ func isDynamicProtoMessage(md protoreflect.MessageDescriptor) bool { // passed in name and json value. func buildPathsBlindly(name string, in interface{}) []string { m, ok := in.(map[string]interface{}) - if !ok { + if !ok || len(m) == 0 { return []string{name} } + // A google.protobuf.Struct/Value field carries arbitrary client JSON, so + // its nesting depth is attacker controlled. Keep each queue entry pointing + // at its parent and its own segment rather than carrying the full path + // string, so a path is concatenated once at the leaf (O(depth)) instead of + // rebuilding the growing prefix at every level (O(depth^2)). A deeply + // nested object otherwise makes this allocate quadratically in the depth + // while producing only a handful of paths. + type pathNode struct { + parent *pathNode + segment string + } + type queueItem struct { + path *pathNode + node map[string]any + } + var paths []string - queue := []fieldMaskPathItem{{path: name, node: m}} + queue := []queueItem{{path: &pathNode{segment: name}, node: m}} for len(queue) > 0 { cur := queue[0] queue = queue[1:] - m, ok := cur.node.(map[string]interface{}) - if !ok { - // This should never happen since we should always check that we only add - // nodes of type map[string]interface{} to the queue. - continue - } - for k, v := range m { - if mi, ok := v.(map[string]interface{}); ok { - queue = append(queue, fieldMaskPathItem{path: cur.path + "." + k, node: mi}) - } else { - // This is not a struct, so there are no more levels to descend. - curPath := cur.path + "." + k - paths = append(paths, curPath) + for k, v := range cur.node { + child := &pathNode{parent: cur.path, segment: k} + if mi, ok := v.(map[string]any); ok && len(mi) > 0 { + queue = append(queue, queueItem{path: child, node: mi}) + continue } + // No populated object remains, so there are no more levels to + // descend. Walk back to the root to materialize the path once. + var segments []string + n := 0 + for p := child; p != nil; p = p.parent { + segments = append(segments, p.segment) + n += len(p.segment) + 1 + } + var b strings.Builder + b.Grow(n - 1) + for i := len(segments) - 1; i >= 0; i-- { + b.WriteString(segments[i]) + if i > 0 { + b.WriteByte('.') + } + } + paths = append(paths, b.String()) } } return paths diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/handler.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/handler.go index 4c9083d..b034747 100644 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/handler.go +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/handler.go @@ -210,7 +210,10 @@ func ForwardResponseMessage(ctx context.Context, mux *ServeMux, marshaler Marsha } func requestAcceptsTrailers(req *http.Request) bool { - te := req.Header.Get("TE") + // "Te", not "TE": Header.Get canonicalises the key it is given, and a key that is already + // canonical is returned as is, while any other spelling costs an allocated copy on every + // call. This one runs once per response. + te := req.Header.Get("Te") return strings.Contains(strings.ToLower(te), "trailers") } diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshal_jsonpb.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshal_jsonpb.go index 3d07063..0a3227b 100644 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshal_jsonpb.go +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshal_jsonpb.go @@ -5,11 +5,13 @@ import ( "encoding/json" "fmt" "io" + "math" "reflect" "strconv" "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/reflect/protoreflect" ) // JSONPb is a Marshaler which marshals/unmarshals into/from JSON @@ -30,6 +32,21 @@ func (*JSONPb) ContentType(_ interface{}) string { // Marshal marshals "v" into JSON. func (j *JSONPb) Marshal(v interface{}) ([]byte, error) { + if p, ok := v.(proto.Message); ok { + // protojson already returns a freshly allocated slice that the caller owns, so + // routing it through a bytes.Buffer only added an allocation and a copy of the + // whole message per call. Every unary response goes through here. + // + // The error is returned with a nil slice rather than whatever protojson produced + // alongside it, matching what the bytes.Buffer path did: marshalTo returned before + // writing anything, so a failed Marshal never handed back partial output. + b, err := j.MarshalOptions.Marshal(p) + if err != nil { + return nil, err + } + return b, nil + } + var buf bytes.Buffer if err := j.marshalTo(&buf, v); err != nil { return nil, err @@ -251,18 +268,36 @@ func decodeNonProtoField(d *json.Decoder, unmarshaler protojson.UnmarshalOptions return fmt.Errorf("unsupported type of map field key: %v", rv.Type().Key()) } - m := make(map[string]*json.RawMessage) - if err := d.Decode(&m); err != nil { + var raw json.RawMessage + if err := d.Decode(&raw); err != nil { return err } + m := make(map[string]*json.RawMessage) + if err := json.Unmarshal(raw, &m); err != nil { + return err + } + // encoding/json keeps the last value of a repeated key, while protojson + // rejects a duplicate map key, also when two spellings convert to the + // same key (e.g. "1" and "01"). Reject both here too. + if k, ok := duplicateObjectKey(raw); ok { + return fmt.Errorf("duplicate map key %q", k) + } + seen := make(map[any]struct{}, len(m)) for k, v := range m { result := conv.Call([]reflect.Value{reflect.ValueOf(k)}) if err := result[1].Interface(); err != nil { return err.(error) } bk := result[0] + if _, ok := seen[bk.Interface()]; ok { + return fmt.Errorf("duplicate map key %q", k) + } + seen[bk.Interface()] = struct{}{} bv := reflect.New(rv.Type().Elem()) if v == nil { + if err := rejectNullEnumItem(rv.Type().Elem()); err != nil { + return err + } null := json.RawMessage("null") v = &null } @@ -293,6 +328,11 @@ func decodeNonProtoField(d *json.Decoder, unmarshaler protojson.UnmarshalOptions rv.Set(reflect.MakeSlice(rv.Type(), 0, 0)) } for _, item := range sl { + if string(item) == "null" { + if err := rejectNullEnumItem(rv.Type().Elem()); err != nil { + return err + } + } bv := reflect.New(rv.Type().Elem()) if err := unmarshalJSONPb([]byte(item), unmarshaler, bv.Interface()); err != nil { return err @@ -308,11 +348,30 @@ func decodeNonProtoField(d *json.Decoder, unmarshaler protojson.UnmarshalOptions } switch v := repr.(type) { case string: - // TODO(yugui) Should use proto.StructProperties? + // protojson writes enums by name, so accept the name here too. + if e, ok := rv.Interface().(protoreflect.Enum); ok { + if ev := e.Descriptor().Values().ByName(protoreflect.Name(v)); ev != nil { + rv.SetInt(int64(ev.Number())) + return nil + } + if unmarshaler.DiscardUnknown { + return nil + } + return fmt.Errorf("invalid value %q for enum %s", v, e.Descriptor().FullName()) + } return fmt.Errorf("unmarshaling of symbolic enum %q not supported: %T", repr, rv.Interface()) case float64: + // Enum values are int32 on the wire. A fractional or out-of-range + // number would otherwise be silently truncated/wrapped into a bogus + // enum here, unlike protojson which rejects it, so reject it too. + if v != math.Trunc(v) || v < math.MinInt32 || v > math.MaxInt32 { + return fmt.Errorf("%v is not a valid value for enum %T", repr, rv.Interface()) + } rv.Set(reflect.ValueOf(int32(v)).Convert(rv.Type())) return nil + case nil: + // protojson leaves a null enum field unset. + return nil default: return fmt.Errorf("cannot assign %#v into Go type %T", repr, rv.Interface()) } @@ -320,6 +379,43 @@ func decodeNonProtoField(d *json.Decoder, unmarshaler protojson.UnmarshalOptions return d.Decode(v) } +// rejectNullEnumItem returns an error when t is an enum other than +// google.protobuf.NullValue. protojson leaves a null enum field unset, but +// rejects null as a list item or map value of such an enum. +func rejectNullEnumItem(t reflect.Type) error { + e, ok := reflect.Zero(t).Interface().(protoreflect.Enum) + if !ok || e.Descriptor().FullName() == "google.protobuf.NullValue" { + return nil + } + return fmt.Errorf("invalid value null for enum %s", e.Descriptor().FullName()) +} + +// duplicateObjectKey returns the first key that appears more than once in the +// JSON object in data. +func duplicateObjectKey(data []byte) (string, bool) { + d := json.NewDecoder(bytes.NewReader(data)) + if t, err := d.Token(); err != nil || t != json.Delim('{') { + return "", false + } + seen := make(map[string]struct{}) + for d.More() { + t, err := d.Token() + if err != nil { + return "", false + } + k, _ := t.(string) + if _, ok := seen[k]; ok { + return k, true + } + seen[k] = struct{}{} + var v json.RawMessage + if err := d.Decode(&v); err != nil { + return "", false + } + } + return "", false +} + type protoEnum interface { fmt.Stringer EnumDescriptor() ([]byte, []int) diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshal_proto.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshal_proto.go index 398c780..22e8992 100644 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshal_proto.go +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshal_proto.go @@ -40,6 +40,13 @@ func (marshaller *ProtoMarshaller) NewDecoder(reader io.Reader) Decoder { if err != nil { return err } + // ReadAll drains the reader, so a call with nothing left to read has + // to report io.EOF like the other decoders. Otherwise it decodes an + // empty message every time, and a loop decoding until io.EOF, such as + // the generated client streaming handlers, never terminates. + if len(buffer) == 0 { + return io.EOF + } return marshaller.Unmarshal(buffer, value) }) } diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshaler_registry.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshaler_registry.go index 07c2811..34a5c91 100644 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshaler_registry.go +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshaler_registry.go @@ -44,6 +44,18 @@ func MarshalerForRequest(mux *ServeMux, r *http.Request) (inbound Marshaler, out } for _, contentTypeVal := range r.Header[contentTypeHeader] { + // A header that is already exactly a registered media type -- "application/json", + // which is what clients send -- needs no parsing. mime.ParseMediaType allocates a + // parameter map even when the value carries no parameters, and it would return this + // value unchanged, so the lookup below would be the same one. + // + // This is also what the Accept loop above already does: the registry is keyed by the + // strings passed to WithMarshalerOption, and that loop matches the header value + // against them directly. + if m, ok := mux.marshalers.mimeMap[contentTypeVal]; ok { + inbound = m + break + } contentType, _, err := mime.ParseMediaType(contentTypeVal) if err != nil { grpclog.Errorf("Failed to parse Content-Type %s: %v", contentTypeVal, err) diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/mux.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/mux.go index 69edf5e..878a3e2 100644 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/mux.go +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/mux.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "mime" "net/http" "net/textproto" "regexp" @@ -44,7 +45,9 @@ const ( UnescapingModeDefault = UnescapingModeLegacy ) -var encodedPathSplitter = regexp.MustCompile("(/|%2F)") +// Percent-encoding is case insensitive (RFC 3986, section 6.2.2.1), so an +// escaped path separator has to be recognized in either spelling. +var encodedPathSplitter = regexp.MustCompile("(/|%2[fF])") // A HandlerFunc handles a specific pair of path pattern and HTTP method. type HandlerFunc func(w http.ResponseWriter, r *http.Request, pathParams map[string]string) @@ -75,6 +78,7 @@ type ServeMux struct { unescapingMode UnescapingMode writeContentLength bool disableChunkedEncoding bool + strictDeepWildcard bool } // ServeMuxOption is an option that can be given to a ServeMux on construction. @@ -137,6 +141,19 @@ func WithDisableChunkedEncoding() ServeMuxOption { } } +// WithStrictDeepWildcardMatching makes deep wildcards ("**") require at least +// one path segment when preceded by another segment. For example, +// "/v3/files/{path=**}" will not match "/v3/files". A trailing slash still +// provides an empty segment, so "/v3/files/" continues to match. +// +// This option applies to all patterns registered with the ServeMux, including +// generated routes and routes registered with HandlePath. +func WithStrictDeepWildcardMatching() ServeMuxOption { + return func(mux *ServeMux) { + mux.strictDeepWildcard = true + } +} + // SetQueryParameterParser sets the query parameter parser, used to populate message from query parameters. // Configuring this will mean the generated OpenAPI output is no longer correct, and it should be // done with careful consideration. @@ -151,24 +168,55 @@ type HeaderMatcherFunc func(string) (string, bool) // DefaultHeaderMatcher is used to pass http request headers to/from gRPC context. This adds permanent HTTP header // keys (as specified by the IANA, e.g: Accept, Cookie, Host) to the gRPC metadata with the grpcgateway- prefix. If you want to know which headers are considered permanent, you can view the isPermanentHTTPHeader function. -// HTTP headers that start with 'Grpc-Metadata-' are mapped to gRPC metadata after removing the prefix 'Grpc-Metadata-'. // Other headers are not added to the gRPC metadata. +// +// Earlier versions also mapped HTTP headers that start with 'Grpc-Metadata-' to gRPC metadata after removing the +// prefix. That let any HTTP client set an arbitrary metadata key, which a backend trusting a key as set by an +// interceptor or the gateway itself could not tell apart from the real value. Use LegacyHeaderMatcher, or the +// WithLegacyHeaderMatching option, to keep forwarding those headers. func DefaultHeaderMatcher(key string) (string, bool) { - switch key = textproto.CanonicalMIMEHeaderKey(key); { - case isPermanentHTTPHeader(key): + if key = textproto.CanonicalMIMEHeaderKey(key); isPermanentHTTPHeader(key) { return MetadataPrefix + key, true - case strings.HasPrefix(key, MetadataHeaderPrefix): - return key[len(MetadataHeaderPrefix):], true } return "", false } +// LegacyHeaderMatcher is the incoming header matcher earlier releases used by default. In addition to the +// permanent HTTP headers DefaultHeaderMatcher maps, HTTP headers that start with 'Grpc-Metadata-' are mapped +// to gRPC metadata after removing the prefix 'Grpc-Metadata-'. +// +// This lets any HTTP client set any metadata key the backend reads, except the ones the gateway reserves for +// itself, so only use it when the backend does not trust a metadata key to have been set by the gateway. +func LegacyHeaderMatcher(key string) (string, bool) { + switch key = textproto.CanonicalMIMEHeaderKey(key); { + case isPermanentHTTPHeader(key): + return MetadataPrefix + key, true + case strings.HasPrefix(key, MetadataHeaderPrefix): + mdKey := key[len(MetadataHeaderPrefix):] + // The grpcgateway- namespace is reserved for permanent HTTP headers the + // gateway maps itself, so refuse to forward a Grpc-Metadata- header that + // strips into it. Otherwise Grpc-Metadata-grpcgateway-host lets a client + // inject a value indistinguishable from the gateway-set grpcgateway-host. + if strings.HasPrefix(strings.ToLower(mdKey), MetadataPrefix) { + return "", false + } + return mdKey, true + } + return "", false +} + +// WithLegacyHeaderMatching returns a ServeMuxOption that restores LegacyHeaderMatcher as the incoming header +// matcher, so HTTP headers that start with 'Grpc-Metadata-' are forwarded as gRPC metadata again. +func WithLegacyHeaderMatching() ServeMuxOption { + return WithIncomingHeaderMatcher(LegacyHeaderMatcher) +} + func defaultOutgoingHeaderMatcher(key string) (string, bool) { - return fmt.Sprintf("%s%s", MetadataHeaderPrefix, key), true + return MetadataHeaderPrefix + key, true } func defaultOutgoingTrailerMatcher(key string) (string, bool) { - return fmt.Sprintf("%s%s", MetadataTrailerPrefix, key), true + return MetadataTrailerPrefix + key, true } // WithIncomingHeaderMatcher returns a ServeMuxOption representing a headerMatcher for incoming request to gateway. @@ -376,15 +424,28 @@ func NewServeMux(opts ...ServeMuxOption) *ServeMux { serveMux.outgoingTrailerMatcher = defaultOutgoingTrailerMatcher } + // Options such as WithHealthEndpointAt register handlers while the options + // are still being applied, so they were wrapped with only the middlewares + // configured before them. Rewrap them now that all middlewares are known. + if len(serveMux.middlewares) > 0 { + chain := chainMiddlewares(serveMux.middlewares) + for _, handlers := range serveMux.handlers { + for i := range handlers { + handlers[i].h = chain(handlers[i].raw) + } + } + } + return serveMux } // Handle associates "h" to the pair of HTTP method and path pattern. func (s *ServeMux) Handle(meth string, pat Pattern, h HandlerFunc) { + raw := h if len(s.middlewares) > 0 { h = chainMiddlewares(s.middlewares)(h) } - s.handlers[meth] = append([]handler{{pat: pat, h: h}}, s.handlers[meth]...) + s.handlers[meth] = append([]handler{{pat: pat, h: h, raw: raw}}, s.handlers[meth]...) } // HandlePath allows users to configure custom path handlers. @@ -415,11 +476,22 @@ func (s *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) { } // TODO(v3): remove UnescapingModeLegacy - if s.unescapingMode != UnescapingModeLegacy && r.URL.RawPath != "" { - path = r.URL.RawPath + unescapingMode := s.unescapingMode + if unescapingMode != UnescapingModeLegacy { + if r.URL.RawPath != "" { + path = r.URL.RawPath + } else { + // net/url only sets RawPath when the request path is not in its + // default encoding. Without it, Path is all there is and it has + // already been unescaped once, so unescaping it again while matching + // would decode a sequence like %252F twice. + unescapingMode = UnescapingModeLegacy + } } - if override := r.Header.Get("X-HTTP-Method-Override"); override != "" && !s.disableHTTPMethodOverride && s.isPathLengthFallback(r) { + // "X-Http-Method-Override" is the canonical spelling; Header.Get allocates a + // canonicalised copy of any other, and this lookup happens on every request. + if override := r.Header.Get("X-Http-Method-Override"); override != "" && !s.disableHTTPMethodOverride && s.isPathLengthFallback(r) { if err := r.ParseForm(); err != nil { _, outboundMarshaler := MarshalerForRequest(s, r) sterr := status.Error(codes.InvalidArgument, err.Error()) @@ -434,7 +506,7 @@ func (s *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) { // in this escaping mode we would be double unescaping but in UnescapingModeAllCharacters, we still do as the // path is the RawPath (i.e. unescaped). That does mean that the behavior of this function will change its default // behavior when the UnescapingModeDefault gets changed from UnescapingModeLegacy to UnescapingModeAllExceptReserved - if s.unescapingMode == UnescapingModeAllCharacters { + if unescapingMode == UnescapingModeAllCharacters { pathComponents = encodedPathSplitter.Split(path[1:], -1) } else { pathComponents = strings.Split(path[1:], "/") @@ -460,20 +532,33 @@ func (s *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) { idx = len(lastPathComponent) - len(patVerb) - 1 } if idx == 0 { - _, outboundMarshaler := MarshalerForRequest(s, r) - s.routingErrorHandler(ctx, s, outboundMarshaler, w, r, http.StatusNotFound) - return + // The last component is the bare verb with nothing before it, + // which this pattern cannot match. Other patterns still might, so + // move on rather than ending the search with a 404. + continue } - comps := make([]string, len(pathComponents)) - copy(comps, pathComponents) - + // Only copy the components when the verb has to be split off the last + // one. MatchAndEscape never mutates its input, so sharing the slice + // across handlers is safe, and copying it per handler otherwise costs + // len(pathComponents) allocations for every registered pattern. + comps := pathComponents if idx > 0 { + comps = make([]string, len(pathComponents)) + copy(comps, pathComponents) comps[len(comps)-1], verb = lastPathComponent[:idx], lastPathComponent[idx+1:] } - pathParams, err := h.pat.MatchAndEscape(comps, verb, s.unescapingMode) + pathParams, err := h.pat.matchAndEscape(comps, verb, unescapingMode, s.strictDeepWildcard) if err != nil { + // ErrNotMatch is returned once for every registered pattern the request does not + // match, so it is by far the most common error reaching this branch. Checking it + // first keeps errors.As off that path: its target parameter is an any, so &mse is + // boxed onto the heap on every call -- one allocation per route a request did not + // match, which grows with the number of registered routes. + if errors.Is(err, ErrNotMatch) { + continue + } var mse MalformedSequenceError if ok := errors.As(err, &mse); ok { _, outboundMarshaler := MarshalerForRequest(s, r) @@ -495,11 +580,24 @@ func (s *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) { // Note we are not eagerly checking the request here as we want to return the // right HTTP status code, and we need to process the fallback candidates in // order to do that. - for m, handlers := range s.handlers { + // GET is tried first when the request is subject to path length fallback: + // map iteration order is random, and a match for another method would + // otherwise return 405 before the GET handler is reached. + methods := make([]string, 0, len(s.handlers)) + if s.isPathLengthFallback(r) { + methods = append(methods, http.MethodGet) + } + for m := range s.handlers { + if m == http.MethodGet && s.isPathLengthFallback(r) { + continue + } + methods = append(methods, m) + } + for _, m := range methods { if m == r.Method { continue } - for _, h := range handlers { + for _, h := range s.handlers[m] { var verb string patVerb := h.pat.Verb() @@ -508,14 +606,14 @@ func (s *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) { idx = len(lastPathComponent) - len(patVerb) - 1 } - comps := make([]string, len(pathComponents)) - copy(comps, pathComponents) - + comps := pathComponents if idx > 0 { + comps = make([]string, len(pathComponents)) + copy(comps, pathComponents) comps[len(comps)-1], verb = lastPathComponent[:idx], lastPathComponent[idx+1:] } - pathParams, err := h.pat.MatchAndEscape(comps, verb, s.unescapingMode) + pathParams, err := h.pat.matchAndEscape(comps, verb, unescapingMode, s.strictDeepWildcard) if err != nil { var mse MalformedSequenceError if ok := errors.As(err, &mse); ok { @@ -558,12 +656,19 @@ func (s *ServeMux) GetForwardResponseOptions() []func(context.Context, http.Resp } func (s *ServeMux) isPathLengthFallback(r *http.Request) bool { - return !s.disablePathLengthFallback && r.Method == "POST" && r.Header.Get("Content-Type") == "application/x-www-form-urlencoded" + if s.disablePathLengthFallback || r.Method != http.MethodPost { + return false + } + // Like net/http's ParseForm, ignore parameters such as charset. + mediaType, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) + return err == nil && mediaType == "application/x-www-form-urlencoded" } type handler struct { pat Pattern h HandlerFunc + // raw is h before middlewares were applied. + raw HandlerFunc } func (s *ServeMux) handleHandler(h handler, w http.ResponseWriter, r *http.Request, pathParams map[string]string) { diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/pattern.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/pattern.go index e545071..b63b3d6 100644 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/pattern.go +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/pattern.go @@ -26,6 +26,9 @@ func (e MalformedSequenceError) Error() string { type op struct { code utilities.OpCode operand int + // multisegment is set on an OpPush that is one segment of a variable + // spanning several segments, such as the "*" in {name=shelves/*}. + multisegment bool } // Pattern is a template pattern of http request paths defined in @@ -43,6 +46,20 @@ type Pattern struct { tailLen int // verb is the VERB part of the path pattern. It is empty if the pattern does not have VERB part. verb string + // strictDeepWildcard makes a deep wildcard ("**") preceded by a segment require at least one + // remaining path component. + strictDeepWildcard bool +} + +// PatternOpt configures optional behavior of a Pattern. +type PatternOpt func(*Pattern) + +// WithStrictDeepWildcard makes a deep wildcard ("**") that is preceded by another +// segment refuse to match zero path segments. For example, "/v3/files/{path=**}" +// will not match "/v3/files". A bare "**" with nothing preceding it still matches +// zero segments. See https://github.com/grpc-ecosystem/grpc-gateway/issues/5771. +func WithStrictDeepWildcard() PatternOpt { + return func(p *Pattern) { p.strictDeepWildcard = true } } // NewPattern returns a new Pattern from the given definition values. @@ -51,6 +68,12 @@ type Pattern struct { // "version" must be 1 for now. // It returns an error if the given definition is invalid. func NewPattern(version int, ops []int, pool []string, verb string) (Pattern, error) { + return NewPatternWithOptions(version, ops, pool, verb) +} + +// NewPatternWithOptions is like NewPattern but additionally accepts options that modify +// the matching behavior of the returned Pattern, e.g. WithStrictDeepWildcard. +func NewPatternWithOptions(version int, ops []int, pool []string, verb string, opts ...PatternOpt) (Pattern, error) { if version != 1 { grpclog.Errorf("unsupported version: %d", version) return Pattern{}, ErrInvalidPattern @@ -106,6 +129,15 @@ func NewPattern(version int, ops []int, pool []string, verb string) (Pattern, er return Pattern{}, ErrInvalidPattern } stack++ + // The segments of a variable are the ops pushed right before its + // OpConcatN, so these are the ones of a multi-segment variable. + if op.operand > 1 { + for j := len(typedOps) - op.operand; j < len(typedOps); j++ { + if typedOps[j].code == utilities.OpPush { + typedOps[j].multisegment = true + } + } + } case utilities.OpCapture: if op.operand < 0 || len(pool) <= op.operand { grpclog.Errorf("variable name index out of bound: %d", op.operand) @@ -129,14 +161,18 @@ func NewPattern(version int, ops []int, pool []string, verb string) (Pattern, er } typedOps = append(typedOps, op) } - return Pattern{ + pat := Pattern{ ops: typedOps, pool: pool, vars: vars, stacksize: maxstack, tailLen: tailLen, verb: verb, - }, nil + } + for _, opt := range opts { + opt(&pat) + } + return pat, nil } // MustPattern is a helper function which makes it easier to call NewPattern in variable initialization. @@ -152,6 +188,10 @@ func MustPattern(p Pattern, err error) Pattern { // matched but contained malformed escape sequences. If successful, the function // returns a mapping from field paths to their captured values. func (p Pattern) MatchAndEscape(components []string, verb string, unescapingMode UnescapingMode) (map[string]string, error) { + return p.matchAndEscape(components, verb, unescapingMode, false) +} + +func (p Pattern) matchAndEscape(components []string, verb string, unescapingMode UnescapingMode, strictDeepWildcard bool) (map[string]string, error) { if p.verb != verb { if p.verb != "" { return nil, ErrNotMatch @@ -165,8 +205,29 @@ func (p Pattern) MatchAndEscape(components []string, verb string, unescapingMode } var pos int - stack := make([]string, 0, p.stacksize) - captured := make([]string, len(p.vars)) + + // Scratch space for the match. Neither backing array escapes -- only the individual + // strings they hold are copied into the returned bindings -- so fixed-size arrays keep + // both off the heap for the patterns generated code registers, where the stack size and + // the variable count are single digits. + // + // This matters beyond one allocation each: ServeHTTP calls matchAndEscape once per + // registered pattern until one matches, and both allocations happened before the + // non-match return below, so a request paid for them once for every route it did not + // match. With a few dozen routes registered that was the largest single source of + // allocations in routing. + var stackArr, capturedArr [8]string + stack := stackArr[:0] + if p.stacksize > len(stackArr) { + stack = make([]string, 0, p.stacksize) + } + var captured []string + if n := len(p.vars); n <= len(capturedArr) { + captured = capturedArr[:n] + } else { + captured = make([]string, n) + } + l := len(components) for _, op := range p.ops { var err error @@ -184,7 +245,14 @@ func (p Pattern) MatchAndEscape(components []string, verb string, unescapingMode return nil, ErrNotMatch } } else if op.code == utilities.OpPush { - if c, err = unescape(c, unescapingMode, false); err != nil { + // google.api.http decodes a variable spanning several segments + // "except %2F and %2f", so a "*" in it can't add a path separator + // to the bound value. Other escapes are decoded as for {var}. + mode := unescapingMode + if op.multisegment && mode == UnescapingModeAllExceptReserved { + mode = UnescapingModeAllExceptSlash + } + if c, err = unescape(c, mode, op.multisegment); err != nil { return nil, err } } @@ -196,6 +264,16 @@ func (p Pattern) MatchAndEscape(components []string, verb string, unescapingMode return nil, ErrNotMatch } end -= p.tailLen + if (p.strictDeepWildcard || strictDeepWildcard) && pos > 0 && pos == end { + // A deep wildcard ("**") is allowed to match zero path segments when it is + // the first thing being matched in the pattern (pos == 0). But once a literal + // or variable segment has already consumed a component, "**" needs the request + // path to continue past that segment — it cannot succeed with nothing left to + // consume at all (though an empty trailing segment, e.g. from a trailing slash, + // still counts as a real component and is fine). + // See https://github.com/grpc-ecosystem/grpc-gateway/issues/5771. + return nil, ErrNotMatch + } c := strings.Join(components[pos:end], "/") if c, err = unescape(c, unescapingMode, true); err != nil { return nil, err diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/query.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/query.go index 8549dfb..792b2b0 100644 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/query.go +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/query.go @@ -4,7 +4,6 @@ import ( "errors" "fmt" "net/url" - "regexp" "strconv" "strings" "time" @@ -16,13 +15,41 @@ import ( "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/reflect/protoregistry" "google.golang.org/protobuf/types/known/durationpb" + "google.golang.org/protobuf/types/known/emptypb" field_mask "google.golang.org/protobuf/types/known/fieldmaskpb" "google.golang.org/protobuf/types/known/structpb" "google.golang.org/protobuf/types/known/timestamppb" "google.golang.org/protobuf/types/known/wrapperspb" ) -var valuesKeyRegexp = regexp.MustCompile(`^(.*)\[(.*)\]$`) +// splitMapKey splits a query parameter name of the form "field[key]" into the part before the +// bracket and the key inside it, reporting whether the name has that shape at all. +// +// This replaces a FindStringSubmatch against `^(.*)\[(.*)\]$`, which ran for every query +// parameter and cost two allocations each -- the submatch slice and the backtracker's state -- +// to answer a question that is two index operations. The returned strings are slices of the +// caller's key, so nothing is copied; the caller rebuilds "[key]" as key[len(prefix):] rather +// than concatenating it back together. +// +// The regexp is matched exactly, including two details worth spelling out: +// +// - The first group is greedy, so the bracket that counts is the last one before the final +// "]". "a[b]c]" splits into "a" and "b]c", which is what LastIndexByte over everything but +// the final byte finds. +// - Go's regexp does not let "." match a newline and anchors ^ and $ at the ends of the text, +// so a key containing a newline could never match the pattern no matter where the brackets +// sat. The explicit newline check keeps that, rather than quietly starting to treat +// "a\n[b]" as a map key. +func splitMapKey(key string) (prefix, inner string, ok bool) { + if len(key) < 2 || key[len(key)-1] != ']' || strings.IndexByte(key, '\n') >= 0 { + return "", "", false + } + open := strings.LastIndexByte(key[:len(key)-1], '[') + if open < 0 { + return "", "", false + } + return key[:open], key[open+1 : len(key)-1], true +} var currentQueryParser QueryParameterParser = &DefaultQueryParser{} @@ -44,30 +71,67 @@ func PopulateQueryParameters(msg proto.Message, values url.Values, filter *utili type DefaultQueryParser struct{} // Parse populates "values" into "msg". -// A value is ignored if its key starts with one of the elements in "filter". +// A value is ignored if its key starts with one of the elements in "filter", +// or names a field that contains one of them. func (*DefaultQueryParser) Parse(msg proto.Message, values url.Values, filter *utilities.DoubleArray) error { + // A field is addressable by both its proto name and its JSON name, so two + // keys can set the same one. Record which fields have been set and refuse a + // second key for a field, the way protojson refuses a duplicate field in a + // body, instead of letting map iteration order pick the value that survives. + seen := make(map[string]struct{}, len(values)) for key, values := range values { - if match := valuesKeyRegexp.FindStringSubmatch(key); len(match) == 3 { - key = match[1] - values = append([]string{match[2]}, values...) + fieldKey, mapKey := key, "" + if prefix, inner, ok := splitMapKey(key); ok { + fieldKey, mapKey = prefix, key[len(prefix):] + values = append([]string{inner}, values...) } msgValue := msg.ProtoReflect() - fieldPath := normalizeFieldPath(msgValue, strings.Split(key, ".")) - if filter.HasCommonPrefix(fieldPath) { + fieldPath := normalizeFieldPath(msgValue, strings.Split(fieldKey, ".")) + if filter.HasCommonPrefix(fieldPath) || containsFilteredField(filter, fieldPath) { continue } - if err := populateFieldValueFromPath(msgValue, fieldPath, values); err != nil { + field := strings.Join(fieldPath, ".") + mapKey + if _, ok := seen[field]; ok { + return fmt.Errorf("duplicate field %q", field) + } + seen[field] = struct{}{} + if err := populateFieldValueFromPath(msgValue, fieldPath, values, mapKey != ""); err != nil { return err } } return nil } +// containsFilteredField reports whether fieldPath names a field that contains +// one of the sequences in filter, such as "id" for a path parameter bound to +// "id.value". Setting such a field from the query, which the parser can do for +// well-known types like wrappers and timestamps, would replace the whole +// message and with it the value already bound from the path or body. +func containsFilteredField(filter *utilities.DoubleArray, fieldPath []string) bool { + if len(filter.Base) == 0 { + return false + } + + var i int + for _, t := range fieldPath { + code, ok := filter.Encoding[t] + if !ok { + return false + } + j := filter.Base[i] + code + if len(filter.Check) <= j || filter.Check[j] != i+1 { + return false + } + i = j + } + return true +} + // PopulateFieldFromPath sets a value in a nested Protobuf structure. func PopulateFieldFromPath(msg proto.Message, fieldPathString string, value string) error { fieldPath := strings.Split(fieldPathString, ".") - return populateFieldValueFromPath(msg.ProtoReflect(), fieldPath, []string{value}) + return populateFieldValueFromPath(msg.ProtoReflect(), fieldPath, []string{value}, false) } func normalizeFieldPath(msgValue protoreflect.Message, fieldPath []string) []string { @@ -102,7 +166,7 @@ func normalizeFieldPath(msgValue protoreflect.Message, fieldPath []string) []str return newFieldPath } -func populateFieldValueFromPath(msgValue protoreflect.Message, fieldPath []string, values []string) error { +func populateFieldValueFromPath(msgValue protoreflect.Message, fieldPath []string, values []string, hasMapKey bool) error { if len(fieldPath) < 1 { return errors.New("no field path") } @@ -149,6 +213,18 @@ func populateFieldValueFromPath(msgValue protoreflect.Message, fieldPath []strin msgValue = msgValue.Mutable(fieldDescriptor).Message() } + // A key using the map syntax (field[key]=value) must name a map field, + // or a repeated field of key/value messages laid out like map entries. + // Otherwise the bracket content would be bound as if it were a regular + // value: appended as a phantom element of a repeated field, or counted + // as a second value for a singular one. + if hasMapKey && !fieldDescriptor.IsMap() { + if isKeyValueList(fieldDescriptor) { + return populateKeyValueListField(fieldDescriptor, msgValue.Mutable(fieldDescriptor).List(), values) + } + return fmt.Errorf("field %q is not a map", fieldDescriptor.FullName().Name()) + } + switch { case fieldDescriptor.IsList(): return populateRepeatedField(fieldDescriptor, msgValue.Mutable(fieldDescriptor).List(), values) @@ -205,6 +281,48 @@ func populateMapField(fieldDescriptor protoreflect.FieldDescriptor, mp protorefl return nil } +// isKeyValueList reports whether fieldDescriptor is a repeated message field +// whose message has exactly a singular "key" and a singular "value" field. +// Such a field is shaped like a map entry list, but can hold more than one +// value for a key. +func isKeyValueList(fieldDescriptor protoreflect.FieldDescriptor) bool { + if !fieldDescriptor.IsList() || fieldDescriptor.Message() == nil { + return false + } + fields := fieldDescriptor.Message().Fields() + if fields.Len() != 2 { + return false + } + key, value := fields.ByName("key"), fields.ByName("value") + return key != nil && key.Cardinality() != protoreflect.Repeated && + value != nil && value.Cardinality() != protoreflect.Repeated +} + +// populateKeyValueListField appends one key/value message to list for each of +// values[1:], all with the key values[0]. +func populateKeyValueListField(fieldDescriptor protoreflect.FieldDescriptor, list protoreflect.List, values []string) error { + fields := fieldDescriptor.Message().Fields() + keyField, valueField := fields.ByName("key"), fields.ByName("value") + + key, err := parseField(keyField, values[0]) + if err != nil { + return fmt.Errorf("parsing map key %q: %w", fieldDescriptor.FullName().Name(), err) + } + + for _, value := range values[1:] { + v, err := parseField(valueField, value) + if err != nil { + return fmt.Errorf("parsing map value %q: %w", fieldDescriptor.FullName().Name(), err) + } + entry := list.NewElement() + entry.Message().Set(keyField, key) + entry.Message().Set(valueField, v) + list.Append(entry) + } + + return nil +} + func parseField(fieldDescriptor protoreflect.FieldDescriptor, value string) (protoreflect.Value, error) { switch fieldDescriptor.Kind() { case protoreflect.BoolKind: @@ -224,7 +342,7 @@ func parseField(fieldDescriptor protoreflect.FieldDescriptor, value string) (pro // Look for enum by name v := enum.Descriptor().Values().ByName(protoreflect.Name(value)) if v == nil { - i, err := strconv.Atoi(value) + i, err := strconv.ParseInt(value, 10, 32) if err != nil { return protoreflect.Value{}, fmt.Errorf("%q is not a valid value", value) } @@ -259,13 +377,13 @@ func parseField(fieldDescriptor protoreflect.FieldDescriptor, value string) (pro } return protoreflect.ValueOfUint64(v), nil case protoreflect.FloatKind: - v, err := strconv.ParseFloat(value, 32) + v, err := parseFloat(value, 32) if err != nil { return protoreflect.Value{}, err } return protoreflect.ValueOfFloat32(float32(v)), nil case protoreflect.DoubleKind: - v, err := strconv.ParseFloat(value, 64) + v, err := parseFloat(value, 64) if err != nil { return protoreflect.Value{}, err } @@ -305,13 +423,13 @@ func parseMessage(msgDescriptor protoreflect.MessageDescriptor, value string) (p } msg = durationpb.New(d) case "google.protobuf.DoubleValue": - v, err := strconv.ParseFloat(value, 64) + v, err := parseFloat(value, 64) if err != nil { return protoreflect.Value{}, err } msg = wrapperspb.Double(v) case "google.protobuf.FloatValue": - v, err := strconv.ParseFloat(value, 32) + v, err := parseFloat(value, 32) if err != nil { return protoreflect.Value{}, err } @@ -356,7 +474,9 @@ func parseMessage(msgDescriptor protoreflect.MessageDescriptor, value string) (p msg = wrapperspb.Bytes(v) case "google.protobuf.FieldMask": fm := &field_mask.FieldMask{} - fm.Paths = append(fm.Paths, strings.Split(value, ",")...) + if value != "" { + fm.Paths = append(fm.Paths, strings.Split(value, ",")...) + } msg = fm case "google.protobuf.Value": var v structpb.Value @@ -370,6 +490,14 @@ func parseMessage(msgDescriptor protoreflect.MessageDescriptor, value string) (p return protoreflect.Value{}, err } msg = &v + case "google.protobuf.Empty": + // An Empty carries nothing, so the only thing the value can say is that the + // field is present. Accept the two spellings of "no content" and reject + // anything else, rather than silently ignoring it. + if value != "" && value != "{}" { + return protoreflect.Value{}, fmt.Errorf("expected an empty value or %q, got %q", "{}", value) + } + msg = &emptypb.Empty{} default: return protoreflect.Value{}, fmt.Errorf("unsupported message type: %q", string(msgDescriptor.FullName())) } diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/utilities/trie.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/utilities/trie.go index dd99b0e..77186a3 100644 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/utilities/trie.go +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/utilities/trie.go @@ -72,6 +72,7 @@ func (n node) children(seqs [][]int) []*node { if lastVal == seqs[i][n.col+1] { continue } + lastVal = seqs[i][n.col+1] last.right = i last = &node{ row: i, @@ -156,6 +157,11 @@ func (da *DoubleArray) HasCommonPrefix(seq []string) bool { var i int for _, t := range seq { + // A sequence ending at this node is already a prefix of seq, even if + // a longer sequence shares the path and the walk could carry on. + if da.hasTerminator(i) { + return true + } code, ok := da.Encoding[t] if !ok { break @@ -166,9 +172,11 @@ func (da *DoubleArray) HasCommonPrefix(seq []string) bool { } i = j } + return da.hasTerminator(i) +} + +// hasTerminator reports whether a sequence in the DoubleArray ends at node i. +func (da *DoubleArray) hasTerminator(i int) bool { j := da.Base[i] + len(da.Encoding) - if len(da.Check) <= j || da.Check[j] != i+1 { - return false - } - return true + return j < len(da.Check) && da.Check[j] == i+1 } diff --git a/vendor/github.com/jackc/pgx/v5/.gitignore b/vendor/github.com/jackc/pgx/v5/.gitignore index a2ebbe9..ff05307 100644 --- a/vendor/github.com/jackc/pgx/v5/.gitignore +++ b/vendor/github.com/jackc/pgx/v5/.gitignore @@ -22,6 +22,26 @@ _testmain.go *.exe .envrc -/.testdb + +# Per-checkout development state: this checkout's allocated TCP ports, the values derived from +# them, its decoded client certificates, and its own PostgreSQL/CockroachDB clusters. A git +# worktree is the native equivalent of a second devcontainer instance, so this is instance-local +# by definition -- never shared, never committed. See DEVELOPMENT.md. +/.dev/ + +# port-tamer writes this checkout's allocation to .dev/ports.env (the --state-file every task +# passes). These are where a bare `port-tamer` run at the repo root would put a stray second +# allocation instead; ignored so it cannot be committed by accident. +/.port-tamer.env +/.port-tamer.env.lock + +# Personal, machine-local mise overrides (mise.toml IS committed/shared). Git has no knowledge of +# mise's conventions, so this must be ignored explicitly. +/mise.local.toml + +# Provisioned on demand with `rake references:setup`; never committed. +/references/ .DS_Store + +/.vscode diff --git a/vendor/github.com/jackc/pgx/v5/Brewfile b/vendor/github.com/jackc/pgx/v5/Brewfile new file mode 100644 index 0000000..e35acd7 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/Brewfile @@ -0,0 +1,15 @@ +# Host dependencies only. Project tools and language runtimes belong in +# mise.toml; scripts/setup-host installs mise itself when necessary. + +# Server and client binaries for the checkout-local test matrix. +brew "postgresql@14" +brew "postgresql@15" +brew "postgresql@16" +brew "postgresql@17" +brew "postgresql@18" + +# mise compiles Ruby from source and links against these. +brew "openssl@3" +brew "readline" +brew "libyaml" +brew "gmp" diff --git a/vendor/github.com/jackc/pgx/v5/CHANGELOG.md b/vendor/github.com/jackc/pgx/v5/CHANGELOG.md index 12e633a..ce75860 100644 --- a/vendor/github.com/jackc/pgx/v5/CHANGELOG.md +++ b/vendor/github.com/jackc/pgx/v5/CHANGELOG.md @@ -1,3 +1,331 @@ +# 5.13.0 (November 11, 2026) + +This release adds automatic client certificate reloading and temporal precision metadata for `database/sql`. +It also fixes a panic on malformed server responses, unsafe retries after connection failures, and range encoding. +See Changes for client certificate configuration behavior that may affect existing applications. + +## Security Fixes + +* **Panic in `Rows.Values` on malformed server responses** + ([GHSA-w9rp-vfrh-q8vv](https://github.com/jackc/pgx/security/advisories/GHSA-w9rp-vfrh-q8vv)). + A server response containing fewer row values than declared fields could cause an index-out-of-range panic in + `Rows.Values`. It now returns an error and closes the rows when the counts differ, including when there are extra + values, matching `Rows.Scan` validation. + +## Features + +* pgconn: reload client certificates and keys configured through `sslcert` and `sslkey` for each TLS certificate + request, allowing new connections to pick up rotated credentials without recreating the configuration or + restarting the application. Files are still validated during configuration parsing. Relative paths retain their + parse-time directory, and reloads follow symlinks (Erin Shepherd) +* stdlib: expose fractional seconds precision for `timestamp`, `timestamptz`, `time`, `timetz`, and `interval` through + `ColumnTypePrecisionScale` and `database/sql.ColumnType.DecimalSize`. These return precision 0, the fractional + seconds precision as scale, and `ok=true`. The scale defaults to 6 when no fractional seconds precision is declared; + precision 0 means numeric precision is not applicable (Danny Xu) + +## Changes + +* pgconn: file-backed client certificates are no longer stored in the parsed `TLSConfig.Certificates` slice. + Setting `TLSConfig.Certificates` (including a non-nil empty slice) or `TLSConfig.GetClientCertificate` overrides + automatic reloading. Replacing `TLSConfig`, including with a direct `TLSConfig.Clone`, discards the file-backed + certificate settings; use `pgconn.Config.Copy` to preserve them when copying a configuration. Certificate and key + files must remain readable for subsequent TLS certificate requests. Encrypted keys reuse the password resolved + during configuration parsing; `GetSSLPassword` is not called again on reload. + +## Bug Fixes + +* pgconn: do not mark a connection-closed error encountered while receiving a response as safe to retry, since the + request may already have reached the server. This prevents `database/sql` from automatically repeating a statement + that may already have executed. The error still supports `errors.Is(err, pgconn.ErrConnClosed)` (Aayush Shah) +* pgconn: skip sending a cancel request when a connection fails during startup, avoiding an unnecessary second + connection attempt (felipe stival) +* pgconn: accept unencrypted combined certificate/key PEM files with the certificate before the key, as well as + key-first files (Erin Shepherd) +* pgtype: encode `Range[any]` values returned by `RangeCodec.DecodeValue` and `Rows.Values` in both binary and text + formats, allowing decoded ranges and multiranges to be reused as query arguments or in `CopyFrom` (waw666waw666) +* stdlib: report `ok=false` for the precision and scale of unconstrained `numeric` columns instead of bogus values + (Danny Xu) +* stdlib: report `math.MaxInt64` for the lengths of unconstrained `varchar`, `bpchar`, and `varbit` columns instead of + negative lengths (PerryLink) + +## Documentation and Tests + +* pgxpool: clarify that a zero `PingTimeout` lets a stalled health-check ping consume the acquiring caller's full + deadline, and explain the tradeoffs of a positive timeout (dajiaohuang) +* Correct the `AppendRows` / `RowToStructByName` benchmark to measure name-based rather than positional mapping + (Samir) + +# 5.12.0 (October 30, 2026) + +This release fixes two security vulnerabilities with narrow triggering conditions but serious impact. Affected +applications should upgrade to v5.12.0; see Security Fixes below. + +It also adds batched transaction startup, client certificate policy controls, and per-query batch timing, +and improves connection pool cancellation and type handling. Custom implementations +of `BatchResults`, including mocks, must add the new `Tx` method. + +## Security Fixes + +* **SQL injection in simple-protocol batches** + ([GHSA-j38q-h3ph-jjpq](https://github.com/jackc/pgx/security/advisories/GHSA-j38q-h3ph-jjpq), high severity). + In pgx v5 before v5.12.0, `SendBatch` using the non-default simple protocol could allow arbitrary SQL execution + with the application's database privileges when a queued query ends in a `--` comment without a newline and the + next query has an attacker-controlled string argument on its first line. Batched queries are now separated by + a newline to end such comments. Extended-protocol modes are unaffected. + Reported by [Igor Kupczyński (@igor-kupczynski)](https://github.com/igor-kupczynski). +* **Bypass of `require_auth` and `channel_binding=require`** + ([GHSA-95fj-3fxw-g62g](https://github.com/jackc/pgx/security/advisories/GHSA-95fj-3fxw-g62g), high severity). + In pgx v5.9.0 through v5.11.0, applications relying on these settings without verifying the server's identity + with `sslmode=verify-full` (or equivalent TLS verification) could accept an impersonating server that skips + authentication. The attacker could read queries and parameters and return fabricated results. pgx now enforces + authentication completion and required channel binding before accepting the connection. This vulnerability does + not bypass TLS server certificate verification. + Reported by [@president-xd](https://github.com/president-xd). + +## Features + +* Add `Batch.BeginTx` and `BatchResults.Tx` to begin a transaction as the first query of a batch, saving the round + trip for `BeginTx`. Call `Batch.BeginTx` before queuing any queries, consume the begin query's result first, and + close the batch before using the transaction. With `pgxpool.Pool.SendBatch`, the connection remains acquired until + the transaction is committed or rolled back. Add `FailedBatchResults` for wrappers that fail before sending a + batch (Timo Furrer) +* Add `TraceBatchQueryData.ReadStartTime` and per-query durations to `tracelog` batch query entries. These measure + result consumption, including application time spent reading rows, rather than server execution alone + (Yasser-Ameur) +* pgconn: support the `sslcertmode` connection parameter, `PGSSLCERTMODE` environment variable, and + `Config.SSLCertMode`. The default, `allow`, sends an available client certificate when requested; `disable` + prevents sending one and skips loading certificate/key files; `require` fails unless the server requests and + receives a certificate. `require` does not guarantee server-side certificate validation, disables TLS session + resumption, and stops further host or TLS fallbacks when the certificate requirement fails (k-zshiba) +* pgtype: add support for PostgreSQL 19's `oid8` and `oid8[]` (k-zshiba) + +## Changes + +* pgxpool: background attempts to satisfy `MinConns` and `MinIdleConns` now have a 60-second timeout, including + connection hooks. Initial background connections preserve the constructor context's values but ignore its + cancellation and deadline. +* pgxpool: canceling `Acquire` during a health-check ping now returns promptly and lets a successful ping return + the connection to the pool. The ping retains the caller's deadline and `PingTimeout`, with at most one additional + minute to finish after cancellation (lazerg) +* pgconn: on Windows, look for the default service file at `%APPDATA%\postgresql\.pg_service.conf`, matching libpq. + Fall back to the previous home-directory location only when the APPDATA file is missing, or APPDATA is unset; + other file errors no longer cause fallback (b84330808) + +## Performance Improvements + +* pgtype: add fast-path slice scan and encode plans for common primitive types (Andrew Suffield) +* pgtype: reduce allocations when encoding numbers and times as text (Guillaume Malette) +* stdlib: cache scan destination type classification on Go 1.27 (DublikuntMux) +* Reuse the begin statement for standard transaction option combinations (Timo Furrer) + +## Bug Fixes + +* Fix `NamedArgs` and `StrictNamedArgs` rewriting parameters inside dollar-quoted strings, truncating queries + containing U+FFFD (youdie006), and treating a trailing backslash as extending a SQL line comment. Fix the same + line-comment handling in simple-protocol argument sanitization. +* Preserve multidimensional array dimensions in `CopyFrom` (arminazimi) +* Deduplicate shared type dependencies returned by `LoadTypes` (Grivn) +* pgconn: preserve SCRAM passwords containing characters unassigned in Unicode 3.2, matching PostgreSQL's SASLprep + behavior +* pgconn: do not retain timeout errors in the background reader after a deadline has been cleared + (Vitalii Cherepanov) +* pgconn: normalize timeout errors after failed writes so context cancellation and deadline errors are reported + consistently (lazerg) +* pgconn: avoid a double-close panic when `OnPgError` closes the connection +* pgtype: fix interval fractional-second parsing beyond microsecond precision, validate all fractional digits + before rounding (Sasha Mitchell), and correctly encode `math.MinInt64` microseconds as text (spicysharkco) +* pgtype: preserve delimiters inside quoted multirange bounds (Sueun Cho) +* pgtype: handle SQL NULL in binary `ltree` scan plans without panicking (Januth Nimnal) +* pgtype: preserve `xid8` values above `math.MaxInt64` when decoding for `sql.Scanner`, returning their decimal + string representation instead of overflowing to a negative integer (k-zshiba) + +# 5.11.0 (September 7, 2026) + +This release adds direct PostgreSQL type scanning through `database/sql` on Go 1.27, improves compatibility with +libpq connection strings and PostgreSQL date/time values, and includes further decoder hardening. See Changes for +connection-string and date/time behavior changes that may affect existing applications. + +## Features + +* stdlib: support Go 1.27's `driver.RowsColumnScanner`, allowing PostgreSQL types such as arrays and ranges to be + scanned directly into Go values without `pgtype.Map.SQLScanner`. Existing `database/sql` scalar conversions and + `sql.Scanner` behavior are preserved. The minimum supported Go version remains 1.25. +* Add `Rows.TypeMap` to expose the type map used to decode rows, including rows created by `RowsFromResultReader` + that have no underlying `Conn`. Custom implementations of `Rows`, including mocks, must add this method. +* pgconn: add `Config.MaxProtocolMessageBodyLen` to configure the maximum incoming protocol message body size + (carter-ya) +* pgconn: add `ErrReadOnlyConnection`, `ErrReadWriteConnection`, `ErrPrimaryConnection`, and `ErrStandbyConnection` + sentinel errors for `target_session_attrs` validation, allowing callers to use `errors.Is` (Adrian-Stefan Mares) +* pgxpool: accept `pool_ping_timeout` in connection strings to configure `Config.PingTimeout`. The default is zero; + zero and negative durations mean no timeout (1991santhu) + +## Changes + +* Name-based row-to-struct mapping now matches explicit `db` tags case-insensitively, with exact matches taking + precedence so tags can still distinguish quoted column names that differ only by case (AlisinaDevelo) +* pgconn: resolve the OS user account only when no user is supplied by the connection string, environment, or service + file, avoiding unnecessary account lookups and crashes in some restricted container environments. Home-directory + defaults for password, service, and TLS files remain available independently of the account lookup. On Unix these + now use `$HOME` rather than the OS account's home directory (Mohamed MAACHE) + +* pgtype: `date`, `timestamp` and `timestamptz` text values are now parsed and written by a hand-written parser and + encoder for PostgreSQL's ISO date/time format instead of `time.Parse` and `time.Format`. Go's layout language cannot + express a variable-width year or the BC era, which is the root of the bugs below. The text scan path is roughly 2.5x + faster for `timestamp` and `timestamptz`. Bug fixes: + * `timestamp` and `timestamptz` no longer silently move February 29 of a BC leap year to March 1 when encoding. + `time.Date(-4712, 2, 29, ...)` was written as `4713-03-01 BC` and is now written as `4713-02-29 BC`. This + affected ordinary four-digit BC years, not only extended-range ones. `date` was never affected. + * `timestamp` and `timestamptz` can now scan BC leap days. `4713-02-29 BC` previously failed with + `day out of range`. `date` could already scan them. + * Years past 9999 can now be scanned. `10000-01-02 03:04:05` previously failed to parse, so `timestamp` and + `timestamptz` values at the high end of PostgreSQL's range were unreadable over the simple protocol and in any + other text-format result. + * `time.Time` arguments in the simple protocol now encode BC dates correctly, using the same timestamp encoder. + * Fractional seconds beyond microsecond precision are rounded the way the server rounds them (round half to even, + carrying into the rest of the value) instead of being kept at full precision. PostgreSQL never sends more than six + fractional digits, so this only affects values from other sources. + + Behavior changes: + * `date` now rejects impossible dates instead of normalizing them. `2024-02-30` returned `2024-03-01` and + `2024-13-01` returned `2025-01-01`; both are now errors. `timestamp` and `timestamptz` already rejected them. + * All three types now reject values outside PostgreSQL's range for that type, in the binary format as well as the + text format. PostgreSQL never sends out-of-range dates, so this only affects corrupt or hand-built input; the range + is checked in both formats so that whether a value is accepted does not depend on `QueryExecMode`. + `timestamptz` also rejects time zone displacements outside PostgreSQL's signed 32-bit seconds range, while accepting + the wider offsets emitted for POSIX time zones, such as `+16`. + * `timestamptz` values scanned from the text format are now returned in `time.Local`, or in `ScanLocation` when it is + set, matching what the binary format has always returned. Previously the text path kept whatever location + `time.Parse` derived from the offset the server sent, so the same value scanned in the two formats could report a + different `Location()` and `Zone()`. The instant is unchanged, but everything that renders the location changes + with it: `Timestamptz.MarshalJSON` now writes the client's offset rather than the server's, so a value the server + sent as `+05:30` marshals as `2024-01-01T13:34:05-08:00` on a UTC-8 client instead of `2024-01-02T03:04:05+05:30`, + and `DecodeDatabaseSQLValue` hands `database/sql` a `time.Time` in that same location. Set the codec's + `ScanLocation` to `time.UTC` to pin the location regardless of the client's zone. + * Error messages from these paths have changed. + +* pgconn: connection URIs (`postgres://...`) are now parsed by a new parser designed to exactly match libpq's URI + parser behavior instead of `net/url`, + making pgx accept and reject exactly the same URIs as libpq (verified by differential fuzzing against libpq itself). + Most connection strings are unaffected. Edge-case behavior changes, all matching libpq: + * `+` in query values is literal, no longer decoded as a space. + * Malformed percent-encoding is a parse error instead of the parameter being silently dropped. `%00` is rejected. + * Leading/trailing spaces in URI components are trimmed; interior spaces are a parse error (encode them as `%20`). + * `#` is ordinary data, not a fragment delimiter. + * The userinfo terminator is the first `@` before any `/` (previously the last `@`). + * When a query parameter is repeated, the last occurrence wins (previously the first). + * `ssl=true` is accepted as an alias for `sslmode=require` in URIs (JDBC compatibility). A repeated `ssl` key + follows the same last-occurrence-wins rule as other repeated parameters, even across the rewrite to `sslmode`. If + the final `ssl` value is not `true`, an independent explicit `sslmode` remains in effect. + * Multiple hosts with mixed port specs are positionally aligned: `postgres://h1,h2:5433/db` now means h1:5432 and + h2:5433 (previously both hosts got port 5433). A port list that is neither a single port nor exactly one port per + host is an error (`could not match N port numbers to M hosts`), also for keyword/value connection strings. + * An IPv6 address in a URI must be enclosed in brackets. A bare `postgres://::1/db` was previously accepted as host + `::1`; it is now read as an empty host followed by port `:1` and fails with an invalid port error. Write it as + `postgres://[::1]/db`. + * Empty host list elements (e.g. `h1,,h2`) get the default host instead of being dropped. Likewise, an empty host in + a keyword/value string (`host=`) now means the default host -- typically the Unix socket directory -- where it + previously meant a TCP connection to an empty hostname. + * An empty port (`?port=` in a URI or `port=` in a keyword/value string) now means the default port 5432 for the + affected hosts; previously it was an invalid port error. Like any connection-string port, a present-but-empty port + takes precedence over `PGPORT`. + * ASCII control characters (tab, newline, ...) in a URI are ordinary data bytes, as they are to libpq; `net/url` + rejected any URI containing one. The exception is a literal NUL byte, which is still rejected, as `net/url` did. + (libpq never sees one -- C strings end at the first NUL -- but in Go a raw NUL could otherwise pass through into + the NUL-delimited startup message and inject extra parameters.) + + Unlike libpq, unrecognized URI query parameters are still accepted (they become runtime parameters or pgx-specific + options). Parse error messages avoid quoting the unredacted connection string and redact recognizable password + fields on a best-effort basis. Invalid connection strings can be structurally ambiguous, so password redaction + cannot be guaranteed for every malformed input. + +* pgconn: keyword/value connection strings (`host=... user=...`) now match libpq's parser exactly, the same treatment + the URI parser received above and verified the same way, by differential fuzzing against libpq itself. Most + connection strings are unaffected. Behavior changes, all matching libpq: + * A backslash escapes whatever character follows it and is dropped, where previously only `\\` and `\'` were + unescaped and every other backslash was kept. A value containing a backslash must now escape it, as libpq + requires: `sslcert=C:\path\to\cert` reads as `C:pathtocert` and has to be written `sslcert=C:\\path\\to\\cert`. + This mainly affects Windows certificate and key paths, which previously came through intact without doubling. + * A trailing backslash in an unquoted value escapes the end of the string, so it is dropped and the value ends + there; it was previously rejected with `invalid backslash`. Inside a quoted value the escaped terminator leaves + the string unterminated, which is still an error. + * Whitespace inside a keyword is an error (`missing "=" after "us" in connection info string`) instead of becoming + part of the key. Whitespace around the `=` is unaffected. This most often shows up with an unquoted value + containing a space: `application_name=my app host=x` previously set neither parameter and sent `app host` to the + server as a runtime parameter, and now fails to parse. + + As with URIs, unrecognized keywords are still accepted where libpq rejects them, and an empty `user=` is still + dropped so that `PGUSER` and the OS user still apply. + +## Fixes + +* Keep the connection open after a recoverable PostgreSQL error from `Begin` or `BeginTx` + (Victor Alejandro Sanz Ararat) +* Call `TraceQueryEnd` when `Exec` fails while deallocating invalidated cached statements (Chris Bandy) +* Deallocate a failed prepare using the statement name actually sent to the server, and skip cleanup if Parse never + completed, avoiding leaked prepared statements and unnecessary cleanup errors (Eliran Ben-Zikri) +* Fix `LoadTypes` overwriting scalar codecs such as `box` and `point` with an incorrect `ArrayCodec` (Arsen Ozhetov) +* pgconn: retrieve field descriptions when cached descriptions are empty, such as for cursor `FETCH` statements, + including batch and pipeline execution (water) +* pgconn: keep batch statement descriptions and result formats aligned when commands return no rows or when + `Batch.ExecStatement` is mixed with other batch commands; preserve field descriptions for empty results +* pgconn: handle empty and comment-only queries in pipeline mode, discard stale statement data after bind errors, + and return a nil result from `Pipeline.GetResults` on error +* pgconn: skip reading the password file when a password is already set (Jared Fowkes) +* pgxpool: treat non-positive `MaxConnLifetime` values as unlimited instead of immediately expiring connections + (Aurelien Pillevesse) +* pgtype: support non-comma text array delimiters through `ArrayCodec.Delimiter`, including the semicolon delimiter + used by `box[]`. `LoadType` and `LoadTypes` now load the delimiter from PostgreSQL (Sueun Cho) +* pgtype: quote text array elements containing internal whitespace (Louisa Huang) +* pgtype: quote and escape text range bounds containing delimiters, quotes, or backslashes, and distinguish empty + string bounds from unbounded ranges (Sueun Cho) +* pgtype: preserve decimal precision in `Numeric.ScanScientific` and accept scientific notation in + `Numeric.UnmarshalJSON`; reject out-of-range scientific exponents and preserve the original input in parse errors + (Sueun Cho) +* pgtype: encode and decode numeric infinity in JSON as `"Infinity"` and `"-Infinity"` instead of encoding it as zero + (Vladimir Saraikin) +* pgtype: treat a valid `Numeric` with a nil `Int` as zero in `Int64Value`, and return errors when converting NaN or + infinity to an integer instead of panicking (Vladimir Saraikin) +* pgtype: fix an infinite loop when decoding binary numeric zero with a nonzero digit count (Vladimir Saraikin) +* pgtype: fix binary numeric digit-count overflow and trailing-byte handling. Binary encoding now rejects values + whose digit count, weight, or scale cannot fit the wire format, while accepting the full unsigned digit-count range. +* pgtype: fix scanning through multiple pointer levels, including SQL NULL and XML values, and return an error + instead of panicking when a pointer-to-pointer scan destination is nil (Rangel Reale) +* pgtype: use bounds-checked binary reads throughout the codecs and reject malformed lengths, counts, and trailing + data. This includes fixes for panics on malformed records and truncated multiranges (Vladimir Saraikin), and + validation of `bit` / `varbit` bit lengths against the actual data (g3m0sis). +* pgtype: return errors instead of panicking on malformed interval text (greymoth-jp), unterminated composite text + fields, and text arrays whose dimensions and element counts disagree +* pgtype: cap the initial allocation estimate when parsing hstore text to avoid excessive allocation from unvalidated + separator counts; valid hstores may still contain any number of pairs (AshSgDe29071999) +* pgtype: correct reversed bounds in integer scan error messages +* pgconn: a backslash as the last byte of a quoted value in a keyword/value connection string no longer panics with + `slice bounds out of range`. `host='a\` -- and the shorter `='\`, reachable through `pgx.ParseConfig` and + `pgxpool.ParseConfig` -- now return `unterminated quoted string in connection info string`, libpq's own message for + the same input. The unquoted branch has been guarded since be69c1c1; the quoted branch carried the same unguarded + increment since the parser was ported from pgx v3. Found by fuzzing (Maxim Korotkov) +* pgconn: error messages that embed the connection string now also redact `password` and `sslpassword` values supplied + as URI query parameters; previously only the userinfo password was redacted. Redaction matches keys the way the + parser does -- percent-encoded spellings such as `pass%77ord=` are recognized -- and masks the entire raw value, so + a password containing a space cannot leak its tail into the error message. Credentials stranded outside the + userinfo by a malformed URI are masked whole, and invalid-port errors no longer embed the offending text (which in + a malformed URI can be a mislaid password). Redaction of invalid connection strings is necessarily best effort: + their structure may be ambiguous, so some malformed inputs can still expose password text in an error. +* pgconn: `ParseConfigOptions.ConnStringAllowedKeys` no longer exempts an explicitly supplied empty port (`?port=` in + a URI or `port=` in a keyword/value string) from the allow-list. Only the implied all-empty port list of a + multi-host URI without ports (`postgres://h1,h2/db`) is exempt. An explicit empty port shadows `PGPORT` even though + it is empty, so it must be allowed like any other user-supplied key. The URI-only `ssl=true` alias is accepted when + either `ssl` or `sslmode` is allowed, and every `ssl`/`sslmode` spelling written in the URI is validated -- + including occurrences superseded by later repeated parameters. +* pgconn: drain socket before close in `asyncClose` so context cancellation produces a TCP FIN instead of RST, avoiding "connection reset by peer" on the server / proxy (Sean Chittenden at CrowdStrike, Inc.) +* pgproto3: `StartupMessage.Encode` rejects a NUL byte in any parameter name or value instead of writing it. The + startup message body is a run of NUL-delimited strings whose length is data-driven, so a NUL in a value ends that + parameter and everything after it is read by the server as further parameters -- an `application_name` of + `x\x00user\x00admin` changed the role the connection logged in as. libpq cannot reach this state because its + parameters are NUL-terminated C strings. `Connect` now fails with nothing written to the wire, which covers + settings that bypass connection string parsing: service files and direct assignment to `Config.RuntimeParams`, + `Config.User`, or `Config.Database`. +* pgconn: keyword/value connection strings containing a NUL byte are rejected by `ParseConfig`, as URIs already were. + # 5.10.0 (June 3, 2026) This release includes a significant amount of hardening against malicious or compromised PostgreSQL servers, diff --git a/vendor/github.com/jackc/pgx/v5/CLAUDE.md b/vendor/github.com/jackc/pgx/v5/CLAUDE.md index 71a8fc1..3b9f300 100644 --- a/vendor/github.com/jackc/pgx/v5/CLAUDE.md +++ b/vendor/github.com/jackc/pgx/v5/CLAUDE.md @@ -8,41 +8,59 @@ pgx is a PostgreSQL driver and toolkit for Go (`github.com/jackc/pgx/v5`). It pr ## Build & Test Commands +Every checkout has its own PostgreSQL 14-18 and CockroachDB instances, supervised by +process-compose. `mise run dev` starts PostgreSQL 18; tests start other targets on demand and stop +them afterwards unless they were explicitly prewarmed. See DEVELOPMENT.md. + ```bash -# Run all tests (requires PGX_TEST_DATABASE to be set) -go test ./... +mise run dev # start PostgreSQL 18 and the database supervisor +mise run dev:all # eagerly start every available database +mise run dev -- -D # ... detached; then `mise run dev:wait`, and + # `mise run dev:down` when finished. Agents must do this. -# Run a specific test -go test -run TestFunctionName ./... +./test.sh # Full suite against PostgreSQL 18 (the default target) +./test.sh pg16 # Against PostgreSQL 16 +./test.sh crdb # Against CockroachDB +./test.sh all # Every target (pg14-18 + crdb) +./test.sh pg16 -run TestConnect # Trailing arguments are passed to `go test` -# Run tests for a specific package -go test ./pgconn/... +go test ./... # Also works: mise loads the default target's PGX_TEST_* +go test -race ./... # With the race detector -# Run tests with race detector -go test -race ./... +goimports -w . # Format (always run after making changes) +golangci-lint run ./... # Lint -# DevContainer: run tests against specific PostgreSQL versions -./test.sh pg18 # Default: PostgreSQL 18 -./test.sh pg16 -run TestConnect # Specific test against PG16 -./test.sh crdb # CockroachDB -./test.sh all # All targets (pg14-18 + crdb) - -# Format (always run after making changes) -goimports -w . - -# Lint -golangci-lint run ./... +mise run dev:ports # This checkout's ports and where each server's data lives +mise run db:start pg16 crdb # Prewarm targets; tests then leave them running +mise run db:stop pg16 crdb # Stop prewarmed targets +mise run db:psql # psql against PostgreSQL 18; `mise run db:psql 16` for another +process-compose process logs pg16 # One server's output ``` +Do not hardcode database ports. They are allocated per checkout by port-tamer and read from the +environment (`PGPORT`, `PGPORT_16`, `CRDB_PORT`) or `.dev/ports.env`; 5432 and 26257 mean nothing +here. + +The `PGX_TEST_*` connection strings have one definition, `scripts/lib/test_targets.rb`. Add or +change a target there, never in a second copy. + ## Test Database Setup -Tests require `PGX_TEST_DATABASE` environment variable. In the devcontainer, `test.sh` handles this. For local development: +The lifecycle scripts handle setup: a PostgreSQL server initializes its cluster on first start and +creates `pgx_test` with the extensions and auth roles from `testsetup/postgresql_setup.sql`. +CockroachDB recreates `pgx_test` after each in-memory restart. Nothing needs to be set up by hand. -```bash -export PGX_TEST_DATABASE="host=localhost user=postgres password=postgres dbname=pgx_test" -``` +Contributors who would rather point pgx at a PostgreSQL server they already have can set +`PGX_TEST_DATABASE` themselves; see CONTRIBUTING.md. Many tests are skipped unless additional +`PGX_TEST_*` variables are set (for TLS, SCRAM, MD5, unix socket, PgBouncer testing). -The test database needs extensions: `hstore`, `ltree`, and a `uint64` domain. See `testsetup/postgresql_setup.sql` for full setup. Many tests are skipped unless additional `PGX_TEST_*` env vars are set (for TLS, SCRAM, MD5, unix socket, PgBouncer testing). +## Reference Material + +`references/` holds read-only reference checkouts used when building pgx — currently the PostgreSQL source tree pinned to `REL_18_STABLE`. It is gitignored and provisioned on demand: bare mirrors are cached at a machine-level path (`/persist/shared/references` in a devcontainer, `~/.local/share/pgx/references` natively; `REFERENCES_MIRROR_DIR` overrides) and lightweight local checkouts are created in `references/` with `rake references:setup`. Each checkout has per-instance Git metadata while borrowing the shared mirror's object store. Related tasks: `rake references:update`, `rake references:status`, `rake references:clean`. + +- Do not automatically provision or update `references/`. +- Never run `rake references:setup`, `rake references:update`, or any large download on your own initiative. +- If reference sources are missing, work without them or ask the user. ## Architecture diff --git a/vendor/github.com/jackc/pgx/v5/CONTRIBUTING.md b/vendor/github.com/jackc/pgx/v5/CONTRIBUTING.md index 2283ae6..c89ec1a 100644 --- a/vendor/github.com/jackc/pgx/v5/CONTRIBUTING.md +++ b/vendor/github.com/jackc/pgx/v5/CONTRIBUTING.md @@ -24,21 +24,30 @@ Using AI is acceptable (not that it can really be stopped) under one the followi ## Development Environment Setup -pgx tests naturally require a PostgreSQL database. It will connect to the database specified in the `PGX_TEST_DATABASE` -environment variable. The `PGX_TEST_DATABASE` environment variable can either be a URL or key-value pairs. In addition, -the standard `PG*` environment variables will be respected. Consider using [direnv](https://github.com/direnv/direnv) to -simplify environment variable handling. +pgx tests naturally require a PostgreSQL database. It will connect to the database specified in the +`PGX_TEST_DATABASE` environment variable. The `PGX_TEST_DATABASE` environment variable can either be +a URL or key-value pairs. In addition, the standard `PG*` environment variables will be respected. -### Devcontainer +### The full environment -The easiest way to start development is with the included devcontainer. It includes containers for each supported -PostgreSQL version as well as CockroachDB. `./test.sh all` will run the tests against all database types. +[DEVELOPMENT.md](DEVELOPMENT.md) describes the maintained setup: [mise](https://mise.jdx.dev) +installs the toolchain, and each checkout has its own PostgreSQL 14-18 clusters and CockroachDB +node, so the whole test matrix is available locally. PostgreSQL 18 stays running; other servers +start and stop around their tests. It works natively on macOS and Linux, and in the included +devcontainer. -### Using an Existing PostgreSQL Cluster Outside of a Devcontainer +``` +mise install +mise run dev:init +mise run dev +./test.sh all +``` -If you already have a PostgreSQL development server this is the quickest way to start and run the majority of the pgx -test suite. Some tests will be skipped that require server configuration changes (e.g. those testing different -authentication methods). +### Using an existing PostgreSQL cluster + +If you already have a PostgreSQL development server this is the quickest way to run the majority of +the pgx test suite, and it needs nothing from the section above. Some tests will be skipped that +require server configuration changes (e.g. those testing different authentication methods). Create and setup a test database: @@ -50,86 +59,30 @@ psql -c 'create extension ltree;' psql -c 'create domain uint64 as numeric(20,0);' ``` -Ensure a `postgres` user exists. This happens by default in normal PostgreSQL installs, but some installation methods -such as Homebrew do not. +Ensure a `postgres` user exists. This happens by default in normal PostgreSQL installs, but some +installation methods such as Homebrew do not. ``` createuser -s postgres ``` -Ensure your `PGX_TEST_DATABASE` environment variable points to the database you just created and run the tests. +Ensure your `PGX_TEST_DATABASE` environment variable points to the database you just created and run +the tests. ``` export PGX_TEST_DATABASE="host=/private/tmp database=pgx_test" go test ./... ``` -This will run the vast majority of the tests, but some tests will be skipped (e.g. those testing different connection methods). - -### Creating a New PostgreSQL Cluster Exclusively for Testing Outside of a Devcontainer - -The following environment variables need to be set both for initial setup and whenever the tests are run. (direnv is -highly recommended). Depending on your platform, you may need to change the host for `PGX_TEST_UNIX_SOCKET_CONN_STRING`. - -``` -export PGPORT=5015 -export PGUSER=postgres -export PGDATABASE=pgx_test -export POSTGRESQL_DATA_DIR=postgresql - -export PGX_TEST_DATABASE="host=127.0.0.1 database=pgx_test user=pgx_md5 password=secret" -export PGX_TEST_UNIX_SOCKET_CONN_STRING="host=/private/tmp database=pgx_test" -export PGX_TEST_TCP_CONN_STRING="host=127.0.0.1 database=pgx_test user=pgx_md5 password=secret" -export PGX_TEST_SCRAM_PASSWORD_CONN_STRING="host=127.0.0.1 user=pgx_scram password=secret database=pgx_test channel_binding=disable" -export PGX_TEST_SCRAM_PLUS_CONN_STRING="host=localhost user=pgx_ssl password=secret sslmode=verify-full sslrootcert=`pwd`/.testdb/ca.pem database=pgx_test channel_binding=require" -export PGX_TEST_MD5_PASSWORD_CONN_STRING="host=127.0.0.1 database=pgx_test user=pgx_md5 password=secret" -export PGX_TEST_PLAIN_PASSWORD_CONN_STRING="host=127.0.0.1 user=pgx_pw password=secret" -export PGX_TEST_TLS_CONN_STRING="host=localhost user=pgx_ssl password=secret sslmode=verify-full sslrootcert=`pwd`/.testdb/ca.pem channel_binding=disable" -export PGX_SSL_PASSWORD=certpw -export PGX_TEST_TLS_CLIENT_CONN_STRING="host=localhost user=pgx_sslcert sslmode=verify-full sslrootcert=`pwd`/.testdb/ca.pem database=pgx_test sslcert=`pwd`/.testdb/pgx_sslcert.crt sslkey=`pwd`/.testdb/pgx_sslcert.key" -``` - -Create a new database cluster. - -``` -initdb --locale=en_US -E UTF-8 --username=postgres .testdb/$POSTGRESQL_DATA_DIR - -echo "listen_addresses = '127.0.0.1'" >> .testdb/$POSTGRESQL_DATA_DIR/postgresql.conf -echo "port = $PGPORT" >> .testdb/$POSTGRESQL_DATA_DIR/postgresql.conf -cat testsetup/postgresql_ssl.conf >> .testdb/$POSTGRESQL_DATA_DIR/postgresql.conf -cp testsetup/pg_hba.conf .testdb/$POSTGRESQL_DATA_DIR/pg_hba.conf - -cd .testdb - -# Generate CA, server, and encrypted client certificates. -go run ../testsetup/generate_certs.go - -# Copy certificates to server directory and set permissions. -cp ca.pem $POSTGRESQL_DATA_DIR/root.crt -cp localhost.key $POSTGRESQL_DATA_DIR/server.key -chmod 600 $POSTGRESQL_DATA_DIR/server.key -cp localhost.crt $POSTGRESQL_DATA_DIR/server.crt - -cd .. -``` - - -Start the new cluster. This will be necessary whenever you are running pgx tests. - -``` -postgres -D .testdb/$POSTGRESQL_DATA_DIR -``` - -Setup the test database in the new cluster. - -``` -createdb -psql --no-psqlrc -f testsetup/postgresql_setup.sql -``` +This will run the vast majority of the tests, but some tests will be skipped (e.g. those testing +different connection methods). ### PgBouncer There are tests specific for PgBouncer that will be executed if `PGX_TEST_PGBOUNCER_CONN_STRING` is set. +The test PgBouncer must be version 1.21.0 or newer, use transaction pooling, and have `max_prepared_statements` set to a +non-zero value. This ensures the tests cover PgBouncer's protocol-level named prepared statement support in addition to +the pgx query modes that do not use named prepared statements. ### Optional Tests diff --git a/vendor/github.com/jackc/pgx/v5/DEVELOPMENT.md b/vendor/github.com/jackc/pgx/v5/DEVELOPMENT.md new file mode 100644 index 0000000..d2a91f8 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/DEVELOPMENT.md @@ -0,0 +1,239 @@ +# Developing pgx + +Two supported environments, one command set. Native macOS or Linux is the fast inner loop; the +devcontainer is a Linux compatibility and isolation option. Both run the same mise tasks against +the same `process-compose.yaml`, so nothing here is specific to one of them except the +prerequisites in §1. + +```sh +scripts/setup-host # native macOS or Ubuntu host prerequisites (once per machine) +export PATH="$HOME/.local/bin:$PATH" # if mise was just installed +mise trust # trust this checkout's configuration +mise install # tool versions from mise.toml +mise run dev:init # this checkout's ports and certificates +mise run dev # start PostgreSQL 18 and the on-demand database supervisor +./test.sh # the suite against PostgreSQL 18 +./test.sh all # every target; non-default servers start and stop around their tests +``` + +--- + +## 1. Prerequisites + +### Native + +[mise](https://mise.jdx.dev) provides Go, Ruby, CockroachDB, process-compose, and port-tamer. +PostgreSQL itself is the one thing it does not: pgx tests against five major versions, and they +come from the system package manager. + +```sh +scripts/setup-host +``` + +On macOS, install [Homebrew](https://brew.sh) first. The script uses `Brewfile` to install +PostgreSQL 14-18 and Ruby build dependencies. On Ubuntu, it uses sudo when needed, configures +the official PostgreSQL apt repository, and installs the same server versions and build +dependencies. Other Linux distributions require manual prerequisite installation. + +The Ubuntu installer temporarily disables automatic `main` cluster creation during server +installation and removes that override on exit, leaving the package-owned cluster configuration +unchanged. The macOS installer does not start Homebrew services. + +The dispatcher installs mise if it is missing and prints its executable path. It does not run +`mise trust`, install project tools, allocate ports, initialize databases, or start servers. Run +the remaining commands above explicitly as your regular development user. + +- **Do not** `brew services start` any of them, and on Debian do not let the packages create a + machine-wide cluster. pgx runs its own clusters per checkout. +- The Homebrew formulas are *keg-only*, so `psql` and `pg_isready` are not on your `PATH` after + install. `mise.toml` adds PostgreSQL 18's `bin` to `PATH` for this project — one client serves + every server, since libpq is backward compatible. +- Only the majors you actually test against need to be installed. `mise run dev` looks for each + one's server binaries and names any that are missing; `./test.sh pg15` reports a direct install + hint rather than trying to launch a missing server. `PGBIN_16` and friends override the search + for a major built or installed somewhere unusual. +- Clusters are created with the `en_US.UTF-8` locale where the system has it (matching CI and the + container images this replaced), falling back to `C.UTF-8` and then `C`. A stock Debian or Ubuntu + has only `C.UTF-8` unless you have run `locale-gen en_US.UTF-8`. + +### Devcontainer + +Reopen in the container; `.devcontainer/` handles the rest. It installs the same five PostgreSQL +servers and runs the same per-checkout clusters — it is a Linux shell around this same setup, not a +second architecture. + +--- + +## 2. Checkouts are the unit of isolation + +A git worktree is the native equivalent of a second devcontainer instance. Each one gets: + +``` +.dev/ # gitignored, per-checkout runtime state + ports.env # this checkout's TCP ports (port-tamer's state file) + derived.env # PG* defaults and the default target's PGX_TEST_* set + certs/ # the client certificates the TLS tests use + logs/ # one log per service + -/postgres/run # one socket directory, shared by all five servers (mode 0700) + -/postgres//data + -/crdb/ +``` + +The last three — the clusters, the CockroachDB store and the socket directory — move when +`PGX_DEV_RUNTIME_DIR` is set. The devcontainer sets it to `/persist/local/dev`, on its own named +volume: `.dev/` is inside the `/workspaces/pgx` bind mount, and `initdb` and Unix sockets do not +work reliably on Docker Desktop's macOS/Windows file sharing. (The per-version PostgreSQL +containers this setup replaced used named volumes for their data and socket directories for the +same reason.) Everything else stays in the checkout. + +```sh +git worktree add ../pgx-feature-x feature-x +cd ../pgx-feature-x +mise run dev:init && mise run dev +``` + +Both checkouts run simultaneously: different ports, independent database state, independent +process-compose instances. `mise run dev:ports` prints the allocation. + +Ports are allocated once per checkout by [port-tamer](https://github.com/jackc/port-tamer) and then +persisted. `port-tamer.toml` declares which ports a checkout needs — **append new entries at the +end**, since inserting or reordering renumbers the existing ones. A listening port never moves an +existing allocation, because it may well belong to this checkout's own running services; when two +checkouts genuinely collide, stop one and run `mise run dev:ports:overwrite`. + +The data directories are keyed by platform because a cluster `initdb`'d by the Linux devcontainer +cannot be read by a native macOS server, and one checkout may be opened both ways. After switching +a checkout between the two, re-run `mise run dev:ports:ensure` so the derived paths follow. + +**Reference sources** (`references/`) are provisioned per checkout with `rake references:setup`, +sharing one machine-level mirror (`/persist/shared` in a container, `~/.local/share/pgx` natively; +`REFERENCES_MIRROR_DIR` overrides). They are a multi-GB download; nothing provisions them +automatically. + +--- + +## 3. The databases + +`mise run dev` starts PostgreSQL 18 under +[process-compose](https://github.com/F1bonacc1/process-compose). PostgreSQL 14-17 and a single-node +in-memory CockroachDB are registered with the same supervisor but disabled initially, ready to be +started by a test or an explicit `db:start`. `mise run dev:all` eagerly starts every available +server. These are the same services the devcontainer used to run as containers; they are now +ordinary processes against this checkout's own clusters. + +Each PostgreSQL server initializes its cluster on first start — `initdb`, this project's +`pg_hba.conf`, and the TLS certificates — then creates `pgx_test` with its extensions and its +`pgx_md5` / `pgx_scram` / `pgx_pw` / `pgx_ssl` / `pgx_sslcert` roles. The default server uses its +follow-on `pg18-setup` process; the lazy lifecycle performs the same idempotent setup directly for +an on-demand target. Restarts are free once the cluster exists. If setup fails partway it drops the +half-built database so the next start retries rather than reporting it as present. + +CockroachDB has no separate setup process: its store is in memory, so every restart is an empty +cluster and its readiness probe creates `pgx_test` itself. + +```sh +process-compose process list # status, scriptable +process-compose process logs pg16 # one server's output +mise run db:start pg16 crdb # prewarm one or more targets +mise run db:stop pg16 crdb # stop them again +mise run db:start all # prewarm every target +process-compose down # stop this checkout's stack only +mise run db:psql # psql against the already-running PostgreSQL 18 +mise run db:start pg16 # prewarm PostgreSQL 16 before interactive use +mise run db:psql 16 # psql against PostgreSQL 16 +mise run db:psql 16 -c 'select 1' # arguments after the major go to psql +``` + +The `process-compose` commands need no flags: `PC_PORT_NUM` is part of this checkout's +environment, so they never reach another checkout's stack. + +`rake db:psql[16]` is the same as `mise run db:psql 16`. Note the brackets — a bare +`rake db:psql 16` is rake asking for a *task* named `16`, not an argument, so the `db:*` tasks +reject it rather than quietly acting on every cluster. + +`mise run db:reset` destroys and re-creates clusters and refuses to run while the selected servers +are up: removing a data directory under a live postmaster corrupts it. Stop selected targets with +`mise run db:stop`, or stop the whole supervisor with `mise run dev:down`. + +All five PostgreSQL servers share **one** Unix socket directory. Sockets are named +`.s.PGSQL.`, so the port picks the server — which is what lets a single +`PGX_TEST_UNIX_SOCKET_CONN_STRING` work for every major, exactly as the container's shared +`/var/run/postgresql` volume did. + +Tests preserve explicit choices: if `db:start` prewarmed a target, tests leave it running. If a +test had to start the target, it stops it in an `ensure` block whether the suite passes, fails, or +is interrupted. A per-target lock prevents concurrent test commands from stopping a server the +other is using. + +--- + +## 4. Running tests + +```sh +./test.sh # PostgreSQL 18, the default target +./test.sh pg14 # PostgreSQL 14 +./test.sh crdb # CockroachDB +./test.sh all # every target, sequentially +./test.sh pg16 -run TestConnect # trailing arguments go to `go test` +``` + +`mise run test` and `mise run test:all` are equivalent. All of them require the stack to be +running, but only their selected database target needs to be up. A stopped target is started, +bootstrapped, and stopped automatically. `./test.sh all` does this sequentially, so at most the +default PostgreSQL 18 plus one additional database is normally resident. + +A bare `go test ./...` also works: mise loads `.dev/derived.env`, which carries the default +target's full `PGX_TEST_*` set, so an activated shell is already pointed at PostgreSQL 18. + +Those connection strings have exactly one definition, `scripts/lib/test_targets.rb`. Both consumers +— the generated `.dev/derived.env` and `./test.sh ` — read it, so there is no second copy +to drift. + +Some tests only run when their environment variable is set. `go test ./... -v | grep SKIP` shows +what is being skipped; on a healthy stack that is the PgBouncer, OAuth, CrateDB, and libpq-oracle +tests, which are CI-only or manual. + +--- + +## 5. Everyday commands + +| Command | What it does | +|---|---| +| `mise run dev` | start PostgreSQL 18 and the on-demand database supervisor | +| `mise run dev:all` | eagerly start every available database | +| `mise run dev -- -D` | start the default stack detached, for CI and agents | +| `mise run dev:wait` / `dev:down` | wait for a detached stack / stop it | +| `mise run dev:init` | allocate this checkout's ports, decode its certificates | +| `mise run dev:ports` | the allocation, and where each server's data lives | +| `mise run test [target]` | the suite against one target | +| `mise run test:all` | every target | +| `mise run db:start [targets...]` / `db:stop` | prewarm or stop targets (`pg16`, `crdb`, or `all`) | +| `mise run db:init [major]` / `db:psql [major]` / `db:reset [major]` | create / open / rebuild the clusters | +| `mise run fmt` | `goimports -w .` | +| `mise run generate` | regenerate the ERB-templated sources | + +`rake ` remains equally valid and is where some of the logic lives; `rake -T` lists +everything, including tasks with no mise wrapper (`references:*`, `db:setup`). + +--- + +## 6. Notes + +- **`PGHOST` and `PGPORT` are a pair.** They come from `.dev/` via mise — `PGPORT` from the + allocation, `PGHOST` derived from it. Setting one without the other names a real port on the + wrong server, and the error will point at a socket nothing ever created. `mise run dev` asserts + the two agree with the cluster before starting anything. +- **`.dev/derived.env` is generated.** If it is ever hand-edited into something mise's dotenv + parser rejects, every `mise` command in the directory fails — including the one that would + rewrite it. Recover with `rm .dev/derived.env && mise run dev:ports:ensure`. +- **A `~/.psqlrc` that changes session defaults** can break the database bootstrap while leaving + interactive use fine. The scripts pass `--no-psqlrc` for that reason. +- **`./test.sh` needs Ruby 3.0+**, which `mise install` provides. If mise is installed but not yet + activated in your shell, `./test.sh` re-runs itself through `mise exec` rather than failing on + the system interpreter. +- **CI does not use any of this.** `.github/workflows/ci.yml` installs system PostgreSQL through + `ci/setup_test.bash` and carries its own copy of the connection strings. Local runs and CI + exercise the same auth paths — `PGX_TEST_DATABASE` connects as `pgx_md5`, and one + `testsetup/pg_hba.conf` serves both — but the two setups are still independent. +- **PgBouncer and the PG18 OAuth validator module** are exercised only in CI. Neither is part of + the local stack, and both were absent from the devcontainer too. diff --git a/vendor/github.com/jackc/pgx/v5/README.md b/vendor/github.com/jackc/pgx/v5/README.md index aa35e4a..2e538ce 100644 --- a/vendor/github.com/jackc/pgx/v5/README.md +++ b/vendor/github.com/jackc/pgx/v5/README.md @@ -12,7 +12,15 @@ The toolkit component is a related set of packages that implement PostgreSQL fun and type mapping between PostgreSQL and Go. These underlying packages can be used to implement alternative drivers, proxies, load balancers, logical replication clients, etc. -## Example Usage +## Quick Start + +### Installation + +```bash +go get github.com/jackc/pgx/v5 +``` + +### Example Usage ```go package main @@ -46,7 +54,18 @@ func main() { } ``` -See the [getting started guide](https://github.com/jackc/pgx/wiki/Getting-started-with-pgx) for more information. +### Connection Configuration + +`pgx.Connect` and `pgxpool.New` accept PostgreSQL connection URLs (such as `postgres://user:pass@host:5432/db?sslmode=verify-full`) as well as `key=value` strings. See [`pgconn.ParseConfig`](https://pkg.go.dev/github.com/jackc/pgx/v5/pgconn#ParseConfig) and the [PostgreSQL connection string documentation](https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING) for supported options and environment variables. + +For a step-by-step walkthrough, see the [getting started guide](https://github.com/jackc/pgx/wiki/Getting-started-with-pgx). + +## Documentation + +Package documentation and API reference are available on [pkg.go.dev](https://pkg.go.dev/github.com/jackc/pgx/v5): +* [`pgx`](https://pkg.go.dev/github.com/jackc/pgx/v5) — base PostgreSQL driver +* [`pgxpool`](https://pkg.go.dev/github.com/jackc/pgx/v5/pgxpool) — concurrency-safe connection pool +* [`stdlib`](https://pkg.go.dev/github.com/jackc/pgx/v5/stdlib) — `database/sql` compatibility adapter ## Features @@ -82,9 +101,30 @@ The pgx interface is recommended when: It is also possible to use the `database/sql` interface and convert a connection to the lower-level pgx interface as needed. -## Testing +## Development and Testing -See [CONTRIBUTING.md](./CONTRIBUTING.md) for setup instructions. +Each checkout has its own PostgreSQL 14-18 clusters and CockroachDB node, so the whole test matrix +is available locally on macOS, on Linux, or in the included devcontainer. Only PostgreSQL 18 stays +running by default; other targets start and stop around their tests: + +```sh +scripts/setup-host # native macOS (Homebrew required) or Ubuntu: host packages and mise +export PATH="$HOME/.local/bin:$PATH" # if mise was just installed +mise trust +mise install # project tools +mise run dev:init # checkout ports and certificates +mise run dev # start PostgreSQL 18 and the on-demand database supervisor +./test.sh # the suite against PostgreSQL 18 +./test.sh all # every target, starting and stopping each server as needed +``` + +Host setup installs PostgreSQL 14-18 and Ruby build dependencies. It does not install project +tools or initialize the checkout; those remain separate steps above. The devcontainer already +provides the host prerequisites. + +See [DEVELOPMENT.md](./DEVELOPMENT.md) for the full setup, and +[CONTRIBUTING.md](./CONTRIBUTING.md) for how to contribute — including how to run the tests against +a PostgreSQL server you already have, without any of the above. ## Architecture @@ -129,6 +169,7 @@ pgerrcode contains constants for the PostgreSQL error codes. * [github.com/jackhopner/pgx-xray-tracer](https://github.com/jackhopner/pgx-xray-tracer) * [github.com/exaring/otelpgx](https://github.com/exaring/otelpgx) +* [github.com/b0r1ssh/pgxotel](https://github.com/b0r1ssh/pgxotel) ## Adapters for 3rd Party Loggers diff --git a/vendor/github.com/jackc/pgx/v5/Rakefile b/vendor/github.com/jackc/pgx/v5/Rakefile index 3e3aa50..57c6050 100644 --- a/vendor/github.com/jackc/pgx/v5/Rakefile +++ b/vendor/github.com/jackc/pgx/v5/Rakefile @@ -1,4 +1,5 @@ require "erb" +require "fileutils" rule '.go' => '.go.erb' do |task| erb = ERB.new(File.read(task.source)) @@ -16,3 +17,293 @@ generated_code_files = [ desc "Generate code" task generate: generated_code_files + +# dev -- per-checkout development state. A git worktree is the native equivalent of a second +# devcontainer instance: same machine, same network stack, so the five PostgreSQL servers and +# CockroachDB that each owned a well-known port in their own container namespace now need distinct +# ones. `dev:ports:*` drives port-tamer (port-tamer.toml declares the names; the allocation lands +# in the gitignored .dev/ports.env) and writes the values derived from it -- scripts/devenv.rb. +namespace :dev do + namespace :ports do + desc "Allocate this checkout's TCP ports if it has none (idempotent)" + task :ensure do + sh RbConfig.ruby, "scripts/devenv.rb", "ensure" + end + + desc "Move this checkout to a different port group (stop its services first)" + task :overwrite do + sh RbConfig.ruby, "scripts/devenv.rb", "overwrite" + end + + desc "Print this checkout's port allocation and where each server's data lives" + task :show do + sh RbConfig.ruby, "scripts/devenv.rb", "show" + end + end +end + +# db -- this checkout's own PostgreSQL clusters, one per major (scripts/devdb.rb). Clusters per +# checkout rather than databases inside shared servers: destructive resets stay local, two +# checkouts run at once, and the layout matches the per-instance devcontainer model it replaces. +# The SERVERS run in the foreground under process-compose (process-compose.yaml); these are the +# one-shot half. Each task takes an optional major, defaulting to all of them. +# +# rake db:init initialize every cluster +# rake db:init[16] just PostgreSQL 16 +# rake db:psql[16] psql against PostgreSQL 16 (default: the newest major) +# +# The mise wrappers (`mise run db:init 16`) call scripts/devdb.rb directly rather than routing +# through these tasks — mise APPENDS its arguments, and `rake db:init 16` means "run task db:init, +# then run task 16", not "run db:init with the argument 16". +namespace :db do + # A bare major on the command line is the natural thing to type and the one rake cannot mean: + # it becomes a second TASK name, so `rake db:reset 16` runs db:reset with no major — every + # cluster — and only then fails on the unknown task, after the data is gone. Catch it first. + def db_major(task, args) + stray = Rake.application.top_level_tasks.find { |t| t =~ /\A\d+\z/ } + if stray + abort "rake: `#{stray}` is being read as a task name, not an argument. " \ + "Write `rake #{task.name}[#{stray}]` (or `mise run #{task.name} #{stray}`)." + end + + Array(args[:major]) + end + + desc "Create this checkout's PostgreSQL clusters under .dev (idempotent). Optional: rake db:init[16]" + task :init, [:major] do |task, args| + sh RbConfig.ruby, "scripts/devdb.rb", "init", *db_major(task, args) + end + + desc "psql against one of this checkout's clusters. Optional: rake db:psql[16]" + task :psql, [:major] do |task, args| + sh RbConfig.ruby, "scripts/devdb.rb", "psql", *db_major(task, args) + end + + desc "Create the pgx_test database and roles in a running cluster (idempotent)" + task :setup, [:major] do |task, args| + sh RbConfig.ruby, "scripts/devdb.rb", "setup", *db_major(task, args) + end + + desc "Destroy this checkout's clusters and re-initialize (destructive; CONFIRM=yes)" + task :reset, [:major] do |task, args| + sh RbConfig.ruby, "scripts/devdb.rb", "reset", *db_major(task, args) + end +end + +# references:* — provision local, read-only checkouts of reference material used +# when building pgx (currently the PostgreSQL source tree). +# +# Storage model: +# * A bare `--mirror` clone of each repo lives on the devcontainer's shared +# persist volume under MIRROR_ROOT. It holds the full history + all +# branches/tags, is downloaded once, and survives container rebuilds. It is +# the canonical copy, shared across every container for this project. +# * Each container creates a lightweight shared clone in ./references/. +# Its Git metadata is local to that checkout while its object store borrows +# from the mirror. Containers can therefore use the same in-container path +# without sharing Git worktree registrations or downloading history again. +# +# Provisioning a new container is therefore cheap: a local clone from the +# already-present mirror, with no network fetch or duplicate object store. + +# Each entry is one reference repo. `ref` is the branch/tag checked out into the +# local checkout. PostgreSQL is pinned to REL_18_STABLE to match the devcontainer's +# default PG18 test target. +REFERENCE_REPOS = [ + { name: "postgres", url: "https://github.com/postgres/postgres.git", ref: "REL_18_STABLE", license: "PostgreSQL License" }, +].freeze + +# Where the canonical bare mirrors live. They are machine-level state, not checkout-level: +# multiple GB, read-only, and identical for every checkout -- so they belong outside the tree, and +# every checkout on the machine shares one copy. +# +# * devcontainer -- the shared persist volume, so every container for this project reuses one +# download and a rebuild costs nothing. +# * native -- an XDG data directory under $HOME, where git worktrees of this repo share it the +# same way containers share the volume. +# +# REFERENCES_MIRROR_DIR overrides both (a second disk, a scratch location, a test). +def default_mirror_root + return "/persist/shared/references" if File.directory?("/persist/shared") + + xdg = ENV["XDG_DATA_HOME"] + base = xdg.nil? || xdg.empty? ? File.join(Dir.home, ".local", "share") : xdg + File.join(base, "pgx", "references") +end + +MIRROR_ROOT = ENV.fetch("REFERENCES_MIRROR_DIR") { default_mirror_root } +CHECKOUT_ROOT = File.join(__dir__, "references") + +def mirror_path(repo) = File.expand_path(File.join(MIRROR_ROOT, "#{repo[:name]}.git")) +def checkout_path(repo) = File.join(CHECKOUT_ROOT, repo[:name]) + +# File.exist? is false for dangling symlinks, which are still leftovers setup +# must replace (and clean must remove). +def path_present?(path) = File.exist?(path) || File.symlink?(path) + +# Run a git command against a bare mirror. Names the gitdir explicitly and lifts +# any safe.bareRepository=explicit guard. Raises on failure. +def git_bare(repo, *args) + sh "git", "-c", "safe.bareRepository=all", "--git-dir", mirror_path(repo), *args +end + +# Capture stdout of a command given as an argv array (no shell parsing, no +# quoting pitfalls). Returns [stdout_string, success_boolean]. +def capture(*args) + out = IO.popen(args, err: File::NULL, &:read) + [out.to_s, $?.success?] +end + +# A managed checkout has its own repository metadata, uses this exact mirror as +# its origin, and borrows that mirror's object database. This rejects ordinary +# clones, linked worktrees left by the old implementation, and dangling gitfiles. +def checkout_valid?(repo) + wp = checkout_path(repo) + git_dir = File.join(wp, ".git") + objects_dir = File.join(git_dir, "objects") + alternates_path = File.join(objects_dir, "info", "alternates") + + return false unless File.directory?(git_dir) && File.file?(alternates_path) + + inside, inside_ok = capture("git", "-C", wp, "rev-parse", "--is-inside-work-tree") + origin, origin_ok = capture("git", "-C", wp, "remote", "get-url", "origin") + return false unless inside_ok && inside.strip == "true" && origin_ok + return false unless File.identical?(File.expand_path(origin.strip, wp), mirror_path(repo)) + + File.foreach(alternates_path).any? do |alternate| + alternate = alternate.strip + next false if alternate.empty? + + File.identical?(File.expand_path(alternate, objects_dir), File.join(mirror_path(repo), "objects")) + end +rescue SystemCallError + false +end + +# A mirror is valid only if it exists AND has at least one ref — this rejects a +# directory left behind by an interrupted clone (which exists but is incomplete). +def mirror_valid?(repo) + return false unless File.directory?(mirror_path(repo)) + out, ok = capture("git", "-c", "safe.bareRepository=all", "--git-dir", mirror_path(repo), "for-each-ref", "--count=1") + ok && !out.strip.empty? +end + +# Clone the bare mirror onto the persist volume if it is missing or broken. +def ensure_mirror(repo) + if mirror_valid?(repo) + puts " mirror cached: #{mirror_path(repo)}" + else + FileUtils.rm_rf(mirror_path(repo)) # clear any partial/broken clone + puts " cloning mirror (full history): #{repo[:url]}" + sh "git", "clone", "--mirror", repo[:url], mirror_path(repo) + end +end + +# Serialize mirror creation and updates across devcontainer instances. Local +# checkouts do not share metadata, but they all read from the same object store. +def with_mirror_lock(repo) + FileUtils.mkdir_p(MIRROR_ROOT) + File.open(File.join(MIRROR_ROOT, ".#{repo[:name]}.lock"), File::RDWR | File::CREAT, 0o644) do |lock| + lock.flock(File::LOCK_EX) + yield + end +end + +# Check out (or re-point) the local clone at the configured ref. Resolve the +# commit in the freshly updated mirror so an existing checkout cannot remain +# stale merely because only the mirror was fetched. +def ensure_checkout(repo) + wp = checkout_path(repo) + ref = repo[:ref] + + commit, ok = capture("git", "-c", "safe.bareRepository=all", "--git-dir", mirror_path(repo), + "rev-parse", "--verify", "#{ref}^{commit}") + raise "ref #{ref.inspect} not found in #{mirror_path(repo)}" unless ok && !commit.strip.empty? + + if checkout_valid?(repo) + puts " checkout present: #{wp} -> #{ref}" + else + puts " replacing invalid checkout: #{wp}" if path_present?(wp) + FileUtils.rm_rf(wp) if path_present?(wp) + puts " cloning checkout: #{wp} -> #{ref}" + sh "git", "clone", "--shared", "--no-checkout", mirror_path(repo), wp + raise "checkout at #{wp} is not linked to #{mirror_path(repo)}" unless checkout_valid?(repo) + end + + sh "git", "-C", wp, "checkout", "--detach", commit.strip +end + +# Run a block per repo, collecting failures so one bad repo does not abort the rest. +def for_each_repo + failures = [] + REFERENCE_REPOS.each do |repo| + puts "#{repo[:name]}:" + begin + yield repo + rescue => e + warn " FAILED: #{e.message}" + failures << repo[:name] + end + end + abort "references: failed for #{failures.join(', ')}" unless failures.empty? +end + +namespace :references do + desc "Clone/refresh reference mirrors on persist and create checkouts in references/" + task :setup do + FileUtils.mkdir_p(MIRROR_ROOT) + FileUtils.mkdir_p(CHECKOUT_ROOT) + for_each_repo do |repo| + with_mirror_lock(repo) do + ensure_mirror(repo) + ensure_checkout(repo) + end + end + puts + puts "Done. Reference sources are in #{CHECKOUT_ROOT}" + Rake::Task["references:status"].invoke + end + + desc "Fetch latest upstream for all mirrors and re-point checkouts" + task :update do + for_each_repo do |repo| + with_mirror_lock(repo) do + abort "mirror missing for #{repo[:name]}; run `rake references:setup`" unless mirror_valid?(repo) + git_bare(repo, "remote", "update", "--prune") + ensure_checkout(repo) + end + end + end + + desc "Show provisioned reference repos, their pinned ref, and current HEAD" + task :status do + puts + puts format(" %-16s %-14s %-14s %s", "REPO", "REF", "HEAD", "LICENSE") + REFERENCE_REPOS.each do |repo| + wp = checkout_path(repo) + state = + if checkout_valid?(repo) + head, ok = capture("git", "-C", wp, "rev-parse", "--short", "HEAD") + ok && !head.strip.empty? ? head.strip : "(invalid)" + elsif path_present?(wp) + "(invalid)" + else + "(not set up)" + end + puts format(" %-16s %-14s %-14s %s", repo[:name], repo[:ref], state, repo[:license]) + end + puts + puts " mirrors: #{MIRROR_ROOT}" + puts " checkouts: #{CHECKOUT_ROOT}" + end + + desc "Remove checkouts from references/ (keeps the cached mirrors on persist)" + task :clean do + REFERENCE_REPOS.each do |repo| + wp = checkout_path(repo) + next unless path_present?(wp) + puts "removing checkout: #{wp}" + FileUtils.rm_rf(wp) + end + end +end diff --git a/vendor/github.com/jackc/pgx/v5/batch.go b/vendor/github.com/jackc/pgx/v5/batch.go index 805cc39..d2cf984 100644 --- a/vendor/github.com/jackc/pgx/v5/batch.go +++ b/vendor/github.com/jackc/pgx/v5/batch.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "time" "github.com/jackc/pgx/v5/pgconn" ) @@ -62,6 +63,21 @@ func (qq *QueuedQuery) Exec(fn func(ct pgconn.CommandTag) error) { // unnecessary network round trips. A Batch must only be sent once. type Batch struct { QueuedQueries []*QueuedQuery + + txOptions *TxOptions +} + +// BeginTx queues the query that begins a transaction with txOptions as the first query of b, saving the round trip that +// [Conn.BeginTx] spends on it. It must be called before any query is queued and panics otherwise. Like any queued query, +// the begin query has a result: it is the first result of the batch. The transaction is available from +// [BatchResults.Tx] once b has been sent. +func (b *Batch) BeginTx(txOptions TxOptions) { + if len(b.QueuedQueries) != 0 { + panic("Batch.BeginTx must be called before any query is queued") + } + + b.Queue(txOptions.beginSQL()) + b.txOptions = &txOptions } // Queue queues a query to batch b. query can be an SQL query or the name of a prepared statement. The only pgx option @@ -113,6 +129,12 @@ type BatchResults interface { // Close is safe to call multiple times. If it returns an error subsequent calls will return the same error. Callback // functions will not be rerun. Close() error + + // Tx returns the transaction begun by [Batch.BeginTx], or nil if the batch did not begin one. It is available before + // Close is called so that a Rollback can be deferred as usual, but the transaction must not otherwise be used until + // Close has been called. If the batch fails before the transaction is begun, the transaction is closed by the time + // Close returns, and its methods return an error where errors.Is(ErrTxClosed) is true. + Tx() Tx } type batchResults struct { @@ -137,6 +159,8 @@ func (br *batchResults) Exec() (pgconn.CommandTag, error) { query, arguments, _ := br.nextQueryAndArgs() + readStartTime := time.Now() + if !br.mrr.NextResult() { err := br.mrr.Close() if err == nil { @@ -144,9 +168,10 @@ func (br *batchResults) Exec() (pgconn.CommandTag, error) { } if br.conn.batchTracer != nil { br.conn.batchTracer.TraceBatchQuery(br.ctx, br.conn, TraceBatchQueryData{ - SQL: query, - Args: arguments, - Err: err, + SQL: query, + Args: arguments, + Err: err, + ReadStartTime: readStartTime, }) } return pgconn.CommandTag{}, err @@ -160,10 +185,11 @@ func (br *batchResults) Exec() (pgconn.CommandTag, error) { if br.conn.batchTracer != nil { br.conn.batchTracer.TraceBatchQuery(br.ctx, br.conn, TraceBatchQueryData{ - SQL: query, - Args: arguments, - CommandTag: commandTag, - Err: br.err, + SQL: query, + Args: arguments, + CommandTag: commandTag, + Err: br.err, + ReadStartTime: readStartTime, }) } @@ -198,9 +224,10 @@ func (br *batchResults) Query() (Rows, error) { if br.conn.batchTracer != nil { br.conn.batchTracer.TraceBatchQuery(br.ctx, br.conn, TraceBatchQueryData{ - SQL: query, - Args: arguments, - Err: rows.err, + SQL: query, + Args: arguments, + Err: rows.err, + ReadStartTime: rows.startTime, }) } @@ -261,6 +288,10 @@ func (br *batchResults) Close() error { return br.err } +func (br *batchResults) Tx() Tx { + return nil +} + func (br *batchResults) earlyError() error { return br.err } @@ -306,9 +337,19 @@ func (br *pipelineBatchResults) Exec() (pgconn.CommandTag, error) { return pgconn.CommandTag{}, err } + readStartTime := time.Now() + results, err := br.pipeline.GetResults() if err != nil { br.err = err + if br.conn.batchTracer != nil { + br.conn.batchTracer.TraceBatchQuery(br.ctx, br.conn, TraceBatchQueryData{ + SQL: query, + Args: arguments, + Err: br.err, + ReadStartTime: readStartTime, + }) + } return pgconn.CommandTag{}, br.err } var commandTag pgconn.CommandTag @@ -316,15 +357,25 @@ func (br *pipelineBatchResults) Exec() (pgconn.CommandTag, error) { case *pgconn.ResultReader: commandTag, br.err = results.Close() default: - return pgconn.CommandTag{}, fmt.Errorf("unexpected pipeline result: %T", results) + err = fmt.Errorf("unexpected pipeline result: %T", results) + if br.conn.batchTracer != nil { + br.conn.batchTracer.TraceBatchQuery(br.ctx, br.conn, TraceBatchQueryData{ + SQL: query, + Args: arguments, + Err: err, + ReadStartTime: readStartTime, + }) + } + return pgconn.CommandTag{}, err } if br.conn.batchTracer != nil { br.conn.batchTracer.TraceBatchQuery(br.ctx, br.conn, TraceBatchQueryData{ - SQL: query, - Args: arguments, - CommandTag: commandTag, - Err: br.err, + SQL: query, + Args: arguments, + CommandTag: commandTag, + Err: br.err, + ReadStartTime: readStartTime, }) } @@ -364,9 +415,10 @@ func (br *pipelineBatchResults) Query() (Rows, error) { if br.conn.batchTracer != nil { br.conn.batchTracer.TraceBatchQuery(br.ctx, br.conn, TraceBatchQueryData{ - SQL: query, - Args: arguments, - Err: err, + SQL: query, + Args: arguments, + Err: err, + ReadStartTime: rows.startTime, }) } } else { @@ -378,6 +430,15 @@ func (br *pipelineBatchResults) Query() (Rows, error) { br.err = err rows.err = err rows.closed = true + + if br.conn.batchTracer != nil { + br.conn.batchTracer.TraceBatchQuery(br.ctx, br.conn, TraceBatchQueryData{ + SQL: query, + Args: arguments, + Err: err, + ReadStartTime: rows.startTime, + }) + } } } @@ -434,6 +495,10 @@ func (br *pipelineBatchResults) Close() error { return br.err } +func (br *pipelineBatchResults) Tx() Tx { + return nil +} + func (br *pipelineBatchResults) earlyError() error { return br.err } @@ -491,6 +556,50 @@ func (br *emptyBatchResults) Close() error { return nil } +func (br *emptyBatchResults) Tx() Tx { + return nil +} + +// txBatchResults are the results of a batch that begins a transaction with [Batch.BeginTx]. +type txBatchResults struct { + BatchResults + tx *dbTx + closed bool + err error +} + +func (br *txBatchResults) Tx() Tx { + return br.tx +} + +// Close closes the batch and, when that leaves the connection outside a transaction because the begin query failed or +// the batch was never sent, the transaction as well. Only the first call does this: once the transaction has been +// committed or rolled back the connection may already be in use elsewhere and must not be touched. +func (br *txBatchResults) Close() error { + if br.closed { + return br.err + } + br.closed = true + + br.err = br.BatchResults.Close() + if br.tx.conn.PgConn().TxStatus() == 'I' { + br.tx.closed = true + } + return br.err +} + +// FailedBatchResults returns [BatchResults] for b that report err from every method, as if sending b had failed before +// anything reached the server. It is for code that wraps [Conn.SendBatch] and can fail before it has a connection to +// send b on, such as a connection pool. If b began a transaction with [Batch.BeginTx], Tx returns a closed transaction. +func FailedBatchResults(b *Batch, err error) BatchResults { + br := &batchResults{err: err} + if b.txOptions == nil { + return br + } + + return &txBatchResults{BatchResults: br, tx: &dbTx{closed: true}, closed: true, err: err} +} + // invalidates statement and description caches on batch results error func invalidateCachesOnBatchResultsError(conn *Conn, b *Batch, err error) { if err != nil && conn != nil && b != nil { diff --git a/vendor/github.com/jackc/pgx/v5/conn.go b/vendor/github.com/jackc/pgx/v5/conn.go index bc5d064..537ff0c 100644 --- a/vendor/github.com/jackc/pgx/v5/conn.go +++ b/vendor/github.com/jackc/pgx/v5/conn.go @@ -36,9 +36,10 @@ type ConnConfig struct { DescriptionCacheCapacity int // DefaultQueryExecMode controls the default mode for executing queries. By default pgx uses the extended protocol - // and automatically prepares and caches prepared statements. However, this may be incompatible with proxies such as - // PGBouncer. In this case it may be preferable to use [QueryExecModeExec] or [QueryExecModeSimpleProtocol]. The same - // functionality can be controlled on a per query basis by passing a [QueryExecMode] as the first query argument. + // and automatically prepares and caches prepared statements. This may be incompatible with proxies such as PgBouncer + // unless they are configured to support protocol-level prepared statements. In an incompatible configuration it may + // be preferable to use [QueryExecModeExec] or [QueryExecModeSimpleProtocol]. The same functionality can be controlled + // on a per query basis by passing a [QueryExecMode] as the first query argument. DefaultQueryExecMode QueryExecMode createdByParseConfig bool // Used to enforce created by ParseConfig rule. @@ -358,8 +359,13 @@ func (c *Conn) Prepare(ctx context.Context, name, sql string) (sd *pgconn.Statem sd, err = c.pgConn.Prepare(ctx, psName, sql, nil) if err != nil { var pErr *pgconn.PrepareError - if errors.As(err, &pErr) { - c.failedDescribeStatement = psKey + if errors.As(err, &pErr) && pErr.ParseComplete { + // The server-side statement was created under psName — the name sent in + // Parse. In the name == sql case psKey is the SQL text, and deallocating + // by it would close a nonexistent statement while leaking the real one. + // When Parse never completed no statement was created at all, so there + // is nothing to clean up. + c.failedDescribeStatement = psName } return nil, err } @@ -475,6 +481,9 @@ func (c *Conn) Exec(ctx context.Context, sql string, arguments ...any) (pgconn.C } if err := c.deallocateInvalidatedCachedStatements(ctx); err != nil { + if c.queryTracer != nil { + c.queryTracer.TraceQueryEnd(ctx, c, TraceQueryEndData{Err: err}) + } return pgconn.CommandTag{}, err } @@ -742,7 +751,7 @@ type QueryRewriter interface { // collected before processing rather than processed while receiving each row. This avoids the possibility of the // application processing rows from a query that the server rejected. The CollectRows function is useful here. // -// An implementor of QueryRewriter may be passed as the first element of args. It can rewrite the sql and change or +// An implementer of QueryRewriter may be passed as the first element of args. It can rewrite the sql and change or // replace args. For example, NamedArgs is QueryRewriter that implements named arguments. // // For extra control over how the query is executed, the types QueryExecMode, QueryResultFormats, and @@ -934,12 +943,24 @@ func (c *Conn) QueryRow(ctx context.Context, sql string, args ...any) Row { } // SendBatch sends all queued queries to the server at once. All queries are run in an implicit transaction unless -// explicit transaction control statements are executed. The returned [BatchResults] must be closed before the connection -// is used again. +// explicit transaction control statements are executed or the batch begins a transaction with [Batch.BeginTx]. The +// returned [BatchResults] must be closed before the connection is used again. // // Depending on the QueryExecMode, all queries may be prepared before any are executed. This means that creating a table // and using it in a subsequent query in the same batch can fail. -func (c *Conn) SendBatch(ctx context.Context, b *Batch) (br BatchResults) { +func (c *Conn) SendBatch(ctx context.Context, b *Batch) BatchResults { + br := c.sendBatch(ctx, b) + if b.txOptions == nil { + return br + } + + return &txBatchResults{ + BatchResults: br, + tx: &dbTx{conn: c, commitQuery: b.txOptions.CommitQuery}, + } +} + +func (c *Conn) sendBatch(ctx context.Context, b *Batch) (br BatchResults) { if len(b.QueuedQueries) == 0 { return &emptyBatchResults{conn: c} } @@ -1018,7 +1039,9 @@ func (c *Conn) sendBatchQueryExecModeSimpleProtocol(ctx context.Context, b *Batc var sb strings.Builder for i, bi := range b.QueuedQueries { if i > 0 { - sb.WriteByte(';') + // The newline ends any trailing line comment in the previous query, which would otherwise swallow the ';' and + // this query. + sb.WriteString("\n;") } sql, err := c.sanitizeForSimpleQuery(bi.SQL, bi.Arguments...) if err != nil { @@ -1305,7 +1328,7 @@ func (c *Conn) LoadType(ctx context.Context, typeName string) (*pgtype.Type, err switch typtype { case "b": // array - elementOID, err := c.getArrayElementOID(ctx, oid) + elementOID, delimiter, err := c.getArrayElementOIDAndDelimiter(ctx, oid) if err != nil { return nil, err } @@ -1315,7 +1338,7 @@ func (c *Conn) LoadType(ctx context.Context, typeName string) (*pgtype.Type, err return nil, errors.New("array element OID not registered") } - return &pgtype.Type{Name: typeName, OID: oid, Codec: &pgtype.ArrayCodec{ElementType: dt}}, nil + return &pgtype.Type{Name: typeName, OID: oid, Codec: &pgtype.ArrayCodec{ElementType: dt, Delimiter: delimiter}}, nil case "c": // composite fields, err := c.getCompositeFields(ctx, oid) if err != nil { @@ -1361,15 +1384,16 @@ func (c *Conn) LoadType(ctx context.Context, typeName string) (*pgtype.Type, err } } -func (c *Conn) getArrayElementOID(ctx context.Context, oid uint32) (uint32, error) { +func (c *Conn) getArrayElementOIDAndDelimiter(ctx context.Context, oid uint32) (uint32, byte, error) { var typelem uint32 + var typdelim string - err := c.QueryRow(ctx, "select typelem from pg_type where oid=$1", oid).Scan(&typelem) + err := c.QueryRow(ctx, "select typelem, typdelim::text from pg_type where oid=$1", oid).Scan(&typelem, &typdelim) if err != nil { - return 0, err + return 0, 0, err } - return typelem, nil + return typelem, parseTypeDelimiter(typdelim), nil } func (c *Conn) getRangeElementOID(ctx context.Context, oid uint32) (uint32, error) { diff --git a/vendor/github.com/jackc/pgx/v5/derived_types.go b/vendor/github.com/jackc/pgx/v5/derived_types.go index 3916006..9da3b9e 100644 --- a/vendor/github.com/jackc/pgx/v5/derived_types.go +++ b/vendor/github.com/jackc/pgx/v5/derived_types.go @@ -64,9 +64,12 @@ UNION ALL -- As can be seen, there are 3 ways this can occur (the last of which -- is due to being a composite class, where the composite fields are children) pc(parent, child) AS ( + -- typtype = 'b' AND typelem != 0 is not sufficient to identify an array type: some + -- scalar types (box, point, line, lseg, name, ...) also set typelem to describe their + -- internal C representation. typcategory = 'A' is the reliable "is an array" signal. SELECT parent.oid, parent.typelem FROM pg_type parent - WHERE parent.typtype = 'b' AND parent.typelem != 0 + WHERE parent.typtype = 'b' AND parent.typelem != 0 AND parent.typcategory = 'A' UNION ALL SELECT parent.oid, parent.typbasetype FROM pg_type parent @@ -82,6 +85,8 @@ UNION ALL -- Now construct a recursive query which includes a 'depth' element. -- This is used to ensure that the "youngest" children are registered before -- their parents. +-- Deduplicate relationships at each depth so shared dependencies do not +-- multiply the work at every level of a nested composite type. relationships(parent, child, depth) AS ( SELECT DISTINCT 0::OID, selected_types.oid, 0 FROM selected_types @@ -90,7 +95,7 @@ UNION ALL FROM selected_classes c inner join pg_type ON (c.reltype = pg_type.oid) inner join pg_attribute on (c.oid = pg_attribute.attrelid) -UNION ALL +UNION SELECT pc.parent, pc.child, relationships.depth + 1 FROM pc INNER JOIN relationships ON (pc.parent = relationships.child) @@ -113,6 +118,7 @@ SELECT typname, typtype, typbasetype, typelem, + typdelim, pg_type.oid,`) if supportsMultirange { parts = append(parts, ` @@ -135,9 +141,13 @@ SELECT typname, parts = append(parts, ` LEFT OUTER JOIN composite USING (oid) LEFT OUTER JOIN pg_namespace ON (pg_type.typnamespace = pg_namespace.oid) - WHERE NOT (typtype = 'b' AND typelem = 0)`) + -- Only emit typtype = 'b' rows that are true arrays (typcategory = 'A'). Other base + -- types, including ones with a non-zero typelem for non-array reasons (box, point, + -- line, lseg, name, ...), already have a codec registered and must not be re-emitted, + -- or LoadTypes will overwrite their correct codec with a bogus ArrayCodec. + WHERE NOT (typtype = 'b' AND NOT (typelem != 0 AND typcategory = 'A'))`) parts = append(parts, ` - GROUP BY typname, pg_namespace.nspname, typtype, typbasetype, typelem, pg_type.oid, pg_range.rngsubtype,`) + GROUP BY typname, pg_namespace.nspname, typtype, typbasetype, typelem, typdelim, pg_type.oid, pg_range.rngsubtype,`) if supportsMultirange { parts = append(parts, ` multirange.rngtypid,`) @@ -150,11 +160,18 @@ SELECT typname, type derivedTypeInfo struct { Oid, Typbasetype, Typelem, Rngsubtype, Rngtypid uint32 - TypeName, Typtype, NspName string + TypeName, Typtype, NspName, Typdelim string Attnames []string Atttypids []uint32 } +func parseTypeDelimiter(typdelim string) byte { + if typdelim == "" { + return 0 + } + return typdelim[0] +} + // LoadTypes performs a single (complex) query, returning all the required // information to register the named types, as well as any other types directly // or indirectly required to complete the registration. @@ -177,7 +194,7 @@ func (c *Conn) LoadTypes(ctx context.Context, typeNames []string) ([]*pgtype.Typ result := make([]*pgtype.Type, 0, 100) for rows.Next() { ti := derivedTypeInfo{} - err = rows.Scan(&ti.TypeName, &ti.NspName, &ti.Typtype, &ti.Typbasetype, &ti.Typelem, &ti.Oid, &ti.Rngtypid, &ti.Rngsubtype, &ti.Attnames, &ti.Atttypids) + err = rows.Scan(&ti.TypeName, &ti.NspName, &ti.Typtype, &ti.Typbasetype, &ti.Typelem, &ti.Typdelim, &ti.Oid, &ti.Rngtypid, &ti.Rngsubtype, &ti.Attnames, &ti.Atttypids) if err != nil { return nil, fmt.Errorf("While scanning type information: %w", err) } @@ -188,7 +205,7 @@ func (c *Conn) LoadTypes(ctx context.Context, typeNames []string) ([]*pgtype.Typ if !ok { return nil, fmt.Errorf("Array element OID %v not registered while loading pgtype %q", ti.Typelem, ti.TypeName) } - type_ = &pgtype.Type{Name: ti.TypeName, OID: ti.Oid, Codec: &pgtype.ArrayCodec{ElementType: dt}} + type_ = &pgtype.Type{Name: ti.TypeName, OID: ti.Oid, Codec: &pgtype.ArrayCodec{ElementType: dt, Delimiter: parseTypeDelimiter(ti.Typdelim)}} case "c": // composite var fields []pgtype.CompositeCodecField for i, fieldName := range ti.Attnames { diff --git a/vendor/github.com/jackc/pgx/v5/doc.go b/vendor/github.com/jackc/pgx/v5/doc.go index 5e48701..9bbe190 100644 --- a/vendor/github.com/jackc/pgx/v5/doc.go +++ b/vendor/github.com/jackc/pgx/v5/doc.go @@ -68,6 +68,15 @@ Use [Conn.Exec] to execute a query that does not return a result set. return errors.New("No row found to delete") } +To match a column against a Go slice, pass the slice as one argument and use +PostgreSQL's ANY. Bare IN $1 is invalid SQL, and IN ($1) compares against the +array as a whole rather than its elements. + + ids := []int64{1, 2, 3} + rows, _ := conn.Query(ctx, "select * from widgets where id = any($1)", ids) + +See https://www.postgresql.org/docs/current/functions-comparisons.html#FUNCTIONS-COMPARISONS-ANY-SOME. + PostgreSQL Data Types pgx uses the [pgtype] package to converting Go values to and from PostgreSQL values. It supports many PostgreSQL types @@ -210,8 +219,18 @@ implemented on top of [pgconn.PgConn]. The [Conn.PgConn] method can be used to a PgBouncer -By default pgx automatically uses prepared statements. Prepared statements are incompatible with PgBouncer. This can be -disabled by setting a different [QueryExecMode] in [ConnConfig.DefaultQueryExecMode]. +By default pgx automatically uses protocol-level named prepared statements. PgBouncer 1.21.0 and newer can use these +prepared statements in transaction and statement pooling modes when its max_prepared_statements setting is greater than +zero. In this configuration the default [QueryExecModeCacheStatement] mode may be used. See the PgBouncer documentation +for limitations and configuration details: https://www.pgbouncer.org/config.html#max_prepared_statements. + +When using an older PgBouncer version or when prepared statement support is disabled, set +[ConnConfig.DefaultQueryExecMode] to [QueryExecModeExec]. [QueryExecModeCacheDescribe] and +[QueryExecModeSimpleProtocol] are also compatible with PgBouncer. Prefer [QueryExecModeExec] over +[QueryExecModeSimpleProtocol] whenever possible. Do not use [QueryExecModeDescribeExec] with transaction pooling because +PgBouncer may assign a different server connection between the describe and execute steps. + +SQL-level prepared statements created with PREPARE are not supported by PgBouncer in transaction pooling mode. */ package pgx diff --git a/vendor/github.com/jackc/pgx/v5/internal/iobufpool/iobufpool.go b/vendor/github.com/jackc/pgx/v5/internal/iobufpool/iobufpool.go index abc41f6..4f133b6 100644 --- a/vendor/github.com/jackc/pgx/v5/internal/iobufpool/iobufpool.go +++ b/vendor/github.com/jackc/pgx/v5/internal/iobufpool/iobufpool.go @@ -33,7 +33,7 @@ func Get(size int) *[]byte { return &buf } - ptrBuf := (pools[i].Get().(*[]byte)) + ptrBuf := pools[i].Get().(*[]byte) *ptrBuf = (*ptrBuf)[:size] return ptrBuf diff --git a/vendor/github.com/jackc/pgx/v5/internal/pgdatetime/pgdatetime.go b/vendor/github.com/jackc/pgx/v5/internal/pgdatetime/pgdatetime.go new file mode 100644 index 0000000..306d0c7 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/internal/pgdatetime/pgdatetime.go @@ -0,0 +1,118 @@ +// Package pgdatetime writes PostgreSQL's ISO date/time text format. +// +// The format is the one EncodeDateTime and AppendSeconds produce in +// src/backend/utils/adt/datetime.c under the default ISO DateStyle: +// +// stamp = date [ SP time [ zone ] ] [ " BC" ] +// date = year "-" 2DIGIT "-" 2DIGIT +// time = 2DIGIT ":" 2DIGIT ":" 2DIGIT [ "." 1*6DIGIT ] +// +// The year is zero-padded to four digits and then grows as wide as it needs, the +// fractional part is omitted when it is zero and never carries trailing zeros, and " BC" +// comes last, after any time zone. Go's layout language can express none of those, which +// is why the format is written out here rather than left to time.Format. +// +// This is the only implementation of the format in pgx. pgtype's date, timestamp and +// timestamptz text encoders and the simple protocol's query sanitizer all go through it, +// so they cannot drift apart. +package pgdatetime + +import ( + "strconv" + "time" +) + +// AppendDate appends t's date. The fields are read from t in its own location. +func AppendDate(buf []byte, t time.Time) []byte { + year, bc := splitBCYear(t.Year()) + buf = appendDate(buf, year, int(t.Month()), t.Day()) + return appendEra(buf, bc) +} + +// AppendTimestamp appends t's date and time of day followed by zone, which goes before +// the era suffix because PostgreSQL writes " BC" last. zone is "Z" for a value already +// converted to UTC and "" for a type that carries no time zone at all. +// +// The fields are read from t in its own location, so a caller that wants the UTC instant +// must convert first. Sub-microsecond precision is discarded, matching the resolution of +// the wire format. +func AppendTimestamp(buf []byte, t time.Time, zone string) []byte { + year, bc := splitBCYear(t.Year()) + buf = appendDate(buf, year, int(t.Month()), t.Day()) + buf = append(buf, ' ') + buf = appendTime(buf, t.Hour(), t.Minute(), t.Second(), t.Nanosecond()) + buf = append(buf, zone...) + return appendEra(buf, bc) +} + +// splitBCYear converts an astronomical year, in which 1 BC is 0 and 2 BC is -1, to the +// year and era PostgreSQL writes. +func splitBCYear(year int) (displayYear int, bc bool) { + if year <= 0 { + return 1 - year, true + } + return year, false +} + +func appendEra(buf []byte, bc bool) []byte { + if bc { + buf = append(buf, " BC"...) + } + return buf +} + +// appendDate appends year-month-day. year is a displayed year from splitBCYear rather +// than an astronomical one. +func appendDate(buf []byte, year, month, day int) []byte { + buf = appendYear(buf, year) + buf = append(buf, '-') + buf = append2Digits(buf, month) + buf = append(buf, '-') + return append2Digits(buf, day) +} + +func appendTime(buf []byte, hour, min, sec, nsec int) []byte { + buf = append2Digits(buf, hour) + buf = append(buf, ':') + buf = append2Digits(buf, min) + buf = append(buf, ':') + buf = append2Digits(buf, sec) + + usec := nsec / 1000 + if usec == 0 { + return buf + } + + var frac [6]byte + for i := 5; i >= 0; i-- { + frac[i] = byte('0' + usec%10) + usec /= 10 + } + + // The server trims trailing zeros, so ".5" rather than ".500000". + end := len(frac) + for end > 1 && frac[end-1] == '0' { + end-- + } + + buf = append(buf, '.') + return append(buf, frac[:end]...) +} + +// append2Digits appends v as exactly two digits. Every field but the year is fixed width +// and comes from a time.Time accessor, so v is always in [0, 99] and the general routine +// below is not needed. +func append2Digits(buf []byte, v int) []byte { + return append(buf, byte('0'+v/10), byte('0'+v%10)) +} + +// appendYear appends v zero-padded to four digits, or wider when the year needs it. v is +// a displayed year from splitBCYear and so is always positive. +func appendYear(buf []byte, v int) []byte { + var tmp [20]byte + s := strconv.AppendInt(tmp[:0], int64(v), 10) + for i := len(s); i < 4; i++ { + buf = append(buf, '0') + } + return append(buf, s...) +} diff --git a/vendor/github.com/jackc/pgx/v5/internal/pgio/doc.go b/vendor/github.com/jackc/pgx/v5/internal/pgio/doc.go index ef2dcc7..60e2fbb 100644 --- a/vendor/github.com/jackc/pgx/v5/internal/pgio/doc.go +++ b/vendor/github.com/jackc/pgx/v5/internal/pgio/doc.go @@ -1,6 +1,8 @@ -// Package pgio is a low-level toolkit building messages in the PostgreSQL wire protocol. +// Package pgio is a low-level toolkit for building and parsing messages in the +// PostgreSQL wire protocol. /* pgio provides functions for appending integers to a []byte while doing byte -order conversion. +order conversion, and a bounds-checked Reader for parsing binary values from +untrusted input. */ package pgio diff --git a/vendor/github.com/jackc/pgx/v5/internal/pgio/read.go b/vendor/github.com/jackc/pgx/v5/internal/pgio/read.go new file mode 100644 index 0000000..9ea42c8 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/internal/pgio/read.go @@ -0,0 +1,250 @@ +package pgio + +import ( + "bytes" + "encoding/binary" + "errors" + "fmt" +) + +// ErrInsufficientBytes is wrapped by all Reader errors caused by a read past +// the end of the source. +var ErrInsufficientBytes = errors.New("insufficient bytes") + +// Reader is a bounds-checked reader for the PostgreSQL binary format. It is +// designed so that decoders of untrusted input cannot forget a length check: +// every read validates against the remaining bytes, and the first failure +// sticks. After a failure all subsequent reads return zero values, so a +// decoder can read an entire structure without intermediate error checks and +// inspect Err or Finish once at the end. +// +// Reads never panic. A decoder that branches on a value it just read (e.g. an +// element count used to size an allocation) should check Err before acting on +// the value. +type Reader struct { + s []byte + rp int + err error +} + +func NewReader(s []byte) *Reader { + return &Reader{s: s} +} + +func (r *Reader) fail(err error) { + if r.err == nil { + r.err = err + } +} + +// need reports whether n more bytes are available, recording an error if not. +// +// The error is built by failShort rather than here so that need stays within +// the inliner's budget. Reads of fixed-size values are the hottest path in the +// driver, and an un-inlined bounds check costs more than the read itself. +func (r *Reader) need(n int) bool { + if r.err != nil { + return false + } + if len(r.s)-r.rp < n { + r.failShort(n) + return false + } + return true +} + +func (r *Reader) failShort(n int) { + r.fail(fmt.Errorf("%w: %d needed at offset %d, %d remain", ErrInsufficientBytes, n, r.rp, len(r.s)-r.rp)) +} + +// Err returns the first error encountered, if any. +func (r *Reader) Err() error { + return r.err +} + +// Remaining returns the number of unread bytes. +func (r *Reader) Remaining() int { + return len(r.s) - r.rp +} + +func (r *Reader) Byte() byte { + if !r.need(1) { + return 0 + } + b := r.s[r.rp] + r.rp += 1 + return b +} + +func (r *Reader) Uint16() uint16 { + if !r.need(2) { + return 0 + } + n := binary.BigEndian.Uint16(r.s[r.rp:]) + r.rp += 2 + return n +} + +func (r *Reader) Int16() int16 { + return int16(r.Uint16()) +} + +func (r *Reader) Uint32() uint32 { + if !r.need(4) { + return 0 + } + n := binary.BigEndian.Uint32(r.s[r.rp:]) + r.rp += 4 + return n +} + +func (r *Reader) Int32() int32 { + return int32(r.Uint32()) +} + +func (r *Reader) Uint64() uint64 { + if !r.need(8) { + return 0 + } + n := binary.BigEndian.Uint64(r.s[r.rp:]) + r.rp += 8 + return n +} + +func (r *Reader) Int64() int64 { + return int64(r.Uint64()) +} + +// Bytes reads the next n bytes. The returned slice aliases the source; it is +// not a copy. +func (r *Reader) Bytes(n int) []byte { + if n < 0 { + r.fail(fmt.Errorf("invalid byte count %d at offset %d", n, r.rp)) + return nil + } + if !r.need(n) { + return nil + } + b := r.s[r.rp : r.rp+n] + r.rp += n + return b +} + +// CString reads a NUL-terminated string, returning the bytes before the +// terminator and consuming the terminator. The returned slice aliases the +// source; it is not a copy. +func (r *Reader) CString() []byte { + if r.err != nil { + return nil + } + i := bytes.IndexByte(r.s[r.rp:], 0) + if i < 0 { + r.fail(fmt.Errorf("%w: unterminated string at offset %d", ErrInsufficientBytes, r.rp)) + return nil + } + b := r.s[r.rp : r.rp+i] + r.rp += i + 1 + return b +} + +// Count reads an int32 element count and validates it against the remaining +// bytes: the count must be non-negative, and since each element occupies at +// least minElemSize bytes, count*minElemSize must not exceed the remaining +// message. This bounds allocations sized from the count against a malicious +// or corrupt message claiming a huge count. Returns 0 on any failure. +func (r *Reader) Count(minElemSize int) int { + offset := r.rp + count := int(r.Int32()) + if r.err != nil { + return 0 + } + if count < 0 { + r.fail(fmt.Errorf("invalid element count %d at offset %d", count, offset)) + return 0 + } + if minElemSize < 1 { + minElemSize = 1 + } + if count > r.Remaining()/minElemSize { + r.fail(fmt.Errorf("element count %d at offset %d exceeds %d remaining bytes", count, offset, r.Remaining())) + return 0 + } + return count +} + +// Value reads an int32 length followed by that many bytes — the standard +// PostgreSQL binary representation of a value. A length of -1 means NULL and +// returns (nil, true). Any other negative length is an error. The returned +// slice aliases the source; null is only meaningful if Err returns nil. +func (r *Reader) Value() (data []byte, null bool) { + offset := r.rp + length := r.Int32() + if r.err != nil { + return nil, false + } + if length == -1 { + return nil, true + } + if length < 0 { + r.fail(fmt.Errorf("invalid value length %d at offset %d", length, offset)) + return nil, false + } + return r.Bytes(int(length)), false +} + +// Finish returns the first error encountered, or an error if unread bytes +// remain. Decoders that must consume the entire source should end with Finish. +func (r *Reader) Finish() error { + if r.err != nil { + return r.err + } + if r.rp != len(r.s) { + return r.errTrailing() + } + return nil +} + +func (r *Reader) errTrailing() error { + return fmt.Errorf("%d unexpected trailing bytes at offset %d", len(r.s)-r.rp, r.rp) +} + +// ErrInvalidLength is wrapped by the errors returned from the exact-length +// read functions below. +var ErrInvalidLength = errors.New("invalid length") + +func errLength(want, got int) error { + return fmt.Errorf("%w: expected %d bytes, got %d", ErrInvalidLength, want, got) +} + +// The Uint*Exact functions read a single fixed-size value that makes up an +// entire message, which is what the scan plans for the fixed-size PostgreSQL +// types receive. They are the counterpart to Reader for values that have no +// internal structure: there is no position to track and no error to make +// sticky, just an exact-length assertion the caller cannot skip. Keeping them +// separate from Reader is deliberate — these are the hottest decode paths in +// the driver and they are small enough for the compiler to inline, which a +// Reader method carrying a bounds check and a read pointer is not. + +// Uint16Exact returns the big-endian uint16 in src, which must be exactly 2 bytes. +func Uint16Exact(src []byte) (uint16, error) { + if len(src) != 2 { + return 0, errLength(2, len(src)) + } + return binary.BigEndian.Uint16(src), nil +} + +// Uint32Exact returns the big-endian uint32 in src, which must be exactly 4 bytes. +func Uint32Exact(src []byte) (uint32, error) { + if len(src) != 4 { + return 0, errLength(4, len(src)) + } + return binary.BigEndian.Uint32(src), nil +} + +// Uint64Exact returns the big-endian uint64 in src, which must be exactly 8 bytes. +func Uint64Exact(src []byte) (uint64, error) { + if len(src) != 8 { + return 0, errLength(8, len(src)) + } + return binary.BigEndian.Uint64(src), nil +} diff --git a/vendor/github.com/jackc/pgx/v5/internal/sanitize/sanitize.go b/vendor/github.com/jackc/pgx/v5/internal/sanitize/sanitize.go index 033a414..22aeeac 100644 --- a/vendor/github.com/jackc/pgx/v5/internal/sanitize/sanitize.go +++ b/vendor/github.com/jackc/pgx/v5/internal/sanitize/sanitize.go @@ -11,6 +11,8 @@ import ( "sync" "time" "unicode/utf8" + + "github.com/jackc/pgx/v5/internal/pgdatetime" ) // Part is either a string or an int. A string is raw SQL. An int is a @@ -81,8 +83,12 @@ func (q *Query) Sanitize(args ...any) (string, error) { case string: p = QuoteString(buf.AvailableBuffer(), arg) case time.Time: - p = arg.Truncate(time.Microsecond). - AppendFormat(buf.AvailableBuffer(), "'2006-01-02 15:04:05.999999999Z07:00:00'") + // pgtype's timestamptz text encoder writes the same format. Going through + // the same code keeps the two from drifting apart, and time.Format cannot + // express PostgreSQL's BC era or its variable width year anyway. + p = append(buf.AvailableBuffer(), '\'') + p = pgdatetime.AppendTimestamp(p, arg.UTC(), "Z") + p = append(p, '\'') default: return "", fmt.Errorf("invalid arg type: %T", arg) } @@ -444,9 +450,6 @@ func oneLineCommentState(l *sqlLexer) stateFn { l.pos += width switch r { - case '\\': - _, width = utf8.DecodeRuneInString(l.src[l.pos:]) - l.pos += width case '\n', '\r': return rawState case utf8.RuneError: diff --git a/vendor/github.com/jackc/pgx/v5/internal/stmtcache/lru_cache.go b/vendor/github.com/jackc/pgx/v5/internal/stmtcache/lru_cache.go index b677d29..63173b0 100644 --- a/vendor/github.com/jackc/pgx/v5/internal/stmtcache/lru_cache.go +++ b/vendor/github.com/jackc/pgx/v5/internal/stmtcache/lru_cache.go @@ -62,7 +62,7 @@ func (c *LRUCache) Put(sd *pgconn.StatementDescription) { return } - // The statement may have been invalidated but not yet handled. Do not readd it to the cache. + // The statement may have been invalidated but not yet handled. Do not re-add it to the cache. if _, invalidated := c.invalidSet[sd.SQL]; invalidated { return } diff --git a/vendor/github.com/jackc/pgx/v5/mise.toml b/vendor/github.com/jackc/pgx/v5/mise.toml index 78610d4..97078ec 100644 --- a/vendor/github.com/jackc/pgx/v5/mise.toml +++ b/vendor/github.com/jackc/pgx/v5/mise.toml @@ -1,8 +1,173 @@ +# mise is this project's single development entry point: the same `mise run ` works on +# native macOS, on native Linux, and inside the devcontainer. See DEVELOPMENT.md. +# +# The division of labour: +# mise tool versions, this checkout's environment, one-shot tasks +# process-compose long-running services (process-compose.yaml) — five PostgreSQL clusters + CRDB +# port-tamer this checkout's TCP ports (port-tamer.toml -> .dev/ports.env) +# +# PostgreSQL itself is the one prerequisite mise does not provide; DEVELOPMENT.md §1 lists it. + [tools] -go = '1.26.3' +go = '1.27.0' +ruby = '4.0.4' "go:github.com/go-critic/go-critic/cmd/gocritic" = "latest" "go:github.com/gordonklaus/ineffassign" = "latest" "go:github.com/mdempsky/unconvert" = "latest" "go:golang.org/x/tools/cmd/goimports" = "latest" "go:mvdan.cc/gofumpt" = "latest" -ruby = '4.0.4' + +# The linter .golangci.yml configures and CLAUDE.md documents. It was never actually provisioned +# by the devcontainer, so `golangci-lint run ./...` only worked if you had installed it yourself. +golangci-lint = '2.13.2' + +# The process supervisor for the long-running development services. Pinned like every other tool +# so macOS, Linux, and the devcontainer run the same version. +process-compose = '1.122.0' + +# Per-checkout TCP port allocation. The `github:` backend takes the prebuilt release binary, so it +# does not depend on the Go toolchain this repo pins. +"github:jackc/port-tamer" = '0.1.0' + +# The CockroachDB test target. Previously a container image; the version tracks the one CI installs +# in ci/setup_test.bash. +cockroach = '25.4.4' + +# --- Environment --------------------------------------------------------------------------------- +# +# This checkout's own service endpoints. Loading them here is what makes the per-checkout clusters +# the DEFAULT: a bare `psql` and a bare `go test ./...` read PG*/PGX_TEST_* from the environment, +# so pointing those at .dev/ in one place moves every consumer at once. +# +# Two files with two owners, and the order matters — the derived values are read after the +# allocation they come from: +# +# .dev/ports.env port-tamer's state file (port-tamer.toml declares the names). NAME= +# lines only; port-tamer rewrites it canonically and rejects anything else. +# .dev/derived.env PGHOST/PGPORT/PGUSER/PGDATABASE plus the default target's PGX_TEST_* set — +# scripts/devenv.rb, via scripts/lib/test_targets.rb. +# +# Both are generated per checkout and gitignored; `mise run dev:init` creates them. Their absence +# is not an error — mise skips a missing file and PG* falls back to whatever the shell already had. +[env] +_.file = ['.dev/ports.env', '.dev/derived.env'] + +# Homebrew's postgresql@ formulas are KEG-ONLY: nothing is linked into the prefix bin, so +# psql and pg_isready are not on PATH after `brew install`. The scripts that need the SERVER +# binaries resolve them per major explicitly (scripts/lib/pg_bin.rb), but the CLIENT tools are +# invoked by name from the readiness probes, `rake db:psql`, and the database bootstrap. +# +# The newest major's client is used for every server: libpq is backward compatible, so one psql +# talks to all five clusters. Both standard Homebrew prefixes are listed (Apple silicon, then +# Intel). Neither exists on Linux, where a nonexistent PATH entry is simply ignored, so this is +# inert in the devcontainer. +_.path = [ + '/opt/homebrew/opt/postgresql@18/bin', + '/usr/local/opt/postgresql@18/bin', +] + +# process-compose's control API address. The port comes from this checkout's allocation +# (PC_PORT_NUM in .dev/ports.env), so every `process-compose ...` command reaches THIS checkout's +# stack with no flags. +PC_ADDRESS = "127.0.0.1" + +# Kept separate deliberately: `mise run dev` writes the supervisor log, and a client command such +# as `process-compose process list` would otherwise truncate the log of the stack it is inspecting. +PC_SERVER_LOG_FILE = "{{config_root}}/.dev/process-compose.log" +PC_LOG_FILE = "{{config_root}}/.dev/process-compose-client.log" + +# --- Tasks: the project's development interface --------------------------------------------------- +# +# Thin wrappers. The logic lives in scripts/ and the Rakefile; these exist so a workflow is +# reachable without knowing what is underneath, and so the same command works in every environment. + +[tasks."dev:init"] +description = "Bootstrap this checkout: allocate its ports, decode its certificates" +run = "ruby scripts/devenv.rb ensure" + +[tasks.dev] +description = "Start PostgreSQL 18 and this checkout's on-demand database supervisor" +run = "ruby scripts/dev.rb" + +[tasks."dev:all"] +description = "Start PostgreSQL 14-18 and CockroachDB eagerly under process-compose" +run = "ruby scripts/dev.rb all" + +[tasks."dev:down"] +description = "Stop this checkout's development stack" +run = "ruby scripts/dev.rb down" + +[tasks."dev:wait"] +description = "Wait for a detached development stack to become ready" +run = "ruby scripts/dev_ready.rb --wait" + +[tasks."dev:ready"] +description = "Require the development stack to be running" +run = "ruby scripts/dev_ready.rb" +hide = true + +[tasks."dev:ports"] +description = "Print this checkout's port allocation and where each server's data lives" +run = "rake dev:ports:show" + +[tasks."dev:ports:ensure"] +description = "Allocate this checkout's ports if it has none (idempotent)" +run = "rake dev:ports:ensure" + +[tasks."dev:ports:overwrite"] +description = "Move this checkout to a different port group (stop its services first)" +run = "rake dev:ports:overwrite" + +# --- Databases ----------------------------------------------------------------------------------- + +[tasks."db:start"] +description = "Prewarm database targets (default: pg18); e.g. mise run db:start pg16 crdb" +run = "ruby scripts/dev_services.rb start" + +[tasks."db:stop"] +description = "Stop database targets (default: pg18); e.g. mise run db:stop pg16 crdb" +run = "ruby scripts/dev_services.rb stop" + +# These call scripts/devdb.rb rather than the equivalent rake tasks. mise APPENDS a task's +# arguments to its `run` line, and `rake db:reset 16` does not mean "db:reset with the argument +# 16" — rake reads the 16 as a SECOND TASK, runs db:reset with no major (which is every cluster), +# and only then fails on the unknown task. devdb.rb takes the major as an ordinary argument, so +# `mise run db:reset 16` reaches it as written. `rake db:reset[16]` is still the rake spelling. + +[tasks."db:init"] +description = "Create this checkout's PostgreSQL clusters under .dev (idempotent); e.g. mise run db:init 16" +run = "ruby scripts/devdb.rb init" + +[tasks."db:psql"] +description = "psql against one of this checkout's clusters (default: the newest major)" +run = "ruby scripts/devdb.rb psql" + +[tasks."db:setup"] +description = "Create pgx_test and its roles in a running cluster (idempotent)" +run = "ruby scripts/devdb.rb setup" + +[tasks."db:reset"] +description = "Destroy and recreate this checkout's clusters (destructive; CONFIRM=yes, stack down)" +run = "ruby scripts/devdb.rb reset" + +# --- Test, format, generate ------------------------------------------------------------------------ + +[tasks.test] +description = "Run the test suite against one target (default pg18); e.g. mise run test pg16" +run = "./test.sh" + +[tasks."test:all"] +description = "Run the test suite against every target: PostgreSQL 14-18 and CockroachDB" +run = "./test.sh all" + +[tasks.fmt] +description = "Format all Go sources with goimports" +run = "goimports -w ." + +[tasks.lint] +description = "Run the linters configured in .golangci.yml" +run = "golangci-lint run ./..." + +[tasks.generate] +description = "Regenerate the ERB-templated Go sources" +run = "rake generate" diff --git a/vendor/github.com/jackc/pgx/v5/named_args.go b/vendor/github.com/jackc/pgx/v5/named_args.go index 1300c91..33390e4 100644 --- a/vendor/github.com/jackc/pgx/v5/named_args.go +++ b/vendor/github.com/jackc/pgx/v5/named_args.go @@ -151,13 +151,18 @@ func dbTagKey(sf reflect.StructField) (key string, ok bool, err error) { type namedArg string +// utf8.RuneError is returned both for a decoding failure and for a literal U+FFFD, which is a valid +// character in a query. Only the former ends the input. +const replacementcharacterwidth = 3 + type sqlLexer struct { - src string - start int - pos int - nested int // multiline comment nesting level. - stateFn stateFn - parts []any + src string + start int + pos int + nested int // multiline comment nesting level. + dollarTag string // active dollar-quote delimiter, including both '$' characters. + stateFn stateFn + parts []any nameToOrdinal map[namedArg]int } @@ -222,6 +227,12 @@ func rawState(l *sqlLexer) stateFn { return singleQuoteState case '"': return doubleQuoteState + case '$': + if tagLen, ok := scanDollarQuoteTag(l.src[l.pos:]); ok { + l.dollarTag = l.src[l.pos-1 : l.pos+tagLen+1] + l.pos += tagLen + 1 + return dollarQuoteState + } case '@': nextRune, _ := utf8.DecodeRuneInString(l.src[l.pos:]) if isLetter(nextRune) || nextRune == '_' { @@ -244,15 +255,70 @@ func rawState(l *sqlLexer) stateFn { return multilineCommentState } case utf8.RuneError: - if l.pos-l.start > 0 { - l.parts = append(l.parts, l.src[l.start:l.pos]) - l.start = l.pos + if width != replacementcharacterwidth { + if l.pos-l.start > 0 { + l.parts = append(l.parts, l.src[l.start:l.pos]) + l.start = l.pos + } + return nil + } + } + + // A dollar sign within an unquoted identifier does not start a + // dollar-quoted string. Consume identifiers as a single token. + if isSQLIdentifierStart(r) { + for l.pos < len(l.src) { + next, width := utf8.DecodeRuneInString(l.src[l.pos:]) + if next == utf8.RuneError && width != replacementcharacterwidth { + break + } + if !(isSQLIdentifierStart(next) || next >= '0' && next <= '9' || next == '$') { + break + } + l.pos += width } - return nil } } } +func isSQLIdentifierStart(r rune) bool { + return isLetter(r) || r == '_' || r >= 0x80 +} + +// scanDollarQuoteTag scans an optional tag and its terminating '$', starting +// just after the opening '$'. Tags follow PostgreSQL's unquoted identifier +// rules except that they cannot contain '$'. +func scanDollarQuoteTag(src string) (int, bool) { + for i := 0; i < len(src); { + r, width := utf8.DecodeRuneInString(src[i:]) + if r == '$' { + return i, true + } + if r == utf8.RuneError && width != replacementcharacterwidth { + return 0, false + } + if !(isSQLIdentifierStart(r) || i > 0 && r >= '0' && r <= '9') { + return 0, false + } + i += width + } + return 0, false +} + +func dollarQuoteState(l *sqlLexer) stateFn { + idx := strings.Index(l.src[l.pos:], l.dollarTag) + if idx < 0 { + // Preserve unterminated literals, leaving syntax validation to PostgreSQL. + l.parts = append(l.parts, l.src[l.start:]) + l.pos = len(l.src) + l.start = l.pos + return nil + } + l.pos += idx + len(l.dollarTag) + l.dollarTag = "" + return rawState +} + func isLetter(r rune) bool { return (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') } @@ -262,7 +328,7 @@ func namedArgState(l *sqlLexer) stateFn { r, width := utf8.DecodeRuneInString(l.src[l.pos:]) l.pos += width - if r == utf8.RuneError { + if r == utf8.RuneError && width != replacementcharacterwidth { if l.pos-l.start > 0 { na := namedArg(l.src[l.start:l.pos]) if _, found := l.nameToOrdinal[na]; !found { @@ -298,11 +364,13 @@ func singleQuoteState(l *sqlLexer) stateFn { } l.pos += width case utf8.RuneError: - if l.pos-l.start > 0 { - l.parts = append(l.parts, l.src[l.start:l.pos]) - l.start = l.pos + if width != replacementcharacterwidth { + if l.pos-l.start > 0 { + l.parts = append(l.parts, l.src[l.start:l.pos]) + l.start = l.pos + } + return nil } - return nil } } } @@ -320,11 +388,13 @@ func doubleQuoteState(l *sqlLexer) stateFn { } l.pos += width case utf8.RuneError: - if l.pos-l.start > 0 { - l.parts = append(l.parts, l.src[l.start:l.pos]) - l.start = l.pos + if width != replacementcharacterwidth { + if l.pos-l.start > 0 { + l.parts = append(l.parts, l.src[l.start:l.pos]) + l.start = l.pos + } + return nil } - return nil } } } @@ -345,11 +415,13 @@ func escapeStringState(l *sqlLexer) stateFn { } l.pos += width case utf8.RuneError: - if l.pos-l.start > 0 { - l.parts = append(l.parts, l.src[l.start:l.pos]) - l.start = l.pos + if width != replacementcharacterwidth { + if l.pos-l.start > 0 { + l.parts = append(l.parts, l.src[l.start:l.pos]) + l.start = l.pos + } + return nil } - return nil } } } @@ -360,17 +432,16 @@ func oneLineCommentState(l *sqlLexer) stateFn { l.pos += width switch r { - case '\\': - _, width = utf8.DecodeRuneInString(l.src[l.pos:]) - l.pos += width case '\n', '\r': return rawState case utf8.RuneError: - if l.pos-l.start > 0 { - l.parts = append(l.parts, l.src[l.start:l.pos]) - l.start = l.pos + if width != replacementcharacterwidth { + if l.pos-l.start > 0 { + l.parts = append(l.parts, l.src[l.start:l.pos]) + l.start = l.pos + } + return nil } - return nil } } } @@ -400,11 +471,13 @@ func multilineCommentState(l *sqlLexer) stateFn { l.nested-- case utf8.RuneError: - if l.pos-l.start > 0 { - l.parts = append(l.parts, l.src[l.start:l.pos]) - l.start = l.pos + if width != replacementcharacterwidth { + if l.pos-l.start > 0 { + l.parts = append(l.parts, l.src[l.start:l.pos]) + l.start = l.pos + } + return nil } - return nil } } } diff --git a/vendor/github.com/jackc/pgx/v5/pgconn/auth_oauth.go b/vendor/github.com/jackc/pgx/v5/pgconn/auth_oauth.go index 991f658..396bdf7 100644 --- a/vendor/github.com/jackc/pgx/v5/pgconn/auth_oauth.go +++ b/vendor/github.com/jackc/pgx/v5/pgconn/auth_oauth.go @@ -32,7 +32,10 @@ func (c *PgConn) oauthAuth(ctx context.Context) error { return err } - msg, err := c.receiveMessage() + // Leave AuthenticationOk for the startup loop, which validates authentication + // policy and records completion for every authentication method. All other + // responses below fail authentication and cause the connection to close. + msg, err := c.peekMessage() if err != nil { return err } diff --git a/vendor/github.com/jackc/pgx/v5/pgconn/auth_scram.go b/vendor/github.com/jackc/pgx/v5/pgconn/auth_scram.go index aeaf8cb..4d1e3bb 100644 --- a/vendor/github.com/jackc/pgx/v5/pgconn/auth_scram.go +++ b/vendor/github.com/jackc/pgx/v5/pgconn/auth_scram.go @@ -28,6 +28,7 @@ import ( "hash" "slices" "strconv" + "unicode" "github.com/jackc/pgx/v5/pgproto3" "golang.org/x/text/secure/precis" @@ -39,16 +40,18 @@ const ( scramSHA256PlusName = "SCRAM-SHA-256-PLUS" ) -// Perform SCRAM authentication. -func (c *PgConn) scramAuth(serverAuthMechanisms []string) error { +// Perform SCRAM authentication and report whether the completed exchange used +// channel binding. A mechanism selection alone is not proof of authentication; +// the server signature must be verified before returning channelBound=true. +func (c *PgConn) scramAuth(serverAuthMechanisms []string) (channelBound bool, err error) { sc, err := newScramClient(serverAuthMechanisms, c.config.Password) if err != nil { - return err + return false, err } serverHasPlus := slices.Contains(sc.serverAuthMechanisms, scramSHA256PlusName) if c.config.ChannelBinding == "require" && !serverHasPlus { - return errors.New("channel binding required but server does not support SCRAM-SHA-256-PLUS") + return false, errors.New("channel binding required but server does not support SCRAM-SHA-256-PLUS") } // If we have a TLS connection and channel binding is not disabled, attempt to @@ -56,7 +59,7 @@ func (c *PgConn) scramAuth(serverAuthMechanisms []string) error { if tlsConn, ok := c.conn.(*tls.Conn); ok && c.config.ChannelBinding != "disable" { certHash, err := getTLSCertificateHash(tlsConn) if err != nil && c.config.ChannelBinding == "require" { - return fmt.Errorf("channel binding required but failed to get server certificate hash: %w", err) + return false, fmt.Errorf("channel binding required but failed to get server certificate hash: %w", err) } // Upgrade to SCRAM-SHA-256-PLUS if we have binding data and the server supports it. @@ -69,7 +72,7 @@ func (c *PgConn) scramAuth(serverAuthMechanisms []string) error { } if c.config.ChannelBinding == "require" && sc.channelBindingData == nil { - return errors.New("channel binding required but channel binding data is not available") + return false, errors.New("channel binding required but channel binding data is not available") } // Send client-first-message in a SASLInitialResponse @@ -80,17 +83,17 @@ func (c *PgConn) scramAuth(serverAuthMechanisms []string) error { c.frontend.Send(saslInitialResponse) err = c.flushWithPotentialWriteReadDeadlock() if err != nil { - return err + return false, err } // Receive server-first-message payload in an AuthenticationSASLContinue. saslContinue, err := c.rxSASLContinue() if err != nil { - return err + return false, err } err = sc.recvServerFirstMessage(saslContinue.Data) if err != nil { - return err + return false, err } // Send client-final-message in a SASLResponse @@ -100,15 +103,18 @@ func (c *PgConn) scramAuth(serverAuthMechanisms []string) error { c.frontend.Send(saslResponse) err = c.flushWithPotentialWriteReadDeadlock() if err != nil { - return err + return false, err } // Receive server-final-message payload in an AuthenticationSASLFinal. saslFinal, err := c.rxSASLFinal() if err != nil { - return err + return false, err } - return sc.recvServerFinalMessage(saslFinal.Data) + if err := sc.recvServerFinalMessage(saslFinal.Data); err != nil { + return false, err + } + return sc.authMechanism == scramSHA256PlusName, nil } func (c *PgConn) rxSASLContinue() (*pgproto3.AuthenticationSASLContinue, error) { @@ -192,16 +198,10 @@ func newScramClient(serverAuthMechanisms []string, password string) (*scramClien return nil, errors.New("server does not support SCRAM-SHA-256") } - // precis.OpaqueString is equivalent to SASLprep for password. - var err error - sc.password, err = precis.OpaqueString.String(password) - if err != nil { - // PostgreSQL allows passwords invalid according to SCRAM / SASLprep. - sc.password = password - } + sc.password = normalizeScramPassword(password) buf := make([]byte, clientNonceLen) - _, err = rand.Read(buf) + _, err := rand.Read(buf) if err != nil { return nil, err } @@ -211,6 +211,25 @@ func newScramClient(serverAuthMechanisms []string, password string) (*scramClien return sc, nil } +// normalizeScramPassword preserves PostgreSQL's raw-password fallback for +// characters that SASLprep considers unassigned. SASLprep uses Unicode 3.2, +// while PRECIS uses newer Unicode tables that can change with x/text or Go +// upgrades. Check the original password before PRECIS can change any bytes. +func normalizeScramPassword(password string) string { + for _, r := range password { + if unicode.Is(saslprepUnassigned, r) { + return password + } + } + + normalized, err := precis.OpaqueString.String(password) + if err != nil { + // PostgreSQL allows passwords invalid according to SCRAM / SASLprep. + return password + } + return normalized +} + func (sc *scramClient) clientFirstMessage() []byte { // The client-first-message is the GS2 header concatenated with the bare // message (username + client nonce). The GS2 header communicates the diff --git a/vendor/github.com/jackc/pgx/v5/pgconn/config.go b/vendor/github.com/jackc/pgx/v5/pgconn/config.go index eec7de6..283c20b 100644 --- a/vendor/github.com/jackc/pgx/v5/pgconn/config.go +++ b/vendor/github.com/jackc/pgx/v5/pgconn/config.go @@ -10,7 +10,6 @@ import ( "maps" "math" "net" - "net/url" "os" "path/filepath" "strconv" @@ -43,6 +42,11 @@ type Config struct { LookupFunc LookupFunc // e.g. net.Resolver.LookupHost BuildFrontend BuildFrontendFunc + // MaxProtocolMessageBodyLen is the maximum length of a PostgreSQL wire protocol message body in octets. If a + // message body exceeds this length, reading the message will fail with pgproto3.ExceededMaxBodyLenErr. The default + // value is 0, which means no maximum is enforced. + MaxProtocolMessageBodyLen int + // BuildContextWatcherHandler is called to create a ContextWatcherHandler for a connection. The handler is called // when a context passed to a PgConn method is canceled. BuildContextWatcherHandler func(*PgConn) ctxwatch.Handler @@ -55,6 +59,14 @@ type Config struct { SSLNegotiation string // sslnegotiation=postgres or sslnegotiation=direct + // SSLCertMode controls client certificate usage. Valid values are "disable", "allow", and "require". + // The default is "allow"; an empty field is also treated as "allow". + // "disable" prevents sending a certificate, even if TLSConfig supplies one. + // "require" rejects successful authentication unless the server requested and the client sent a certificate. + // TLS session resumption is disabled in "require" mode so that every connection exchanges a certificate. + // It does not guarantee that the server validated the certificate. + SSLCertMode string + // AfterNetConnect is called after the network connection, including TLS if applicable, is established but before any // PostgreSQL protocol communication. It takes the established net.Conn and returns a net.Conn that will be used in // its place. It can be used to wrap the net.Conn (e.g. for logging, diagnostics, or testing). Its functionality has @@ -107,8 +119,17 @@ type Config struct { RequireAuth string createdByParseConfig bool // Used to enforce created by ParseConfig rule. + + // File-backed client certificates are installed only on connection-specific TLS + // configs, so callers can override Certificates or GetClientCertificate. + clientCertificateLoaders map[*tls.Config]func(*tls.CertificateRequestInfo) (*tls.Certificate, error) } +// defaultPort is the port used when neither the connection string, the environment, nor the +// service file supplies one. It is also the per-element fallback for empty entries in a +// multi-host port list. +const defaultPort = "5432" + // connStringKeyAliases maps libpq parameter keywords to the canonical key names this package // uses internally in the parsed-settings map. Most keywords are already canonical; this map // holds only those whose pgx-internal name differs from the libpq spelling. @@ -137,7 +158,11 @@ type ParseConfigOptions struct { // defaults are not checked: only keys that originate from the connString argument. // // Keys may be given in either their libpq spelling ("dbname") or pgx-internal spelling - // ("database"); both are accepted. + // ("database"); both are accepted. The URI-only ssl=true alias for sslmode=require is + // accepted when either "ssl" or "sslmode" is allowed; an explicit sslmode key or a + // non-"true" ssl value only matches its own spelling. Every ssl/sslmode occurrence in + // the connection string is validated, including occurrences superseded by a later + // repeated parameter. // // A nil slice (the default) applies no restriction and matches libpq behaviour. An empty // non-nil slice rejects every key, i.e. connString must be empty. @@ -156,8 +181,18 @@ type ParseConfigOptions struct { func (c *Config) Copy() *Config { newConf := new(Config) *newConf = *c + if c.clientCertificateLoaders != nil { + newConf.clientCertificateLoaders = make(map[*tls.Config]func(*tls.CertificateRequestInfo) (*tls.Certificate, error), len(c.clientCertificateLoaders)) + } + cloneTLSConfig := func(config *tls.Config) *tls.Config { + cloned := config.Clone() + if loader := c.clientCertificateLoaders[config]; loader != nil { + newConf.clientCertificateLoaders[cloned] = loader + } + return cloned + } if newConf.TLSConfig != nil { - newConf.TLSConfig = c.TLSConfig.Clone() + newConf.TLSConfig = cloneTLSConfig(c.TLSConfig) } if newConf.RuntimeParams != nil { newConf.RuntimeParams = make(map[string]string, len(c.RuntimeParams)) @@ -169,7 +204,7 @@ func (c *Config) Copy() *Config { newFallback := new(FallbackConfig) *newFallback = *fallback if newFallback.TLSConfig != nil { - newFallback.TLSConfig = fallback.TLSConfig.Clone() + newFallback.TLSConfig = cloneTLSConfig(fallback.TLSConfig) } newConf.Fallbacks[i] = newFallback } @@ -232,16 +267,21 @@ func NetworkAddress(host string, port uint16) (network, address string) { // to only read from the environment. If a password is not supplied it will attempt to read the .pgpass file. // // # Example Keyword/Value -// user=jack password=secret host=pg.example.com port=5432 dbname=mydb sslmode=verify-ca +// user=jack password=secret host=pg.example.com port=5432 dbname=mydb sslmode=verify-full // // # Example URL -// postgres://jack:secret@pg.example.com:5432/mydb?sslmode=verify-ca +// postgres://jack:secret@pg.example.com:5432/mydb?sslmode=verify-full // // The returned *Config may be modified. However, it is strongly recommended that any configuration that can be done // through the connection string be done there. In particular the fields Host, Port, TLSConfig, and Fallbacks can be // interdependent (e.g. TLSConfig needs knowledge of the host to validate the server certificate). These fields should // not be modified individually. They should all be modified or all left unchanged. // +// Client certificates configured with sslcert and sslkey are reloaded for each TLS certificate request. +// Setting TLSConfig.Certificates (including a non-nil empty slice) or TLSConfig.GetClientCertificate overrides +// this behavior. Replacing TLSConfig discards its file-backed certificate settings; use Config.Copy to retain +// those settings when copying a configuration. +// // ParseConfig supports specifying multiple hosts in similar manner to libpq. Host and port may include comma separated // values that will be tried in order. This can be used as part of a high availability system. See // https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-MULTIPLE-HOSTS for more information. @@ -307,6 +347,21 @@ func NetworkAddress(host string, port uint16) (network, address string) { // When multiple hosts are specified, libpq allows them to have different passwords set via the .pgpass file. pgconn // does not. // +// URL query parameters that libpq does not recognize cause libpq to fail with an "invalid URI query parameter" error. +// ParseConfig accepts them: they become runtime parameters or pgx-specific options (e.g. pool_max_conns). +// +// Connection strings containing a NUL byte are rejected, in both URI and keyword/value form. libpq cannot encounter +// one because its conninfo strings are NUL-terminated C strings, but a Go string can carry a NUL into the startup +// packet, where it delimits parameters rather than being data. Settings reaching Config by other routes (a service +// file, or direct assignment to Config.RuntimeParams, User, or Database) are not checked here; a NUL in those is +// caught when the startup message is encoded, and Connect fails rather than sending it. +// +// Error messages from ParseConfig avoid quoting the unredacted connection string and attempt to redact recognizable +// password fields, while libpq quotes the failing input verbatim. This redaction is best effort. An invalid connection +// string can be structurally ambiguous, so pgconn cannot guarantee that every password in malformed input will be +// identified or redacted. Applications should not assume that parse errors are safe to expose when connection strings +// may contain secrets. +// // In addition, ParseConfig accepts the following options: // // - servicefile. @@ -325,11 +380,12 @@ func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*Con envSettings := parseEnvSettings() connStringSettings := make(map[string]string) + var urlMeta parseURLMeta if connString != "" { var err error // connString may be a database URL or in PostgreSQL keyword/value format if strings.HasPrefix(connString, "postgres://") || strings.HasPrefix(connString, "postgresql://") { - connStringSettings, err = parseURLSettings(connString) + connStringSettings, urlMeta, err = parseURLSettings(connString) if err != nil { return nil, &ParseConfigError{ConnString: connString, msg: "failed to parse as URL", err: err} } @@ -346,14 +402,77 @@ func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*Con for _, k := range options.ConnStringAllowedKeys { allowed[canonicalConnStringKey(k)] = struct{}{} } + notAllowed := func(k string) error { + return &ParseConfigError{ConnString: connString, msg: fmt.Sprintf("connection string key %q is not in ConnStringAllowedKeys", k)} + } + _, sslAllowed := allowed["ssl"] + _, sslmodeAllowed := allowed["sslmode"] + + // Repeated-key handling and the URI ssl=true alias rewrite can remove + // ssl/sslmode occurrences from the final settings map, so those two keys + // are validated from what the user actually wrote -- every occurrence, + // fail closed -- rather than from what survived. The alias itself is + // accepted under either spelling, the same way dbname/database are + // interchangeable; an explicit sslmode key or a non-"true" ssl value + // only matches its own spelling. + if urlMeta.sawRawSSLKey && !sslAllowed { + return nil, notAllowed("ssl") + } + if urlMeta.sawExplicitSSLModeKey && !sslmodeAllowed { + return nil, notAllowed("sslmode") + } + if urlMeta.sawSSLTrueAlias && !sslAllowed && !sslmodeAllowed { + return nil, notAllowed("ssl") + } + for k := range connStringSettings { - if _, ok := allowed[k]; !ok { - return nil, &ParseConfigError{ConnString: connString, msg: fmt.Sprintf("connection string key %q is not in ConnStringAllowedKeys", k)} + if _, ok := allowed[k]; ok { + continue } + // A multi-host URI with no explicit ports produces an implied + // all-empty port list (e.g. ","), matching libpq. Only that list + // -- identified by the parser from the raw syntax, not inferred + // from the value -- is exempt from the allow-list: it carries no + // user-supplied port text. An explicit empty port (?port= in a + // URI or port= in keyword/value form) is user-supplied, and + // because a present-but-empty port still shadows PGPORT it must + // pass the allow-list like any other key. + if k == "port" && urlMeta.impliedEmptyPortList { + continue + } + // A surviving ssl or sslmode entry from a URI was already + // validated above against every spelling the user wrote. + if k == "ssl" && urlMeta.sawRawSSLKey { + continue + } + if k == "sslmode" && (urlMeta.sawSSLTrueAlias || urlMeta.sawExplicitSSLModeKey) { + continue + } + return nil, notAllowed(k) } } settings := mergeSettings(defaultSettings, envSettings, connStringSettings) + + // The home-directory-derived defaults (passfile, servicefile, sslcert, + // sslkey, sslrootcert) are already present in settings at this point: + // defaultSettings resolves them via the user's home directory, which is + // safe and cheap to look up (see defaults.go / defaults_windows.go). + // + // The default PostgreSQL user name is different: resolving it requires + // looking up the OS user account, which can be slow or, in some + // restricted container environments, crash the process. So that lookup + // is memoized and only performed lazily below, the first time it is + // actually needed -- i.e. only when a connection string or environment + // does not already supply a user. + var cachedOSUserSettings map[string]string + lazyOSUserSettings := func() map[string]string { + if cachedOSUserSettings == nil { + cachedOSUserSettings = osUserSettings() + } + return cachedOSUserSettings + } + if service, present := settings["service"]; present { serviceSettings, err := parseServiceSettings(settings["servicefile"], service) if err != nil { @@ -363,6 +482,13 @@ func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*Con settings = mergeSettings(defaultSettings, envSettings, serviceSettings, connStringSettings) } + // Only fall back to the OS user account for the default PostgreSQL user + // name when it was not already supplied by the connection string, + // environment, or service file. + if settings["user"] == "" { + settings = mergeSettings(lazyOSUserSettings(), settings) + } + config := &Config{ createdByParseConfig: true, Database: settings["database"], @@ -382,6 +508,16 @@ func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*Con }, } + sslCertMode, present := settings["sslcertmode"] + if !present { + sslCertMode = "allow" + } + var err error + config.SSLCertMode, err = parseSSLCertMode(sslCertMode) + if err != nil { + return nil, &ParseConfigError{ConnString: connString, msg: "invalid sslcertmode", err: err} + } + if connectTimeoutSetting, present := settings["connect_timeout"]; present { connectTimeout, err := parseConnectTimeoutSetting(connectTimeoutSetting) if err != nil { @@ -407,6 +543,7 @@ func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*Con "sslmode": {}, "sslkey": {}, "sslcert": {}, + "sslcertmode": {}, "sslrootcert": {}, "sslnegotiation": {}, "sslpassword": {}, @@ -442,17 +579,41 @@ func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*Con hosts := strings.Split(settings["host"], ",") ports := strings.Split(settings["port"], ",") + // Like libpq, if exactly one port is given it applies to all hosts; + // otherwise there must be exactly one port per host. Empty list elements + // mean "use the default". + if len(ports) > 1 && len(ports) != len(hosts) { + return nil, &ParseConfigError{ConnString: connString, msg: fmt.Sprintf("could not match %d port numbers to %d hosts", len(ports), len(hosts))} + } + + // defaultHost stats candidate socket directories, so resolve it at most + // once even when several host list elements are empty. It never returns "". + resolvedDefaultHost := "" for i, host := range hosts { - var portStr string - if i < len(ports) { - portStr = ports[i] - } else { - portStr = ports[0] + if host == "" { + if resolvedDefaultHost == "" { + resolvedDefaultHost = defaultHost() + } + host = resolvedDefaultHost } + portStr := ports[0] + if len(ports) > 1 { + portStr = ports[i] + } + if portStr == "" { + portStr = defaultPort + } + + // The strconv error is deliberately not wrapped: it quotes the + // offending text, and in a malformed URI the bytes that land in the + // port position can be a mislaid password (postgres://u:sec:ret@h + // parses "sec:ret@h" as the port). The best-effort-redacted connection + // string in ParseConfigError provides the available context without + // deliberately quoting the offending port text again. port, err := parsePort(portStr) if err != nil { - return nil, &ParseConfigError{ConnString: connString, msg: "invalid port", err: err} + return nil, &ParseConfigError{ConnString: connString, msg: "invalid port"} } var tlsConfigs []*tls.Config @@ -462,7 +623,7 @@ func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*Con tlsConfigs = append(tlsConfigs, nil) } else { var err error - tlsConfigs, err = configTLS(settings, host, options) + tlsConfigs, err = config.configTLS(settings, host, options) if err != nil { return nil, &ParseConfigError{ConnString: connString, msg: "failed to configure TLS", err: err} } @@ -483,14 +644,13 @@ func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*Con config.Fallbacks = fallbacks[1:] config.SSLNegotiation = settings["sslnegotiation"] - passfile, err := pgpassfile.ReadPassfile(settings["passfile"]) - if err == nil { - if config.Password == "" { + if config.Password == "" { + passfile, err := pgpassfile.ReadPassfile(settings["passfile"]) + if err == nil { host := config.Host if network, _ := NetworkAddress(config.Host, config.Port); network == "unix" { host = "localhost" } - config.Password = passfile.FindPassword(host, strconv.Itoa(int(config.Port)), config.Database, config.User) } } @@ -591,6 +751,7 @@ func parseEnvSettings() map[string]string { "PGSSLMODE": "sslmode", "PGSSLKEY": "sslkey", "PGSSLCERT": "sslcert", + "PGSSLCERTMODE": "sslcertmode", "PGSSLSNI": "sslsni", "PGSSLROOTCERT": "sslrootcert", "PGSSLPASSWORD": "sslpassword", @@ -607,8 +768,9 @@ func parseEnvSettings() map[string]string { } for envname, realname := range nameMap { - value := os.Getenv(envname) - if value != "" { + value, present := os.LookupEnv(envname) + // Preserve an explicitly empty sslcertmode so it is rejected, like libpq. + if value != "" || (present && realname == "sslcertmode") { settings[realname] = value } } @@ -616,76 +778,46 @@ func parseEnvSettings() map[string]string { return settings } -func parseURLSettings(connString string) (map[string]string, error) { - settings := make(map[string]string) - - parsedURL, err := url.Parse(connString) - if err != nil { - if urlErr := new(url.Error); errors.As(err, &urlErr) { - return nil, urlErr.Err - } - return nil, err - } - - if parsedURL.User != nil { - if u := parsedURL.User.Username(); u != "" { - settings["user"] = u - } - if password, present := parsedURL.User.Password(); present { - settings["password"] = password - } - } - - // Handle multiple host:port's in url.Host by splitting them into host,host,host and port,port,port. - var hosts []string - var ports []string - for host := range strings.SplitSeq(parsedURL.Host, ",") { - if host == "" { - continue - } - if isIPOnly(host) { - hosts = append(hosts, strings.Trim(host, "[]")) - continue - } - h, p, err := net.SplitHostPort(host) - if err != nil { - return nil, fmt.Errorf("failed to split host:port in '%s', err: %w", host, err) - } - if h != "" { - hosts = append(hosts, h) - } - if p != "" { - ports = append(ports, p) - } - } - if len(hosts) > 0 { - settings["host"] = strings.Join(hosts, ",") - } - if len(ports) > 0 { - settings["port"] = strings.Join(ports, ",") - } - - database := strings.TrimLeft(parsedURL.Path, "/") - if database != "" { - settings["database"] = database - } - - for k, v := range parsedURL.Query() { - settings[canonicalConnStringKey(k)] = v[0] - } - - return settings, nil -} - -func isIPOnly(host string) bool { - return net.ParseIP(strings.Trim(host, "[]")) != nil || !strings.Contains(host, ":") -} - var asciiSpace = [256]uint8{'\t': 1, '\n': 1, '\v': 1, '\f': 1, '\r': 1, ' ': 1} +// unescapeKeywordValue applies libpq's backslash rule to the raw text of a +// keyword/value value: a backslash is dropped and whatever follows it is taken +// literally, whatever that character is. A backslash at the very end escapes +// the end of the string, so it is dropped and contributes nothing -- which is +// how libpq accepts `host=a\`. Only the unquoted branch can reach that case; +// inside quotes the escaped terminator leaves the string unterminated and the +// caller has already rejected it. +func unescapeKeywordValue(s string) string { + if !strings.ContainsRune(s, '\\') { + return s + } + + var sb strings.Builder + sb.Grow(len(s)) + for i := 0; i < len(s); i++ { + if s[i] == '\\' { + i++ + if i == len(s) { + break + } + } + sb.WriteByte(s[i]) + } + return sb.String() +} + func parseKeywordValueSettings(s string) (map[string]string, error) { settings := make(map[string]string) + // Reject NUL bytes up front, as parseURLSettings does. libpq never sees one + // because its conninfo strings are NUL-terminated C strings; a Go string can + // carry a NUL through to the startup packet, where it acts as a parameter + // delimiter rather than data. StartupMessage.Encode refuses such parameters, + // but failing here reports the problem against the input that caused it. + if strings.IndexByte(s, 0) >= 0 { + return nil, errors.New("forbidden NUL byte in connection string") + } + // Trim any leading whitespace so that the loop exits cleanly when only // spaces remain (e.g. trailing spaces after the last value). s = strings.TrimLeft(s, " \t\n\r\v\f") @@ -697,6 +829,15 @@ func parseKeywordValueSettings(s string) (map[string]string, error) { } key = strings.Trim(s[:eqIdx], " \t\n\r\v\f") + // libpq reads a keyword as a run of non-space characters and then + // requires the next non-space character to be '=', so whitespace + // inside a keyword terminates it and is an error. Trimming alone would + // accept the space as part of the key and turn a typo into a bogus + // RuntimeParam that only the server rejects. Report it as libpq does, + // naming the keyword it had read. + if i := strings.IndexAny(key, " \t\n\r\v\f"); i >= 0 { + return nil, fmt.Errorf(`missing "=" after %q in connection info string`, key[:i]) + } s = strings.TrimLeft(s[eqIdx+1:], " \t\n\r\v\f") switch { case len(s) == 0: @@ -708,12 +849,15 @@ func parseKeywordValueSettings(s string) (map[string]string, error) { } if s[end] == '\\' { end++ + // A trailing backslash escapes the end of the string. + // libpq drops it and ends the value there. Break rather + // than let the loop's post-increment push end past len(s). if end == len(s) { - return nil, errors.New("invalid backslash") + break } } } - val = strings.ReplaceAll(strings.ReplaceAll(s[:end], "\\\\", "\\"), "\\'", "'") + val = unescapeKeywordValue(s[:end]) // Consume the value and trim any subsequent whitespace so that // multiple trailing spaces don't cause a spurious parse failure. s = strings.TrimLeft(s[end:], " \t\n\r\v\f") @@ -726,12 +870,15 @@ func parseKeywordValueSettings(s string) (map[string]string, error) { } if s[end] == '\\' { end++ + if end == len(s) { + return nil, errors.New("unterminated quoted string in connection info string") + } } } if end == len(s) { return nil, errors.New("unterminated quoted string in connection info string") } - val = strings.ReplaceAll(strings.ReplaceAll(s[:end], "\\\\", "\\"), "\\'", "'") + val = unescapeKeywordValue(s[:end]) // Consume the closing quote and any subsequent whitespace. s = strings.TrimLeft(s[end+1:], " \t\n\r\v\f") } @@ -773,12 +920,16 @@ func parseServiceSettings(servicefilePath, serviceName string) (map[string]strin // configTLS uses libpq's TLS parameters to construct []*tls.Config. It is // necessary to allow returning multiple TLS configs as sslmode "allow" and // "prefer" allow fallback. -func configTLS(settings map[string]string, thisHost string, parseConfigOptions ParseConfigOptions) ([]*tls.Config, error) { +func (c *Config) configTLS(settings map[string]string, thisHost string, parseConfigOptions ParseConfigOptions) ([]*tls.Config, error) { host := thisHost sslmode := settings["sslmode"] sslrootcert := settings["sslrootcert"] sslcert := settings["sslcert"] sslkey := settings["sslkey"] + if settings["sslcertmode"] == "disable" { + // Like libpq, do not read client certificate or key files in this mode. + sslcert, sslkey = "", "" + } sslpassword := settings["sslpassword"] sslsni := settings["sslsni"] sslnegotiation := settings["sslnegotiation"] @@ -892,57 +1043,41 @@ func configTLS(settings map[string]string, thisHost string, parseConfigOptions P } if sslcert != "" && sslkey != "" { - buf, err := os.ReadFile(sslkey) + // Retain the directory used at parse time, while still following symlinks + // on each load so certificate rotation can replace their targets. + var err error + sslcert, err = filepath.Abs(sslcert) if err != nil { - return nil, fmt.Errorf("unable to read sslkey: %w", err) + return nil, fmt.Errorf("unable to resolve sslcert: %w", err) } - block, _ := pem.Decode(buf) - if block == nil { - return nil, errors.New("failed to decode sslkey") + sslkey, err = filepath.Abs(sslkey) + if err != nil { + return nil, fmt.Errorf("unable to resolve sslkey: %w", err) } - var pemKey []byte - var decryptedKey []byte - var decryptedError error - // If PEM is encrypted, attempt to decrypt using pass phrase - if x509.IsEncryptedPEMBlock(block) { - // Attempt decryption with pass phrase - // NOTE: only supports RSA (PKCS#1) - if sslpassword != "" { - decryptedKey, decryptedError = x509.DecryptPEMBlock(block, []byte(sslpassword)) //nolint:ineffassign - } - // if sslpassword not provided or has decryption error when use it - // try to find sslpassword with callback function - if sslpassword == "" || decryptedError != nil { - if parseConfigOptions.GetSSLPassword != nil { - sslpassword = parseConfigOptions.GetSSLPassword(context.Background()) - } - if sslpassword == "" { - return nil, fmt.Errorf("unable to find sslpassword") - } - } - decryptedKey, decryptedError = x509.DecryptPEMBlock(block, []byte(sslpassword)) - // Should we also provide warning for PKCS#1 needed? - if decryptedError != nil { - return nil, fmt.Errorf("unable to decrypt key: %w", decryptedError) + + // Read the key & cert so + // (a) we can provide error feedback now and + // (b) invoke the GetSSLPassword callback once if necessary + _, resolvedPassword, err := loadClientCertificate(sslcert, sslkey, sslpassword, parseConfigOptions) + if err != nil { + return nil, err + } + + if c.clientCertificateLoaders == nil { + c.clientCertificateLoaders = make(map[*tls.Config]func(*tls.CertificateRequestInfo) (*tls.Certificate, error)) + } + c.clientCertificateLoaders[tlsConfig] = func(cri *tls.CertificateRequestInfo) (*tls.Certificate, error) { + cert, _, err := loadClientCertificate(sslcert, sslkey, resolvedPassword, ParseConfigOptions{}) + if err != nil { + return nil, err } - pemBytes := pem.Block{ - Type: "RSA PRIVATE KEY", - Bytes: decryptedKey, + // Same check crypto/tls provides when passing certs through config.Certificates + if cri != nil && cri.SupportsCertificate(&cert) != nil { + return new(tls.Certificate), nil } - pemKey = pem.EncodeToMemory(&pemBytes) - } else { - pemKey = pem.EncodeToMemory(block) + return &cert, nil } - certfile, err := os.ReadFile(sslcert) - if err != nil { - return nil, fmt.Errorf("unable to read cert: %w", err) - } - cert, err := tls.X509KeyPair(certfile, pemKey) - if err != nil { - return nil, fmt.Errorf("unable to load cert: %w", err) - } - tlsConfig.Certificates = []tls.Certificate{cert} } // Set Server Name Indication (SNI), if enabled by connection parameters. @@ -964,6 +1099,144 @@ func configTLS(settings map[string]string, thisHost string, parseConfigOptions P } } +// loadClientCertificate reads sslcert and sslkey and returns the pair, along +// with the password that decrypted the key (empty when the key is not +// encrypted). When the key is encrypted and sslpassword does not decrypt it, +// parseConfigOptions.GetSSLPassword is asked for one. +func loadClientCertificate(sslcert, sslkey, sslpassword string, parseConfigOptions ParseConfigOptions) (tls.Certificate, string, error) { + buf, err := os.ReadFile(sslkey) + if err != nil { + return tls.Certificate{}, "", fmt.Errorf("unable to read sslkey: %w", err) + } + block, _ := pem.Decode(buf) + if block == nil { + return tls.Certificate{}, "", errors.New("failed to decode sslkey") + } + var pemKey []byte + var decryptedKey []byte + var decryptedError error + // If PEM is encrypted, attempt to decrypt using pass phrase + if x509.IsEncryptedPEMBlock(block) { + // Attempt decryption with pass phrase + if sslpassword != "" { + decryptedKey, decryptedError = x509.DecryptPEMBlock(block, []byte(sslpassword)) //nolint:ineffassign + } + // if sslpassword not provided or has decryption error when use it + // try to find sslpassword with callback function + if sslpassword == "" || decryptedError != nil { + if parseConfigOptions.GetSSLPassword != nil { + sslpassword = parseConfigOptions.GetSSLPassword(context.Background()) + } + if sslpassword == "" { + return tls.Certificate{}, "", fmt.Errorf("unable to find sslpassword") + } + } + decryptedKey, decryptedError = x509.DecryptPEMBlock(block, []byte(sslpassword)) + if decryptedError != nil { + return tls.Certificate{}, "", fmt.Errorf("unable to decrypt key: %w", decryptedError) + } + + pemBytes := pem.Block{ + // Preserve the old loader's tolerance of non-key PEM labels. + // X509KeyPair determines the key format from the decrypted DER. + Type: "PRIVATE KEY", + Bytes: decryptedKey, + } + pemKey = pem.EncodeToMemory(&pemBytes) + } else { + // Hand over the whole file rather than the first block: X509KeyPair + // skips blocks that are not a key, so a combined key+certificate file + // works whatever order it is written in. + pemKey = buf + } + certfile, err := os.ReadFile(sslcert) + if err != nil { + return tls.Certificate{}, "", fmt.Errorf("unable to read cert: %w", err) + } + cert, err := tls.X509KeyPair(certfile, pemKey) + if err != nil { + return tls.Certificate{}, "", fmt.Errorf("unable to load cert: %w", err) + } + return cert, sslpassword, nil +} + +type sslCertState struct { + requested bool + sent bool +} + +// checkRequired verifies the required certificate exchange during connection startup. +// In require mode, a nil state means that no TLS connection was made. +func (s *sslCertState) checkRequired() error { + if s == nil || !s.requested { + return &sslCertModeError{msg: "server did not request an SSL certificate"} + } + if !s.sent { + return &sslCertModeError{msg: "server accepted connection without a valid SSL certificate"} + } + return nil +} + +// prepareTLSConfigForConnect prepares certificate reloading and sslcertmode for one connection. +// In require mode, the returned state must be checked before accepting AuthenticationOk or ReadyForQuery. +// Configs may be shared by concurrent connection attempts, so any callback state must +// belong to a clone made for this attempt, not the original config. +func (c *Config) prepareTLSConfigForConnect(config *tls.Config) (*tls.Config, *sslCertState) { + if c.SSLCertMode != "disable" && config.Certificates == nil && config.GetClientCertificate == nil { + if loader := c.clientCertificateLoaders[config]; loader != nil { + config = config.Clone() + config.GetClientCertificate = loader + } + } + switch c.SSLCertMode { + case "disable": + config = config.Clone() + config.Certificates = nil + config.GetClientCertificate = func(*tls.CertificateRequestInfo) (*tls.Certificate, error) { + return new(tls.Certificate), nil + } + return config, nil + case "require": + state := new(sslCertState) + original := config + config = config.Clone() + // Resumed sessions skip the certificate exchange and its callback. + config.ClientSessionCache = nil + config.GetClientCertificate = func(cri *tls.CertificateRequestInfo) (*tls.Certificate, error) { + state.requested = true + var cert *tls.Certificate + var err error + if original.GetClientCertificate != nil { + cert, err = original.GetClientCertificate(cri) + } else { + // Preserve crypto/tls's default certificate selection, including its + // signature scheme and acceptable CA checks. + cert = new(tls.Certificate) + for i := range original.Certificates { + if cri.SupportsCertificate(&original.Certificates[i]) == nil { + cert = &original.Certificates[i] + break + } + } + } + state.sent = err == nil && cert != nil && len(cert.Certificate) > 0 + return cert, err + } + return config, state + default: + return config, nil + } +} + +func parseSSLCertMode(s string) (string, error) { + switch s { + case "disable", "allow", "require": + return s, nil + default: + return "", fmt.Errorf("unknown sslcertmode value: %v", s) + } +} + func parsePort(s string) (uint16, error) { port, err := strconv.ParseUint(s, 10, 16) if err != nil { @@ -1001,6 +1274,17 @@ func makeConnectTimeoutDialFunc(timeout time.Duration) DialFunc { return d.DialContext } +var ( + // ErrReadOnlyConnection is returned when a read-write connection is required but the connection is read-only. + ErrReadOnlyConnection = errors.New("read only connection") + // ErrReadWriteConnection is returned when a read-only connection is required but the connection is read-write. + ErrReadWriteConnection = errors.New("connection is not read only") + // ErrPrimaryConnection is returned when a standby connection is required but the server is primary. + ErrPrimaryConnection = errors.New("server is not in hot standby mode") + // ErrStandbyConnection is returned when a primary connection is required but the server is in standby mode. + ErrStandbyConnection = errors.New("server is in standby mode") +) + // ValidateConnectTargetSessionAttrsReadWrite is a ValidateConnectFunc that implements libpq compatible // target_session_attrs=read-write. func ValidateConnectTargetSessionAttrsReadWrite(ctx context.Context, pgConn *PgConn) error { @@ -1010,7 +1294,7 @@ func ValidateConnectTargetSessionAttrsReadWrite(ctx context.Context, pgConn *PgC } if string(result[0].Rows[0][0]) == "on" { - return errors.New("read only connection") + return ErrReadOnlyConnection } return nil @@ -1025,7 +1309,7 @@ func ValidateConnectTargetSessionAttrsReadOnly(ctx context.Context, pgConn *PgCo } if string(result[0].Rows[0][0]) != "on" { - return errors.New("connection is not read only") + return ErrReadWriteConnection } return nil @@ -1040,7 +1324,7 @@ func ValidateConnectTargetSessionAttrsStandby(ctx context.Context, pgConn *PgCon } if string(result[0].Rows[0][0]) != "t" { - return errors.New("server is not in hot standby mode") + return ErrPrimaryConnection } return nil @@ -1055,7 +1339,7 @@ func ValidateConnectTargetSessionAttrsPrimary(ctx context.Context, pgConn *PgCon } if string(result[0].Rows[0][0]) == "t" { - return errors.New("server is in standby mode") + return ErrStandbyConnection } return nil @@ -1070,7 +1354,7 @@ func ValidateConnectTargetSessionAttrsPreferStandby(ctx context.Context, pgConn } if string(result[0].Rows[0][0]) != "t" { - return &NotPreferredError{err: errors.New("server is not in hot standby mode")} + return &NotPreferredError{err: ErrPrimaryConnection} } return nil diff --git a/vendor/github.com/jackc/pgx/v5/pgconn/defaults.go b/vendor/github.com/jackc/pgx/v5/pgconn/defaults.go index 1dd514f..03b0d33 100644 --- a/vendor/github.com/jackc/pgx/v5/pgconn/defaults.go +++ b/vendor/github.com/jackc/pgx/v5/pgconn/defaults.go @@ -1,5 +1,4 @@ //go:build !windows -// +build !windows package pgconn @@ -9,22 +8,46 @@ import ( "path/filepath" ) +// currentOSUser resolves the current OS user account. It is a seam so tests +// can simulate os/user.Current failing -- including the unrecoverable +// crashes reported in some restricted/broken-NSS container environments -- +// without needing such an environment. +var currentOSUser = user.Current + +// userHomeDir resolves the current user's home directory. It is a seam so +// tests can simulate os.UserHomeDir failing without needing to unset $HOME +// for the whole process. +// +// os.UserHomeDir only reads the $HOME environment variable on this platform; +// it never calls into cgo or NSS, so unlike os/user.Current it cannot crash +// in restricted/broken container environments. That also means it can +// resolve a different directory than the OS account's passwd-file home +// directory if $HOME has been overridden -- this is an accepted tradeoff so +// that home-directory-derived defaults (pgpass, pg_service.conf, client SSL +// certificate/key/root files) keep resolving even when the OS user account +// lookup itself is unavailable or unsafe to call. +var userHomeDir = os.UserHomeDir + func defaultSettings() map[string]string { settings := make(map[string]string) settings["host"] = defaultHost() - settings["port"] = "5432" + settings["port"] = defaultPort + settings["target_session_attrs"] = "any" - // Default to the OS user name. Purposely ignoring err getting user name from - // OS. The client application will simply have to specify the user in that - // case (which they typically will be doing anyway). - user, err := user.Current() - if err == nil { - settings["user"] = user.Username - settings["passfile"] = filepath.Join(user.HomeDir, ".pgpass") - settings["servicefile"] = filepath.Join(user.HomeDir, ".pg_service.conf") - sslcert := filepath.Join(user.HomeDir, ".postgresql", "postgresql.crt") - sslkey := filepath.Join(user.HomeDir, ".postgresql", "postgresql.key") + // The home-directory-derived defaults (~/.pgpass, ~/.pg_service.conf, + // and the client SSL certificate/key/root files under ~/.postgresql) + // only need the user's home directory, not the full OS user account, so + // they are resolved unconditionally here via os.UserHomeDir. This keeps + // them available even when looking up the OS user account (needed only + // for the default PostgreSQL user name, see osUserSettings) is slow, + // fails, or -- in some restricted container environments with a broken + // NSS/CGO setup -- would crash the process. + if homeDir, err := userHomeDir(); err == nil { + settings["passfile"] = filepath.Join(homeDir, ".pgpass") + settings["servicefile"] = filepath.Join(homeDir, ".pg_service.conf") + sslcert := filepath.Join(homeDir, ".postgresql", "postgresql.crt") + sslkey := filepath.Join(homeDir, ".postgresql", "postgresql.key") if _, err := os.Stat(sslcert); err == nil { if _, err := os.Stat(sslkey); err == nil { // Both the cert and key must be present to use them, or do not use either @@ -32,13 +55,33 @@ func defaultSettings() map[string]string { settings["sslkey"] = sslkey } } - sslrootcert := filepath.Join(user.HomeDir, ".postgresql", "root.crt") + sslrootcert := filepath.Join(homeDir, ".postgresql", "root.crt") if _, err := os.Stat(sslrootcert); err == nil { settings["sslrootcert"] = sslrootcert } } - settings["target_session_attrs"] = "any" + return settings +} + +// osUserSettings returns the default PostgreSQL user name derived from the +// current OS user account. +// +// Resolving this requires looking up the OS user account, which can be slow +// or, in some restricted container environments (e.g. distroless images +// with a broken NSS/CGO setup), crash the process. Callers must only call +// osUserSettings when the default user name is not already supplied by the +// connection string, environment, or service file. +func osUserSettings() map[string]string { + settings := make(map[string]string) + + // Default to the OS user name. Purposely ignoring err getting user name from + // OS. The client application will simply have to specify the user in that + // case (which they typically will be doing anyway). + user, err := currentOSUser() + if err == nil { + settings["user"] = user.Username + } return settings } diff --git a/vendor/github.com/jackc/pgx/v5/pgconn/defaults_windows.go b/vendor/github.com/jackc/pgx/v5/pgconn/defaults_windows.go index 33b4a1f..3a4068b 100644 --- a/vendor/github.com/jackc/pgx/v5/pgconn/defaults_windows.go +++ b/vendor/github.com/jackc/pgx/v5/pgconn/defaults_windows.go @@ -7,28 +7,45 @@ import ( "strings" ) +// currentOSUser resolves the current OS user account. It is a seam so tests +// can simulate os/user.Current failing -- including the unrecoverable +// crashes reported in some restricted/broken-NSS container environments -- +// without needing such an environment. +var currentOSUser = user.Current + +// userHomeDir resolves the current user's home directory. It is a seam so +// tests can simulate os.UserHomeDir failing without needing to unset the +// relevant environment variables for the whole process. +// +// os.UserHomeDir only reads %USERPROFILE% (falling back to +// %HOMEDRIVE%+%HOMEPATH%) on this platform; it never calls into the Windows +// user account APIs, so unlike os/user.Current it cannot crash in +// restricted/broken container environments. That also means it can resolve +// a different directory than the OS account API's reported home directory +// if those environment variables have been overridden -- this is an +// accepted tradeoff so that home-directory-derived defaults (pg_service.conf) +// keep resolving even when the OS user account lookup itself is unavailable +// or unsafe to call. +var userHomeDir = os.UserHomeDir + func defaultSettings() map[string]string { settings := make(map[string]string) settings["host"] = defaultHost() - settings["port"] = "5432" + settings["port"] = defaultPort + settings["target_session_attrs"] = "any" - // Default to the OS user name. Purposely ignoring err getting user name from - // OS. The client application will simply have to specify the user in that - // case (which they typically will be doing anyway). - user, err := user.Current() - appData := os.Getenv("APPDATA") - if err == nil { - // Windows gives us the username here as `DOMAIN\user` or `LOCALPCNAME\user`, - // but the libpq default is just the `user` portion, so we strip off the first part. - username := user.Username - if strings.Contains(username, "\\") { - username = username[strings.LastIndex(username, "\\")+1:] - } - - settings["user"] = username + // The %APPDATA%\postgresql-derived defaults (pgpass.conf, .pg_service.conf + // and the client SSL certificate/key/root files) only need the APPDATA + // environment variable, not the full OS user account, so they are resolved + // unconditionally here. This keeps them available even when looking up + // the OS user account (needed only for the default PostgreSQL user + // name, see osUserSettings) is slow, fails, or -- in some restricted + // container environments with a broken NSS/CGO setup -- would crash the + // process. + if appData := os.Getenv("APPDATA"); appData != "" { settings["passfile"] = filepath.Join(appData, "postgresql", "pgpass.conf") - settings["servicefile"] = filepath.Join(user.HomeDir, ".pg_service.conf") + settings["servicefile"] = filepath.Join(appData, "postgresql", ".pg_service.conf") sslcert := filepath.Join(appData, "postgresql", "postgresql.crt") sslkey := filepath.Join(appData, "postgresql", "postgresql.key") if _, err := os.Stat(sslcert); err == nil { @@ -44,7 +61,50 @@ func defaultSettings() map[string]string { } } - settings["target_session_attrs"] = "any" + // libpq looks for the service file at %APPDATA%\postgresql\.pg_service.conf + // on Windows, but pgx used to look for it at ~/.pg_service.conf. Keep + // using that file when there is none at the libpq location, so existing + // setups keep working. The home directory is resolved the same crash-safe + // way as on other platforms (see defaults.go). + if homeDir, err := userHomeDir(); err == nil { + homeServicefile := filepath.Join(homeDir, ".pg_service.conf") + if servicefile, ok := settings["servicefile"]; !ok { + settings["servicefile"] = homeServicefile + } else if _, err := os.Stat(servicefile); os.IsNotExist(err) { + if _, err := os.Stat(homeServicefile); err == nil { + settings["servicefile"] = homeServicefile + } + } + } + + return settings +} + +// osUserSettings returns the default PostgreSQL user name derived from the +// current OS user account. +// +// Resolving this requires looking up the OS user account, which can be slow +// or, in some restricted container environments (e.g. distroless images +// with a broken NSS/CGO setup), crash the process. Callers must only call +// osUserSettings when the default user name is not already supplied by the +// connection string, environment, or service file. +func osUserSettings() map[string]string { + settings := make(map[string]string) + + // Default to the OS user name. Purposely ignoring err getting user name from + // OS. The client application will simply have to specify the user in that + // case (which they typically will be doing anyway). + user, err := currentOSUser() + if err == nil { + // Windows gives us the username here as `DOMAIN\user` or `LOCALPCNAME\user`, + // but the libpq default is just the `user` portion, so we strip off the first part. + username := user.Username + if strings.Contains(username, "\\") { + username = username[strings.LastIndex(username, "\\")+1:] + } + + settings["user"] = username + } return settings } diff --git a/vendor/github.com/jackc/pgx/v5/pgconn/doc.go b/vendor/github.com/jackc/pgx/v5/pgconn/doc.go index f970726..19a6cf1 100644 --- a/vendor/github.com/jackc/pgx/v5/pgconn/doc.go +++ b/vendor/github.com/jackc/pgx/v5/pgconn/doc.go @@ -34,6 +34,18 @@ explicitly: These parameters may also be set via the PGSSLMODE, PGSSLROOTCERT, PGCHANNELBINDING, and PGREQUIREAUTH environment variables. +Client Certificates + +The sslcertmode connection parameter (or PGSSLCERTMODE environment variable) controls whether a client certificate +is sent. The default, allow, sends a certificate if the server requests one and a suitable certificate is available. +The disable mode prevents sending a certificate, including certificates supplied through Config.TLSConfig, and skips +loading sslcert and sslkey files. The require mode fails if the server successfully authenticates the client without +requesting and receiving a client certificate. It does not guarantee that the server validated the certificate. +If this check fails, no further TLS or host fallbacks are tried. +TLS session resumption is disabled in require mode so every connection exchanges a certificate. +An explicitly empty sslcertmode parameter or PGSSLCERTMODE environment variable is invalid. +This parameter is independent of sslmode, which controls TLS and server certificate verification. + Executing a Query ExecParams and ExecPrepared execute a single query. They return readers that iterate over each row. The Read method diff --git a/vendor/github.com/jackc/pgx/v5/pgconn/errors.go b/vendor/github.com/jackc/pgx/v5/pgconn/errors.go index 9fbe68c..49606e5 100644 --- a/vendor/github.com/jackc/pgx/v5/pgconn/errors.go +++ b/vendor/github.com/jackc/pgx/v5/pgconn/errors.go @@ -5,7 +5,6 @@ import ( "errors" "fmt" "net" - "net/url" "regexp" "strings" ) @@ -93,10 +92,20 @@ func (e *perDialConnectError) Unwrap() error { return e.err } +// sslCertModeError is a client-side authentication failure that must stop +// connection fallback, matching libpq's sslcertmode=require behavior. +type sslCertModeError struct { + msg string +} + +func (e *sslCertModeError) Error() string { + return e.msg +} + // ErrConnClosed is returned (possibly wrapped) when an operation is attempted // on a connection that the driver has already closed, e.g. because a prior // query was cancelled mid-flight or the underlying socket went away. Use -// errors.Is to test for it, since it shows up wrapped inside connLockError. +// errors.Is to test for it, since it is usually wrapped in another error. var ErrConnClosed = errors.New("conn closed") type connLockError struct { @@ -118,9 +127,11 @@ func (e *connLockError) Unwrap() error { return nil } -// ParseConfigError is the error returned when a connection string cannot be parsed. +// ParseConfigError is the error returned when a connection string cannot be +// parsed. Its error text masks recognizable passwords on a best-effort basis, +// but malformed input can be too ambiguous to redact completely. type ParseConfigError struct { - ConnString string // The connection string that could not be parsed. + ConnString string // The original, unredacted connection string that could not be parsed. msg string err error } @@ -134,9 +145,11 @@ func NewParseConfigError(conn, msg string, err error) error { } func (e *ParseConfigError) Error() string { - // Now that ParseConfigError is public and ConnString is available to the developer, perhaps it would be better only - // return a static string. That would ensure that the error message cannot leak a password. The ConnString field would - // allow access to the original string if desired and Unwrap would allow access to the underlying error. + // redactPW is necessarily best effort: an invalid connection string can be + // too ambiguous to identify every password. Returning only a static string + // would be the way to guarantee that Error cannot leak one. The public + // ConnString field would still allow access to the original string if + // desired, and Unwrap would allow access to the underlying error. connString := redactPW(e.ConnString) if e.err == nil { return fmt.Sprintf("cannot parse `%s`: %s", connString, e.msg) @@ -227,11 +240,12 @@ func newContextAlreadyDoneError(ctx context.Context) (err error) { return &errTimeout{&contextAlreadyDoneError{err: ctx.Err()}} } +// redactPW masks recognizable password fields on a best-effort basis. It +// cannot guarantee redaction when malformed input makes component boundaries +// ambiguous. func redactPW(connString string) string { if strings.HasPrefix(connString, "postgres://") || strings.HasPrefix(connString, "postgresql://") { - if u, err := url.Parse(connString); err == nil { - return redactURL(u) - } + return redactURLPassword(connString) } quotedKV := regexp.MustCompile(`password='[^']*'`) connString = quotedKV.ReplaceAllLiteralString(connString, "password=xxxxx") @@ -242,14 +256,164 @@ func redactPW(connString string) string { return connString } -func redactURL(u *url.URL) string { - if u == nil { - return "" +// redactURLPassword masks recognizable password values in a connection URI. +// For a URI that parses cleanly the component boundaries are certain, and +// every password position -- the userinfo password and password/sslpassword +// query values -- is reliably masked with the rest of the string left intact. +// It is also deliberately usable without a successful parse -- the strings +// that reach ParseConfigError are often exactly the ones that failed to parse +// -- but malformed syntax can make component boundaries ambiguous, so for +// such input redaction is best-effort and may over-mask. +// +// For URI shapes it recognizes, it mirrors parseURLSettings structurally +// rather than pattern-matching the raw text: the userinfo password is whatever +// follows the first ':' before the terminating '@' (found with the parser's +// lookahead), and a query value is masked when its percent-decoded key +// canonicalizes to password or sslpassword. This uses the same decoding as the +// parser, so encoded spellings like pass%77ord are caught and the whole +// recognized raw value is masked no matter what bytes it contains. +func redactURLPassword(connString string) string { + const mask = "xxxxx" + var b strings.Builder + b.Grow(len(connString)) + + p := connString + for _, prefix := range []string{"postgresql://", "postgres://"} { + if rest, ok := strings.CutPrefix(connString, prefix); ok { + b.WriteString(prefix) + p = rest + break + } } - if _, pwSet := u.User.Password(); pwSet { - u.User = url.UserPassword(u.User.Username(), "xxxxx") + + // Userinfo: same lookahead as parseURLSettings. + if i := strings.IndexAny(p, "@/"); i >= 0 && p[i] == '@' { + user, _, hasPassword := strings.Cut(p[:i], ":") + p = p[i+1:] + b.WriteString(user) + if hasPassword { + b.WriteString(":" + mask) + } + b.WriteByte('@') } - return u.String() + + // Nothing after the userinfo is a password position, but a password can + // land there in malformed URIs: an unencoded '/' or '?' in a userinfo + // password turns everything after it into path or query, stranding the + // '@' (postgres://user:pass/word?x=y@host). As a best-effort heuristic, + // while an '@' remains, mask everything shaped like + // ":candidate-credential@" across the whole + // remainder -- before the query is split off, or a stranded '@' inside + // the query would hide the pattern, and greedily up to each '@', so a + // ':' inside the stranded password (user:sec:ret@host) cannot split the + // mask and leak the part before it. + // + // The heuristic must not run when the connection string is structurally + // unambiguous: then nothing can be stranded, a remaining '@' is ordinary + // data (typically in a query value), and the greedy mask would swallow + // the '/' and '?' delimiters -- hiding the query from the password-key + // masking below, so a password=... query parameter would leak. Valid + // URIs must always redact exactly; the heuristic is reserved for + // malformed input, where only best effort is possible. + if strings.IndexByte(p, '@') >= 0 && !uriStructureUnambiguous(connString) { + brokenUserinfo := regexp.MustCompile(`:[^@]+@`) + p = brokenUserinfo.ReplaceAllLiteralString(p, ":xxxxxx@") + } + + qi := uriQueryStart(p) + if qi < 0 { + b.WriteString(p) + return b.String() + } + b.WriteString(p[:qi]) + query := p[qi+1:] + b.WriteByte('?') + + for i, pair := range strings.Split(query, "&") { + if i > 0 { + b.WriteByte('&') + } + rawKey, _, hasValue := strings.Cut(pair, "=") + if !hasValue { + b.WriteString(pair) + continue + } + switch canonicalConnStringKey(uriDecodeLenient(rawKey)) { + case "password", "sslpassword": + b.WriteString(rawKey) + b.WriteByte('=') + b.WriteString(mask) + default: + b.WriteString(pair) + } + } + return b.String() +} + +// uriStructureUnambiguous reports whether connString parses as a connection +// URI whose component boundaries are certain, meaning redactURLPassword's +// structural walk is exact and no password bytes can sit outside the two +// positions it masks (the userinfo password and password-keyed query values). +// That requires parseURLSettings to accept the string and every port element +// to be numeric or empty: the parser accepts arbitrary text in the port slot +// (postgres://a@u:sec:ret@h parses with port "sec:ret@h"), so a non-numeric +// port may be a mislaid password and keeps the string in best-effort +// territory. +func uriStructureUnambiguous(connString string) bool { + settings, _, err := parseURLSettings(connString) + if err != nil { + return false + } + for part := range strings.SplitSeq(settings["port"], ",") { + for i := 0; i < len(part); i++ { + if part[i] < '0' || part[i] > '9' { + return false + } + } + } + return true +} + +// uriQueryStart returns the index of the '?' that begins the query component +// of p (the post-scheme, post-userinfo part of a connection URI), or -1 if +// there is none. It follows parseURLSettings' structure: '[' at the start of +// a netloc element opens an IPv6 bracket whose contents -- deliberately +// unvalidated -- may contain a literal '?' that is host data, not the query +// delimiter. On an unterminated bracket (the parser errors there) it falls +// back to the first '?' anywhere. With no valid structure to follow, +// over-including text gives the best-effort redactor more candidate pairs to +// inspect. +func uriQueryStart(p string) int { + i := 0 + for { + if i < len(p) && p[i] == '[' { + end := strings.IndexByte(p[i:], ']') + if end < 0 { + return strings.IndexByte(p, '?') + } + i += end + 1 + } + // Host and port data: everything up to a '/', '?', or ','. + for i < len(p) && p[i] != '/' && p[i] != '?' && p[i] != ',' { + i++ + } + if i < len(p) && p[i] == ',' { + i++ + continue + } + break + } + if i == len(p) { + return -1 + } + if p[i] == '?' { + return i + } + // p[i] == '/': a path follows; the first '?' after it starts the query. + if j := strings.IndexByte(p[i:], '?'); j >= 0 { + return i + j + } + return -1 } type NotPreferredError struct { diff --git a/vendor/github.com/jackc/pgx/v5/pgconn/gen_saslprep_unassigned.py b/vendor/github.com/jackc/pgx/v5/pgconn/gen_saslprep_unassigned.py new file mode 100644 index 0000000..8de2361 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgconn/gen_saslprep_unassigned.py @@ -0,0 +1,52 @@ +"""Generate RFC 3454 table A.1 using Python's fixed Unicode 3.2 database. + +Run from this directory with: python3 gen_saslprep_unassigned.py +Only the Python standard library is needed; no network access is required. +""" + +from pathlib import Path +import stringprep +from unicodedata import ucd_3_2_0 + +assert ucd_3_2_0.unidata_version == "3.2.0" + + +def ranges(start, stop): + first = None + for code in range(start, stop): + if stringprep.in_table_a1(chr(code)): + if first is None: + first = code + elif first is not None: + yield first, code - 1 + first = None + if first is not None: + yield first, stop - 1 + + +lines = [ + "// Code generated by gen_saslprep_unassigned.py; DO NOT EDIT.", + "", + "package pgconn", + "", + 'import "unicode"', + "", + "//go:generate python3 gen_saslprep_unassigned.py", + "", + "// saslprepUnassigned is RFC 3454 table A.1: code points unassigned in", + "// Unicode 3.2. This table must not track the Go toolchain's Unicode version.", + "// https://www.rfc-editor.org/rfc/rfc3454#appendix-A.1", + "var saslprepUnassigned = &unicode.RangeTable{", +] +for name, width, start, stop in [ + ("R16", 16, 0, 0x10000), + ("R32", 32, 0x10000, 0x110000), +]: + lines.append(f"\t{name}: []unicode.Range{width}{{") + for first, last in ranges(start, stop): + lines.append(f"\t\t{{0x{first:04x}, 0x{last:04x}, 1}},") + lines.append("\t},") +lines.extend(["}", ""]) +Path(__file__).with_name("saslprep_unassigned.go").write_text( + "\n".join(lines), encoding="utf-8" +) diff --git a/vendor/github.com/jackc/pgx/v5/pgconn/internal/bgreader/bgreader.go b/vendor/github.com/jackc/pgx/v5/pgconn/internal/bgreader/bgreader.go index e65c2c2..6f2002d 100644 --- a/vendor/github.com/jackc/pgx/v5/pgconn/internal/bgreader/bgreader.go +++ b/vendor/github.com/jackc/pgx/v5/pgconn/internal/bgreader/bgreader.go @@ -2,7 +2,9 @@ package bgreader import ( + "errors" "io" + "net" "sync" "github.com/jackc/pgx/v5/internal/iobufpool" @@ -76,7 +78,18 @@ func (r *BGReader) bgRead() { *buf = (*buf)[:n] r.cond.L.Lock() - r.readResults = append(r.readResults, readResult{buf: buf, err: err}) + // A timeout belongs to the deadline that was in effect for this read, not to the data stream. It is not buffered + // because a later Read could receive it after the deadline has already been cleared. The background reader stops + // instead and the next Read goes to the underlying reader, which returns a fresh timeout if the deadline is still + // in effect. + switch { + case !isTimeout(err): + r.readResults = append(r.readResults, readResult{buf: buf, err: err}) + case n > 0: + r.readResults = append(r.readResults, readResult{buf: buf}) + default: + iobufpool.Put(buf) + } if r.status == StatusStopping || err != nil { r.status = StatusStopped keepReading = false @@ -91,20 +104,22 @@ func (r *BGReader) Read(p []byte) (int, error) { r.cond.L.Lock() defer r.cond.L.Unlock() + // Wait for results from the background reader + for len(r.readResults) == 0 && r.status != StatusStopped { + r.cond.Wait() + } + if len(r.readResults) > 0 { return r.readFromReadResults(p) } // There are no unread background read results and the background reader is stopped. - if r.status == StatusStopped { - return r.r.Read(p) - } + return r.r.Read(p) +} - // Wait for results from the background reader - for len(r.readResults) == 0 { - r.cond.Wait() - } - return r.readFromReadResults(p) +func isTimeout(err error) bool { + var netErr net.Error + return errors.As(err, &netErr) && netErr.Timeout() } // readBackgroundResults reads a result previously read by the background reader. r.cond.L must be held. diff --git a/vendor/github.com/jackc/pgx/v5/pgconn/parse_url.go b/vendor/github.com/jackc/pgx/v5/pgconn/parse_url.go new file mode 100644 index 0000000..3cc8d91 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgconn/parse_url.go @@ -0,0 +1,397 @@ +package pgconn + +import ( + "errors" + "fmt" + "maps" + "strings" +) + +// This file parses PostgreSQL connection URIs using a parser designed to +// exactly match libpq's URI parser behavior (conninfo_uri_parse_options, +// conninfo_uri_parse_params, and conninfo_uri_decode in +// src/interfaces/libpq/fe-connect.c), so that pgx accepts and rejects exactly +// the same URIs as libpq, including libpq's multiple-host extension +// (postgresql://host1:port1,host2:port2/db), which is not valid RFC 3986 syntax. +// +// Deliberate differences from libpq: +// +// - Query parameters that libpq does not recognize are accepted. They become +// runtime parameters or pgx-specific options (e.g. pool_max_conns) instead +// of failing the parse. +// - Error messages avoid quoting the unredacted connection string and mask +// recognizable password fields on a best-effort basis. Invalid connection +// strings can be structurally ambiguous, so password redaction cannot be +// guaranteed for every malformed input. libpq quotes the failing input +// verbatim, which can leak a password into error messages and logs. +// - Literal NUL bytes are rejected. libpq never sees them because C strings +// end at the first NUL; a Go string can carry one into the startup packet, +// where it would act as a protocol delimiter and inject extra parameters. + +// parseURLMeta reports provenance facts about a parsed URI that +// ParseConfigWithOptions needs for ConnStringAllowedKeys validation and that +// cannot be recovered from the settings map itself. +type parseURLMeta struct { + // impliedEmptyPortList: the "port" entry is an all-empty list synthesized + // from the host list (postgres://h1,h2 yields port=",") with no port + // bytes supplied by the user. Determined from the raw port syntax, not + // the decoded value: a port of literal spaces (postgres://h: /db) + // decodes to empty but was user-supplied. + impliedEmptyPortList bool + // sawRawSSLKey / sawSSLTrueAlias / sawExplicitSSLModeKey record which + // spellings of the ssl and sslmode query keys appeared anywhere in the + // URI -- including occurrences later superseded under last-occurrence- + // wins. The ssl=true alias rewrite and ordinary repeated-key handling can + // remove those occurrences from the final settings map, so + // ConnStringAllowedKeys cannot fail closed from that map alone; it must see + // every key the user actually wrote. + sawRawSSLKey bool // key "ssl" with a value other than "true" + sawSSLTrueAlias bool // key "ssl" with value "true" (stored as sslmode=require) + sawExplicitSSLModeKey bool // key "sslmode" +} + +// parseURLSettings parses a connection URI into a settings map. connString +// must start with "postgres://" or "postgresql://". +// +// Multiple hosts are represented in the returned map the same way libpq +// represents them internally: settings["host"] and settings["port"] are +// comma-separated lists that are positionally aligned, with empty elements +// meaning "use the default". The lists are split in ParseConfigWithOptions. +func parseURLSettings(connString string) (settings map[string]string, meta parseURLMeta, err error) { + settings = make(map[string]string) + + if strings.IndexByte(connString, 0) >= 0 { + return nil, meta, errors.New("forbidden NUL byte in connection string") + } + + p, ok := strings.CutPrefix(connString, "postgresql://") + if !ok { + p, ok = strings.CutPrefix(connString, "postgres://") + } + if !ok { + return nil, meta, errors.New("invalid URI propagated to internal parser routine") + } + + // Look ahead for a possible user credentials designator. Like libpq, only + // a '/' stops the search, so a '@' anywhere before the path -- even inside + // what looks like a query string -- is treated as the userinfo terminator. + if i := strings.IndexAny(p, "@/"); i >= 0 && p[i] == '@' { + user, password, hasPassword := strings.Cut(p[:i], ":") + p = p[i+1:] + if user != "" { + val, err := uriDecode(user, "") + if err != nil { + return nil, meta, err + } + settings["user"] = val + } + if hasPassword && password != "" { + val, err := uriDecode(password, "password") + if err != nil { + return nil, meta, err + } + settings["password"] = val + } + } + + // Parse the comma-separated list of netloc[:port] specifications. Hosts + // and ports accumulate into positionally aligned comma-joined lists: every + // separator appends a comma to both, so postgres://h1,h2:5433 yields + // host="h1,h2" port=",5433". + var hostBuf, portBuf strings.Builder + + for { + if peekByte(p) == '[' { + // IPv6 address. The bracket contents are not validated, matching libpq. + end := strings.IndexByte(p, ']') + if end < 0 { + return nil, meta, errors.New(`end of string reached when looking for matching "]" in IPv6 host address in URI`) + } + if end == 1 { + return nil, meta, errors.New("IPv6 host address may not be empty in URI") + } + hostBuf.WriteString(p[1:end]) + p = p[end+1:] + if c := peekByte(p); c != 0 && c != ':' && c != '/' && c != '?' && c != ',' { + return nil, meta, fmt.Errorf(`unexpected character "%c" at position %d in URI (expected ":" or "/")`, c, len(connString)-len(p)+1) + } + } else { + // DNS-named or IPv4 netloc: everything up to a ':', '/', '?', or ','. + i := strings.IndexAny(p, ":/?,") + if i < 0 { + i = len(p) + } + hostBuf.WriteString(p[:i]) + p = p[i:] + } + + if peekByte(p) == ':' { + p = p[1:] + i := strings.IndexAny(p, "/?,") + if i < 0 { + i = len(p) + } + portBuf.WriteString(p[:i]) + p = p[i:] + } + + if peekByte(p) != ',' { + break + } + p = p[1:] + hostBuf.WriteByte(',') + portBuf.WriteByte(',') + } + + // The joined lists are percent-decoded as a unit, after joining. This + // means %2C decodes to a comma that later splits like a real separator -- + // a host name containing a literal comma is inexpressible, as in libpq. + if hostBuf.Len() > 0 { + hostList, err := uriDecode(hostBuf.String(), "") + if err != nil { + return nil, meta, err + } + settings["host"] = hostList + } + // Like libpq, the port list is stored even when every element is empty + // (postgres://h1,h2 yields port=","). This matters: a connection string + // port shadows PGPORT during settings merge, so with PGPORT=1,2 a + // three-host URI without ports must use the default port for every host, + // not fail the port/host count check. Such an implied all-empty list + // carries no user-supplied port text, which is what + // meta.impliedEmptyPortList reports -- judged on the raw bytes, before + // percent-decoding trims spaces, so a port the user actually typed never + // counts as implied even when it decodes to empty. + if portBuf.Len() > 0 { + meta.impliedEmptyPortList = strings.Trim(portBuf.String(), ",") == "" + portList, err := uriDecode(portBuf.String(), "") + if err != nil { + return nil, meta, err + } + settings["port"] = portList + } + + if peekByte(p) == '/' { + p = p[1:] + dbname := p + p = "" + if i := strings.IndexByte(dbname, '?'); i >= 0 { + p = dbname[i:] + dbname = dbname[:i] + } + // Like libpq, an empty path component leaves dbname unset so the + // default stays in effect. + if dbname != "" { + val, err := uriDecode(dbname, "") + if err != nil { + return nil, meta, err + } + settings["database"] = val + } + } + + if peekByte(p) == '?' { + // Query parameters land in their own map first: an explicit ?port= + // overrides the netloc-derived port list and is user-supplied port + // text, so it cancels the implied-list exemption even when its value + // is empty. + query := make(map[string]string) + if err := parseURLQueryParams(p[1:], query, &meta); err != nil { + return nil, meta, err + } + if _, ok := query["port"]; ok { + meta.impliedEmptyPortList = false + } + maps.Copy(settings, query) + } + + return settings, meta, nil +} + +// peekByte returns the first byte of s, or 0 if s is empty. A NUL byte is a +// safe end-of-input sentinel because parseURLSettings rejects literal NULs. +func peekByte(s string) byte { + if len(s) == 0 { + return 0 + } + return s[0] +} + +// parseURLQueryParams parses the query part of a connection URI into settings, +// mirroring libpq's conninfo_uri_parse_params: '&'-separated pairs, exactly +// one raw '=' per pair, both halves percent-decoded, last occurrence wins. It +// records in meta which spellings of the ssl/sslmode keys it saw (see +// parseURLMeta). +func parseURLQueryParams(params string, settings map[string]string, meta *parseURLMeta) error { + // sslWasLast records whether ssl or sslmode was encountered most recently. + // This matters if the final repeated ssl value is "true": the alias wins + // only when it occurs after the final explicit sslmode. + sslWasLast := false + + for params != "" { + pair := params + if i := strings.IndexByte(params, '&'); i >= 0 { + pair = params[:i] + params = params[i+1:] + } else { + params = "" + } + + rawKey, rawValue, found := strings.Cut(pair, "=") + if !found { + return fmt.Errorf(`missing key/value separator "=" in URI query parameter: "%s"`, rawKey) + } + if strings.IndexByte(rawValue, '=') >= 0 { + return fmt.Errorf(`extra key/value separator "=" in URI query parameter: "%s"`, rawKey) + } + + key, err := uriDecode(rawKey, "") + if err != nil { + return err + } + key = canonicalConnStringKey(key) + + secretName := "" + if key == "password" || key == "sslpassword" { + secretName = key + } + value, err := uriDecode(rawValue, secretName) + if err != nil { + return err + } + + // Resolve repeated ssl values under their raw key before applying the + // JDBC compatibility alias. Otherwise ssl=true would overwrite an + // independent explicit sslmode that must reappear if a later ssl value + // supersedes the alias. The alias is URI-only and applies only to the + // literal value "true". + switch key { + case "ssl": + sslWasLast = true + if value == "true" { + meta.sawSSLTrueAlias = true + } else { + meta.sawRawSSLKey = true + } + case "sslmode": + sslWasLast = false + meta.sawExplicitSSLModeKey = true + } + + settings[key] = value + } + + if value, ok := settings["ssl"]; ok && value == "true" { + delete(settings, "ssl") + if sslWasLast { + settings["sslmode"] = "require" + } + } + + return nil +} + +// uriDecode percent-decodes a URI component with the same rules as libpq's +// conninfo_uri_decode: '%' followed by exactly two case-insensitive hex +// digits, %00 forbidden, leading and trailing ASCII spaces skipped, interior +// spaces rejected. Decoded bytes are emitted raw with no character set +// validation. +// +// If secretName is non-empty, error messages identify that component by name +// instead of quoting its raw value. This prevents the known component's raw +// contents from being copied into the decode error; it does not make the +// separate, best-effort redaction of an invalid connection string complete. +func uriDecode(raw, secretName string) (string, error) { + // The component may be a secret; every error must be built by fail so the + // quote-the-raw-value-or-not redaction decision lives in exactly one place. + fail := func(secretFormat, publicFormat string) (string, error) { + if secretName != "" { + return "", fmt.Errorf(secretFormat, secretName) + } + return "", fmt.Errorf(publicFormat, raw) + } + + var b strings.Builder + b.Grow(len(raw)) + + i := 0 + for i < len(raw) && raw[i] == ' ' { + i++ + } + for i < len(raw) && raw[i] != ' ' { + if raw[i] != '%' { + b.WriteByte(raw[i]) + i++ + continue + } + + var hi, lo byte + var ok1, ok2 bool + if i+1 < len(raw) { + hi, ok1 = hexDigit(raw[i+1]) + } + if i+2 < len(raw) { + lo, ok2 = hexDigit(raw[i+2]) + } + if !ok1 || !ok2 { + return fail("invalid percent-encoded token in %s", `invalid percent-encoded token: "%s"`) + } + + c := hi<<4 | lo + if c == 0 { + return fail("forbidden value %%00 in percent-encoded value in %s", `forbidden value %%00 in percent-encoded value: "%s"`) + } + b.WriteByte(c) + i += 3 + } + for i < len(raw) && raw[i] == ' ' { + i++ + } + if i < len(raw) { + return fail("unexpected spaces found in %s, use percent-encoded spaces (%%20) instead", `unexpected spaces found in "%s", use percent-encoded spaces (%%20) instead`) + } + + return b.String(), nil +} + +// uriDecodeLenient is a non-failing variant of uriDecode used for best-effort +// redaction: valid percent-encodings are decoded, anything uriDecode would +// reject passes through unchanged. Redaction processing itself must not fail, +// and it must see the same key spelling the parser would (pass%77ord decodes +// to password), so encoded password keys are recognized even in connection +// strings that do not parse. This helps recognize keys but cannot make +// redaction complete when malformed input has ambiguous component boundaries. +func uriDecodeLenient(raw string) string { + raw = strings.Trim(raw, " ") + + var b strings.Builder + b.Grow(len(raw)) + + for i := 0; i < len(raw); { + if raw[i] == '%' && i+2 < len(raw) { + hi, ok1 := hexDigit(raw[i+1]) + lo, ok2 := hexDigit(raw[i+2]) + if ok1 && ok2 { + b.WriteByte(hi<<4 | lo) + i += 3 + continue + } + } + b.WriteByte(raw[i]) + i++ + } + + return b.String() +} + +func hexDigit(c byte) (byte, bool) { + switch { + case c >= '0' && c <= '9': + return c - '0', true + case c >= 'A' && c <= 'F': + return c - 'A' + 10, true + case c >= 'a' && c <= 'f': + return c - 'a' + 10, true + } + return 0, false +} diff --git a/vendor/github.com/jackc/pgx/v5/pgconn/pgconn.go b/vendor/github.com/jackc/pgx/v5/pgconn/pgconn.go index d181f7f..6e5bcee 100644 --- a/vendor/github.com/jackc/pgx/v5/pgconn/pgconn.go +++ b/vendor/github.com/jackc/pgx/v5/pgconn/pgconn.go @@ -13,6 +13,7 @@ import ( "maps" "math" "net" + "slices" "strconv" "strings" "sync" @@ -146,6 +147,13 @@ func ConnectConfig(ctx context.Context, config *Config) (*PgConn, error) { panic("config must be created by ParseConfig") } + // Config may have been modified after ParseConfig. Validate before resolving hosts. + if config.SSLCertMode != "" { + if _, err := parseSSLCertMode(config.SSLCertMode); err != nil { + return nil, &ConnectError{Config: config, err: fmt.Errorf("invalid sslcertmode: %w", err)} + } + } + var allErrors []error connectConfigs, errs := buildConnectOneConfigs(ctx, config) @@ -269,6 +277,11 @@ func connectPreferred(ctx context.Context, config *Config, connectOneConfigs []* allErrors = append(allErrors, err) + var sslCertErr *sslCertModeError + if errors.As(err, &sslCertErr) { + return nil, allErrors + } + var pgErr *PgError if errors.As(err, &pgErr) { // pgx will try next host even if libpq does not in certain cases (see #2246) @@ -340,7 +353,10 @@ func connectOne(ctx context.Context, config *Config, connectConfig *connectOneCo return nil, newPerDialConnectError("dial error", err) } + var sslCert *sslCertState if connectConfig.tlsConfig != nil { + tlsConfig, state := config.prepareTLSConfigForConnect(connectConfig.tlsConfig) + sslCert = state pgConn.contextWatcher = ctxwatch.NewContextWatcher(&DeadlineContextWatcherHandler{Conn: pgConn.conn}) pgConn.contextWatcher.Watch(ctx) var ( @@ -348,9 +364,9 @@ func connectOne(ctx context.Context, config *Config, connectConfig *connectOneCo err error ) if config.SSLNegotiation == "direct" { - tlsConn = tls.Client(pgConn.conn, connectConfig.tlsConfig) + tlsConn = tls.Client(pgConn.conn, tlsConfig) } else { - tlsConn, err = startTLS(pgConn.conn, connectConfig.tlsConfig) + tlsConn, err = startTLS(pgConn.conn, tlsConfig) } pgConn.contextWatcher.Unwatch() // Always unwatch `netConn` after TLS. if err != nil { @@ -392,6 +408,9 @@ func connectOne(ctx context.Context, config *Config, connectConfig *connectOneCo pgConn.slowWriteTimer.Stop() pgConn.bgReaderStarted = make(chan struct{}) pgConn.frontend = config.BuildFrontend(pgConn.bgReader, pgConn.conn) + if config.MaxProtocolMessageBodyLen > 0 { + pgConn.frontend.SetMaxBodyLen(config.MaxProtocolMessageBodyLen) + } startupMsg := pgproto3.StartupMessage{ ProtocolVersion: maxProtocolVersion, @@ -426,6 +445,12 @@ func connectOne(ctx context.Context, config *Config, connectConfig *connectOneCo return nil, newPerDialConnectError("require_auth check failed", err) } clientFinishedAuth := false + authenticationAccepted := false + channelBound := false + channelBindingFail := func() (*PgConn, error) { + pgConn.conn.Close() + return nil, newPerDialConnectError("channel binding check failed", errors.New("channel binding required but server did not authenticate using channel binding")) + } for { msg, err := pgConn.receiveMessage() @@ -437,15 +462,33 @@ func connectOne(ctx context.Context, config *Config, connectConfig *connectOneCo return nil, newPerDialConnectError("failed to receive message", err) } + if config.ChannelBinding == "require" { + switch msg.(type) { + case *pgproto3.AuthenticationCleartextPassword, *pgproto3.AuthenticationMD5Password, *pgproto3.AuthenticationGSS: + // Reject incompatible methods before sending credentials. + return channelBindingFail() + } + } + switch msg := msg.(type) { case *pgproto3.BackendKeyData: pgConn.pid = msg.ProcessID pgConn.secretKey = msg.SecretKey case *pgproto3.AuthenticationOk: + if config.SSLCertMode == "require" { + if err := sslCert.checkRequired(); err != nil { + pgConn.conn.Close() + return nil, newPerDialConnectError("sslcertmode check failed", err) + } + } + if config.ChannelBinding == "require" && !channelBound { + return channelBindingFail() + } if requireAuthPolicy.authRequired && !clientFinishedAuth { return requireAuthFail(requireAuthPolicy.check(authMethodNone)) } + authenticationAccepted = true case *pgproto3.AuthenticationCleartextPassword: if err := requireAuthPolicy.check(authMethodPassword); err != nil { return requireAuthFail(err) @@ -469,15 +512,12 @@ func connectOne(ctx context.Context, config *Config, connectConfig *connectOneCo clientFinishedAuth = true case *pgproto3.AuthenticationSASL: // Check if OAUTHBEARER is supported - serverSupportsOAuthBearer := false - for _, mech := range msg.AuthMechanisms { - if mech == "OAUTHBEARER" { - serverSupportsOAuthBearer = true - break - } - } + serverSupportsOAuthBearer := slices.Contains(msg.AuthMechanisms, "OAUTHBEARER") if serverSupportsOAuthBearer && pgConn.config.OAuthTokenProvider != nil { + if config.ChannelBinding == "require" { + return channelBindingFail() + } if err := requireAuthPolicy.check(authMethodOAuth); err != nil { return requireAuthFail(err) } @@ -486,7 +526,7 @@ func connectOne(ctx context.Context, config *Config, connectConfig *connectOneCo if err := requireAuthPolicy.check(authMethodSCRAMSHA256); err != nil { return requireAuthFail(err) } - err = pgConn.scramAuth(msg.AuthMechanisms) + channelBound, err = pgConn.scramAuth(msg.AuthMechanisms) } if err != nil { pgConn.conn.Close() @@ -504,6 +544,20 @@ func connectOne(ctx context.Context, config *Config, connectConfig *connectOneCo } clientFinishedAuth = true case *pgproto3.ReadyForQuery: + // Preserve terminal sslcertmode failures even for malformed startup + // sequences that omit AuthenticationOk. + if config.SSLCertMode == "require" { + if err := sslCert.checkRequired(); err != nil { + pgConn.conn.Close() + return nil, newPerDialConnectError("sslcertmode check failed", err) + } + } + // AuthenticationOk must have passed all completion-policy checks before + // exposing the connection to ValidateConnect or the caller. + if !authenticationAccepted { + pgConn.conn.Close() + return nil, newPerDialConnectError("protocol error", errors.New("received ReadyForQuery before AuthenticationOk")) + } pgConn.status = connStatusIdle // The connect-phase deadline-only watcher is no longer needed; replace // it with the application-supplied watcher so subsequent operations @@ -574,10 +628,10 @@ func (pgConn *PgConn) signalMessage() chan struct{} { panic("BUG: signalMessage when already in progress") } + ch := make(chan struct{}) pgConn.bufferingReceive = true pgConn.bufferingReceiveMux.Lock() - ch := make(chan struct{}) go func() { pgConn.bufferingReceiveMsg, pgConn.bufferingReceiveErr = pgConn.frontend.Receive() pgConn.bufferingReceiveMux.Unlock() @@ -663,7 +717,9 @@ func (pgConn *PgConn) peekMessage() (pgproto3.BackendMessage, error) { // receiveMessage receives a message without setting up context cancellation func (pgConn *PgConn) receiveMessage() (pgproto3.BackendMessage, error) { if pgConn.status == connStatusClosed { - return nil, &connLockError{status: "conn closed"} + // The connection was closed by a failure earlier in this operation, after a request may already have been sent. + // Unlike a lock failure this is not safe to retry. + return nil, &pgconnError{err: ErrConnClosed, safeToRetry: false} } msg, err := pgConn.peekMessage() @@ -680,6 +736,10 @@ func (pgConn *PgConn) receiveMessage() (pgproto3.BackendMessage, error) { case *pgproto3.ErrorResponse: err := ErrorResponseToPgError(msg) if pgConn.config.OnPgError != nil && !pgConn.config.OnPgError(pgConn, err) { + // The callback may have already closed the connection. + if pgConn.status == connStatusClosed { + return nil, err + } pgConn.status = connStatusClosed pgConn.conn.Close() // Ignore error as the connection is already broken and there is already an error to return. close(pgConn.cleanupDone) @@ -768,11 +828,12 @@ func (pgConn *PgConn) Close(ctx context.Context) error { } // asyncClose marks the connection as closed and asynchronously sends a cancel query message and closes the underlying -// connection. +// connection. The cancel query message is not sent if the connection is still starting up, as no query can be running. func (pgConn *PgConn) asyncClose() { if pgConn.status == connStatusClosed { return } + sendCancelRequest := pgConn.status != connStatusConnecting pgConn.status = connStatusClosed go func() { @@ -784,12 +845,24 @@ func (pgConn *PgConn) asyncClose() { ctx, cancel := context.WithDeadline(context.Background(), deadline) defer cancel() - pgConn.CancelRequest(ctx) + if sendCancelRequest { + pgConn.CancelRequest(ctx) + } pgConn.conn.SetDeadline(deadline) pgConn.frontend.Send(&pgproto3.Terminate{}) pgConn.flushWithPotentialWriteReadDeadlock() + + // Drain any data already in flight from the server (DataRows that were sent before the + // CancelRequest landed, the resulting ErrorResponse, ReadyForQuery, and finally the server's + // own close after it processes Terminate). Closing a TCP socket while unread data remains in + // the kernel receive buffer causes the OS to send RST instead of FIN, which surfaces on the + // server or proxy as "connection reset by peer". The deadline set above bounds how long this + // will block; on timeout we fall through to Close() and accept the abortive close. + // + // See https://github.com/jackc/pgx/issues/2584 + io.Copy(io.Discard, pgConn.conn) }() } @@ -969,7 +1042,7 @@ func (pgConn *PgConn) Prepare(ctx context.Context, name, sql string, paramOIDs [ err := pgConn.flushWithPotentialWriteReadDeadlock() if err != nil { pgConn.asyncClose() - return nil, err + return nil, normalizeTimeoutError(ctx, err) } psd := &StatementDescription{Name: name, SQL: sql} @@ -1034,7 +1107,7 @@ func (pgConn *PgConn) Deallocate(ctx context.Context, name string) error { err := pgConn.flushWithPotentialWriteReadDeadlock() if err != nil { pgConn.asyncClose() - return err + return normalizeTimeoutError(ctx, err) } for { @@ -1128,11 +1201,13 @@ func (pgConn *PgConn) CancelRequest(ctx context.Context) error { // cancel connection. The legacy unencrypted path is still used when the primary connection is // plaintext (e.g. unix sockets or sslmode=disable). if pgConn.tlsConfig != nil { + // Cancel requests have no AuthenticationOk, so only the prepared TLS config is needed. + tlsConfig, _ := pgConn.config.prepareTLSConfigForConnect(pgConn.tlsConfig) var tlsCancelConn net.Conn if pgConn.config.SSLNegotiation == "direct" { - tlsCancelConn = tls.Client(cancelConn, pgConn.tlsConfig) + tlsCancelConn = tls.Client(cancelConn, tlsConfig) } else { - tlsCancelConn, err = startTLS(cancelConn, pgConn.tlsConfig) + tlsCancelConn, err = startTLS(cancelConn, tlsConfig) if err != nil { return fmt.Errorf("tls error on cancel connection: %w", err) } @@ -1225,7 +1300,7 @@ func (pgConn *PgConn) Exec(ctx context.Context, sql string) *MultiResultReader { pgConn.asyncClose() pgConn.contextWatcher.Unwatch() multiResult.closed = true - multiResult.err = err + multiResult.err = normalizeTimeoutError(ctx, err) pgConn.unlock() return multiResult } @@ -1295,7 +1370,9 @@ func (pgConn *PgConn) ExecPrepared(ctx context.Context, stmtName string, paramVa // // This differs from [PgConn.ExecPrepared] in that it takes a [*StatementDescription] instead of the prepared statement name. // Because it has the [*StatementDescription] it can avoid the Describe Portal message that [PgConn.ExecPrepared] must send to get -// the result column descriptions. +// the result column descriptions. However, if the statement description has no fields then a Describe is still sent, as +// an empty Fields may mean the results were not knowable at prepare time, e.g. a FETCH from a cursor that did not exist +// yet. // // paramValues are the parameter values. It must be encoded in the format given by paramFormats. // @@ -1356,7 +1433,10 @@ func (pgConn *PgConn) execExtendedPrefix(ctx context.Context, paramValues [][]by } func (pgConn *PgConn) execExtendedSuffix(result *ResultReader, statementDescription *StatementDescription, resultFormats []int16) { - if statementDescription == nil { + if statementDescription == nil || len(statementDescription.Fields) == 0 { + // The cached field descriptions are missing or empty. Empty field descriptions can occur when the statement's + // result set was not known at prepare time, e.g. a FETCH from a cursor that did not exist yet. Send a Describe + // so the server supplies the actual row description when the statement is executed. pgConn.frontend.SendDescribe(&pgproto3.Describe{ObjectType: 'P'}) } pgConn.frontend.SendExecute(&pgproto3.Execute{}) @@ -1365,7 +1445,7 @@ func (pgConn *PgConn) execExtendedSuffix(result *ResultReader, statementDescript err := pgConn.flushWithPotentialWriteReadDeadlock() if err != nil { pgConn.asyncClose() - result.concludeCommand(CommandTag{}, err) + result.concludeCommand(CommandTag{}, normalizeTimeoutError(result.ctx, err)) pgConn.contextWatcher.Unwatch() result.closed = true pgConn.unlock() @@ -1399,7 +1479,7 @@ func (pgConn *PgConn) CopyTo(ctx context.Context, w io.Writer, sql string) (Comm if err != nil { pgConn.asyncClose() pgConn.unlock() - return CommandTag{}, err + return CommandTag{}, normalizeTimeoutError(ctx, err) } // Read results @@ -1456,7 +1536,7 @@ func (pgConn *PgConn) CopyFrom(ctx context.Context, r io.Reader, sql string) (Co err := pgConn.flushWithPotentialWriteReadDeadlock() if err != nil { pgConn.asyncClose() - return CommandTag{}, err + return CommandTag{}, normalizeTimeoutError(ctx, err) } // Send copy data @@ -1542,7 +1622,7 @@ func (pgConn *PgConn) CopyFrom(ctx context.Context, r io.Reader, sql string) (Co err = pgConn.flushWithPotentialWriteReadDeadlock() if err != nil { pgConn.asyncClose() - return CommandTag{}, err + return CommandTag{}, normalizeTimeoutError(ctx, err) } // Read results @@ -1572,10 +1652,15 @@ type MultiResultReader struct { rr *ResultReader - // Data from when the batch was queued. + // Data from when the batch was queued. There is one entry per command in the batch. Entries are nil for commands + // other than Batch.ExecStatement, which is the only command that does not request a RowDescription from the server. statementDescriptions []*StatementDescription resultFormats [][]int16 + // Statement data for the command currently being processed. Popped from the queues above at each BindComplete. + currentStatementDescription *StatementDescription + currentResultFormats []int16 + closed bool err error } @@ -1619,19 +1704,19 @@ func (mrr *MultiResultReader) NextResult() bool { for !mrr.closed && mrr.err == nil { msg, _ := mrr.pgConn.peekMessage() if _, ok := msg.(*pgproto3.DataRow); ok { - if len(mrr.statementDescriptions) > 0 { + if sd := mrr.currentStatementDescription; sd != nil { rr := ResultReader{ pgConn: mrr.pgConn, multiResultReader: mrr, ctx: mrr.ctx, } - // This result corresponds to a prepared statement description that was provided when queuing the batch. - sd := mrr.statementDescriptions[0] - mrr.statementDescriptions = mrr.statementDescriptions[1:] - - resultFormats := mrr.resultFormats[0] - mrr.resultFormats = mrr.resultFormats[1:] + // This result corresponds to a Batch.ExecStatement command. No RowDescription was requested from the + // server so the field descriptions come from the statement description that was provided when queuing + // the batch. + resultFormats := mrr.currentResultFormats + mrr.currentStatementDescription = nil + mrr.currentResultFormats = nil sdFields := sd.Fields rr.fieldDescriptions = rr.pgConn.getFieldDescriptionSlice(len(sdFields)) @@ -1656,7 +1741,24 @@ func (mrr *MultiResultReader) NextResult() bool { } switch msg := msg.(type) { + case *pgproto3.BindComplete: + // Every command in a batch begins with a BindComplete. Pop this command's statement data so that the + // following messages are matched with the correct statement description. It must be popped here rather than + // when a DataRow is peeked because a command that returns no rows would otherwise leave its entry in the + // queue, misaligning the statement descriptions for all subsequent commands. + if len(mrr.statementDescriptions) > 0 { + mrr.currentStatementDescription = mrr.statementDescriptions[0] + mrr.statementDescriptions = mrr.statementDescriptions[1:] + mrr.currentResultFormats = mrr.resultFormats[0] + mrr.resultFormats = mrr.resultFormats[1:] + } else { + mrr.currentStatementDescription = nil + mrr.currentResultFormats = nil + } case *pgproto3.RowDescription: + mrr.currentStatementDescription = nil + mrr.currentResultFormats = nil + mrr.pgConn.resultReader = ResultReader{ pgConn: mrr.pgConn, multiResultReader: mrr, @@ -1668,11 +1770,25 @@ func (mrr *MultiResultReader) NextResult() bool { mrr.rr = &mrr.pgConn.resultReader return true case *pgproto3.CommandComplete: - mrr.pgConn.resultReader = ResultReader{ + rr := ResultReader{ commandTag: mrr.pgConn.makeCommandTag(msg.CommandTag), commandConcluded: true, closed: true, } + + if sd := mrr.currentStatementDescription; sd != nil { + // A Batch.ExecStatement command that returned no rows. Attach the field descriptions from the statement + // description so the result reports its columns the same as a result that was described by the server. + rr.fieldDescriptions = mrr.pgConn.getFieldDescriptionSlice(len(sd.Fields)) + err := combineFieldDescriptionsAndResultFormats(rr.fieldDescriptions, sd.Fields, mrr.currentResultFormats) + if err != nil { + rr.err = err + } + mrr.currentStatementDescription = nil + mrr.currentResultFormats = nil + } + + mrr.pgConn.resultReader = rr mrr.rr = &mrr.pgConn.resultReader return true case *pgproto3.EmptyQueryResponse: @@ -1953,6 +2069,11 @@ func (batch *Batch) ExecPrepared(stmtName string, paramValues [][]byte, paramFor return } + // The statement data queues must have one entry per command so results can be matched with the correct statement + // description. This command requests a RowDescription from the server so it queues a nil placeholder. + batch.statementDescriptions = append(batch.statementDescriptions, nil) + batch.resultFormats = append(batch.resultFormats, nil) + batch.buf, batch.err = (&pgproto3.Describe{ObjectType: 'P'}).Encode(batch.buf) if batch.err != nil { return @@ -1968,7 +2089,9 @@ func (batch *Batch) ExecPrepared(stmtName string, paramValues [][]byte, paramFor // // This differs from ExecPrepared in that it takes a *StatementDescription instead of just the prepared statement name. // Because it has the *StatementDescription it can avoid the Describe Portal message that ExecPrepared must send to get -// the result column descriptions. +// the result column descriptions. However, if the statement description has no fields then a Describe is still sent, as +// an empty Fields may mean the results were not knowable at prepare time, e.g. a FETCH from a cursor that did not exist +// yet. func (batch *Batch) ExecStatement(statementDescription *StatementDescription, paramValues [][]byte, paramFormats, resultFormats []int16) { if batch.err != nil { return @@ -1979,6 +2102,16 @@ func (batch *Batch) ExecStatement(statementDescription *StatementDescription, pa return } + if len(statementDescription.Fields) == 0 { + // The cached field descriptions are empty, which can occur when the statement's result set was not known at + // prepare time, e.g. a FETCH from a cursor that did not exist yet. Send a Describe so the server supplies the + // actual row description when the statement is executed. + batch.buf, batch.err = (&pgproto3.Describe{ObjectType: 'P'}).Encode(batch.buf) + if batch.err != nil { + return + } + } + batch.statementDescriptions = append(batch.statementDescriptions, statementDescription) batch.resultFormats = append(batch.resultFormats, resultFormats) @@ -2242,6 +2375,9 @@ func Construct(hc *HijackedConn) (*PgConn, error) { pgConn.slowWriteTimer.Stop() pgConn.bgReaderStarted = make(chan struct{}) pgConn.frontend = hc.Config.BuildFrontend(pgConn.bgReader, pgConn.conn) + if hc.Config.MaxProtocolMessageBodyLen > 0 { + pgConn.frontend.SetMaxBodyLen(hc.Config.MaxProtocolMessageBodyLen) + } return pgConn, nil } @@ -2512,6 +2648,12 @@ func (p *Pipeline) SendQueryStatement(statementDescription *StatementDescription } p.conn.frontend.SendBind(&pgproto3.Bind{PreparedStatement: statementDescription.Name, ParameterFormatCodes: paramFormats, Parameters: paramValues, ResultFormatCodes: resultFormats}) + if len(statementDescription.Fields) == 0 { + // The cached field descriptions are empty. This can occur when the statement's result set is + // not known at prepare time, e.g. a FETCH from a cursor that did not exist yet. Send a + // Describe so the server supplies the actual row description when the statement is executed. + p.conn.frontend.SendDescribe(&pgproto3.Describe{ObjectType: 'P'}) + } p.conn.frontend.SendExecute(&pgproto3.Execute{}) p.state.PushBackRequestType(pipelineQueryStatement) p.state.PushBackStatementData(statementDescription, resultFormats) @@ -2607,22 +2749,29 @@ func (p *Pipeline) getResults() (results any, err error) { case pipelineNil: return nil, nil case pipelinePrepare: - return p.getResultsPrepare() + results, err = p.getResultsPrepare() case pipelineQueryParams: - return p.getResultsQueryParams() + results, err = p.getResultsQueryParams() case pipelineQueryPrepared: - return p.getResultsQueryPrepared() + results, err = p.getResultsQueryPrepared() case pipelineQueryStatement: - return p.getResultsQueryStatement() + results, err = p.getResultsQueryStatement() case pipelineDeallocate: - return p.getResultsDeallocate() + results, err = p.getResultsDeallocate() case pipelineSyncRequest: - return p.getResultsSync() + results, err = p.getResultsSync() case pipelineFlushRequest: return nil, errors.New("BUG: pipelineFlushRequest should not be in request queue") default: return nil, errors.New("BUG: unknown pipeline request type") } + + if err != nil { + // Return an untyped nil instead of an interface containing a typed nil pointer so that callers can compare + // results to nil. + return nil, err + } + return results, nil } func (p *Pipeline) getResultsPrepare() (*StatementDescription, error) { @@ -2699,21 +2848,48 @@ func (p *Pipeline) getResultsQueryPrepared() (*ResultReader, error) { } func (p *Pipeline) getResultsQueryStatement() (*ResultReader, error) { + // The statement data must be extracted even if an error occurs. Otherwise, it would still be in the queue and + // subsequent QueryStatement results would be misaligned with their statement descriptions. + sd, resultFormats := p.state.ExtractFrontStatementData() + if sd == nil { + return nil, errors.New("BUG: missing statement description or result formats for QueryStatement") + } + err := p.receiveBindComplete("QueryStatement") if err != nil { return nil, err } + sdFields := sd.Fields + if len(sdFields) == 0 { + // A Describe was sent for this statement (see SendQueryStatement). Read the server-provided + // row description which may include fields that were not known at prepare time. + msg, err := p.receiveMessage() + if err != nil { + return nil, err + } + + switch msg := msg.(type) { + case *pgproto3.RowDescription: + sdFields = make([]FieldDescription, len(msg.Fields)) + convertRowDescription(sdFields, msg) + case *pgproto3.NoData: + // Statement returns no rows. + case *pgproto3.ErrorResponse: + pgErr := ErrorResponseToPgError(msg) + p.state.HandleError(pgErr) + p.conn.resultReader.closed = true + return nil, pgErr + default: + return nil, p.handleUnexpectedMessage("QueryStatement RowDescription or NoData", msg) + } + } + msg, err := p.receiveMessage() if err != nil { return nil, err } - sd, resultFormats := p.state.ExtractFrontStatementData() - if sd == nil { - return nil, errors.New("BUG: missing statement description or result formats for QueryStatement") - } - sdFields := sd.Fields fieldDescriptions := p.conn.getFieldDescriptionSlice(len(sdFields)) err = combineFieldDescriptionsAndResultFormats(fieldDescriptions, sdFields, resultFormats) if err != nil { @@ -2739,6 +2915,12 @@ func (p *Pipeline) getResultsQueryStatement() (*ResultReader, error) { fieldDescriptions: fieldDescriptions, } return &p.conn.resultReader, nil + case *pgproto3.EmptyQueryResponse: + p.conn.resultReader = ResultReader{ + commandConcluded: true, + closed: true, + } + return &p.conn.resultReader, nil case *pgproto3.ErrorResponse: pgErr := ErrorResponseToPgError(msg) p.state.HandleError(pgErr) @@ -2866,6 +3048,15 @@ func (p *Pipeline) receiveDescribedResultReader(errStr string) (*ResultReader, e closed: true, } return &p.conn.resultReader, nil + + // EmptyQueryResponse is returned instead of CommandComplete when the query is empty. e.g. A comment-only query. + case *pgproto3.EmptyQueryResponse: + p.conn.resultReader = ResultReader{ + commandConcluded: true, + closed: true, + } + return &p.conn.resultReader, nil + case *pgproto3.ErrorResponse: pgErr := ErrorResponseToPgError(msg) p.state.HandleError(pgErr) diff --git a/vendor/github.com/jackc/pgx/v5/pgconn/saslprep_unassigned.go b/vendor/github.com/jackc/pgx/v5/pgconn/saslprep_unassigned.go new file mode 100644 index 0000000..aea5825 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgconn/saslprep_unassigned.go @@ -0,0 +1,413 @@ +// Code generated by gen_saslprep_unassigned.py; DO NOT EDIT. + +package pgconn + +import "unicode" + +//go:generate python3 gen_saslprep_unassigned.py + +// saslprepUnassigned is RFC 3454 table A.1: code points unassigned in +// Unicode 3.2. This table must not track the Go toolchain's Unicode version. +// https://www.rfc-editor.org/rfc/rfc3454#appendix-A.1 +var saslprepUnassigned = &unicode.RangeTable{ + R16: []unicode.Range16{ + {0x0221, 0x0221, 1}, + {0x0234, 0x024f, 1}, + {0x02ae, 0x02af, 1}, + {0x02ef, 0x02ff, 1}, + {0x0350, 0x035f, 1}, + {0x0370, 0x0373, 1}, + {0x0376, 0x0379, 1}, + {0x037b, 0x037d, 1}, + {0x037f, 0x0383, 1}, + {0x038b, 0x038b, 1}, + {0x038d, 0x038d, 1}, + {0x03a2, 0x03a2, 1}, + {0x03cf, 0x03cf, 1}, + {0x03f7, 0x03ff, 1}, + {0x0487, 0x0487, 1}, + {0x04cf, 0x04cf, 1}, + {0x04f6, 0x04f7, 1}, + {0x04fa, 0x04ff, 1}, + {0x0510, 0x0530, 1}, + {0x0557, 0x0558, 1}, + {0x0560, 0x0560, 1}, + {0x0588, 0x0588, 1}, + {0x058b, 0x0590, 1}, + {0x05a2, 0x05a2, 1}, + {0x05ba, 0x05ba, 1}, + {0x05c5, 0x05cf, 1}, + {0x05eb, 0x05ef, 1}, + {0x05f5, 0x060b, 1}, + {0x060d, 0x061a, 1}, + {0x061c, 0x061e, 1}, + {0x0620, 0x0620, 1}, + {0x063b, 0x063f, 1}, + {0x0656, 0x065f, 1}, + {0x06ee, 0x06ef, 1}, + {0x06ff, 0x06ff, 1}, + {0x070e, 0x070e, 1}, + {0x072d, 0x072f, 1}, + {0x074b, 0x077f, 1}, + {0x07b2, 0x0900, 1}, + {0x0904, 0x0904, 1}, + {0x093a, 0x093b, 1}, + {0x094e, 0x094f, 1}, + {0x0955, 0x0957, 1}, + {0x0971, 0x0980, 1}, + {0x0984, 0x0984, 1}, + {0x098d, 0x098e, 1}, + {0x0991, 0x0992, 1}, + {0x09a9, 0x09a9, 1}, + {0x09b1, 0x09b1, 1}, + {0x09b3, 0x09b5, 1}, + {0x09ba, 0x09bb, 1}, + {0x09bd, 0x09bd, 1}, + {0x09c5, 0x09c6, 1}, + {0x09c9, 0x09ca, 1}, + {0x09ce, 0x09d6, 1}, + {0x09d8, 0x09db, 1}, + {0x09de, 0x09de, 1}, + {0x09e4, 0x09e5, 1}, + {0x09fb, 0x0a01, 1}, + {0x0a03, 0x0a04, 1}, + {0x0a0b, 0x0a0e, 1}, + {0x0a11, 0x0a12, 1}, + {0x0a29, 0x0a29, 1}, + {0x0a31, 0x0a31, 1}, + {0x0a34, 0x0a34, 1}, + {0x0a37, 0x0a37, 1}, + {0x0a3a, 0x0a3b, 1}, + {0x0a3d, 0x0a3d, 1}, + {0x0a43, 0x0a46, 1}, + {0x0a49, 0x0a4a, 1}, + {0x0a4e, 0x0a58, 1}, + {0x0a5d, 0x0a5d, 1}, + {0x0a5f, 0x0a65, 1}, + {0x0a75, 0x0a80, 1}, + {0x0a84, 0x0a84, 1}, + {0x0a8c, 0x0a8c, 1}, + {0x0a8e, 0x0a8e, 1}, + {0x0a92, 0x0a92, 1}, + {0x0aa9, 0x0aa9, 1}, + {0x0ab1, 0x0ab1, 1}, + {0x0ab4, 0x0ab4, 1}, + {0x0aba, 0x0abb, 1}, + {0x0ac6, 0x0ac6, 1}, + {0x0aca, 0x0aca, 1}, + {0x0ace, 0x0acf, 1}, + {0x0ad1, 0x0adf, 1}, + {0x0ae1, 0x0ae5, 1}, + {0x0af0, 0x0b00, 1}, + {0x0b04, 0x0b04, 1}, + {0x0b0d, 0x0b0e, 1}, + {0x0b11, 0x0b12, 1}, + {0x0b29, 0x0b29, 1}, + {0x0b31, 0x0b31, 1}, + {0x0b34, 0x0b35, 1}, + {0x0b3a, 0x0b3b, 1}, + {0x0b44, 0x0b46, 1}, + {0x0b49, 0x0b4a, 1}, + {0x0b4e, 0x0b55, 1}, + {0x0b58, 0x0b5b, 1}, + {0x0b5e, 0x0b5e, 1}, + {0x0b62, 0x0b65, 1}, + {0x0b71, 0x0b81, 1}, + {0x0b84, 0x0b84, 1}, + {0x0b8b, 0x0b8d, 1}, + {0x0b91, 0x0b91, 1}, + {0x0b96, 0x0b98, 1}, + {0x0b9b, 0x0b9b, 1}, + {0x0b9d, 0x0b9d, 1}, + {0x0ba0, 0x0ba2, 1}, + {0x0ba5, 0x0ba7, 1}, + {0x0bab, 0x0bad, 1}, + {0x0bb6, 0x0bb6, 1}, + {0x0bba, 0x0bbd, 1}, + {0x0bc3, 0x0bc5, 1}, + {0x0bc9, 0x0bc9, 1}, + {0x0bce, 0x0bd6, 1}, + {0x0bd8, 0x0be6, 1}, + {0x0bf3, 0x0c00, 1}, + {0x0c04, 0x0c04, 1}, + {0x0c0d, 0x0c0d, 1}, + {0x0c11, 0x0c11, 1}, + {0x0c29, 0x0c29, 1}, + {0x0c34, 0x0c34, 1}, + {0x0c3a, 0x0c3d, 1}, + {0x0c45, 0x0c45, 1}, + {0x0c49, 0x0c49, 1}, + {0x0c4e, 0x0c54, 1}, + {0x0c57, 0x0c5f, 1}, + {0x0c62, 0x0c65, 1}, + {0x0c70, 0x0c81, 1}, + {0x0c84, 0x0c84, 1}, + {0x0c8d, 0x0c8d, 1}, + {0x0c91, 0x0c91, 1}, + {0x0ca9, 0x0ca9, 1}, + {0x0cb4, 0x0cb4, 1}, + {0x0cba, 0x0cbd, 1}, + {0x0cc5, 0x0cc5, 1}, + {0x0cc9, 0x0cc9, 1}, + {0x0cce, 0x0cd4, 1}, + {0x0cd7, 0x0cdd, 1}, + {0x0cdf, 0x0cdf, 1}, + {0x0ce2, 0x0ce5, 1}, + {0x0cf0, 0x0d01, 1}, + {0x0d04, 0x0d04, 1}, + {0x0d0d, 0x0d0d, 1}, + {0x0d11, 0x0d11, 1}, + {0x0d29, 0x0d29, 1}, + {0x0d3a, 0x0d3d, 1}, + {0x0d44, 0x0d45, 1}, + {0x0d49, 0x0d49, 1}, + {0x0d4e, 0x0d56, 1}, + {0x0d58, 0x0d5f, 1}, + {0x0d62, 0x0d65, 1}, + {0x0d70, 0x0d81, 1}, + {0x0d84, 0x0d84, 1}, + {0x0d97, 0x0d99, 1}, + {0x0db2, 0x0db2, 1}, + {0x0dbc, 0x0dbc, 1}, + {0x0dbe, 0x0dbf, 1}, + {0x0dc7, 0x0dc9, 1}, + {0x0dcb, 0x0dce, 1}, + {0x0dd5, 0x0dd5, 1}, + {0x0dd7, 0x0dd7, 1}, + {0x0de0, 0x0df1, 1}, + {0x0df5, 0x0e00, 1}, + {0x0e3b, 0x0e3e, 1}, + {0x0e5c, 0x0e80, 1}, + {0x0e83, 0x0e83, 1}, + {0x0e85, 0x0e86, 1}, + {0x0e89, 0x0e89, 1}, + {0x0e8b, 0x0e8c, 1}, + {0x0e8e, 0x0e93, 1}, + {0x0e98, 0x0e98, 1}, + {0x0ea0, 0x0ea0, 1}, + {0x0ea4, 0x0ea4, 1}, + {0x0ea6, 0x0ea6, 1}, + {0x0ea8, 0x0ea9, 1}, + {0x0eac, 0x0eac, 1}, + {0x0eba, 0x0eba, 1}, + {0x0ebe, 0x0ebf, 1}, + {0x0ec5, 0x0ec5, 1}, + {0x0ec7, 0x0ec7, 1}, + {0x0ece, 0x0ecf, 1}, + {0x0eda, 0x0edb, 1}, + {0x0ede, 0x0eff, 1}, + {0x0f48, 0x0f48, 1}, + {0x0f6b, 0x0f70, 1}, + {0x0f8c, 0x0f8f, 1}, + {0x0f98, 0x0f98, 1}, + {0x0fbd, 0x0fbd, 1}, + {0x0fcd, 0x0fce, 1}, + {0x0fd0, 0x0fff, 1}, + {0x1022, 0x1022, 1}, + {0x1028, 0x1028, 1}, + {0x102b, 0x102b, 1}, + {0x1033, 0x1035, 1}, + {0x103a, 0x103f, 1}, + {0x105a, 0x109f, 1}, + {0x10c6, 0x10cf, 1}, + {0x10f9, 0x10fa, 1}, + {0x10fc, 0x10ff, 1}, + {0x115a, 0x115e, 1}, + {0x11a3, 0x11a7, 1}, + {0x11fa, 0x11ff, 1}, + {0x1207, 0x1207, 1}, + {0x1247, 0x1247, 1}, + {0x1249, 0x1249, 1}, + {0x124e, 0x124f, 1}, + {0x1257, 0x1257, 1}, + {0x1259, 0x1259, 1}, + {0x125e, 0x125f, 1}, + {0x1287, 0x1287, 1}, + {0x1289, 0x1289, 1}, + {0x128e, 0x128f, 1}, + {0x12af, 0x12af, 1}, + {0x12b1, 0x12b1, 1}, + {0x12b6, 0x12b7, 1}, + {0x12bf, 0x12bf, 1}, + {0x12c1, 0x12c1, 1}, + {0x12c6, 0x12c7, 1}, + {0x12cf, 0x12cf, 1}, + {0x12d7, 0x12d7, 1}, + {0x12ef, 0x12ef, 1}, + {0x130f, 0x130f, 1}, + {0x1311, 0x1311, 1}, + {0x1316, 0x1317, 1}, + {0x131f, 0x131f, 1}, + {0x1347, 0x1347, 1}, + {0x135b, 0x1360, 1}, + {0x137d, 0x139f, 1}, + {0x13f5, 0x1400, 1}, + {0x1677, 0x167f, 1}, + {0x169d, 0x169f, 1}, + {0x16f1, 0x16ff, 1}, + {0x170d, 0x170d, 1}, + {0x1715, 0x171f, 1}, + {0x1737, 0x173f, 1}, + {0x1754, 0x175f, 1}, + {0x176d, 0x176d, 1}, + {0x1771, 0x1771, 1}, + {0x1774, 0x177f, 1}, + {0x17dd, 0x17df, 1}, + {0x17ea, 0x17ff, 1}, + {0x180f, 0x180f, 1}, + {0x181a, 0x181f, 1}, + {0x1878, 0x187f, 1}, + {0x18aa, 0x1dff, 1}, + {0x1e9c, 0x1e9f, 1}, + {0x1efa, 0x1eff, 1}, + {0x1f16, 0x1f17, 1}, + {0x1f1e, 0x1f1f, 1}, + {0x1f46, 0x1f47, 1}, + {0x1f4e, 0x1f4f, 1}, + {0x1f58, 0x1f58, 1}, + {0x1f5a, 0x1f5a, 1}, + {0x1f5c, 0x1f5c, 1}, + {0x1f5e, 0x1f5e, 1}, + {0x1f7e, 0x1f7f, 1}, + {0x1fb5, 0x1fb5, 1}, + {0x1fc5, 0x1fc5, 1}, + {0x1fd4, 0x1fd5, 1}, + {0x1fdc, 0x1fdc, 1}, + {0x1ff0, 0x1ff1, 1}, + {0x1ff5, 0x1ff5, 1}, + {0x1fff, 0x1fff, 1}, + {0x2053, 0x2056, 1}, + {0x2058, 0x205e, 1}, + {0x2064, 0x2069, 1}, + {0x2072, 0x2073, 1}, + {0x208f, 0x209f, 1}, + {0x20b2, 0x20cf, 1}, + {0x20eb, 0x20ff, 1}, + {0x213b, 0x213c, 1}, + {0x214c, 0x2152, 1}, + {0x2184, 0x218f, 1}, + {0x23cf, 0x23ff, 1}, + {0x2427, 0x243f, 1}, + {0x244b, 0x245f, 1}, + {0x24ff, 0x24ff, 1}, + {0x2614, 0x2615, 1}, + {0x2618, 0x2618, 1}, + {0x267e, 0x267f, 1}, + {0x268a, 0x2700, 1}, + {0x2705, 0x2705, 1}, + {0x270a, 0x270b, 1}, + {0x2728, 0x2728, 1}, + {0x274c, 0x274c, 1}, + {0x274e, 0x274e, 1}, + {0x2753, 0x2755, 1}, + {0x2757, 0x2757, 1}, + {0x275f, 0x2760, 1}, + {0x2795, 0x2797, 1}, + {0x27b0, 0x27b0, 1}, + {0x27bf, 0x27cf, 1}, + {0x27ec, 0x27ef, 1}, + {0x2b00, 0x2e7f, 1}, + {0x2e9a, 0x2e9a, 1}, + {0x2ef4, 0x2eff, 1}, + {0x2fd6, 0x2fef, 1}, + {0x2ffc, 0x2fff, 1}, + {0x3040, 0x3040, 1}, + {0x3097, 0x3098, 1}, + {0x3100, 0x3104, 1}, + {0x312d, 0x3130, 1}, + {0x318f, 0x318f, 1}, + {0x31b8, 0x31ef, 1}, + {0x321d, 0x321f, 1}, + {0x3244, 0x3250, 1}, + {0x327c, 0x327e, 1}, + {0x32cc, 0x32cf, 1}, + {0x32ff, 0x32ff, 1}, + {0x3377, 0x337a, 1}, + {0x33de, 0x33df, 1}, + {0x33ff, 0x33ff, 1}, + {0x4db6, 0x4dff, 1}, + {0x9fa6, 0x9fff, 1}, + {0xa48d, 0xa48f, 1}, + {0xa4c7, 0xabff, 1}, + {0xd7a4, 0xd7ff, 1}, + {0xfa2e, 0xfa2f, 1}, + {0xfa6b, 0xfaff, 1}, + {0xfb07, 0xfb12, 1}, + {0xfb18, 0xfb1c, 1}, + {0xfb37, 0xfb37, 1}, + {0xfb3d, 0xfb3d, 1}, + {0xfb3f, 0xfb3f, 1}, + {0xfb42, 0xfb42, 1}, + {0xfb45, 0xfb45, 1}, + {0xfbb2, 0xfbd2, 1}, + {0xfd40, 0xfd4f, 1}, + {0xfd90, 0xfd91, 1}, + {0xfdc8, 0xfdcf, 1}, + {0xfdfd, 0xfdff, 1}, + {0xfe10, 0xfe1f, 1}, + {0xfe24, 0xfe2f, 1}, + {0xfe47, 0xfe48, 1}, + {0xfe53, 0xfe53, 1}, + {0xfe67, 0xfe67, 1}, + {0xfe6c, 0xfe6f, 1}, + {0xfe75, 0xfe75, 1}, + {0xfefd, 0xfefe, 1}, + {0xff00, 0xff00, 1}, + {0xffbf, 0xffc1, 1}, + {0xffc8, 0xffc9, 1}, + {0xffd0, 0xffd1, 1}, + {0xffd8, 0xffd9, 1}, + {0xffdd, 0xffdf, 1}, + {0xffe7, 0xffe7, 1}, + {0xffef, 0xfff8, 1}, + }, + R32: []unicode.Range32{ + {0x10000, 0x102ff, 1}, + {0x1031f, 0x1031f, 1}, + {0x10324, 0x1032f, 1}, + {0x1034b, 0x103ff, 1}, + {0x10426, 0x10427, 1}, + {0x1044e, 0x1cfff, 1}, + {0x1d0f6, 0x1d0ff, 1}, + {0x1d127, 0x1d129, 1}, + {0x1d1de, 0x1d3ff, 1}, + {0x1d455, 0x1d455, 1}, + {0x1d49d, 0x1d49d, 1}, + {0x1d4a0, 0x1d4a1, 1}, + {0x1d4a3, 0x1d4a4, 1}, + {0x1d4a7, 0x1d4a8, 1}, + {0x1d4ad, 0x1d4ad, 1}, + {0x1d4ba, 0x1d4ba, 1}, + {0x1d4bc, 0x1d4bc, 1}, + {0x1d4c1, 0x1d4c1, 1}, + {0x1d4c4, 0x1d4c4, 1}, + {0x1d506, 0x1d506, 1}, + {0x1d50b, 0x1d50c, 1}, + {0x1d515, 0x1d515, 1}, + {0x1d51d, 0x1d51d, 1}, + {0x1d53a, 0x1d53a, 1}, + {0x1d53f, 0x1d53f, 1}, + {0x1d545, 0x1d545, 1}, + {0x1d547, 0x1d549, 1}, + {0x1d551, 0x1d551, 1}, + {0x1d6a4, 0x1d6a7, 1}, + {0x1d7ca, 0x1d7cd, 1}, + {0x1d800, 0x1fffd, 1}, + {0x2a6d7, 0x2f7ff, 1}, + {0x2fa1e, 0x2fffd, 1}, + {0x30000, 0x3fffd, 1}, + {0x40000, 0x4fffd, 1}, + {0x50000, 0x5fffd, 1}, + {0x60000, 0x6fffd, 1}, + {0x70000, 0x7fffd, 1}, + {0x80000, 0x8fffd, 1}, + {0x90000, 0x9fffd, 1}, + {0xa0000, 0xafffd, 1}, + {0xb0000, 0xbfffd, 1}, + {0xc0000, 0xcfffd, 1}, + {0xd0000, 0xdfffd, 1}, + {0xe0000, 0xe0000, 1}, + {0xe0002, 0xe001f, 1}, + {0xe0080, 0xefffd, 1}, + }, +} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/negotiate_protocol_version.go b/vendor/github.com/jackc/pgx/v5/pgproto3/negotiate_protocol_version.go index 43bd7ec..936576a 100644 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/negotiate_protocol_version.go +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/negotiate_protocol_version.go @@ -34,7 +34,7 @@ func (dst *NegotiateProtocolVersion) Decode(src []byte) error { capHint = remaining } dst.UnrecognizedOptions = make([]string, 0, capHint) - for i := 0; i < optionCount; i++ { + for range optionCount { if rp >= len(src) { return &invalidMessageFormatErr{messageType: "NegotiateProtocolVersion"} } diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/startup_message.go b/vendor/github.com/jackc/pgx/v5/pgproto3/startup_message.go index eb48f72..69cf99a 100644 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/startup_message.go +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/startup_message.go @@ -6,6 +6,7 @@ import ( "encoding/json" "errors" "fmt" + "strings" "github.com/jackc/pgx/v5/internal/pgio" ) @@ -75,6 +76,24 @@ func (src *StartupMessage) Encode(dst []byte) ([]byte, error) { dst = pgio.AppendUint32(dst, src.ProtocolVersion) for k, v := range src.Parameters { + // The startup message body is a run of NUL-delimited strings whose + // length is data-driven: the server keeps reading name/value pairs + // until the empty name that terminates the list. Other messages have a + // field count fixed by the message type, so a stray NUL there leaves + // trailing bytes and the server rejects the message; here it simply + // yields more parameters. A libpq caller cannot reach this state + // because its parameters are NUL-terminated C strings, but a Go string + // can carry a NUL, so an application_name of "x\x00user\x00admin" + // would silently change the role the connection logs in as. Refuse to + // encode instead. + if strings.IndexByte(k, 0) >= 0 { + return nil, errors.New("startup message parameter name contains NUL byte") + } + if strings.IndexByte(v, 0) >= 0 { + // Name the parameter but not the value: values can hold secrets. + return nil, fmt.Errorf("startup message parameter %q contains NUL byte in value", k) + } + dst = append(dst, k...) dst = append(dst, 0) dst = append(dst, v...) diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/array.go b/vendor/github.com/jackc/pgx/v5/pgtype/array.go index 26505fb..7e03de8 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/array.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/array.go @@ -2,7 +2,6 @@ package pgtype import ( "bytes" - "encoding/binary" "fmt" "io" "strconv" @@ -45,39 +44,30 @@ func cardinality(dimensions []ArrayDimension) int { return elementCount } -func (dst *arrayHeader) DecodeBinary(m *Map, src []byte) (int, error) { - if len(src) < 12 { - return 0, fmt.Errorf("array header too short: %d", len(src)) +func (dst *arrayHeader) DecodeBinary(r *pgio.Reader) error { + // Each dimension is 8 bytes, which also bounds the Dimensions allocation below. + numDims := r.Count(8) + if err := r.Err(); err != nil { + return fmt.Errorf("array header: %w", err) } - rp := 0 - - numDims := int(binary.BigEndian.Uint32(src[rp:])) - rp += 4 - if numDims > 6 { - return 0, fmt.Errorf("array has too many dimensions: %d", numDims) + return fmt.Errorf("array has too many dimensions: %d", numDims) } - dst.ContainsNull = binary.BigEndian.Uint32(src[rp:]) == 1 - rp += 4 + dst.ContainsNull = r.Uint32() == 1 + dst.ElementOID = r.Uint32() - dst.ElementOID = binary.BigEndian.Uint32(src[rp:]) - rp += 4 - - if len(src) < 12+numDims*8 { - return 0, fmt.Errorf("array header too short for %d dimensions: %d", numDims, len(src)) - } dst.Dimensions = make([]ArrayDimension, numDims) for i := range dst.Dimensions { - dst.Dimensions[i].Length = int32(binary.BigEndian.Uint32(src[rp:])) - rp += 4 - - dst.Dimensions[i].LowerBound = int32(binary.BigEndian.Uint32(src[rp:])) - rp += 4 + dst.Dimensions[i].Length = r.Int32() + dst.Dimensions[i].LowerBound = r.Int32() } - return rp, nil + if err := r.Err(); err != nil { + return fmt.Errorf("array header: %w", err) + } + return nil } func (src arrayHeader) EncodeBinary(buf []byte) []byte { @@ -105,7 +95,11 @@ type untypedTextArray struct { Dimensions []ArrayDimension } -func parseUntypedTextArray(src string) (*untypedTextArray, error) { +func parseUntypedTextArray(src string, delimiter byte) (*untypedTextArray, error) { + if delimiter == 0 { + delimiter = ',' + } + dst := &untypedTextArray{ Elements: []string{}, Quoted: []bool{}, @@ -212,7 +206,7 @@ func parseUntypedTextArray(src string) (*untypedTextArray, error) { implicitDimensions[currentDim].Length++ } currentDim++ - case ',': + case rune(delimiter): case '}': currentDim-- if currentDim < counterDim { @@ -220,7 +214,7 @@ func parseUntypedTextArray(src string) (*untypedTextArray, error) { } default: buf.UnreadRune() - value, quoted, err := arrayParseValue(buf) + value, quoted, err := arrayParseValue(buf, delimiter) if err != nil { return nil, fmt.Errorf("invalid array value: %w", err) } @@ -264,7 +258,7 @@ func skipWhitespace(buf *bytes.Buffer) { } } -func arrayParseValue(buf *bytes.Buffer) (string, bool, error) { +func arrayParseValue(buf *bytes.Buffer, delimiter byte) (string, bool, error) { r, _, err := buf.ReadRune() if err != nil { return "", false, err @@ -283,7 +277,7 @@ func arrayParseValue(buf *bytes.Buffer) (string, bool, error) { } switch r { - case ',', '}': + case rune(delimiter), '}': buf.UnreadRune() return s.String(), false, nil } @@ -355,9 +349,9 @@ func encodeTextArrayDimensions(buf []byte, dimensions []ArrayDimension) []byte { for _, dim := range dimensions { buf = append(buf, '[') - buf = append(buf, strconv.FormatInt(int64(dim.LowerBound), 10)...) + buf = strconv.AppendInt(buf, int64(dim.LowerBound), 10) buf = append(buf, ':') - buf = append(buf, strconv.FormatInt(int64(dim.LowerBound+dim.Length-1), 10)...) + buf = strconv.AppendInt(buf, int64(dim.LowerBound+dim.Length-1), 10) buf = append(buf, ']') } @@ -370,14 +364,12 @@ func quoteArrayElement(src string) string { return `"` + quoteArrayReplacer.Replace(src) + `"` } -func isSpace(ch byte) bool { - // see array_isspace: - // https://github.com/postgres/postgres/blob/master/src/backend/utils/adt/arrayfuncs.c - return ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r' || ch == '\v' || ch == '\f' -} +func quoteArrayElementIfNeeded(src string, delimiter byte) string { + if delimiter == 0 { + delimiter = ',' + } -func quoteArrayElementIfNeeded(src string) string { - if src == "" || (len(src) == 4 && strings.EqualFold(src, "null")) || isSpace(src[0]) || isSpace(src[len(src)-1]) || strings.ContainsAny(src, `{},"\`) { + if src == "" || (len(src) == 4 && strings.EqualFold(src, "null")) || strings.ContainsAny(src, " \t\n\r\v\f") || strings.ContainsAny(src, `{},"\`) || strings.ContainsRune(src, rune(delimiter)) { return quoteArrayElement(src) } return src diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/array_codec.go b/vendor/github.com/jackc/pgx/v5/pgtype/array_codec.go index ac01496..1c9acc9 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/array_codec.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/array_codec.go @@ -2,7 +2,6 @@ package pgtype import ( "database/sql/driver" - "encoding/binary" "fmt" "reflect" @@ -39,6 +38,16 @@ type ArraySetter interface { // ArrayCodec is a codec for any array type. type ArrayCodec struct { ElementType *Type + // Delimiter is the character PostgreSQL uses to separate array elements for this type. + // If unset, "," is used. + Delimiter byte +} + +func (c *ArrayCodec) delimiter() byte { + if c.Delimiter == 0 { + return ',' + } + return c.Delimiter } func (c *ArrayCodec) FormatSupported(format int16) bool { @@ -118,9 +127,10 @@ func (p *encodePlanArrayCodecText) Encode(value any, buf []byte) (newBuf []byte, var encodePlan EncodePlan var lastElemType reflect.Type inElemBuf := make([]byte, 0, 32) + delimiter := p.ac.delimiter() for i := range elementCount { if i > 0 { - buf = append(buf, ',') + buf = append(buf, delimiter) } for _, dec := range dimElemCounts { @@ -155,7 +165,7 @@ func (p *encodePlanArrayCodecText) Encode(value any, buf []byte) (newBuf []byte, if elemBuf == nil { buf = append(buf, `NULL`...) } else { - buf = append(buf, quoteArrayElementIfNeeded(string(elemBuf))...) + buf = append(buf, quoteArrayElementIfNeeded(string(elemBuf), delimiter)...) } for _, dec := range dimElemCounts { @@ -261,8 +271,9 @@ func (c *ArrayCodec) PlanScan(m *Map, oid uint32, format int16, target any) Scan } func (c *ArrayCodec) decodeBinary(m *Map, arrayOID uint32, src []byte, array ArraySetter) error { + r := pgio.NewReader(src) var arrayHeader arrayHeader - rp, err := arrayHeader.DecodeBinary(m, src) + err := arrayHeader.DecodeBinary(r) if err != nil { return err } @@ -271,8 +282,8 @@ func (c *ArrayCodec) decodeBinary(m *Map, arrayOID uint32, src []byte, array Arr // Each element carries at minimum a 4-byte length header, so elementCount cannot exceed the // remaining bytes / 4. This bounds the allocation in SetDimensions and the loop below against a // malicious server claiming huge dimensions in a small message. - if maxElements := len(src[rp:]) / 4; elementCount > maxElements { - return fmt.Errorf("array claims %d elements but only %d bytes remain", elementCount, len(src[rp:])) + if maxElements := r.Remaining() / 4; elementCount > maxElements { + return fmt.Errorf("array claims %d elements but only %d bytes remain", elementCount, r.Remaining()) } err = array.SetDimensions(arrayHeader.Dimensions) @@ -281,7 +292,7 @@ func (c *ArrayCodec) decodeBinary(m *Map, arrayOID uint32, src []byte, array Arr } if elementCount == 0 { - return nil + return r.Finish() } elementScanPlan := c.ElementType.Codec.PlanScan(m, c.ElementType.OID, BinaryFormatCode, array.ScanIndex(0)) @@ -290,19 +301,10 @@ func (c *ArrayCodec) decodeBinary(m *Map, arrayOID uint32, src []byte, array Arr } for i := range elementCount { - if len(src[rp:]) < 4 { - return fmt.Errorf("array body truncated at element %d", i) - } elem := array.ScanIndex(i) - elemLen := int(int32(binary.BigEndian.Uint32(src[rp:]))) - rp += 4 - var elemSrc []byte - if elemLen >= 0 { - if len(src[rp:]) < elemLen { - return fmt.Errorf("array element %d length %d exceeds remaining %d bytes", i, elemLen, len(src[rp:])) - } - elemSrc = src[rp : rp+elemLen] - rp += elemLen + elemSrc, _ := r.Value() + if err := r.Err(); err != nil { + return fmt.Errorf("array element %d: %w", i, err) } err = elementScanPlan.Scan(elemSrc, elem) if err != nil { @@ -310,15 +312,21 @@ func (c *ArrayCodec) decodeBinary(m *Map, arrayOID uint32, src []byte, array Arr } } - return nil + return r.Finish() } func (c *ArrayCodec) decodeText(m *Map, arrayOID uint32, src []byte, array ArraySetter) error { - uta, err := parseUntypedTextArray(string(src)) + uta, err := parseUntypedTextArray(string(src), c.delimiter()) if err != nil { return err } + // The element loop below indexes the value sized by SetDimensions, so the + // dimensions and the parsed elements must agree. + if elementCount := cardinality(uta.Dimensions); elementCount != len(uta.Elements) { + return fmt.Errorf("array dimensions describe %d elements but %d were parsed", elementCount, len(uta.Elements)) + } + err = array.SetDimensions(uta.Dimensions) if err != nil { return err diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/bits.go b/vendor/github.com/jackc/pgx/v5/pgtype/bits.go index 986fe23..052c157 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/bits.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/bits.go @@ -2,7 +2,6 @@ package pgtype import ( "database/sql/driver" - "encoding/binary" "fmt" "github.com/jackc/pgx/v5/internal/pgio" @@ -162,20 +161,31 @@ func (c BitsCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (an type scanPlanBinaryBitsToBitsScanner struct{} func (scanPlanBinaryBitsToBitsScanner) Scan(src []byte, dst any) error { - scanner := (dst).(BitsScanner) + scanner := dst.(BitsScanner) if src == nil { return scanner.ScanBits(Bits{}) } - if len(src) < 4 { - return fmt.Errorf("invalid length for bit/varbit: %v", len(src)) + r := pgio.NewReader(src) + + bitLen := r.Int32() + if err := r.Err(); err != nil { + return fmt.Errorf("invalid length for bit/varbit: %w", err) + } + if bitLen < 0 { + return fmt.Errorf("invalid length for bit/varbit: bitLen=%d", bitLen) } - bitLen := int32(binary.BigEndian.Uint32(src)) - rp := 4 - buf := make([]byte, len(src[rp:])) - copy(buf, src[rp:]) + // Finish rejects trailing bytes, so together with the read below the data + // must be exactly the number of bytes bitLen calls for. + data := r.Bytes((int(bitLen) + 7) / 8) + if err := r.Finish(); err != nil { + return fmt.Errorf("invalid length for bit/varbit: bitLen=%d: %w", bitLen, err) + } + + buf := make([]byte, len(data)) + copy(buf, data) return scanner.ScanBits(Bits{Bytes: buf, Len: bitLen, Valid: true}) } @@ -183,7 +193,7 @@ func (scanPlanBinaryBitsToBitsScanner) Scan(src []byte, dst any) error { type scanPlanTextAnyToBitsScanner struct{} func (scanPlanTextAnyToBitsScanner) Scan(src []byte, dst any) error { - scanner := (dst).(BitsScanner) + scanner := dst.(BitsScanner) if src == nil { return scanner.ScanBits(Bits{}) diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/bool.go b/vendor/github.com/jackc/pgx/v5/pgtype/bool.go index 077668e..986ae19 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/bool.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/bool.go @@ -252,7 +252,7 @@ func (scanPlanBinaryBoolToBool) Scan(src []byte, dst any) error { return fmt.Errorf("invalid length for bool: %v", len(src)) } - p, ok := (dst).(*bool) + p, ok := dst.(*bool) if !ok { return ErrScanTargetTypeChanged } @@ -273,7 +273,7 @@ func (scanPlanTextAnyToBool) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan empty string into %T", dst) } - p, ok := (dst).(*bool) + p, ok := dst.(*bool) if !ok { return ErrScanTargetTypeChanged } @@ -291,7 +291,7 @@ func (scanPlanTextAnyToBool) Scan(src []byte, dst any) error { type scanPlanBinaryBoolToBoolScanner struct{} func (scanPlanBinaryBoolToBoolScanner) Scan(src []byte, dst any) error { - s, ok := (dst).(BoolScanner) + s, ok := dst.(BoolScanner) if !ok { return ErrScanTargetTypeChanged } @@ -310,7 +310,7 @@ func (scanPlanBinaryBoolToBoolScanner) Scan(src []byte, dst any) error { type scanPlanTextAnyToBoolScanner struct{} func (scanPlanTextAnyToBoolScanner) Scan(src []byte, dst any) error { - s, ok := (dst).(BoolScanner) + s, ok := dst.(BoolScanner) if !ok { return ErrScanTargetTypeChanged } diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/box.go b/vendor/github.com/jackc/pgx/v5/pgtype/box.go index 8270aaf..d05bef2 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/box.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/box.go @@ -2,7 +2,6 @@ package pgtype import ( "database/sql/driver" - "encoding/binary" "fmt" "math" "strconv" @@ -145,20 +144,22 @@ func (BoxCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan type scanPlanBinaryBoxToBoxScanner struct{} func (scanPlanBinaryBoxToBoxScanner) Scan(src []byte, dst any) error { - scanner := (dst).(BoxScanner) + scanner := dst.(BoxScanner) if src == nil { return scanner.ScanBox(Box{}) } - if len(src) != 32 { - return fmt.Errorf("invalid length for Box: %v", len(src)) - } + r := pgio.NewReader(src) - x1 := binary.BigEndian.Uint64(src) - y1 := binary.BigEndian.Uint64(src[8:]) - x2 := binary.BigEndian.Uint64(src[16:]) - y2 := binary.BigEndian.Uint64(src[24:]) + x1 := r.Uint64() + y1 := r.Uint64() + x2 := r.Uint64() + y2 := r.Uint64() + + if err := r.Finish(); err != nil { + return fmt.Errorf("Box: %w", err) + } return scanner.ScanBox(Box{ P: [2]Vec2{ @@ -172,7 +173,7 @@ func (scanPlanBinaryBoxToBoxScanner) Scan(src []byte, dst any) error { type scanPlanTextAnyToBoxScanner struct{} func (scanPlanTextAnyToBoxScanner) Scan(src []byte, dst any) error { - scanner := (dst).(BoxScanner) + scanner := dst.(BoxScanner) if src == nil { return scanner.ScanBox(Box{}) diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/builtin_wrappers.go b/vendor/github.com/jackc/pgx/v5/pgtype/builtin_wrappers.go index a412763..bfae662 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/builtin_wrappers.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/builtin_wrappers.go @@ -599,7 +599,7 @@ func (w *netipAddrWrapper) ScanNetipPrefix(v netip.Prefix) error { } func (w netipAddrWrapper) NetipPrefixValue() (netip.Prefix, error) { - addr := (netip.Addr)(w) + addr := netip.Addr(w) if !addr.IsValid() { return netip.Prefix{}, nil } diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/bytea.go b/vendor/github.com/jackc/pgx/v5/pgtype/bytea.go index 6c4f0c5..32c026e 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/bytea.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/bytea.go @@ -185,7 +185,7 @@ func (scanPlanBinaryBytesToBytes) Scan(src []byte, dst any) error { type scanPlanBinaryBytesToBytesScanner struct{} func (scanPlanBinaryBytesToBytesScanner) Scan(src []byte, dst any) error { - scanner := (dst).(BytesScanner) + scanner := dst.(BytesScanner) return scanner.ScanBytes(src) } @@ -210,7 +210,7 @@ func (scanPlanTextByteaToBytes) Scan(src []byte, dst any) error { type scanPlanTextByteaToBytesScanner struct{} func (scanPlanTextByteaToBytesScanner) Scan(src []byte, dst any) error { - scanner := (dst).(BytesScanner) + scanner := dst.(BytesScanner) buf, err := decodeHexBytea(src) if err != nil { return err diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/circle.go b/vendor/github.com/jackc/pgx/v5/pgtype/circle.go index ea1d629..c72c2fe 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/circle.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/circle.go @@ -2,7 +2,6 @@ package pgtype import ( "database/sql/driver" - "encoding/binary" "fmt" "math" "strconv" @@ -161,19 +160,21 @@ func (c CircleCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) ( type scanPlanBinaryCircleToCircleScanner struct{} func (scanPlanBinaryCircleToCircleScanner) Scan(src []byte, dst any) error { - scanner := (dst).(CircleScanner) + scanner := dst.(CircleScanner) if src == nil { return scanner.ScanCircle(Circle{}) } - if len(src) != 24 { - return fmt.Errorf("invalid length for Circle: %v", len(src)) - } + rd := pgio.NewReader(src) - x := binary.BigEndian.Uint64(src) - y := binary.BigEndian.Uint64(src[8:]) - r := binary.BigEndian.Uint64(src[16:]) + x := rd.Uint64() + y := rd.Uint64() + r := rd.Uint64() + + if err := rd.Finish(); err != nil { + return fmt.Errorf("Circle: %w", err) + } return scanner.ScanCircle(Circle{ P: Vec2{math.Float64frombits(x), math.Float64frombits(y)}, @@ -185,7 +186,7 @@ func (scanPlanBinaryCircleToCircleScanner) Scan(src []byte, dst any) error { type scanPlanTextAnyToCircleScanner struct{} func (scanPlanTextAnyToCircleScanner) Scan(src []byte, dst any) error { - scanner := (dst).(CircleScanner) + scanner := dst.(CircleScanner) if src == nil { return scanner.ScanCircle(Circle{}) diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/composite.go b/vendor/github.com/jackc/pgx/v5/pgtype/composite.go index 7f96ab4..ae1b6eb 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/composite.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/composite.go @@ -130,7 +130,7 @@ type scanPlanBinaryCompositeToCompositeIndexScanner struct { } func (plan *scanPlanBinaryCompositeToCompositeIndexScanner) Scan(src []byte, target any) error { - targetScanner := (target).(CompositeIndexScanner) + targetScanner := target.(CompositeIndexScanner) if src == nil { return targetScanner.ScanNull() @@ -139,14 +139,17 @@ func (plan *scanPlanBinaryCompositeToCompositeIndexScanner) Scan(src []byte, tar scanner := NewCompositeBinaryScanner(plan.m, src) for i, field := range plan.cc.Fields { if scanner.Next() { - fieldTarget := targetScanner.ScanIndex(i) + fieldTarget, err := compositeFieldTarget(targetScanner, i) + if err != nil { + return err + } if fieldTarget != nil { fieldPlan := plan.m.PlanScan(field.Type.OID, BinaryFormatCode, fieldTarget) if fieldPlan == nil { return fmt.Errorf("unable to encode %v into OID %d in binary format", field, field.Type.OID) } - err := fieldPlan.Scan(scanner.Bytes(), fieldTarget) + err = fieldPlan.Scan(scanner.Bytes(), fieldTarget) if err != nil { return err } @@ -169,7 +172,7 @@ type scanPlanTextCompositeToCompositeIndexScanner struct { } func (plan *scanPlanTextCompositeToCompositeIndexScanner) Scan(src []byte, target any) error { - targetScanner := (target).(CompositeIndexScanner) + targetScanner := target.(CompositeIndexScanner) if src == nil { return targetScanner.ScanNull() @@ -277,9 +280,8 @@ func (c *CompositeCodec) DecodeValue(m *Map, oid uint32, format int16, src []byt } type CompositeBinaryScanner struct { - m *Map - rp int - src []byte + m *Map + r *pgio.Reader fieldCount int32 fieldBytes []byte @@ -289,19 +291,18 @@ type CompositeBinaryScanner struct { // NewCompositeBinaryScanner a scanner over a binary encoded composite value. func NewCompositeBinaryScanner(m *Map, src []byte) *CompositeBinaryScanner { - rp := 0 - if len(src[rp:]) < 4 { - return &CompositeBinaryScanner{err: fmt.Errorf("Record incomplete %v", src)} - } + r := pgio.NewReader(src) - fieldCount := int32(binary.BigEndian.Uint32(src[rp:])) - rp += 4 + // Each field requires at least 8 bytes: 4 for the OID and 4 for the length prefix. + fieldCount := r.Count(8) + if err := r.Err(); err != nil { + return &CompositeBinaryScanner{err: fmt.Errorf("Record incomplete: %w", err)} + } return &CompositeBinaryScanner{ m: m, - rp: rp, - src: src, - fieldCount: fieldCount, + r: r, + fieldCount: int32(fieldCount), } } @@ -312,30 +313,16 @@ func (cfs *CompositeBinaryScanner) Next() bool { return false } - if cfs.rp == len(cfs.src) { + if cfs.r.Remaining() == 0 { return false } - if len(cfs.src[cfs.rp:]) < 8 { - cfs.err = fmt.Errorf("Record incomplete %v", cfs.src) + cfs.fieldOID = cfs.r.Uint32() + cfs.fieldBytes, _ = cfs.r.Value() + if err := cfs.r.Err(); err != nil { + cfs.err = fmt.Errorf("Record incomplete: %w", err) return false } - cfs.fieldOID = binary.BigEndian.Uint32(cfs.src[cfs.rp:]) - cfs.rp += 4 - - fieldLen := int(int32(binary.BigEndian.Uint32(cfs.src[cfs.rp:]))) - cfs.rp += 4 - - if fieldLen >= 0 { - if len(cfs.src[cfs.rp:]) < fieldLen { - cfs.err = fmt.Errorf("Record incomplete rp=%d src=%v", cfs.rp, cfs.src) - return false - } - cfs.fieldBytes = cfs.src[cfs.rp : cfs.rp+fieldLen] - cfs.rp += fieldLen - } else { - cfs.fieldBytes = nil - } return true } @@ -344,6 +331,17 @@ func (cfs *CompositeBinaryScanner) FieldCount() int { return int(cfs.fieldCount) } +// compositeFieldTarget returns the scan target for field i. CompositeFields is +// a slice, so indexing past its end would panic. A source with more fields than +// the destination is a mismatch that must be reported as an error. +func compositeFieldTarget(targetScanner CompositeIndexScanner, i int) (any, error) { + if cf, ok := targetScanner.(CompositeFields); ok && i >= len(cf) { + return nil, fmt.Errorf("cannot scan composite field %d into CompositeFields of length %d", i, len(cf)) + } + + return targetScanner.ScanIndex(i), nil +} + // Bytes returns the bytes of the field most recently read by Scan(). func (cfs *CompositeBinaryScanner) Bytes() []byte { return cfs.fieldBytes @@ -396,7 +394,7 @@ func (cfs *CompositeTextScanner) Next() bool { return false } - if cfs.rp == len(cfs.src) { + if cfs.rp >= len(cfs.src) { return false } @@ -410,12 +408,18 @@ func (cfs *CompositeTextScanner) Next() bool { cfs.fieldBytes = make([]byte, 0, 16) quotedValue: for { + // A quote or escape may have consumed the final ')', leaving an + // unterminated quoted field. + if cfs.rp >= len(cfs.src) { + cfs.err = fmt.Errorf("composite text format unterminated quoted field") + return false + } ch := cfs.src[cfs.rp] switch ch { case '"': cfs.rp++ - if cfs.src[cfs.rp] == '"' { + if cfs.rp < len(cfs.src) && cfs.src[cfs.rp] == '"' { cfs.fieldBytes = append(cfs.fieldBytes, '"') cfs.rp++ } else { @@ -423,6 +427,10 @@ func (cfs *CompositeTextScanner) Next() bool { } case '\\': cfs.rp++ + if cfs.rp >= len(cfs.src) { + cfs.err = fmt.Errorf("composite text format unterminated quoted field") + return false + } cfs.fieldBytes = append(cfs.fieldBytes, cfs.src[cfs.rp]) cfs.rp++ default: diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/date.go b/vendor/github.com/jackc/pgx/v5/pgtype/date.go index 305d83c..82c5e74 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/date.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/date.go @@ -2,12 +2,11 @@ package pgtype import ( "database/sql/driver" - "encoding/binary" "encoding/json" "fmt" - "strconv" "time" + "github.com/jackc/pgx/v5/internal/pgdatetime" "github.com/jackc/pgx/v5/internal/pgio" ) @@ -189,33 +188,7 @@ func (encodePlanDateCodecText) Encode(value any, buf []byte) (newBuf []byte, err switch date.InfinityModifier { case Finite: - // Year 0000 is 1 BC - bc := false - year := date.Time.Year() - if year <= 0 { - year = -year + 1 - bc = true - } - - yearBytes := strconv.AppendInt(make([]byte, 0, 6), int64(year), 10) - for i := len(yearBytes); i < 4; i++ { - buf = append(buf, '0') - } - buf = append(buf, yearBytes...) - buf = append(buf, '-') - if date.Time.Month() < 10 { - buf = append(buf, '0') - } - buf = strconv.AppendInt(buf, int64(date.Time.Month()), 10) - buf = append(buf, '-') - if date.Time.Day() < 10 { - buf = append(buf, '0') - } - buf = strconv.AppendInt(buf, int64(date.Time.Day()), 10) - - if bc { - buf = append(buf, " BC"...) - } + buf = pgdatetime.AppendDate(buf, date.Time) case Infinity: buf = append(buf, "infinity"...) case NegativeInfinity: @@ -243,17 +216,18 @@ func (DateCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan type scanPlanBinaryDateToDateScanner struct{} func (scanPlanBinaryDateToDateScanner) Scan(src []byte, dst any) error { - scanner := (dst).(DateScanner) + scanner := dst.(DateScanner) if src == nil { return scanner.ScanDate(Date{}) } - if len(src) != 4 { - return fmt.Errorf("invalid length for date: %v", len(src)) + raw, err := pgio.Uint32Exact(src) + if err != nil { + return fmt.Errorf("date: %w", err) } - dayOffset := int32(binary.BigEndian.Uint32(src)) + dayOffset := int32(raw) switch dayOffset { case infinityDayOffset: @@ -262,6 +236,10 @@ func (scanPlanBinaryDateToDateScanner) Scan(src []byte, dst any) error { return scanner.ScanDate(Date{InfinityModifier: -Infinity, Valid: true}) default: t := time.Date(2000, 1, int(1+dayOffset), 0, 0, 0, 0, time.UTC) + if t.Before(minDateTime) || !t.Before(endDate) { + return fmt.Errorf("date %d days from 2000-01-01 is out of range", dayOffset) + } + return scanner.ScanDate(Date{Time: t, Valid: true}) } } @@ -269,112 +247,33 @@ func (scanPlanBinaryDateToDateScanner) Scan(src []byte, dst any) error { type scanPlanTextAnyToDateScanner struct{} func (scanPlanTextAnyToDateScanner) Scan(src []byte, dst any) error { - scanner := (dst).(DateScanner) + scanner := dst.(DateScanner) if src == nil { return scanner.ScanDate(Date{}) } - // Check infinity cases first - if len(src) == 8 && string(src) == "infinity" { - return scanner.ScanDate(Date{InfinityModifier: Infinity, Valid: true}) - } - if len(src) == 9 && string(src) == "-infinity" { - return scanner.ScanDate(Date{InfinityModifier: -Infinity, Valid: true}) - } - - // Format: YYYY-MM-DD or YYYY...-MM-DD BC - // Minimum: 10 chars (2000-01-01), with BC: 13 chars - if len(src) < 10 { - return fmt.Errorf("invalid date format") - } - - // Check for BC suffix - bc := false - datePart := src - if len(src) >= 13 && string(src[len(src)-3:]) == " BC" { - bc = true - datePart = src[:len(src)-3] - } - - // Find year-month separator (first dash after at least 4 digits) - yearEnd := -1 - for i := 4; i < len(datePart); i++ { - if datePart[i] == '-' { - yearEnd = i - break - } - if datePart[i] < '0' || datePart[i] > '9' { - return fmt.Errorf("invalid date format") - } - } - if yearEnd == -1 || yearEnd+6 > len(datePart) { - return fmt.Errorf("invalid date format") - } - - // Validate: -MM-DD structure after year - if datePart[yearEnd+3] != '-' { - return fmt.Errorf("invalid date format") - } - - // Parse year - year, err := parseDigits(datePart[:yearEnd]) + dt, err := parseTextDateTime(src) if err != nil { - return fmt.Errorf("invalid date format") + return err } - // Parse month (2 digits) - month, err := parse2Digits(datePart[yearEnd+1 : yearEnd+3]) + if dt.infinity != Finite { + return scanner.ScanDate(Date{InfinityModifier: dt.infinity, Valid: true}) + } + + if dt.hasTime { + return badDateTime(src) + } + + t, err := dt.toTime(src, "date", endDate) if err != nil { - return fmt.Errorf("invalid date format") + return err } - // Parse day (2 digits) - day, err := parse2Digits(datePart[yearEnd+4 : yearEnd+6]) - if err != nil { - return fmt.Errorf("invalid date format") - } - - // Ensure nothing extra after day - if yearEnd+6 != len(datePart) { - return fmt.Errorf("invalid date format") - } - - if bc { - year = -year + 1 - } - - t := time.Date(int(year), time.Month(month), int(day), 0, 0, 0, 0, time.UTC) return scanner.ScanDate(Date{Time: t, Valid: true}) } -// parse2Digits parses exactly 2 ASCII digits. -func parse2Digits(b []byte) (int64, error) { - if len(b) != 2 { - return 0, fmt.Errorf("expected 2 digits") - } - d1, d2 := b[0], b[1] - if d1 < '0' || d1 > '9' || d2 < '0' || d2 > '9' { - return 0, fmt.Errorf("expected digits") - } - return int64(d1-'0')*10 + int64(d2-'0'), nil -} - -// parseDigits parses a sequence of ASCII digits. -func parseDigits(b []byte) (int64, error) { - if len(b) == 0 { - return 0, fmt.Errorf("empty") - } - var n int64 - for _, c := range b { - if c < '0' || c > '9' { - return 0, fmt.Errorf("non-digit") - } - n = n*10 + int64(c-'0') - } - return n, nil -} - func (c DateCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { if src == nil { return nil, nil diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/datetime_text.go b/vendor/github.com/jackc/pgx/v5/pgtype/datetime_text.go new file mode 100644 index 0000000..6a7ff76 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgtype/datetime_text.go @@ -0,0 +1,378 @@ +package pgtype + +import ( + "fmt" + "math" + "strconv" + "time" +) + +// PostgreSQL's ISO date/time output grammar, from EncodeDateTime, EncodeTimezone and +// AppendSeconds in src/backend/utils/adt/datetime.c (the USE_ISO_DATES branch): +// +// value = "infinity" / "-infinity" / stamp +// stamp = date [ SP time [ offset ] ] [ " BC" ] +// date = year "-" 2DIGIT "-" 2DIGIT +// year = 4*DIGIT ; zero-padded to exactly 4, never wider than necessary +// time = 2DIGIT ":" 2DIGIT ":" 2DIGIT [ "." 1*6DIGIT ] +// offset = ("+" / "-") 2*DIGIT [ ":" 2DIGIT [ ":" 2DIGIT ] ] +// +// " BC" is always last, after any offset. Fractional seconds are omitted entirely when +// zero and never carry trailing zeros. This is only the shape the server emits under the +// default ISO DateStyle; the other styles are not supported. +// +// Writing the format is the other half of this and lives in internal/pgdatetime, which the +// simple protocol's query sanitizer shares. + +const ( + secondsPerHour = 60 * 60 + + // maxDateTimeYearDigits is the width of the largest year PostgreSQL can represent, + // which is date's 5874897. Capping the digit count keeps the accumulated year inside + // an int on 32 bit platforms as well as 64 bit ones. + maxDateTimeYearDigits = 7 +) + +// PostgreSQL's valid ranges, from src/include/datatype/timestamp.h. They differ by type: +// date runs to 5874897 AD (JULIAN_MAXYEAR) while timestamp stops at 294276 AD +// (END_TIMESTAMP). Both share a lower bound of 4714-11-24 BC. +var ( + minDateTime = time.Date(-4713, 11, 24, 0, 0, 0, 0, time.UTC) + endDate = time.Date(5874898, 1, 1, 0, 0, 0, 0, time.UTC) + endTimestamp = time.Date(294277, 1, 1, 0, 0, 0, 0, time.UTC) +) + +// textDateTime is a date/time value parsed from PostgreSQL's text format. It holds the +// fields as written on the wire rather than a time.Time so that each codec can apply its +// own range limits and time zone rules. +type textDateTime struct { + // year uses astronomical numbering: 1 BC is 0, 2 BC is -1. + year int + month int + day int + + hour int + min int + sec int + // nsec is always a multiple of 1000. Fractional seconds are rounded to microseconds + // the way the server rounds them. + nsec int + + // offset is seconds east of UTC and is only meaningful when hasOffset is true. + offset int + + hasTime bool + hasOffset bool + + infinity InfinityModifier +} + +// in builds the parsed fields as a time.Time in loc. The fields are a wall clock reading, +// so this reinterprets them in loc rather than converting an instant into it. +func (dt textDateTime) in(loc *time.Location) time.Time { + return time.Date(dt.year, time.Month(dt.month), dt.day, dt.hour, dt.min, dt.sec, dt.nsec, loc) +} + +// toTime resolves the parsed fields to the instant they name, applying any time zone +// offset, and rejects anything outside the range of the type named by name. The upper +// limit differs by type -- date reaches 5874897 AD while timestamp stops at 294276 AD -- +// so end is supplied by the caller and is exclusive. src is only used to build the error. +func (dt textDateTime) toTime(src []byte, name string, end time.Time) (time.Time, error) { + t := dt.in(time.UTC).Add(-time.Duration(dt.offset) * time.Second) + if t.Before(minDateTime) || !t.Before(end) { + return time.Time{}, fmt.Errorf("%s %q is out of range", name, src) + } + + return t, nil +} + +// parseTextDateTime parses the grammar above. It validates the grammar and the calendar +// but applies no range limits, because PostgreSQL's limits differ by type: date reaches +// 5874897 AD while timestamp stops at 294276 AD. +func parseTextDateTime(src []byte) (textDateTime, error) { + var dt textDateTime + + switch string(src) { + case "infinity": + dt.infinity = Infinity + return dt, nil + case "-infinity": + dt.infinity = NegativeInfinity + return dt, nil + } + + s := src + bc := false + if len(s) > 3 && s[len(s)-3] == ' ' && s[len(s)-2] == 'B' && s[len(s)-1] == 'C' { + s = s[:len(s)-3] + bc = true + } + + i := 0 + + // Year. Variable width, so it runs to the first non-digit rather than a fixed offset. + yearStart := i + for i < len(s) && isDigit(s[i]) { + if i-yearStart >= maxDateTimeYearDigits { + return dt, badDateTime(src) + } + dt.year = dt.year*10 + int(s[i]-'0') + i++ + } + if i-yearStart < 4 || dt.year < 1 { + return dt, badDateTime(src) + } + + var ok bool + if i, ok = expect(s, i, '-'); !ok { + return dt, badDateTime(src) + } + if dt.month, i, ok = parse2Digits(s, i); !ok { + return dt, badDateTime(src) + } + if i, ok = expect(s, i, '-'); !ok { + return dt, badDateTime(src) + } + if dt.day, i, ok = parse2Digits(s, i); !ok { + return dt, badDateTime(src) + } + + if bc { + dt.year = 1 - dt.year + } + + if dt.month < 1 || dt.month > 12 || dt.day < 1 || dt.day > daysInMonth(dt.year, dt.month) { + return dt, badDateTime(src) + } + + // Time of day. + var carrySecond bool + if i < len(s) && s[i] == ' ' { + i++ + dt.hasTime = true + + if dt.hour, i, ok = parse2Digits(s, i); !ok { + return dt, badDateTime(src) + } + if i, ok = expect(s, i, ':'); !ok { + return dt, badDateTime(src) + } + if dt.min, i, ok = parse2Digits(s, i); !ok { + return dt, badDateTime(src) + } + if i, ok = expect(s, i, ':'); !ok { + return dt, badDateTime(src) + } + if dt.sec, i, ok = parse2Digits(s, i); !ok { + return dt, badDateTime(src) + } + if dt.hour > 23 || dt.min > 59 || dt.sec > 59 { + return dt, badDateTime(src) + } + + if i < len(s) && s[i] == '.' { + i++ + fracStart := i + for i < len(s) && isDigit(s[i]) { + i++ + } + if i == fracStart { + return dt, badDateTime(src) + } + + usec, err := roundFractionToMicroseconds(s[fracStart:i]) + if err != nil { + return dt, badDateTime(src) + } + if usec == microsecondsPerSecond { + usec = 0 + carrySecond = true + } + dt.nsec = usec * 1000 + } + + // Time zone displacement. + if i < len(s) { + switch s[i] { + case 'Z': + // Not something the server emits, but pgx's own text encoder writes it. + i++ + dt.hasOffset = true + case '+', '-': + if dt.offset, i, ok = parseOffset(s, i); !ok { + return dt, badDateTime(src) + } + dt.hasOffset = true + } + } + } + + if i != len(s) { + return dt, badDateTime(src) + } + + if carrySecond { + dt.addSecond() + } + + return dt, nil +} + +// addSecond advances by one second, carrying through to the year. It is only reached when +// rounding the fractional part rolls over, and it assumes the fields are already valid. +func (dt *textDateTime) addSecond() { + dt.sec++ + if dt.sec < 60 { + return + } + dt.sec = 0 + + dt.min++ + if dt.min < 60 { + return + } + dt.min = 0 + + dt.hour++ + if dt.hour < 24 { + return + } + dt.hour = 0 + + dt.day++ + if dt.day <= daysInMonth(dt.year, dt.month) { + return + } + dt.day = 1 + + dt.month++ + if dt.month <= 12 { + return + } + dt.month = 1 + + // Astronomical numbering has a year 0, so this needs no adjustment for the AD/BC + // boundary. + dt.year++ +} + +// roundFractionToMicroseconds converts fractional second digits to microseconds. The +// result may be microsecondsPerSecond, which the caller must carry. +func roundFractionToMicroseconds(digits []byte) (int, error) { + if len(digits) <= 6 { + usec := 0 + for _, c := range digits { + usec = usec*10 + int(c-'0') + } + for i := len(digits); i < 6; i++ { + usec *= 10 + } + return usec, nil + } + + // PostgreSQL's ParseFractionalSecond reads the fraction with strtod and rounds with + // rint, which is round-half-to-even on a binary double. Mirror that arithmetic + // exactly rather than rounding the decimal digits, so that values the server rounds + // down are not rounded up here: the server turns .0000005 into 0, while rounding the + // digits half away from zero would produce 1 microsecond. + // + // The server never emits more than six digits, so this path only handles input from + // other sources. + f, err := strconv.ParseFloat("0."+string(digits), 64) + if err != nil { + return 0, err + } + + return int(math.RoundToEven(f * 1e6)), nil +} + +func parseOffset(s []byte, i int) (offset, next int, ok bool) { + neg := s[i] == '-' + i++ + + var hour, min, sec int + if hour, i, ok = parse2Digits(s, i); !ok { + return 0, i, false + } + // PostgreSQL's MAX_TZDISP_HOUR limits numeric input, not output from named + // or POSIX time zones. These can emit offsets with more than two hour digits. + // Bound by the server's int32 seconds representation instead. + for i < len(s) && isDigit(s[i]) { + hour = hour*10 + int(s[i]-'0') + i++ + if hour > math.MaxInt32/secondsPerHour { + return 0, i, false + } + } + if i, ok = expect(s, i, ':'); ok { + if min, i, ok = parse2Digits(s, i); !ok { + return 0, i, false + } + if i, ok = expect(s, i, ':'); ok { + if sec, i, ok = parse2Digits(s, i); !ok { + return 0, i, false + } + } + } + + if min > 59 || sec > 59 { + return 0, i, false + } + + seconds := int64(hour)*secondsPerHour + int64(min*60+sec) + if neg { + seconds = -seconds + } + if seconds < math.MinInt32 || seconds > math.MaxInt32 { + return 0, i, false + } + + return int(seconds), i, true +} + +func parse2Digits(s []byte, i int) (v, next int, ok bool) { + if i+1 >= len(s) || !isDigit(s[i]) || !isDigit(s[i+1]) { + return 0, i, false + } + return int(s[i]-'0')*10 + int(s[i+1]-'0'), i + 2, true +} + +func expect(s []byte, i int, c byte) (next int, ok bool) { + if i >= len(s) || s[i] != c { + return i, false + } + return i + 1, true +} + +func isDigit(c byte) bool { return c >= '0' && c <= '9' } + +func badDateTime(src []byte) error { + const maxLen = 64 + s := string(src) + if len(s) > maxLen { + s = s[:maxLen] + "..." + } + return fmt.Errorf("invalid PostgreSQL date/time value %q", s) +} + +// isLeapYear reports whether year, in astronomical numbering, is a leap year in the +// proleptic Gregorian calendar. Go's % keeps the sign of the dividend, so the usual +// divisibility tests hold for years at or below zero. +func isLeapYear(year int) bool { + return year%4 == 0 && (year%100 != 0 || year%400 == 0) +} + +func daysInMonth(year, month int) int { + switch month { + case 1, 3, 5, 7, 8, 10, 12: + return 31 + case 4, 6, 9, 11: + return 30 + case 2: + if isLeapYear(year) { + return 29 + } + return 28 + } + return 0 +} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/enum_codec.go b/vendor/github.com/jackc/pgx/v5/pgtype/enum_codec.go index 5e787c1..f4173ad 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/enum_codec.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/enum_codec.go @@ -88,7 +88,7 @@ func (plan *scanPlanTextAnyToEnumString) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - p := (dst).(*string) + p := dst.(*string) *p = plan.codec.lookupAndCacheString(src) return nil @@ -99,7 +99,7 @@ type scanPlanTextAnyToEnumTextScanner struct { } func (plan *scanPlanTextAnyToEnumTextScanner) Scan(src []byte, dst any) error { - scanner := (dst).(TextScanner) + scanner := dst.(TextScanner) if src == nil { return scanner.ScanText(Text{}) diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/float4.go b/vendor/github.com/jackc/pgx/v5/pgtype/float4.go index a43553f..64e3d5b 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/float4.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/float4.go @@ -2,7 +2,6 @@ package pgtype import ( "database/sql/driver" - "encoding/binary" "encoding/json" "fmt" "math" @@ -140,7 +139,7 @@ type encodePlanTextFloat32 struct{} func (encodePlanTextFloat32) Encode(value any, buf []byte) (newBuf []byte, err error) { n := value.(float32) - return append(buf, strconv.FormatFloat(float64(n), 'f', -1, 32)...), nil + return strconv.AppendFloat(buf, float64(n), 'f', -1, 32), nil } type encodePlanFloat4CodecBinaryFloat64Valuer struct{} @@ -208,12 +207,13 @@ func (scanPlanBinaryFloat4ToFloat32) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 4 { - return fmt.Errorf("invalid length for float4: %v", len(src)) + raw, err := pgio.Uint32Exact(src) + if err != nil { + return fmt.Errorf("float4: %w", err) } - n := int32(binary.BigEndian.Uint32(src)) - f := (dst).(*float32) + n := int32(raw) + f := dst.(*float32) *f = math.Float32frombits(uint32(n)) return nil @@ -222,34 +222,36 @@ func (scanPlanBinaryFloat4ToFloat32) Scan(src []byte, dst any) error { type scanPlanBinaryFloat4ToFloat64Scanner struct{} func (scanPlanBinaryFloat4ToFloat64Scanner) Scan(src []byte, dst any) error { - s := (dst).(Float64Scanner) + s := dst.(Float64Scanner) if src == nil { return s.ScanFloat64(Float8{}) } - if len(src) != 4 { - return fmt.Errorf("invalid length for float4: %v", len(src)) + raw, err := pgio.Uint32Exact(src) + if err != nil { + return fmt.Errorf("float4: %w", err) } - n := int32(binary.BigEndian.Uint32(src)) + n := int32(raw) return s.ScanFloat64(Float8{Float64: float64(math.Float32frombits(uint32(n))), Valid: true}) } type scanPlanBinaryFloat4ToInt64Scanner struct{} func (scanPlanBinaryFloat4ToInt64Scanner) Scan(src []byte, dst any) error { - s := (dst).(Int64Scanner) + s := dst.(Int64Scanner) if src == nil { return s.ScanInt64(Int8{}) } - if len(src) != 4 { - return fmt.Errorf("invalid length for float4: %v", len(src)) + raw, err := pgio.Uint32Exact(src) + if err != nil { + return fmt.Errorf("float4: %w", err) } - ui32 := int32(binary.BigEndian.Uint32(src)) + ui32 := int32(raw) f32 := math.Float32frombits(uint32(ui32)) i64 := int64(f32) if f32 != float32(i64) { @@ -262,17 +264,18 @@ func (scanPlanBinaryFloat4ToInt64Scanner) Scan(src []byte, dst any) error { type scanPlanBinaryFloat4ToTextScanner struct{} func (scanPlanBinaryFloat4ToTextScanner) Scan(src []byte, dst any) error { - s := (dst).(TextScanner) + s := dst.(TextScanner) if src == nil { return s.ScanText(Text{}) } - if len(src) != 4 { - return fmt.Errorf("invalid length for float4: %v", len(src)) + raw, err := pgio.Uint32Exact(src) + if err != nil { + return fmt.Errorf("float4: %w", err) } - ui32 := int32(binary.BigEndian.Uint32(src)) + ui32 := int32(raw) f32 := math.Float32frombits(uint32(ui32)) return s.ScanText(Text{String: strconv.FormatFloat(float64(f32), 'f', -1, 32), Valid: true}) @@ -290,7 +293,7 @@ func (scanPlanTextAnyToFloat32) Scan(src []byte, dst any) error { return err } - f := (dst).(*float32) + f := dst.(*float32) *f = float32(n) return nil diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/float8.go b/vendor/github.com/jackc/pgx/v5/pgtype/float8.go index 6234231..c30d53b 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/float8.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/float8.go @@ -2,7 +2,6 @@ package pgtype import ( "database/sql/driver" - "encoding/binary" "encoding/json" "fmt" "math" @@ -148,7 +147,7 @@ type encodePlanTextFloat64 struct{} func (encodePlanTextFloat64) Encode(value any, buf []byte) (newBuf []byte, err error) { n := value.(float64) - return append(buf, strconv.FormatFloat(n, 'f', -1, 64)...), nil + return strconv.AppendFloat(buf, n, 'f', -1, 64), nil } type encodePlanFloat8CodecBinaryFloat64Valuer struct{} @@ -178,7 +177,7 @@ func (encodePlanTextFloat64Valuer) Encode(value any, buf []byte) (newBuf []byte, return nil, nil } - return append(buf, strconv.FormatFloat(n.Float64, 'f', -1, 64)...), nil + return strconv.AppendFloat(buf, n.Float64, 'f', -1, 64), nil } type encodePlanFloat8CodecBinaryInt64Valuer struct{} @@ -209,7 +208,7 @@ func (encodePlanTextInt64Valuer) Encode(value any, buf []byte) (newBuf []byte, e return nil, nil } - return append(buf, strconv.FormatInt(n.Int64, 10)...), nil + return strconv.AppendInt(buf, n.Int64, 10), nil } func (Float8Codec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { @@ -246,12 +245,13 @@ func (scanPlanBinaryFloat8ToFloat64) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 8 { - return fmt.Errorf("invalid length for float8: %v", len(src)) + raw, err := pgio.Uint64Exact(src) + if err != nil { + return fmt.Errorf("float8: %w", err) } - n := int64(binary.BigEndian.Uint64(src)) - f := (dst).(*float64) + n := int64(raw) + f := dst.(*float64) *f = math.Float64frombits(uint64(n)) return nil @@ -260,34 +260,36 @@ func (scanPlanBinaryFloat8ToFloat64) Scan(src []byte, dst any) error { type scanPlanBinaryFloat8ToFloat64Scanner struct{} func (scanPlanBinaryFloat8ToFloat64Scanner) Scan(src []byte, dst any) error { - s := (dst).(Float64Scanner) + s := dst.(Float64Scanner) if src == nil { return s.ScanFloat64(Float8{}) } - if len(src) != 8 { - return fmt.Errorf("invalid length for float8: %v", len(src)) + raw, err := pgio.Uint64Exact(src) + if err != nil { + return fmt.Errorf("float8: %w", err) } - n := int64(binary.BigEndian.Uint64(src)) + n := int64(raw) return s.ScanFloat64(Float8{Float64: math.Float64frombits(uint64(n)), Valid: true}) } type scanPlanBinaryFloat8ToInt64Scanner struct{} func (scanPlanBinaryFloat8ToInt64Scanner) Scan(src []byte, dst any) error { - s := (dst).(Int64Scanner) + s := dst.(Int64Scanner) if src == nil { return s.ScanInt64(Int8{}) } - if len(src) != 8 { - return fmt.Errorf("invalid length for float8: %v", len(src)) + raw, err := pgio.Uint64Exact(src) + if err != nil { + return fmt.Errorf("float8: %w", err) } - ui64 := int64(binary.BigEndian.Uint64(src)) + ui64 := int64(raw) f64 := math.Float64frombits(uint64(ui64)) i64 := int64(f64) if f64 != float64(i64) { @@ -300,17 +302,18 @@ func (scanPlanBinaryFloat8ToInt64Scanner) Scan(src []byte, dst any) error { type scanPlanBinaryFloat8ToTextScanner struct{} func (scanPlanBinaryFloat8ToTextScanner) Scan(src []byte, dst any) error { - s := (dst).(TextScanner) + s := dst.(TextScanner) if src == nil { return s.ScanText(Text{}) } - if len(src) != 8 { - return fmt.Errorf("invalid length for float8: %v", len(src)) + raw, err := pgio.Uint64Exact(src) + if err != nil { + return fmt.Errorf("float8: %w", err) } - ui64 := int64(binary.BigEndian.Uint64(src)) + ui64 := int64(raw) f64 := math.Float64frombits(uint64(ui64)) return s.ScanText(Text{String: strconv.FormatFloat(f64, 'f', -1, 64), Valid: true}) @@ -328,7 +331,7 @@ func (scanPlanTextAnyToFloat64) Scan(src []byte, dst any) error { return err } - f := (dst).(*float64) + f := dst.(*float64) *f = n return nil @@ -337,7 +340,7 @@ func (scanPlanTextAnyToFloat64) Scan(src []byte, dst any) error { type scanPlanTextAnyToFloat64Scanner struct{} func (scanPlanTextAnyToFloat64Scanner) Scan(src []byte, dst any) error { - s := (dst).(Float64Scanner) + s := dst.(Float64Scanner) if src == nil { return s.ScanFloat64(Float8{}) diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/hstore.go b/vendor/github.com/jackc/pgx/v5/pgtype/hstore.go index 4a2bb0a..5813768 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/hstore.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/hstore.go @@ -2,7 +2,6 @@ package pgtype import ( "database/sql/driver" - "encoding/binary" "errors" "fmt" "strings" @@ -180,29 +179,19 @@ func (HstoreCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPl type scanPlanBinaryHstoreToHstoreScanner struct{} func (scanPlanBinaryHstoreToHstoreScanner) Scan(src []byte, dst any) error { - scanner := (dst).(HstoreScanner) + scanner := dst.(HstoreScanner) if src == nil { return scanner.ScanHstore(Hstore(nil)) } - rp := 0 + r := pgio.NewReader(src) - const uint32Len = 4 - if len(src[rp:]) < uint32Len { - return fmt.Errorf("hstore incomplete %v", src) - } - pairCount := int(int32(binary.BigEndian.Uint32(src[rp:]))) - rp += uint32Len - - if pairCount < 0 { - return fmt.Errorf("hstore invalid pair count: %d", pairCount) - } - // Each pair carries at minimum two int32 length headers (key, value), so pairCount cannot - // exceed the remaining bytes / 8. This bounds the up-front make() against a malicious server - // claiming a huge pair count in a small message. - if maxPairs := len(src[rp:]) / (2 * uint32Len); pairCount > maxPairs { - return fmt.Errorf("hstore invalid pair count %d for %d remaining bytes", pairCount, len(src[rp:])) + // Each pair carries at minimum two int32 length headers (key, value). This bounds the + // up-front make() against a malicious server claiming a huge pair count in a small message. + pairCount := r.Count(8) + if err := r.Err(); err != nil { + return fmt.Errorf("hstore: %w", err) } hstore := make(Hstore, pairCount) @@ -210,47 +199,34 @@ func (scanPlanBinaryHstoreToHstoreScanner) Scan(src []byte, dst any) error { valueStrings := make([]string, pairCount) for i := range pairCount { - if len(src[rp:]) < uint32Len { - return fmt.Errorf("hstore incomplete %v", src) + keyBytes, keyNull := r.Value() + valueBytes, valueNull := r.Value() + if err := r.Err(); err != nil { + return fmt.Errorf("hstore pair %d: %w", i, err) } - keyLen := int(int32(binary.BigEndian.Uint32(src[rp:]))) - rp += uint32Len - - if keyLen < 0 { - return fmt.Errorf("hstore invalid key length: %d", keyLen) + if keyNull { + return fmt.Errorf("hstore pair %d: key cannot be NULL", i) } - if len(src[rp:]) < keyLen { - return fmt.Errorf("hstore incomplete %v", src) - } - key := string(src[rp : rp+keyLen]) - rp += keyLen - if len(src[rp:]) < uint32Len { - return fmt.Errorf("hstore incomplete %v", src) - } - valueLen := int(int32(binary.BigEndian.Uint32(src[rp:]))) - rp += 4 - - if valueLen >= 0 { - if len(src[rp:]) < valueLen { - return fmt.Errorf("hstore incomplete %v", src) - } - valueStrings[i] = string(src[rp : rp+valueLen]) - rp += valueLen - - hstore[key] = &valueStrings[i] - } else { + key := string(keyBytes) + if valueNull { hstore[key] = nil + } else { + valueStrings[i] = string(valueBytes) + hstore[key] = &valueStrings[i] } } + if err := r.Finish(); err != nil { + return fmt.Errorf("hstore: %w", err) + } return scanner.ScanHstore(hstore) } type scanPlanTextAnyToHstoreScanner struct{} func (s scanPlanTextAnyToHstoreScanner) Scan(src []byte, dst any) error { - scanner := (dst).(HstoreScanner) + scanner := dst.(HstoreScanner) if src == nil { return scanner.ScanHstore(Hstore(nil)) @@ -455,8 +431,13 @@ func parseHstore(s string) (Hstore, error) { p := newHSP(s) // This is an over-estimate of the number of key/value pairs. Use '>' because I am guessing it - // is less likely to occur in keys/values than '=' or ','. + // is less likely to occur in keys/values than '=' or ','. Clamp so an unvalidated + // separator count cannot pre-size a huge map from garbage input. + const maxHstorePairsEstimate = 1024 numPairsEstimate := strings.Count(s, ">") + if numPairsEstimate > maxHstorePairsEstimate { + numPairsEstimate = maxHstorePairsEstimate + } // makes one allocation of strings for the entire Hstore, rather than one allocation per value. valueStrings := make([]string, 0, numPairsEstimate) result := make(Hstore, numPairsEstimate) diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/inet.go b/vendor/github.com/jackc/pgx/v5/pgtype/inet.go index 2592a5b..23155fe 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/inet.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/inet.go @@ -146,7 +146,7 @@ func (c InetCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (an type scanPlanBinaryInetToNetipPrefixScanner struct{} func (scanPlanBinaryInetToNetipPrefixScanner) Scan(src []byte, dst any) error { - scanner := (dst).(NetipPrefixScanner) + scanner := dst.(NetipPrefixScanner) if src == nil { return scanner.ScanNetipPrefix(netip.Prefix{}) @@ -172,7 +172,7 @@ func (scanPlanBinaryInetToNetipPrefixScanner) Scan(src []byte, dst any) error { type scanPlanTextAnyToNetipPrefixScanner struct{} func (scanPlanTextAnyToNetipPrefixScanner) Scan(src []byte, dst any) error { - scanner := (dst).(NetipPrefixScanner) + scanner := dst.(NetipPrefixScanner) if src == nil { return scanner.ScanNetipPrefix(netip.Prefix{}) diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/int.go b/vendor/github.com/jackc/pgx/v5/pgtype/int.go index 95032e5..f53c5df 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/int.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/int.go @@ -4,7 +4,6 @@ package pgtype import ( "database/sql/driver" - "encoding/binary" "encoding/json" "fmt" "math" @@ -163,7 +162,7 @@ type encodePlanInt2CodecTextInt16 struct{} func (encodePlanInt2CodecTextInt16) Encode(value any, buf []byte) (newBuf []byte, err error) { n := value.(int16) - return append(buf, strconv.FormatInt(int64(n), 10)...), nil + return strconv.AppendInt(buf, int64(n), 10), nil } type encodePlanInt2CodecBinaryInt64Valuer struct{} @@ -207,7 +206,7 @@ func (encodePlanInt2CodecTextInt64Valuer) Encode(value any, buf []byte) (newBuf return nil, fmt.Errorf("%d is less than minimum value for int2", n.Int64) } - return append(buf, strconv.FormatInt(n.Int64, 10)...), nil + return strconv.AppendInt(buf, n.Int64, 10), nil } func (Int2Codec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { @@ -303,8 +302,9 @@ func (scanPlanBinaryInt2ToInt8) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 2 { - return fmt.Errorf("invalid length for int2: %v", len(src)) + raw, err := pgio.Uint16Exact(src) + if err != nil { + return fmt.Errorf("int2: %w", err) } p, ok := (dst).(*int8) @@ -312,7 +312,7 @@ func (scanPlanBinaryInt2ToInt8) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - n := int16(binary.BigEndian.Uint16(src)) + n := int16(raw) if n < math.MinInt8 { return fmt.Errorf("%d is less than minimum value for int8", n) } else if n > math.MaxInt8 { @@ -331,8 +331,9 @@ func (scanPlanBinaryInt2ToUint8) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 2 { - return fmt.Errorf("invalid length for uint2: %v", len(src)) + raw, err := pgio.Uint16Exact(src) + if err != nil { + return fmt.Errorf("uint2: %w", err) } p, ok := (dst).(*uint8) @@ -340,7 +341,7 @@ func (scanPlanBinaryInt2ToUint8) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - n := int16(binary.BigEndian.Uint16(src)) + n := int16(raw) if n < 0 { return fmt.Errorf("%d is less than minimum value for uint8", n) } @@ -361,8 +362,9 @@ func (scanPlanBinaryInt2ToInt16) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 2 { - return fmt.Errorf("invalid length for int2: %v", len(src)) + raw, err := pgio.Uint16Exact(src) + if err != nil { + return fmt.Errorf("int2: %w", err) } p, ok := (dst).(*int16) @@ -370,7 +372,7 @@ func (scanPlanBinaryInt2ToInt16) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - *p = int16(binary.BigEndian.Uint16(src)) + *p = int16(raw) return nil } @@ -382,8 +384,9 @@ func (scanPlanBinaryInt2ToUint16) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 2 { - return fmt.Errorf("invalid length for uint2: %v", len(src)) + raw, err := pgio.Uint16Exact(src) + if err != nil { + return fmt.Errorf("uint2: %w", err) } p, ok := (dst).(*uint16) @@ -391,7 +394,7 @@ func (scanPlanBinaryInt2ToUint16) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - n := int16(binary.BigEndian.Uint16(src)) + n := int16(raw) if n < 0 { return fmt.Errorf("%d is less than minimum value for uint16", n) } @@ -408,8 +411,9 @@ func (scanPlanBinaryInt2ToInt32) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 2 { - return fmt.Errorf("invalid length for int2: %v", len(src)) + raw, err := pgio.Uint16Exact(src) + if err != nil { + return fmt.Errorf("int2: %w", err) } p, ok := (dst).(*int32) @@ -417,7 +421,7 @@ func (scanPlanBinaryInt2ToInt32) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - *p = int32(int16(binary.BigEndian.Uint16(src))) + *p = int32(int16(raw)) return nil } @@ -429,8 +433,9 @@ func (scanPlanBinaryInt2ToUint32) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 2 { - return fmt.Errorf("invalid length for uint2: %v", len(src)) + raw, err := pgio.Uint16Exact(src) + if err != nil { + return fmt.Errorf("uint2: %w", err) } p, ok := (dst).(*uint32) @@ -438,7 +443,7 @@ func (scanPlanBinaryInt2ToUint32) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - n := int16(binary.BigEndian.Uint16(src)) + n := int16(raw) if n < 0 { return fmt.Errorf("%d is less than minimum value for uint32", n) } @@ -455,8 +460,9 @@ func (scanPlanBinaryInt2ToInt64) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 2 { - return fmt.Errorf("invalid length for int2: %v", len(src)) + raw, err := pgio.Uint16Exact(src) + if err != nil { + return fmt.Errorf("int2: %w", err) } p, ok := (dst).(*int64) @@ -464,7 +470,7 @@ func (scanPlanBinaryInt2ToInt64) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - *p = int64(int16(binary.BigEndian.Uint16(src))) + *p = int64(int16(raw)) return nil } @@ -476,8 +482,9 @@ func (scanPlanBinaryInt2ToUint64) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 2 { - return fmt.Errorf("invalid length for uint2: %v", len(src)) + raw, err := pgio.Uint16Exact(src) + if err != nil { + return fmt.Errorf("uint2: %w", err) } p, ok := (dst).(*uint64) @@ -485,7 +492,7 @@ func (scanPlanBinaryInt2ToUint64) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - n := int16(binary.BigEndian.Uint16(src)) + n := int16(raw) if n < 0 { return fmt.Errorf("%d is less than minimum value for uint64", n) } @@ -502,8 +509,9 @@ func (scanPlanBinaryInt2ToInt) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 2 { - return fmt.Errorf("invalid length for int2: %v", len(src)) + raw, err := pgio.Uint16Exact(src) + if err != nil { + return fmt.Errorf("int2: %w", err) } p, ok := (dst).(*int) @@ -511,7 +519,7 @@ func (scanPlanBinaryInt2ToInt) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - *p = int(int16(binary.BigEndian.Uint16(src))) + *p = int(int16(raw)) return nil } @@ -523,8 +531,9 @@ func (scanPlanBinaryInt2ToUint) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 2 { - return fmt.Errorf("invalid length for uint2: %v", len(src)) + raw, err := pgio.Uint16Exact(src) + if err != nil { + return fmt.Errorf("uint2: %w", err) } p, ok := (dst).(*uint) @@ -532,7 +541,7 @@ func (scanPlanBinaryInt2ToUint) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - n := int64(int16(binary.BigEndian.Uint16(src))) + n := int64(int16(raw)) if n < 0 { return fmt.Errorf("%d is less than minimum value for uint", n) } @@ -554,11 +563,12 @@ func (scanPlanBinaryInt2ToInt64Scanner) Scan(src []byte, dst any) error { return s.ScanInt64(Int8{}) } - if len(src) != 2 { - return fmt.Errorf("invalid length for int2: %v", len(src)) + raw, err := pgio.Uint16Exact(src) + if err != nil { + return fmt.Errorf("int2: %w", err) } - n := int64(int16(binary.BigEndian.Uint16(src))) + n := int64(int16(raw)) return s.ScanInt64(Int8{Int64: n, Valid: true}) } @@ -575,11 +585,12 @@ func (scanPlanBinaryInt2ToTextScanner) Scan(src []byte, dst any) error { return s.ScanText(Text{}) } - if len(src) != 2 { - return fmt.Errorf("invalid length for int2: %v", len(src)) + raw, err := pgio.Uint16Exact(src) + if err != nil { + return fmt.Errorf("int2: %w", err) } - n := int64(int16(binary.BigEndian.Uint16(src))) + n := int64(int16(raw)) return s.ScanText(Text{String: strconv.FormatInt(n, 10), Valid: true}) } @@ -726,7 +737,7 @@ type encodePlanInt4CodecTextInt32 struct{} func (encodePlanInt4CodecTextInt32) Encode(value any, buf []byte) (newBuf []byte, err error) { n := value.(int32) - return append(buf, strconv.FormatInt(int64(n), 10)...), nil + return strconv.AppendInt(buf, int64(n), 10), nil } type encodePlanInt4CodecBinaryInt64Valuer struct{} @@ -770,7 +781,7 @@ func (encodePlanInt4CodecTextInt64Valuer) Encode(value any, buf []byte) (newBuf return nil, fmt.Errorf("%d is less than minimum value for int4", n.Int64) } - return append(buf, strconv.FormatInt(n.Int64, 10)...), nil + return strconv.AppendInt(buf, n.Int64, 10), nil } func (Int4Codec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { @@ -866,8 +877,9 @@ func (scanPlanBinaryInt4ToInt8) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 4 { - return fmt.Errorf("invalid length for int4: %v", len(src)) + raw, err := pgio.Uint32Exact(src) + if err != nil { + return fmt.Errorf("int4: %w", err) } p, ok := (dst).(*int8) @@ -875,7 +887,7 @@ func (scanPlanBinaryInt4ToInt8) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - n := int32(binary.BigEndian.Uint32(src)) + n := int32(raw) if n < math.MinInt8 { return fmt.Errorf("%d is less than minimum value for int8", n) } else if n > math.MaxInt8 { @@ -894,8 +906,9 @@ func (scanPlanBinaryInt4ToUint8) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 4 { - return fmt.Errorf("invalid length for uint4: %v", len(src)) + raw, err := pgio.Uint32Exact(src) + if err != nil { + return fmt.Errorf("uint4: %w", err) } p, ok := (dst).(*uint8) @@ -903,7 +916,7 @@ func (scanPlanBinaryInt4ToUint8) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - n := int32(binary.BigEndian.Uint32(src)) + n := int32(raw) if n < 0 { return fmt.Errorf("%d is less than minimum value for uint8", n) } @@ -924,8 +937,9 @@ func (scanPlanBinaryInt4ToInt16) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 4 { - return fmt.Errorf("invalid length for int4: %v", len(src)) + raw, err := pgio.Uint32Exact(src) + if err != nil { + return fmt.Errorf("int4: %w", err) } p, ok := (dst).(*int16) @@ -933,7 +947,7 @@ func (scanPlanBinaryInt4ToInt16) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - n := int32(binary.BigEndian.Uint32(src)) + n := int32(raw) if n < math.MinInt16 { return fmt.Errorf("%d is less than minimum value for int16", n) } else if n > math.MaxInt16 { @@ -952,8 +966,9 @@ func (scanPlanBinaryInt4ToUint16) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 4 { - return fmt.Errorf("invalid length for uint4: %v", len(src)) + raw, err := pgio.Uint32Exact(src) + if err != nil { + return fmt.Errorf("uint4: %w", err) } p, ok := (dst).(*uint16) @@ -961,7 +976,7 @@ func (scanPlanBinaryInt4ToUint16) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - n := int32(binary.BigEndian.Uint32(src)) + n := int32(raw) if n < 0 { return fmt.Errorf("%d is less than minimum value for uint16", n) } @@ -982,8 +997,9 @@ func (scanPlanBinaryInt4ToInt32) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 4 { - return fmt.Errorf("invalid length for int4: %v", len(src)) + raw, err := pgio.Uint32Exact(src) + if err != nil { + return fmt.Errorf("int4: %w", err) } p, ok := (dst).(*int32) @@ -991,7 +1007,7 @@ func (scanPlanBinaryInt4ToInt32) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - *p = int32(binary.BigEndian.Uint32(src)) + *p = int32(raw) return nil } @@ -1003,8 +1019,9 @@ func (scanPlanBinaryInt4ToUint32) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 4 { - return fmt.Errorf("invalid length for uint4: %v", len(src)) + raw, err := pgio.Uint32Exact(src) + if err != nil { + return fmt.Errorf("uint4: %w", err) } p, ok := (dst).(*uint32) @@ -1012,7 +1029,7 @@ func (scanPlanBinaryInt4ToUint32) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - n := int32(binary.BigEndian.Uint32(src)) + n := int32(raw) if n < 0 { return fmt.Errorf("%d is less than minimum value for uint32", n) } @@ -1029,8 +1046,9 @@ func (scanPlanBinaryInt4ToInt64) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 4 { - return fmt.Errorf("invalid length for int4: %v", len(src)) + raw, err := pgio.Uint32Exact(src) + if err != nil { + return fmt.Errorf("int4: %w", err) } p, ok := (dst).(*int64) @@ -1038,7 +1056,7 @@ func (scanPlanBinaryInt4ToInt64) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - *p = int64(int32(binary.BigEndian.Uint32(src))) + *p = int64(int32(raw)) return nil } @@ -1050,8 +1068,9 @@ func (scanPlanBinaryInt4ToUint64) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 4 { - return fmt.Errorf("invalid length for uint4: %v", len(src)) + raw, err := pgio.Uint32Exact(src) + if err != nil { + return fmt.Errorf("uint4: %w", err) } p, ok := (dst).(*uint64) @@ -1059,7 +1078,7 @@ func (scanPlanBinaryInt4ToUint64) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - n := int32(binary.BigEndian.Uint32(src)) + n := int32(raw) if n < 0 { return fmt.Errorf("%d is less than minimum value for uint64", n) } @@ -1076,8 +1095,9 @@ func (scanPlanBinaryInt4ToInt) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 4 { - return fmt.Errorf("invalid length for int4: %v", len(src)) + raw, err := pgio.Uint32Exact(src) + if err != nil { + return fmt.Errorf("int4: %w", err) } p, ok := (dst).(*int) @@ -1085,7 +1105,7 @@ func (scanPlanBinaryInt4ToInt) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - *p = int(int32(binary.BigEndian.Uint32(src))) + *p = int(int32(raw)) return nil } @@ -1097,8 +1117,9 @@ func (scanPlanBinaryInt4ToUint) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 4 { - return fmt.Errorf("invalid length for uint4: %v", len(src)) + raw, err := pgio.Uint32Exact(src) + if err != nil { + return fmt.Errorf("uint4: %w", err) } p, ok := (dst).(*uint) @@ -1106,7 +1127,7 @@ func (scanPlanBinaryInt4ToUint) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - n := int64(int32(binary.BigEndian.Uint32(src))) + n := int64(int32(raw)) if n < 0 { return fmt.Errorf("%d is less than minimum value for uint", n) } @@ -1128,11 +1149,12 @@ func (scanPlanBinaryInt4ToInt64Scanner) Scan(src []byte, dst any) error { return s.ScanInt64(Int8{}) } - if len(src) != 4 { - return fmt.Errorf("invalid length for int4: %v", len(src)) + raw, err := pgio.Uint32Exact(src) + if err != nil { + return fmt.Errorf("int4: %w", err) } - n := int64(int32(binary.BigEndian.Uint32(src))) + n := int64(int32(raw)) return s.ScanInt64(Int8{Int64: n, Valid: true}) } @@ -1149,11 +1171,12 @@ func (scanPlanBinaryInt4ToTextScanner) Scan(src []byte, dst any) error { return s.ScanText(Text{}) } - if len(src) != 4 { - return fmt.Errorf("invalid length for int4: %v", len(src)) + raw, err := pgio.Uint32Exact(src) + if err != nil { + return fmt.Errorf("int4: %w", err) } - n := int64(int32(binary.BigEndian.Uint32(src))) + n := int64(int32(raw)) return s.ScanText(Text{String: strconv.FormatInt(n, 10), Valid: true}) } @@ -1215,7 +1238,7 @@ func (dst *Int8) Scan(src any) error { } if n < math.MinInt64 { - return fmt.Errorf("%d is greater than maximum value for Int8", n) + return fmt.Errorf("%d is less than minimum value for Int8", n) } if n > math.MaxInt64 { return fmt.Errorf("%d is greater than maximum value for Int8", n) @@ -1300,7 +1323,7 @@ type encodePlanInt8CodecTextInt64 struct{} func (encodePlanInt8CodecTextInt64) Encode(value any, buf []byte) (newBuf []byte, err error) { n := value.(int64) - return append(buf, strconv.FormatInt(int64(n), 10)...), nil + return strconv.AppendInt(buf, int64(n), 10), nil } type encodePlanInt8CodecBinaryInt64Valuer struct{} @@ -1344,7 +1367,7 @@ func (encodePlanInt8CodecTextInt64Valuer) Encode(value any, buf []byte) (newBuf return nil, fmt.Errorf("%d is less than minimum value for int8", n.Int64) } - return append(buf, strconv.FormatInt(n.Int64, 10)...), nil + return strconv.AppendInt(buf, n.Int64, 10), nil } func (Int8Codec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { @@ -1440,8 +1463,9 @@ func (scanPlanBinaryInt8ToInt8) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 8 { - return fmt.Errorf("invalid length for int8: %v", len(src)) + raw, err := pgio.Uint64Exact(src) + if err != nil { + return fmt.Errorf("int8: %w", err) } p, ok := (dst).(*int8) @@ -1449,7 +1473,7 @@ func (scanPlanBinaryInt8ToInt8) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - n := int64(binary.BigEndian.Uint64(src)) + n := int64(raw) if n < math.MinInt8 { return fmt.Errorf("%d is less than minimum value for int8", n) } else if n > math.MaxInt8 { @@ -1468,8 +1492,9 @@ func (scanPlanBinaryInt8ToUint8) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 8 { - return fmt.Errorf("invalid length for uint8: %v", len(src)) + raw, err := pgio.Uint64Exact(src) + if err != nil { + return fmt.Errorf("uint8: %w", err) } p, ok := (dst).(*uint8) @@ -1477,7 +1502,7 @@ func (scanPlanBinaryInt8ToUint8) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - n := int64(binary.BigEndian.Uint64(src)) + n := int64(raw) if n < 0 { return fmt.Errorf("%d is less than minimum value for uint8", n) } @@ -1498,8 +1523,9 @@ func (scanPlanBinaryInt8ToInt16) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 8 { - return fmt.Errorf("invalid length for int8: %v", len(src)) + raw, err := pgio.Uint64Exact(src) + if err != nil { + return fmt.Errorf("int8: %w", err) } p, ok := (dst).(*int16) @@ -1507,7 +1533,7 @@ func (scanPlanBinaryInt8ToInt16) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - n := int64(binary.BigEndian.Uint64(src)) + n := int64(raw) if n < math.MinInt16 { return fmt.Errorf("%d is less than minimum value for int16", n) } else if n > math.MaxInt16 { @@ -1526,8 +1552,9 @@ func (scanPlanBinaryInt8ToUint16) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 8 { - return fmt.Errorf("invalid length for uint8: %v", len(src)) + raw, err := pgio.Uint64Exact(src) + if err != nil { + return fmt.Errorf("uint8: %w", err) } p, ok := (dst).(*uint16) @@ -1535,7 +1562,7 @@ func (scanPlanBinaryInt8ToUint16) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - n := int64(binary.BigEndian.Uint64(src)) + n := int64(raw) if n < 0 { return fmt.Errorf("%d is less than minimum value for uint16", n) } @@ -1556,8 +1583,9 @@ func (scanPlanBinaryInt8ToInt32) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 8 { - return fmt.Errorf("invalid length for int8: %v", len(src)) + raw, err := pgio.Uint64Exact(src) + if err != nil { + return fmt.Errorf("int8: %w", err) } p, ok := (dst).(*int32) @@ -1565,7 +1593,7 @@ func (scanPlanBinaryInt8ToInt32) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - n := int64(binary.BigEndian.Uint64(src)) + n := int64(raw) if n < math.MinInt32 { return fmt.Errorf("%d is less than minimum value for int32", n) } else if n > math.MaxInt32 { @@ -1584,8 +1612,9 @@ func (scanPlanBinaryInt8ToUint32) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 8 { - return fmt.Errorf("invalid length for uint8: %v", len(src)) + raw, err := pgio.Uint64Exact(src) + if err != nil { + return fmt.Errorf("uint8: %w", err) } p, ok := (dst).(*uint32) @@ -1593,7 +1622,7 @@ func (scanPlanBinaryInt8ToUint32) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - n := int64(binary.BigEndian.Uint64(src)) + n := int64(raw) if n < 0 { return fmt.Errorf("%d is less than minimum value for uint32", n) } @@ -1614,8 +1643,9 @@ func (scanPlanBinaryInt8ToInt64) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 8 { - return fmt.Errorf("invalid length for int8: %v", len(src)) + raw, err := pgio.Uint64Exact(src) + if err != nil { + return fmt.Errorf("int8: %w", err) } p, ok := (dst).(*int64) @@ -1623,7 +1653,7 @@ func (scanPlanBinaryInt8ToInt64) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - *p = int64(binary.BigEndian.Uint64(src)) + *p = int64(raw) return nil } @@ -1635,8 +1665,9 @@ func (scanPlanBinaryInt8ToUint64) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 8 { - return fmt.Errorf("invalid length for uint8: %v", len(src)) + raw, err := pgio.Uint64Exact(src) + if err != nil { + return fmt.Errorf("uint8: %w", err) } p, ok := (dst).(*uint64) @@ -1644,7 +1675,7 @@ func (scanPlanBinaryInt8ToUint64) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - n := int64(binary.BigEndian.Uint64(src)) + n := int64(raw) if n < 0 { return fmt.Errorf("%d is less than minimum value for uint64", n) } @@ -1661,8 +1692,9 @@ func (scanPlanBinaryInt8ToInt) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 8 { - return fmt.Errorf("invalid length for int8: %v", len(src)) + raw, err := pgio.Uint64Exact(src) + if err != nil { + return fmt.Errorf("int8: %w", err) } p, ok := (dst).(*int) @@ -1670,7 +1702,7 @@ func (scanPlanBinaryInt8ToInt) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - n := int64(binary.BigEndian.Uint64(src)) + n := int64(raw) if n < math.MinInt { return fmt.Errorf("%d is less than minimum value for int", n) } else if n > math.MaxInt { @@ -1689,8 +1721,9 @@ func (scanPlanBinaryInt8ToUint) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 8 { - return fmt.Errorf("invalid length for uint8: %v", len(src)) + raw, err := pgio.Uint64Exact(src) + if err != nil { + return fmt.Errorf("uint8: %w", err) } p, ok := (dst).(*uint) @@ -1698,7 +1731,7 @@ func (scanPlanBinaryInt8ToUint) Scan(src []byte, dst any) error { return ErrScanTargetTypeChanged } - n := int64(int64(binary.BigEndian.Uint64(src))) + n := int64(int64(raw)) if n < 0 { return fmt.Errorf("%d is less than minimum value for uint", n) } @@ -1724,11 +1757,12 @@ func (scanPlanBinaryInt8ToInt64Scanner) Scan(src []byte, dst any) error { return s.ScanInt64(Int8{}) } - if len(src) != 8 { - return fmt.Errorf("invalid length for int8: %v", len(src)) + raw, err := pgio.Uint64Exact(src) + if err != nil { + return fmt.Errorf("int8: %w", err) } - n := int64(int64(binary.BigEndian.Uint64(src))) + n := int64(int64(raw)) return s.ScanInt64(Int8{Int64: n, Valid: true}) } @@ -1745,11 +1779,12 @@ func (scanPlanBinaryInt8ToTextScanner) Scan(src []byte, dst any) error { return s.ScanText(Text{}) } - if len(src) != 8 { - return fmt.Errorf("invalid length for int8: %v", len(src)) + raw, err := pgio.Uint64Exact(src) + if err != nil { + return fmt.Errorf("int8: %w", err) } - n := int64(int64(binary.BigEndian.Uint64(src))) + n := int64(int64(raw)) return s.ScanText(Text{String: strconv.FormatInt(n, 10), Valid: true}) } diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/int.go.erb b/vendor/github.com/jackc/pgx/v5/pgtype/int.go.erb index c2d40f6..9987554 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/int.go.erb +++ b/vendor/github.com/jackc/pgx/v5/pgtype/int.go.erb @@ -79,7 +79,7 @@ func (dst *Int<%= pg_byte_size %>) Scan(src any) error { } if n < math.MinInt<%= pg_bit_size %> { - return fmt.Errorf("%d is greater than maximum value for Int<%= pg_byte_size %>", n) + return fmt.Errorf("%d is less than minimum value for Int<%= pg_byte_size %>", n) } if n > math.MaxInt<%= pg_bit_size %> { return fmt.Errorf("%d is greater than maximum value for Int<%= pg_byte_size %>", n) @@ -164,7 +164,7 @@ type encodePlanInt<%= pg_byte_size %>CodecTextInt<%= pg_bit_size %> struct{} func (encodePlanInt<%= pg_byte_size %>CodecTextInt<%= pg_bit_size %>) Encode(value any, buf []byte) (newBuf []byte, err error) { n := value.(int<%= pg_bit_size %>) - return append(buf, strconv.FormatInt(int64(n), 10)...), nil + return strconv.AppendInt(buf, int64(n), 10), nil } type encodePlanInt<%= pg_byte_size %>CodecBinaryInt64Valuer struct{} @@ -208,7 +208,7 @@ func (encodePlanInt<%= pg_byte_size %>CodecTextInt64Valuer) Encode(value any, bu return nil, fmt.Errorf("%d is less than minimum value for int<%= pg_byte_size %>", n.Int64) } - return append(buf, strconv.FormatInt(n.Int64, 10)...), nil + return strconv.AppendInt(buf, n.Int64, 10), nil } func (Int<%= pg_byte_size %>Codec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { @@ -306,8 +306,9 @@ func (scanPlanBinaryInt<%= pg_byte_size %>ToInt<%= dst_bit_size %>) Scan(src []b return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != <%= pg_byte_size %> { - return fmt.Errorf("invalid length for int<%= pg_byte_size %>: %v", len(src)) + raw, err := pgio.Uint<%= pg_bit_size %>Exact(src) + if err != nil { + return fmt.Errorf("int<%= pg_byte_size %>: %w", err) } p, ok := (dst).(*int<%= dst_bit_size %>) @@ -316,7 +317,7 @@ func (scanPlanBinaryInt<%= pg_byte_size %>ToInt<%= dst_bit_size %>) Scan(src []b } <% if dst_bit_size < pg_bit_size %> - n := int<%= pg_bit_size %>(binary.BigEndian.Uint<%= pg_bit_size %>(src)) + n := int<%= pg_bit_size %>(raw) if n < math.MinInt<%= dst_bit_size %> { return fmt.Errorf("%d is less than minimum value for int<%= dst_bit_size %>", n) } else if n > math.MaxInt<%= dst_bit_size %> { @@ -325,9 +326,9 @@ func (scanPlanBinaryInt<%= pg_byte_size %>ToInt<%= dst_bit_size %>) Scan(src []b *p = int<%= dst_bit_size %>(n) <% elsif dst_bit_size == pg_bit_size %> - *p = int<%= dst_bit_size %>(binary.BigEndian.Uint<%= pg_bit_size %>(src)) + *p = int<%= dst_bit_size %>(raw) <% else %> - *p = int<%= dst_bit_size %>(int<%= pg_bit_size %>(binary.BigEndian.Uint<%= pg_bit_size %>(src))) + *p = int<%= dst_bit_size %>(int<%= pg_bit_size %>(raw)) <% end %> return nil @@ -340,8 +341,9 @@ func (scanPlanBinaryInt<%= pg_byte_size %>ToUint<%= dst_bit_size %>) Scan(src [] return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != <%= pg_byte_size %> { - return fmt.Errorf("invalid length for uint<%= pg_byte_size %>: %v", len(src)) + raw, err := pgio.Uint<%= pg_bit_size %>Exact(src) + if err != nil { + return fmt.Errorf("uint<%= pg_byte_size %>: %w", err) } p, ok := (dst).(*uint<%= dst_bit_size %>) @@ -349,7 +351,7 @@ func (scanPlanBinaryInt<%= pg_byte_size %>ToUint<%= dst_bit_size %>) Scan(src [] return ErrScanTargetTypeChanged } - n := int<%= pg_bit_size %>(binary.BigEndian.Uint<%= pg_bit_size %>(src)) + n := int<%= pg_bit_size %>(raw) if n < 0 { return fmt.Errorf("%d is less than minimum value for uint<%= dst_bit_size %>", n) } @@ -372,8 +374,9 @@ func (scanPlanBinaryInt<%= pg_byte_size %>ToInt) Scan(src []byte, dst any) error return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != <%= pg_byte_size %> { - return fmt.Errorf("invalid length for int<%= pg_byte_size %>: %v", len(src)) + raw, err := pgio.Uint<%= pg_bit_size %>Exact(src) + if err != nil { + return fmt.Errorf("int<%= pg_byte_size %>: %w", err) } p, ok := (dst).(*int) @@ -382,7 +385,7 @@ func (scanPlanBinaryInt<%= pg_byte_size %>ToInt) Scan(src []byte, dst any) error } <% if 32 < pg_bit_size %> - n := int64(binary.BigEndian.Uint<%= pg_bit_size %>(src)) + n := int64(raw) if n < math.MinInt { return fmt.Errorf("%d is less than minimum value for int", n) } else if n > math.MaxInt { @@ -391,7 +394,7 @@ func (scanPlanBinaryInt<%= pg_byte_size %>ToInt) Scan(src []byte, dst any) error *p = int(n) <% else %> - *p = int(int<%= pg_bit_size %>(binary.BigEndian.Uint<%= pg_bit_size %>(src))) + *p = int(int<%= pg_bit_size %>(raw)) <% end %> return nil @@ -404,8 +407,9 @@ func (scanPlanBinaryInt<%= pg_byte_size %>ToUint) Scan(src []byte, dst any) erro return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != <%= pg_byte_size %> { - return fmt.Errorf("invalid length for uint<%= pg_byte_size %>: %v", len(src)) + raw, err := pgio.Uint<%= pg_bit_size %>Exact(src) + if err != nil { + return fmt.Errorf("uint<%= pg_byte_size %>: %w", err) } p, ok := (dst).(*uint) @@ -413,7 +417,7 @@ func (scanPlanBinaryInt<%= pg_byte_size %>ToUint) Scan(src []byte, dst any) erro return ErrScanTargetTypeChanged } - n := int64(int<%= pg_bit_size %>(binary.BigEndian.Uint<%= pg_bit_size %>(src))) + n := int64(int<%= pg_bit_size %>(raw)) if n < 0 { return fmt.Errorf("%d is less than minimum value for uint", n) } @@ -440,12 +444,13 @@ func (scanPlanBinaryInt<%= pg_byte_size %>ToInt64Scanner) Scan(src []byte, dst a return s.ScanInt64(Int8{}) } - if len(src) != <%= pg_byte_size %> { - return fmt.Errorf("invalid length for int<%= pg_byte_size %>: %v", len(src)) + raw, err := pgio.Uint<%= pg_bit_size %>Exact(src) + if err != nil { + return fmt.Errorf("int<%= pg_byte_size %>: %w", err) } - n := int64(int<%= pg_bit_size %>(binary.BigEndian.Uint<%= pg_bit_size %>(src))) + n := int64(int<%= pg_bit_size %>(raw)) return s.ScanInt64(Int8{Int64: n, Valid: true}) } @@ -463,12 +468,13 @@ func (scanPlanBinaryInt<%= pg_byte_size %>ToTextScanner) Scan(src []byte, dst an return s.ScanText(Text{}) } - if len(src) != <%= pg_byte_size %> { - return fmt.Errorf("invalid length for int<%= pg_byte_size %>: %v", len(src)) + raw, err := pgio.Uint<%= pg_bit_size %>Exact(src) + if err != nil { + return fmt.Errorf("int<%= pg_byte_size %>: %w", err) } - n := int64(int<%= pg_bit_size %>(binary.BigEndian.Uint<%= pg_bit_size %>(src))) + n := int64(int<%= pg_bit_size %>(raw)) return s.ScanText(Text{String: strconv.FormatInt(n, 10), Valid: true}) } diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/interval.go b/vendor/github.com/jackc/pgx/v5/pgtype/interval.go index be8decd..346c6db 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/interval.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/interval.go @@ -2,7 +2,6 @@ package pgtype import ( "database/sql/driver" - "encoding/binary" "fmt" "strconv" "strings" @@ -127,31 +126,31 @@ func (encodePlanIntervalCodecText) Encode(value any, buf []byte) (newBuf []byte, } if interval.Months != 0 { - buf = append(buf, strconv.FormatInt(int64(interval.Months), 10)...) + buf = strconv.AppendInt(buf, int64(interval.Months), 10) buf = append(buf, " mon "...) } if interval.Days != 0 { - buf = append(buf, strconv.FormatInt(int64(interval.Days), 10)...) + buf = strconv.AppendInt(buf, int64(interval.Days), 10) buf = append(buf, " day "...) } - absMicroseconds := interval.Microseconds - if absMicroseconds < 0 { + absMicroseconds := uint64(interval.Microseconds) + if interval.Microseconds < 0 { absMicroseconds = -absMicroseconds buf = append(buf, '-') } - hours := absMicroseconds / microsecondsPerHour - minutes := (absMicroseconds % microsecondsPerHour) / microsecondsPerMinute - seconds := (absMicroseconds % microsecondsPerMinute) / microsecondsPerSecond + hours := int64(absMicroseconds / microsecondsPerHour) + minutes := int64((absMicroseconds % microsecondsPerHour) / microsecondsPerMinute) + seconds := int64((absMicroseconds % microsecondsPerMinute) / microsecondsPerSecond) - timeStr := fmt.Sprintf("%02d:%02d:%02d", hours, minutes, seconds) - buf = append(buf, timeStr...) + buf = appendTimeText(buf, hours, minutes, seconds) - microseconds := absMicroseconds % microsecondsPerSecond + microseconds := int64(absMicroseconds % microsecondsPerSecond) if microseconds != 0 { - buf = append(buf, fmt.Sprintf(".%06d", microseconds)...) + buf = append(buf, '.') + buf = appendZeroPaddedInt64(buf, microseconds, 6) } return buf, nil @@ -175,19 +174,21 @@ func (IntervalCodec) PlanScan(m *Map, oid uint32, format int16, target any) Scan type scanPlanBinaryIntervalToIntervalScanner struct{} func (scanPlanBinaryIntervalToIntervalScanner) Scan(src []byte, dst any) error { - scanner := (dst).(IntervalScanner) + scanner := dst.(IntervalScanner) if src == nil { return scanner.ScanInterval(Interval{}) } - if len(src) != 16 { - return fmt.Errorf("Received an invalid size for an interval: %d", len(src)) - } + r := pgio.NewReader(src) - microseconds := int64(binary.BigEndian.Uint64(src)) - days := int32(binary.BigEndian.Uint32(src[8:])) - months := int32(binary.BigEndian.Uint32(src[12:])) + microseconds := r.Int64() + days := r.Int32() + months := r.Int32() + + if err := r.Finish(); err != nil { + return fmt.Errorf("Received an invalid size for an interval: %w", err) + } return scanner.ScanInterval(Interval{Microseconds: microseconds, Days: days, Months: months, Valid: true}) } @@ -195,7 +196,7 @@ func (scanPlanBinaryIntervalToIntervalScanner) Scan(src []byte, dst any) error { type scanPlanTextAnyToIntervalScanner struct{} func (scanPlanTextAnyToIntervalScanner) Scan(src []byte, dst any) error { - scanner := (dst).(IntervalScanner) + scanner := dst.(IntervalScanner) if src == nil { return scanner.ScanInterval(Interval{}) @@ -232,7 +233,7 @@ func (scanPlanTextAnyToIntervalScanner) Scan(src []byte, dst any) error { } var negative bool - if timeParts[0][0] == '-' { + if len(timeParts[0]) > 0 && timeParts[0][0] == '-' { negative = true timeParts[0] = timeParts[0][1:] } @@ -256,14 +257,21 @@ func (scanPlanTextAnyToIntervalScanner) Scan(src []byte, dst any) error { var uSeconds int64 if secFracFound { - uSeconds, err = strconv.ParseInt(secFrac, 10, 64) + if secFrac == "" { + return fmt.Errorf("bad interval decimal format: %s", secFrac) + } + for i := 0; i < len(secFrac); i++ { + if !isDigit(secFrac[i]) { + return fmt.Errorf("bad interval decimal format: %s", secFrac) + } + } + // Digits past the microsecond were left unscaled, so 1.0000001 + // seconds became 1.000001 seconds. Same rounding as timestamps. + usec, err := roundFractionToMicroseconds([]byte(secFrac)) if err != nil { return fmt.Errorf("bad interval decimal format: %s", secFrac) } - - for i := 0; i < 6-len(secFrac); i++ { - uSeconds *= 10 - } + uSeconds = int64(usec) } microseconds = hours * microsecondsPerHour diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/line.go b/vendor/github.com/jackc/pgx/v5/pgtype/line.go index 73b0636..8fb02bb 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/line.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/line.go @@ -2,7 +2,6 @@ package pgtype import ( "database/sql/driver" - "encoding/binary" "fmt" "math" "strconv" @@ -147,19 +146,21 @@ func (LineCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan type scanPlanBinaryLineToLineScanner struct{} func (scanPlanBinaryLineToLineScanner) Scan(src []byte, dst any) error { - scanner := (dst).(LineScanner) + scanner := dst.(LineScanner) if src == nil { return scanner.ScanLine(Line{}) } - if len(src) != 24 { - return fmt.Errorf("invalid length for line: %v", len(src)) - } + r := pgio.NewReader(src) - a := binary.BigEndian.Uint64(src) - b := binary.BigEndian.Uint64(src[8:]) - c := binary.BigEndian.Uint64(src[16:]) + a := r.Uint64() + b := r.Uint64() + c := r.Uint64() + + if err := r.Finish(); err != nil { + return fmt.Errorf("line: %w", err) + } return scanner.ScanLine(Line{ A: math.Float64frombits(a), @@ -172,7 +173,7 @@ func (scanPlanBinaryLineToLineScanner) Scan(src []byte, dst any) error { type scanPlanTextAnyToLineScanner struct{} func (scanPlanTextAnyToLineScanner) Scan(src []byte, dst any) error { - scanner := (dst).(LineScanner) + scanner := dst.(LineScanner) if src == nil { return scanner.ScanLine(Line{}) diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/lseg.go b/vendor/github.com/jackc/pgx/v5/pgtype/lseg.go index 438b45b..a239c09 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/lseg.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/lseg.go @@ -2,7 +2,6 @@ package pgtype import ( "database/sql/driver" - "encoding/binary" "fmt" "math" "strconv" @@ -145,20 +144,22 @@ func (LsegCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan type scanPlanBinaryLsegToLsegScanner struct{} func (scanPlanBinaryLsegToLsegScanner) Scan(src []byte, dst any) error { - scanner := (dst).(LsegScanner) + scanner := dst.(LsegScanner) if src == nil { return scanner.ScanLseg(Lseg{}) } - if len(src) != 32 { - return fmt.Errorf("invalid length for lseg: %v", len(src)) - } + r := pgio.NewReader(src) - x1 := binary.BigEndian.Uint64(src) - y1 := binary.BigEndian.Uint64(src[8:]) - x2 := binary.BigEndian.Uint64(src[16:]) - y2 := binary.BigEndian.Uint64(src[24:]) + x1 := r.Uint64() + y1 := r.Uint64() + x2 := r.Uint64() + y2 := r.Uint64() + + if err := r.Finish(); err != nil { + return fmt.Errorf("lseg: %w", err) + } return scanner.ScanLseg(Lseg{ P: [2]Vec2{ @@ -172,7 +173,7 @@ func (scanPlanBinaryLsegToLsegScanner) Scan(src []byte, dst any) error { type scanPlanTextAnyToLsegScanner struct{} func (scanPlanTextAnyToLsegScanner) Scan(src []byte, dst any) error { - scanner := (dst).(LsegScanner) + scanner := dst.(LsegScanner) if src == nil { return scanner.ScanLseg(Lseg{}) diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/ltree.go b/vendor/github.com/jackc/pgx/v5/pgtype/ltree.go index 6af3177..e661c90 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/ltree.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/ltree.go @@ -21,7 +21,7 @@ func (l LtreeCodec) PreferredFormat() int16 { func (l LtreeCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { switch format { case TextFormatCode: - return (TextCodec)(l).PlanEncode(m, oid, format, value) + return TextCodec(l).PlanEncode(m, oid, format, value) case BinaryFormatCode: switch value.(type) { case string: @@ -72,7 +72,7 @@ func (encodeLtreeCodecBinaryTextValuer) Encode(value any, buf []byte) (newBuf [] func (l LtreeCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { switch format { case TextFormatCode: - return (TextCodec)(l).PlanScan(m, oid, format, target) + return TextCodec(l).PlanScan(m, oid, format, target) case BinaryFormatCode: switch target.(type) { case *string: @@ -88,12 +88,16 @@ func (l LtreeCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanP type scanPlanBinaryLtreeToString struct{} func (scanPlanBinaryLtreeToString) Scan(src []byte, target any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", target) + } + version := src[0] if version != 1 { return fmt.Errorf("unsupported ltree version %d", version) } - p := (target).(*string) + p := target.(*string) *p = string(src[1:]) return nil @@ -102,21 +106,26 @@ func (scanPlanBinaryLtreeToString) Scan(src []byte, target any) error { type scanPlanBinaryLtreeToTextScanner struct{} func (scanPlanBinaryLtreeToTextScanner) Scan(src []byte, target any) error { + scanner := target.(TextScanner) + + if src == nil { + return scanner.ScanText(Text{}) + } + version := src[0] if version != 1 { return fmt.Errorf("unsupported ltree version %d", version) } - scanner := (target).(TextScanner) return scanner.ScanText(Text{String: string(src[1:]), Valid: true}) } // DecodeDatabaseSQLValue returns src decoded into a value compatible with the sql.Scanner interface. func (l LtreeCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { - return (TextCodec)(l).DecodeDatabaseSQLValue(m, oid, format, src) + return TextCodec(l).DecodeDatabaseSQLValue(m, oid, format, src) } // DecodeValue returns src decoded into its default format. func (l LtreeCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { - return (TextCodec)(l).DecodeValue(m, oid, format, src) + return TextCodec(l).DecodeValue(m, oid, format, src) } diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/macaddr.go b/vendor/github.com/jackc/pgx/v5/pgtype/macaddr.go index e913ec9..045975e 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/macaddr.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/macaddr.go @@ -116,7 +116,7 @@ func (scanPlanBinaryMacaddrToHardwareAddr) Scan(src []byte, dst any) error { type scanPlanBinaryMacaddrToTextScanner struct{} func (scanPlanBinaryMacaddrToTextScanner) Scan(src []byte, dst any) error { - scanner := (dst).(TextScanner) + scanner := dst.(TextScanner) if src == nil { return scanner.ScanText(Text{}) } diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/multirange.go b/vendor/github.com/jackc/pgx/v5/pgtype/multirange.go index 11f30b4..52cdb6e 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/multirange.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/multirange.go @@ -3,7 +3,6 @@ package pgtype import ( "bytes" "database/sql/driver" - "encoding/binary" "fmt" "reflect" @@ -205,14 +204,12 @@ func (c *MultirangeCodec) PlanScan(m *Map, oid uint32, format int16, target any) } func (c *MultirangeCodec) decodeBinary(m *Map, multirangeOID uint32, src []byte, multirange MultirangeSetter) error { - rp := 0 - - elementCount := int(binary.BigEndian.Uint32(src[rp:])) - rp += 4 + r := pgio.NewReader(src) // Each element requires at least 4 bytes for its length prefix. - if elementCount > len(src)/4 { - return fmt.Errorf("multirange element count %d exceeds available data", elementCount) + elementCount := r.Count(4) + if err := r.Err(); err != nil { + return fmt.Errorf("multirange: %w", err) } err := multirange.SetLen(elementCount) @@ -221,7 +218,7 @@ func (c *MultirangeCodec) decodeBinary(m *Map, multirangeOID uint32, src []byte, } if elementCount == 0 { - return nil + return r.Finish() } elementScanPlan := c.ElementType.Codec.PlanScan(m, c.ElementType.OID, BinaryFormatCode, multirange.ScanIndex(0)) @@ -231,18 +228,9 @@ func (c *MultirangeCodec) decodeBinary(m *Map, multirangeOID uint32, src []byte, for i := range elementCount { elem := multirange.ScanIndex(i) - if len(src[rp:]) < 4 { - return fmt.Errorf("multirange body truncated at element %d", i) - } - elemLen := int(int32(binary.BigEndian.Uint32(src[rp:]))) - rp += 4 - var elemSrc []byte - if elemLen >= 0 { - if len(src[rp:]) < elemLen { - return fmt.Errorf("multirange element %d length %d exceeds remaining %d bytes", i, elemLen, len(src[rp:])) - } - elemSrc = src[rp : rp+elemLen] - rp += elemLen + elemSrc, _ := r.Value() + if err := r.Err(); err != nil { + return fmt.Errorf("multirange element %d: %w", i, err) } err = elementScanPlan.Scan(elemSrc, elem) if err != nil { @@ -250,7 +238,7 @@ func (c *MultirangeCodec) decodeBinary(m *Map, multirangeOID uint32, src []byte, } } - return nil + return r.Finish() } func (c *MultirangeCodec) decodeText(m *Map, multirangeOID uint32, src []byte, multirange MultirangeSetter) error { @@ -390,21 +378,33 @@ parseValueLoop: func parseRange(buf *bytes.Buffer) (string, error) { s := &bytes.Buffer{} - boundSepRead := false + inRange := false + inQuotes := false + escaped := false for { r, _, err := buf.ReadRune() if err != nil { return "", err } - switch r { - case ',', '}': - if r == ',' && !boundSepRead { - boundSepRead = true - break + if escaped { + escaped = false + } else if r == '\\' { + escaped = true + } else if r == '"' { + inQuotes = !inQuotes + } else if !inQuotes { + switch r { + case '[', '(': + inRange = true + case ']', ')': + inRange = false + case ',', '}': + if !inRange { + buf.UnreadRune() + return s.String(), nil + } } - buf.UnreadRune() - return s.String(), nil } s.WriteRune(r) diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/numeric.go b/vendor/github.com/jackc/pgx/v5/pgtype/numeric.go index caf5ff1..5bde0e6 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/numeric.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/numeric.go @@ -3,7 +3,7 @@ package pgtype import ( "bytes" "database/sql/driver" - "encoding/binary" + "errors" "fmt" "math" "math/big" @@ -16,6 +16,14 @@ import ( // PostgreSQL internal numeric storage uses 16-bit "digits" with base of 10,000 const nbase = 10_000 +// Numeric's binary representation stores the exponent through a base-10,000 +// weight and an int16 dscale. These are also the largest exponents that can be +// safely materialized by the text encoders. +const ( + minNumericExponent = -math.MaxInt16 + maxNumericExponent = math.MaxInt16*4 + 3 +) + const ( pgNumericNaN = 0x00000000c0000000 pgNumericNaNSign = 0xc000 @@ -89,7 +97,7 @@ func (n Numeric) Float64Value() (Float8, error) { buf = append(buf, n.Int.String()...) } buf = append(buf, 'e') - buf = append(buf, strconv.FormatInt(int64(n.Exp), 10)...) + buf = strconv.AppendInt(buf, int64(n.Exp), 10) f, err := strconv.ParseFloat(string(buf), 64) if err != nil { @@ -133,12 +141,7 @@ func (n *Numeric) ScanScientific(src string) error { return scanPlanTextAnyToNumericScanner{}.Scan([]byte(src), n) } - if bigF, ok := new(big.Float).SetString(src); ok { - smallF, _ := bigF.Float64() - src = strconv.FormatFloat(smallF, 'f', -1, 64) - } - - num, exp, err := parseNumericString(src) + num, exp, err := parseScientificNumericString(src) if err != nil { return err } @@ -148,7 +151,45 @@ func (n *Numeric) ScanScientific(src string) error { return nil } +func parseScientificNumericString(str string) (n *big.Int, exp int32, err error) { + idx := strings.IndexAny(str, "eE") + if idx == -1 { + return parseNumericString(str) + } + + mantissa := str[:idx] + scientificExp, err := strconv.ParseInt(str[idx+1:], 10, 32) + if err != nil { + if errors.Is(err, strconv.ErrRange) { + return nil, 0, fmt.Errorf("%s exponent out of range", str) + } + return nil, 0, fmt.Errorf("%s is not a number", str) + } + + num, mantissaExp, err := parseNumericString(mantissa) + if err != nil { + return nil, 0, fmt.Errorf("%s is not a number", str) + } + + combinedExp := int64(mantissaExp) + scientificExp + if combinedExp < minNumericExponent || combinedExp > maxNumericExponent { + return nil, 0, fmt.Errorf("%s exponent out of range", str) + } + + return num, int32(combinedExp), nil +} + func (n *Numeric) toBigInt() (*big.Int, error) { + if n.NaN { + return nil, fmt.Errorf("cannot convert NaN to integer") + } else if n.InfinityModifier != Finite { + return nil, fmt.Errorf("cannot convert %v to integer", n.InfinityModifier) + } + + if n.Int == nil { + return big.NewInt(0), nil + } + if n.Exp == 0 { return n.Int, nil } @@ -173,40 +214,41 @@ func (n *Numeric) toBigInt() (*big.Int, error) { } func parseNumericString(str string) (n *big.Int, exp int32, err error) { - idx := strings.IndexByte(str, '.') + // Keep str intact so errors report what the caller actually passed in. + digits := str + idx := strings.IndexByte(digits, '.') if idx == -1 { - for len(str) > 1 && str[len(str)-1] == '0' && str[len(str)-2] != '-' { - str = str[:len(str)-1] + for len(digits) > 1 && digits[len(digits)-1] == '0' && digits[len(digits)-2] != '-' { + digits = digits[:len(digits)-1] exp++ } } else { - exp = int32(-(len(str) - idx - 1)) - str = str[:idx] + str[idx+1:] + exp = int32(-(len(digits) - idx - 1)) + digits = digits[:idx] + digits[idx+1:] } accum := &big.Int{} - if _, ok := accum.SetString(str, 10); !ok { + if _, ok := accum.SetString(digits, 10); !ok { return nil, 0, fmt.Errorf("%s is not a number", str) } return accum, exp, nil } -func nbaseDigitsToInt64(src []byte) (accum int64, bytesRead, digitsRead int) { - digits := min(len(src)/2, 4) - - rp := 0 +// nbaseDigitsToInt64 reads up to 4 nbase digits and packs them into an int64. +// It stops early at digitsLeft or at the end of r, whichever comes first. +func nbaseDigitsToInt64(r *pgio.Reader, digitsLeft int) (accum int64, digitsRead int) { + digits := min(digitsLeft, r.Remaining()/2, 4) for i := range digits { if i > 0 { accum *= nbase } - accum += int64(binary.BigEndian.Uint16(src[rp:])) - rp += 2 + accum += int64(r.Uint16()) } - return accum, rp, digits + return accum, digits } // Scan implements the [database/sql.Scanner] interface. @@ -242,8 +284,13 @@ func (n Numeric) MarshalJSON() ([]byte, error) { return []byte("null"), nil } - if n.NaN { + switch { + case n.NaN: return []byte(`"NaN"`), nil + case n.InfinityModifier == Infinity: + return []byte(`"Infinity"`), nil + case n.InfinityModifier == NegativeInfinity: + return []byte(`"-Infinity"`), nil } return n.numberTextBytes(), nil @@ -259,7 +306,17 @@ func (n *Numeric) UnmarshalJSON(src []byte) error { *n = Numeric{NaN: true, Valid: true} return nil } - return scanPlanTextAnyToNumericScanner{}.Scan(src, n) + if bytes.Equal(src, []byte(`"Infinity"`)) { + *n = Numeric{InfinityModifier: Infinity, Valid: true} + return nil + } + if bytes.Equal(src, []byte(`"-Infinity"`)) { + *n = Numeric{InfinityModifier: NegativeInfinity, Valid: true} + return nil + } + // JSON numbers may use scientific notation even when the producer did not + // write it that way: encoding/json emits 1e+21 for float64(1e21). + return n.ScanScientific(string(src)) } // numberString returns a string of the number. undefined if NaN, infinite, or NULL @@ -416,6 +473,14 @@ func encodeNumericBinary(n Numeric, buf []byte) (newBuf []byte, err error) { sign = 16384 } + // The binary format stores ndigits as uint16 and weight and dscale as int16, + // so values that do not fit must be rejected rather than silently truncated. + // Exp maps directly onto dscale, so check it before doing any big.Int work: a very + // negative exponent would otherwise build an enormous divisor below. + if n.Exp < -math.MaxInt16 { + return nil, fmt.Errorf("cannot encode numeric: exponent %d is out of range", n.Exp) + } + absInt := &big.Int{} wholePart := &big.Int{} fracPart := &big.Int{} @@ -443,7 +508,7 @@ func encodeNumericBinary(n Numeric, buf []byte) (newBuf []byte, err error) { if exp < 0 { divisor := &big.Int{} - divisor.Exp(big10, big.NewInt(int64(-exp)), nil) + divisor.Exp(big10, big.NewInt(-int64(exp)), nil) wholePart.DivMod(absInt, divisor, fracPart) fracPart.Add(fracPart, divisor) } else { @@ -464,18 +529,25 @@ func encodeNumericBinary(n Numeric, buf []byte) (newBuf []byte, err error) { } } - buf = pgio.AppendInt16(buf, int16(len(wholeDigits)+len(fracDigits))) + ndigits := len(wholeDigits) + len(fracDigits) + if ndigits > math.MaxUint16 { + return nil, fmt.Errorf("cannot encode numeric: %d digits is out of range", ndigits) + } + buf = pgio.AppendUint16(buf, uint16(ndigits)) - var weight int16 + var weight int64 if len(wholeDigits) > 0 { - weight = int16(len(wholeDigits) - 1) + weight = int64(len(wholeDigits) - 1) if exp > 0 { - weight += int16(exp / 4) + weight += int64(exp) / 4 } } else { - weight = int16(exp/4) - 1 + int16(len(fracDigits)) + weight = int64(exp)/4 - 1 + int64(len(fracDigits)) } - buf = pgio.AppendInt16(buf, weight) + if weight > math.MaxInt16 || weight < math.MinInt16 { + return nil, fmt.Errorf("cannot encode numeric: exponent %d is out of range", n.Exp) + } + buf = pgio.AppendInt16(buf, int16(weight)) buf = pgio.AppendInt16(buf, sign) @@ -527,7 +599,7 @@ func (encodePlanNumericCodecTextFloat64Valuer) Encode(value any, buf []byte) (ne case math.IsInf(n.Float64, -1): buf = append(buf, "-Infinity"...) default: - buf = append(buf, strconv.FormatFloat(n.Float64, 'f', -1, 64)...) + buf = strconv.AppendFloat(buf, n.Float64, 'f', -1, 64) } return buf, nil } @@ -544,7 +616,7 @@ func (encodePlanNumericCodecTextInt64Valuer) Encode(value any, buf []byte) (newB return nil, nil } - buf = append(buf, strconv.FormatInt(n.Int64, 10)...) + buf = strconv.AppendInt(buf, n.Int64, 10) return buf, nil } @@ -600,25 +672,21 @@ func (NumericCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanP type scanPlanBinaryNumericToNumericScanner struct{} func (scanPlanBinaryNumericToNumericScanner) Scan(src []byte, dst any) error { - scanner := (dst).(NumericScanner) + scanner := dst.(NumericScanner) if src == nil { return scanner.ScanNumeric(Numeric{}) } - if len(src) < 8 { - return fmt.Errorf("numeric incomplete %v", src) - } + r := pgio.NewReader(src) - rp := 0 - ndigits := binary.BigEndian.Uint16(src[rp:]) - rp += 2 - weight := int16(binary.BigEndian.Uint16(src[rp:])) - rp += 2 - sign := binary.BigEndian.Uint16(src[rp:]) - rp += 2 - dscale := int16(binary.BigEndian.Uint16(src[rp:])) - rp += 2 + ndigits := r.Uint16() + weight := r.Int16() + sign := r.Uint16() + dscale := r.Int16() + if err := r.Err(); err != nil { + return fmt.Errorf("numeric incomplete: %w", err) + } switch sign { case pgNumericNaNSign: @@ -633,15 +701,16 @@ func (scanPlanBinaryNumericToNumericScanner) Scan(src []byte, dst any) error { return scanner.ScanNumeric(Numeric{Int: big.NewInt(0), Valid: true}) } - if len(src[rp:]) < int(ndigits)*2 { + if r.Remaining() < int(ndigits)*2 { return fmt.Errorf("numeric incomplete %v", src) } accum := &big.Int{} - for i := 0; i < int(ndigits+3)/4; i++ { - int64accum, bytesRead, digitsRead := nbaseDigitsToInt64(src[rp:]) - rp += bytesRead + // int(ndigits) before the addition: ndigits is a uint16, so ndigits+3 + // would wrap for counts above 65532 and skip the loop entirely. + for i := 0; i < (int(ndigits)+3)/4; i++ { + int64accum, digitsRead := nbaseDigitsToInt64(r, int(ndigits)-i*4) if i > 0 { var mul *big.Int @@ -663,6 +732,10 @@ func (scanPlanBinaryNumericToNumericScanner) Scan(src []byte, dst any) error { accum.Add(accum, big.NewInt(int64accum)) } + if err := r.Finish(); err != nil { + return fmt.Errorf("numeric: %w", err) + } + exp := (int32(weight) - int32(ndigits) + 1) * 4 if dscale > 0 { @@ -687,7 +760,7 @@ func (scanPlanBinaryNumericToNumericScanner) Scan(src []byte, dst any) error { reduced := &big.Int{} remainder := &big.Int{} - if exp >= 0 { + if exp >= 0 && accum.Sign() != 0 { for { reduced.DivMod(accum, big10, remainder) if remainder.Sign() != 0 { @@ -708,7 +781,7 @@ func (scanPlanBinaryNumericToNumericScanner) Scan(src []byte, dst any) error { type scanPlanBinaryNumericToFloat64Scanner struct{} func (scanPlanBinaryNumericToFloat64Scanner) Scan(src []byte, dst any) error { - scanner := (dst).(Float64Scanner) + scanner := dst.(Float64Scanner) if src == nil { return scanner.ScanFloat64(Float8{}) @@ -732,7 +805,7 @@ func (scanPlanBinaryNumericToFloat64Scanner) Scan(src []byte, dst any) error { type scanPlanBinaryNumericToInt64Scanner struct{} func (scanPlanBinaryNumericToInt64Scanner) Scan(src []byte, dst any) error { - scanner := (dst).(Int64Scanner) + scanner := dst.(Int64Scanner) if src == nil { return scanner.ScanInt64(Int8{}) @@ -760,7 +833,7 @@ func (scanPlanBinaryNumericToInt64Scanner) Scan(src []byte, dst any) error { type scanPlanBinaryNumericToTextScanner struct{} func (scanPlanBinaryNumericToTextScanner) Scan(src []byte, dst any) error { - scanner := (dst).(TextScanner) + scanner := dst.(TextScanner) if src == nil { return scanner.ScanText(Text{}) @@ -784,7 +857,7 @@ func (scanPlanBinaryNumericToTextScanner) Scan(src []byte, dst any) error { type scanPlanTextAnyToNumericScanner struct{} func (scanPlanTextAnyToNumericScanner) Scan(src []byte, dst any) error { - scanner := (dst).(NumericScanner) + scanner := dst.(NumericScanner) if src == nil { return scanner.ScanNumeric(Numeric{}) diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/path.go b/vendor/github.com/jackc/pgx/v5/pgtype/path.go index 6398b58..0afceac 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/path.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/path.go @@ -2,7 +2,6 @@ package pgtype import ( "database/sql/driver" - "encoding/binary" "fmt" "math" "strconv" @@ -172,34 +171,32 @@ func (PathCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan type scanPlanBinaryPathToPathScanner struct{} func (scanPlanBinaryPathToPathScanner) Scan(src []byte, dst any) error { - scanner := (dst).(PathScanner) + scanner := dst.(PathScanner) if src == nil { return scanner.ScanPath(Path{}) } - if len(src) < 5 { - return fmt.Errorf("invalid length for Path: %v", len(src)) - } + r := pgio.NewReader(src) - closed := src[0] == 1 - pointCount := int(binary.BigEndian.Uint32(src[1:])) - - rp := 5 - - if 5+pointCount*16 != len(src) { - return fmt.Errorf("invalid length for Path with %d points: %v", pointCount, len(src)) + closed := r.Byte() == 1 + // Each point is two float64s. + pointCount := r.Count(16) + if err := r.Err(); err != nil { + return fmt.Errorf("invalid length for Path: %w", err) } points := make([]Vec2, pointCount) for i := range points { - x := binary.BigEndian.Uint64(src[rp:]) - rp += 8 - y := binary.BigEndian.Uint64(src[rp:]) - rp += 8 + x := r.Uint64() + y := r.Uint64() points[i] = Vec2{math.Float64frombits(x), math.Float64frombits(y)} } + if err := r.Finish(); err != nil { + return fmt.Errorf("invalid length for Path with %d points: %w", pointCount, err) + } + return scanner.ScanPath(Path{ P: points, Closed: closed, @@ -210,7 +207,7 @@ func (scanPlanBinaryPathToPathScanner) Scan(src []byte, dst any) error { type scanPlanTextAnyToPathScanner struct{} func (scanPlanTextAnyToPathScanner) Scan(src []byte, dst any) error { - scanner := (dst).(PathScanner) + scanner := dst.(PathScanner) if src == nil { return scanner.ScanPath(Path{}) diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/pgtype.go b/vendor/github.com/jackc/pgx/v5/pgtype/pgtype.go index 46b892b..2e20847 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/pgtype.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/pgtype.go @@ -127,6 +127,8 @@ const ( TstzmultirangeArrayOID = 6153 DatemultirangeArrayOID = 6155 Int8multirangeArrayOID = 6157 + OID8OID = 6437 + OID8ArrayOID = 6442 ) type InfinityModifier int8 @@ -412,7 +414,7 @@ func (scanPlanString) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - p := (dst).(*string) + p := dst.(*string) *p = string(src) return nil } @@ -497,7 +499,12 @@ type pointerPointerScanPlan struct { func (plan *pointerPointerScanPlan) SetNext(next ScanPlan) { plan.next = next } func (plan *pointerPointerScanPlan) Scan(src []byte, dst any) error { - el := reflect.ValueOf(dst).Elem() + dstValue := reflect.ValueOf(dst) + if dstValue.Kind() != reflect.Pointer || dstValue.IsNil() { + return fmt.Errorf("cannot scan into non-pointer or nil destinations %T", dst) + } + + el := dstValue.Elem() if src == nil { el.Set(reflect.Zero(el.Type())) return nil @@ -510,11 +517,11 @@ func (plan *pointerPointerScanPlan) Scan(src []byte, dst any) error { // TryPointerPointerScanPlan handles a pointer to a pointer by setting the target to nil for SQL NULL and allocating and // scanning for non-NULL. func TryPointerPointerScanPlan(target any) (plan WrappedScanPlanNextSetter, nextTarget any, ok bool) { - if dstValue := reflect.ValueOf(target); dstValue.Kind() == reflect.Pointer { - elemValue := dstValue.Elem() - if elemValue.Kind() == reflect.Pointer { - plan = &pointerPointerScanPlan{dstType: dstValue.Type()} - return plan, reflect.Zero(elemValue.Type()).Interface(), true + if dstType := reflect.TypeOf(target); dstType != nil && dstType.Kind() == reflect.Pointer { + elemType := dstType.Elem() + if elemType.Kind() == reflect.Pointer { + plan = &pointerPointerScanPlan{dstType: dstType} + return plan, reflect.Zero(elemType).Interface(), true } } @@ -575,8 +582,7 @@ func TryFindUnderlyingTypeScanPlan(dst any) (plan WrappedScanPlanNextSetter, nex if nextDstType == nil { if elemValue.Kind() == reflect.Slice { if elemValue.Type().Elem().Kind() == reflect.Uint8 { - var v *[]byte - nextDstType = reflect.TypeOf(v) + nextDstType = reflect.TypeFor[*[]byte]() } } @@ -955,12 +961,24 @@ func (plan *wrapAnyPtrStructScanPlan) Scan(src []byte, target any) error { func TryWrapPtrSliceScanPlan(target any) (plan WrappedScanPlanNextSetter, nextValue any, ok bool) { // Avoid using reflect path for common types. switch target := target.(type) { + case *[]int8: + return &wrapPtrSliceScanPlan[int8]{}, (*FlatArray[int8])(target), true case *[]int16: return &wrapPtrSliceScanPlan[int16]{}, (*FlatArray[int16])(target), true case *[]int32: return &wrapPtrSliceScanPlan[int32]{}, (*FlatArray[int32])(target), true case *[]int64: return &wrapPtrSliceScanPlan[int64]{}, (*FlatArray[int64])(target), true + case *[]int: + return &wrapPtrSliceScanPlan[int]{}, (*FlatArray[int])(target), true + case *[]uint16: + return &wrapPtrSliceScanPlan[uint16]{}, (*FlatArray[uint16])(target), true + case *[]uint32: + return &wrapPtrSliceScanPlan[uint32]{}, (*FlatArray[uint32])(target), true + case *[]uint64: + return &wrapPtrSliceScanPlan[uint64]{}, (*FlatArray[uint64])(target), true + case *[]uint: + return &wrapPtrSliceScanPlan[uint]{}, (*FlatArray[uint])(target), true case *[]float32: return &wrapPtrSliceScanPlan[float32]{}, (*FlatArray[float32])(target), true case *[]float64: @@ -969,6 +987,10 @@ func TryWrapPtrSliceScanPlan(target any) (plan WrappedScanPlanNextSetter, nextVa return &wrapPtrSliceScanPlan[string]{}, (*FlatArray[string])(target), true case *[]time.Time: return &wrapPtrSliceScanPlan[time.Time]{}, (*FlatArray[time.Time])(target), true + case *[]bool: + return &wrapPtrSliceScanPlan[bool]{}, (*FlatArray[bool])(target), true + case *[][16]byte: + return &wrapPtrSliceScanPlan[[16]byte]{}, (*FlatArray[[16]byte])(target), true } targetType := reflect.TypeOf(target) @@ -1827,20 +1849,36 @@ func TryWrapSliceEncodePlan(value any) (plan WrappedEncodePlanNextSetter, nextVa // Avoid using reflect path for common types. switch value := value.(type) { + case []int8: + return &wrapSliceEncodePlan[int8]{}, FlatArray[int8](value), true case []int16: - return &wrapSliceEncodePlan[int16]{}, (FlatArray[int16])(value), true + return &wrapSliceEncodePlan[int16]{}, FlatArray[int16](value), true case []int32: - return &wrapSliceEncodePlan[int32]{}, (FlatArray[int32])(value), true + return &wrapSliceEncodePlan[int32]{}, FlatArray[int32](value), true case []int64: - return &wrapSliceEncodePlan[int64]{}, (FlatArray[int64])(value), true + return &wrapSliceEncodePlan[int64]{}, FlatArray[int64](value), true + case []int: + return &wrapSliceEncodePlan[int]{}, FlatArray[int](value), true + case []uint16: + return &wrapSliceEncodePlan[uint16]{}, FlatArray[uint16](value), true + case []uint32: + return &wrapSliceEncodePlan[uint32]{}, FlatArray[uint32](value), true + case []uint64: + return &wrapSliceEncodePlan[uint64]{}, FlatArray[uint64](value), true + case []uint: + return &wrapSliceEncodePlan[uint]{}, FlatArray[uint](value), true case []float32: - return &wrapSliceEncodePlan[float32]{}, (FlatArray[float32])(value), true + return &wrapSliceEncodePlan[float32]{}, FlatArray[float32](value), true case []float64: - return &wrapSliceEncodePlan[float64]{}, (FlatArray[float64])(value), true + return &wrapSliceEncodePlan[float64]{}, FlatArray[float64](value), true case []string: - return &wrapSliceEncodePlan[string]{}, (FlatArray[string])(value), true + return &wrapSliceEncodePlan[string]{}, FlatArray[string](value), true case []time.Time: - return &wrapSliceEncodePlan[time.Time]{}, (FlatArray[time.Time])(value), true + return &wrapSliceEncodePlan[time.Time]{}, FlatArray[time.Time](value), true + case []bool: + return &wrapSliceEncodePlan[bool]{}, FlatArray[bool](value), true + case [][16]byte: + return &wrapSliceEncodePlan[[16]byte]{}, FlatArray[[16]byte](value), true } if valueType := reflect.TypeOf(value); valueType != nil && valueType.Kind() == reflect.Slice { @@ -1860,7 +1898,7 @@ type wrapSliceEncodePlan[T any] struct { func (plan *wrapSliceEncodePlan[T]) SetNext(next EncodePlan) { plan.next = next } func (plan *wrapSliceEncodePlan[T]) Encode(value any, buf []byte) (newBuf []byte, err error) { - return plan.next.Encode((FlatArray[T])(value.([]T)), buf) + return plan.next.Encode(FlatArray[T](value.([]T)), buf) } type wrapSliceEncodeReflectPlan struct { @@ -1999,6 +2037,9 @@ func (m *Map) Encode(oid uint32, formatCode int16, value any, buf []byte) (newBu // // This uses the type of v to look up the PostgreSQL OID that v presumably came from. This means v must be registered // with m by calling RegisterDefaultPgType. +// +// As of Go 1.27, database/sql calls the driver directly to scan columns when using pgx's stdlib package, so this is +// no longer necessary. func (m *Map) SQLScanner(v any) sql.Scanner { if s, ok := v.(sql.Scanner); ok { return s diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/pgtype_default.go b/vendor/github.com/jackc/pgx/v5/pgtype/pgtype_default.go index 42b39d8..13fe884 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/pgtype_default.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/pgtype_default.go @@ -75,6 +75,7 @@ func initDefaultMap() { defaultMap.RegisterType(&Type{Name: "name", OID: NameOID, Codec: TextCodec{}}) defaultMap.RegisterType(&Type{Name: "numeric", OID: NumericOID, Codec: NumericCodec{}}) defaultMap.RegisterType(&Type{Name: "oid", OID: OIDOID, Codec: Uint32Codec{}}) + defaultMap.RegisterType(&Type{Name: "oid8", OID: OID8OID, Codec: Uint64Codec{}}) defaultMap.RegisterType(&Type{Name: "path", OID: PathOID, Codec: PathCodec{}}) defaultMap.RegisterType(&Type{Name: "point", OID: PointOID, Codec: PointCodec{}}) defaultMap.RegisterType(&Type{Name: "polygon", OID: PolygonOID, Codec: PolygonCodec{}}) @@ -131,7 +132,7 @@ func initDefaultMap() { defaultMap.RegisterType(&Type{Name: "_aclitem", OID: ACLItemArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[ACLItemOID]}}) defaultMap.RegisterType(&Type{Name: "_bit", OID: BitArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[BitOID]}}) defaultMap.RegisterType(&Type{Name: "_bool", OID: BoolArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[BoolOID]}}) - defaultMap.RegisterType(&Type{Name: "_box", OID: BoxArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[BoxOID]}}) + defaultMap.RegisterType(&Type{Name: "_box", OID: BoxArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[BoxOID], Delimiter: ';'}}) defaultMap.RegisterType(&Type{Name: "_bpchar", OID: BPCharArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[BPCharOID]}}) defaultMap.RegisterType(&Type{Name: "_bytea", OID: ByteaArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[ByteaOID]}}) defaultMap.RegisterType(&Type{Name: "_char", OID: QCharArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[QCharOID]}}) @@ -159,6 +160,7 @@ func initDefaultMap() { defaultMap.RegisterType(&Type{Name: "_numeric", OID: NumericArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[NumericOID]}}) defaultMap.RegisterType(&Type{Name: "_numrange", OID: NumrangeArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[NumrangeOID]}}) defaultMap.RegisterType(&Type{Name: "_oid", OID: OIDArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[OIDOID]}}) + defaultMap.RegisterType(&Type{Name: "_oid8", OID: OID8ArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[OID8OID]}}) defaultMap.RegisterType(&Type{Name: "_path", OID: PathArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[PathOID]}}) defaultMap.RegisterType(&Type{Name: "_point", OID: PointArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[PointOID]}}) defaultMap.RegisterType(&Type{Name: "_polygon", OID: PolygonArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[PolygonOID]}}) diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/point.go b/vendor/github.com/jackc/pgx/v5/pgtype/point.go index d90cb70..4536e1e 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/point.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/point.go @@ -3,7 +3,6 @@ package pgtype import ( "bytes" "database/sql/driver" - "encoding/binary" "fmt" "math" "strconv" @@ -215,18 +214,20 @@ func (c PointCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (a type scanPlanBinaryPointToPointScanner struct{} func (scanPlanBinaryPointToPointScanner) Scan(src []byte, dst any) error { - scanner := (dst).(PointScanner) + scanner := dst.(PointScanner) if src == nil { return scanner.ScanPoint(Point{}) } - if len(src) != 16 { - return fmt.Errorf("invalid length for point: %v", len(src)) - } + r := pgio.NewReader(src) - x := binary.BigEndian.Uint64(src) - y := binary.BigEndian.Uint64(src[8:]) + x := r.Uint64() + y := r.Uint64() + + if err := r.Finish(); err != nil { + return fmt.Errorf("point: %w", err) + } return scanner.ScanPoint(Point{ P: Vec2{math.Float64frombits(x), math.Float64frombits(y)}, @@ -237,7 +238,7 @@ func (scanPlanBinaryPointToPointScanner) Scan(src []byte, dst any) error { type scanPlanTextAnyToPointScanner struct{} func (scanPlanTextAnyToPointScanner) Scan(src []byte, dst any) error { - scanner := (dst).(PointScanner) + scanner := dst.(PointScanner) if src == nil { return scanner.ScanPoint(Point{}) diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/polygon.go b/vendor/github.com/jackc/pgx/v5/pgtype/polygon.go index 34aa0a6..c9e2df0 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/polygon.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/polygon.go @@ -2,7 +2,6 @@ package pgtype import ( "database/sql/driver" - "encoding/binary" "fmt" "math" "strconv" @@ -157,32 +156,31 @@ func (PolygonCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanP type scanPlanBinaryPolygonToPolygonScanner struct{} func (scanPlanBinaryPolygonToPolygonScanner) Scan(src []byte, dst any) error { - scanner := (dst).(PolygonScanner) + scanner := dst.(PolygonScanner) if src == nil { return scanner.ScanPolygon(Polygon{}) } - if len(src) < 5 { - return fmt.Errorf("invalid length for polygon: %v", len(src)) - } + r := pgio.NewReader(src) - pointCount := int(binary.BigEndian.Uint32(src)) - rp := 4 - - if 4+pointCount*16 != len(src) { - return fmt.Errorf("invalid length for Polygon with %d points: %v", pointCount, len(src)) + // Each point is two float64s. + pointCount := r.Count(16) + if err := r.Err(); err != nil { + return fmt.Errorf("invalid length for polygon: %w", err) } points := make([]Vec2, pointCount) for i := range points { - x := binary.BigEndian.Uint64(src[rp:]) - rp += 8 - y := binary.BigEndian.Uint64(src[rp:]) - rp += 8 + x := r.Uint64() + y := r.Uint64() points[i] = Vec2{math.Float64frombits(x), math.Float64frombits(y)} } + if err := r.Finish(); err != nil { + return fmt.Errorf("invalid length for Polygon with %d points: %w", pointCount, err) + } + return scanner.ScanPolygon(Polygon{ P: points, Valid: true, @@ -192,7 +190,7 @@ func (scanPlanBinaryPolygonToPolygonScanner) Scan(src []byte, dst any) error { type scanPlanTextAnyToPolygonScanner struct{} func (scanPlanTextAnyToPolygonScanner) Scan(src []byte, dst any) error { - scanner := (dst).(PolygonScanner) + scanner := dst.(PolygonScanner) if src == nil { return scanner.ScanPolygon(Polygon{}) diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/range.go b/vendor/github.com/jackc/pgx/v5/pgtype/range.go index dec153e..dba88fb 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/range.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/range.go @@ -2,8 +2,9 @@ package pgtype import ( "bytes" - "encoding/binary" "fmt" + + "github.com/jackc/pgx/v5/internal/pgio" ) type BoundType byte @@ -201,17 +202,16 @@ const ( func parseUntypedBinaryRange(src []byte) (*untypedBinaryRange, error) { ubr := &untypedBinaryRange{} + r := pgio.NewReader(src) - if len(src) == 0 { + rangeType := r.Byte() + if r.Err() != nil { return nil, fmt.Errorf("range too short: %v", len(src)) } - rangeType := src[0] - rp := 1 - if rangeType&emptyMask > 0 { - if len(src[rp:]) > 0 { - return nil, fmt.Errorf("unexpected trailing bytes parsing empty range: %v", len(src[rp:])) + if err := r.Finish(); err != nil { + return nil, fmt.Errorf("empty range: %w", err) } ubr.LowerType = Empty ubr.UpperType = Empty @@ -236,50 +236,24 @@ func parseUntypedBinaryRange(src []byte) (*untypedBinaryRange, error) { ubr.UpperType = Exclusive } - if ubr.LowerType == Unbounded && ubr.UpperType == Unbounded { - if len(src[rp:]) > 0 { - return nil, fmt.Errorf("unexpected trailing bytes parsing unbounded range: %v", len(src[rp:])) - } - return ubr, nil - } - - if len(src[rp:]) < 4 { - return nil, fmt.Errorf("too few bytes for size: %v", src[rp:]) - } - valueLen := int(binary.BigEndian.Uint32(src[rp:])) - rp += 4 - - if valueLen < 0 || len(src[rp:]) < valueLen { - return nil, fmt.Errorf("range lower bound length %d exceeds remaining %d bytes", valueLen, len(src[rp:])) - } - val := src[rp : rp+valueLen] - rp += valueLen - if ubr.LowerType != Unbounded { - ubr.Lower = val - } else { - ubr.Upper = val - if len(src[rp:]) > 0 { - return nil, fmt.Errorf("unexpected trailing bytes parsing range: %v", len(src[rp:])) + val, null := r.Value() + if null { + return nil, fmt.Errorf("range lower bound cannot be NULL") } - return ubr, nil + ubr.Lower = val } if ubr.UpperType != Unbounded { - if len(src[rp:]) < 4 { - return nil, fmt.Errorf("too few bytes for size: %v", src[rp:]) + val, null := r.Value() + if null { + return nil, fmt.Errorf("range upper bound cannot be NULL") } - valueLen := int(binary.BigEndian.Uint32(src[rp:])) - rp += 4 - if valueLen < 0 || len(src[rp:]) < valueLen { - return nil, fmt.Errorf("range upper bound length %d exceeds remaining %d bytes", valueLen, len(src[rp:])) - } - ubr.Upper = src[rp : rp+valueLen] - rp += valueLen + ubr.Upper = val } - if len(src[rp:]) > 0 { - return nil, fmt.Errorf("unexpected trailing bytes parsing range: %v", len(src[rp:])) + if err := r.Finish(); err != nil { + return nil, fmt.Errorf("range: %w", err) } return ubr, nil diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/range_codec.go b/vendor/github.com/jackc/pgx/v5/pgtype/range_codec.go index dc1ac8b..100b555 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/range_codec.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/range_codec.go @@ -3,6 +3,7 @@ package pgtype import ( "database/sql/driver" "fmt" + "strings" "github.com/jackc/pgx/v5/internal/pgio" ) @@ -79,6 +80,7 @@ func (plan *encodePlanRangeCodecRangeValuerToBinary) Encode(value any, buf []byt lowerType, upperType := getter.BoundTypes() lower, upper := getter.Bounds() + lower, upper = derefAnyRangeBound(lower), derefAnyRangeBound(upper) var rangeType byte switch lowerType { @@ -170,6 +172,7 @@ func (plan *encodePlanRangeCodecRangeValuerToText) Encode(value any, buf []byte) lowerType, upperType := getter.BoundTypes() lower, upper := getter.Bounds() + lower, upper = derefAnyRangeBound(lower), derefAnyRangeBound(upper) switch lowerType { case Exclusive, Unbounded: @@ -192,6 +195,7 @@ func (plan *encodePlanRangeCodecRangeValuerToText) Encode(value any, buf []byte) return nil, fmt.Errorf("cannot encode %v as element of range", lower) } + boundStart := len(buf) buf, err = lowerPlan.Encode(lower, buf) if err != nil { return nil, fmt.Errorf("failed to encode %v as element of range: %w", lower, err) @@ -199,6 +203,7 @@ func (plan *encodePlanRangeCodecRangeValuerToText) Encode(value any, buf []byte) if buf == nil { return nil, fmt.Errorf("Lower cannot be NULL unless LowerType is Unbounded") } + buf = append(buf[:boundStart], quoteRangeBoundIfNeeded(string(buf[boundStart:]))...) } buf = append(buf, ',') @@ -213,6 +218,7 @@ func (plan *encodePlanRangeCodecRangeValuerToText) Encode(value any, buf []byte) return nil, fmt.Errorf("cannot encode %v as element of range", upper) } + boundStart := len(buf) buf, err = upperPlan.Encode(upper, buf) if err != nil { return nil, fmt.Errorf("failed to encode %v as element of range: %w", upper, err) @@ -220,6 +226,7 @@ func (plan *encodePlanRangeCodecRangeValuerToText) Encode(value any, buf []byte) if buf == nil { return nil, fmt.Errorf("Upper cannot be NULL unless UpperType is Unbounded") } + buf = append(buf[:boundStart], quoteRangeBoundIfNeeded(string(buf[boundStart:]))...) } switch upperType { @@ -234,6 +241,23 @@ func (plan *encodePlanRangeCodecRangeValuerToText) Encode(value any, buf []byte) return buf, nil } +// derefAnyRangeBound returns the value held by v when v is a *any. Range[any], which is what RangeCodec.DecodeValue +// returns, reports its bounds as *any. No encode plan can be found for a pointer to an interface, so the bound value +// must be unwrapped before planning. +func derefAnyRangeBound(v any) any { + if p, ok := v.(*any); ok && p != nil { + return *p + } + return v +} + +func quoteRangeBoundIfNeeded(src string) string { + if src == "" || strings.ContainsAny(src, "\"\\,()[]") { + return quoteArrayElement(src) + } + return src +} + func (c *RangeCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { switch format { case BinaryFormatCode: @@ -255,7 +279,7 @@ type scanPlanBinaryRangeToRangeScanner struct { } func (plan *scanPlanBinaryRangeToRangeScanner) Scan(src []byte, target any) error { - rangeScanner := (target).(RangeScanner) + rangeScanner := target.(RangeScanner) if src == nil { return rangeScanner.ScanNull() @@ -305,7 +329,7 @@ type scanPlanTextRangeToRangeScanner struct { } func (plan *scanPlanTextRangeToRangeScanner) Scan(src []byte, target any) error { - rangeScanner := (target).(RangeScanner) + rangeScanner := target.(RangeScanner) if src == nil { return rangeScanner.ScanNull() diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/record_codec.go b/vendor/github.com/jackc/pgx/v5/pgtype/record_codec.go index a663e4d..6fef94e 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/record_codec.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/record_codec.go @@ -40,7 +40,7 @@ type scanPlanBinaryRecordToCompositeIndexScanner struct { } func (plan *scanPlanBinaryRecordToCompositeIndexScanner) Scan(src []byte, target any) error { - targetScanner := (target).(CompositeIndexScanner) + targetScanner := target.(CompositeIndexScanner) if src == nil { return targetScanner.ScanNull() @@ -48,14 +48,17 @@ func (plan *scanPlanBinaryRecordToCompositeIndexScanner) Scan(src []byte, target scanner := NewCompositeBinaryScanner(plan.m, src) for i := 0; scanner.Next(); i++ { - fieldTarget := targetScanner.ScanIndex(i) + fieldTarget, err := compositeFieldTarget(targetScanner, i) + if err != nil { + return err + } if fieldTarget != nil { fieldPlan := plan.m.PlanScan(scanner.OID(), BinaryFormatCode, fieldTarget) if fieldPlan == nil { return fmt.Errorf("unable to scan OID %d in binary format into %v", scanner.OID(), fieldTarget) } - err := fieldPlan.Scan(scanner.Bytes(), fieldTarget) + err = fieldPlan.Scan(scanner.Bytes(), fieldTarget) if err != nil { return err } @@ -96,8 +99,11 @@ func (RecordCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (an return string(src), nil case BinaryFormatCode: scanner := NewCompositeBinaryScanner(m, src) - values := make([]any, scanner.FieldCount()) - for i := 0; scanner.Next(); i++ { + // The field count is a hint for the initial allocation only. Append the + // values actually present rather than indexing into a presized slice, as + // the source may carry more or fewer fields than the header claims. + values := make([]any, 0, scanner.FieldCount()) + for scanner.Next() { var v any fieldPlan := m.PlanScan(scanner.OID(), BinaryFormatCode, &v) if fieldPlan == nil { @@ -109,7 +115,7 @@ func (RecordCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (an return nil, err } - values[i] = v + values = append(values, v) } if err := scanner.Err(); err != nil { diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/text.go b/vendor/github.com/jackc/pgx/v5/pgtype/text.go index e08b125..f20cf2a 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/text.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/text.go @@ -186,7 +186,7 @@ func (scanPlanTextAnyToString) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - p := (dst).(*string) + p := dst.(*string) *p = string(src) return nil @@ -195,7 +195,7 @@ func (scanPlanTextAnyToString) Scan(src []byte, dst any) error { type scanPlanAnyToNewByteSlice struct{} func (scanPlanAnyToNewByteSlice) Scan(src []byte, dst any) error { - p := (dst).(*[]byte) + p := dst.(*[]byte) if src == nil { *p = nil } else { @@ -209,14 +209,14 @@ func (scanPlanAnyToNewByteSlice) Scan(src []byte, dst any) error { type scanPlanAnyToByteScanner struct{} func (scanPlanAnyToByteScanner) Scan(src []byte, dst any) error { - p := (dst).(BytesScanner) + p := dst.(BytesScanner) return p.ScanBytes(src) } type scanPlanTextAnyToTextScanner struct{} func (scanPlanTextAnyToTextScanner) Scan(src []byte, dst any) error { - scanner := (dst).(TextScanner) + scanner := dst.(TextScanner) if src == nil { return scanner.ScanText(Text{}) diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/tid.go b/vendor/github.com/jackc/pgx/v5/pgtype/tid.go index 98d067a..a572e86 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/tid.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/tid.go @@ -2,7 +2,6 @@ package pgtype import ( "database/sql/driver" - "encoding/binary" "fmt" "strconv" "strings" @@ -152,19 +151,24 @@ func (TIDCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan type scanPlanBinaryTIDToTIDScanner struct{} func (scanPlanBinaryTIDToTIDScanner) Scan(src []byte, dst any) error { - scanner := (dst).(TIDScanner) + scanner := dst.(TIDScanner) if src == nil { return scanner.ScanTID(TID{}) } - if len(src) != 6 { - return fmt.Errorf("invalid length for tid: %v", len(src)) + r := pgio.NewReader(src) + + blockNumber := r.Uint32() + offsetNumber := r.Uint16() + + if err := r.Finish(); err != nil { + return fmt.Errorf("tid: %w", err) } return scanner.ScanTID(TID{ - BlockNumber: binary.BigEndian.Uint32(src), - OffsetNumber: binary.BigEndian.Uint16(src[4:]), + BlockNumber: blockNumber, + OffsetNumber: offsetNumber, Valid: true, }) } @@ -172,18 +176,20 @@ func (scanPlanBinaryTIDToTIDScanner) Scan(src []byte, dst any) error { type scanPlanBinaryTIDToTextScanner struct{} func (scanPlanBinaryTIDToTextScanner) Scan(src []byte, dst any) error { - scanner := (dst).(TextScanner) + scanner := dst.(TextScanner) if src == nil { return scanner.ScanText(Text{}) } - if len(src) != 6 { - return fmt.Errorf("invalid length for tid: %v", len(src)) - } + r := pgio.NewReader(src) - blockNumber := binary.BigEndian.Uint32(src) - offsetNumber := binary.BigEndian.Uint16(src[4:]) + blockNumber := r.Uint32() + offsetNumber := r.Uint16() + + if err := r.Finish(); err != nil { + return fmt.Errorf("tid: %w", err) + } return scanner.ScanText(Text{ String: fmt.Sprintf(`(%d,%d)`, blockNumber, offsetNumber), @@ -194,7 +200,7 @@ func (scanPlanBinaryTIDToTextScanner) Scan(src []byte, dst any) error { type scanPlanTextAnyToTIDScanner struct{} func (scanPlanTextAnyToTIDScanner) Scan(src []byte, dst any) error { - scanner := (dst).(TIDScanner) + scanner := dst.(TIDScanner) if src == nil { return scanner.ScanTID(TID{}) diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/time.go b/vendor/github.com/jackc/pgx/v5/pgtype/time.go index 72cdb50..70fef8a 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/time.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/time.go @@ -2,7 +2,6 @@ package pgtype import ( "database/sql/driver" - "encoding/binary" "fmt" "strconv" @@ -132,9 +131,36 @@ func (encodePlanTimeCodecText) Encode(value any, buf []byte) (newBuf []byte, err seconds := usec / microsecondsPerSecond usec -= seconds * microsecondsPerSecond - s := fmt.Sprintf("%02d:%02d:%02d.%06d", hours, minutes, seconds, usec) + buf = appendTimeText(buf, hours, minutes, seconds) + buf = append(buf, '.') + return appendZeroPaddedInt64(buf, usec, 6), nil +} - return append(buf, s...), nil +func appendTimeText(buf []byte, hours, minutes, seconds int64) []byte { + buf = appendZeroPaddedInt64(buf, hours, 2) + buf = append(buf, ':') + buf = appendZeroPaddedInt64(buf, minutes, 2) + buf = append(buf, ':') + return appendZeroPaddedInt64(buf, seconds, 2) +} + +func appendZeroPaddedInt64(buf []byte, n int64, minWidth int) []byte { + var digits [20]byte + var formatted []byte + if n < 0 { + buf = append(buf, '-') + minWidth-- + magnitude := uint64(-(n + 1)) + 1 + formatted = strconv.AppendUint(digits[:0], magnitude, 10) + } else { + formatted = strconv.AppendInt(digits[:0], n, 10) + } + + for len(formatted) < minWidth { + buf = append(buf, '0') + minWidth-- + } + return append(buf, formatted...) } func (TimeCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { @@ -158,17 +184,18 @@ func (TimeCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan type scanPlanBinaryTimeToTimeScanner struct{} func (scanPlanBinaryTimeToTimeScanner) Scan(src []byte, dst any) error { - scanner := (dst).(TimeScanner) + scanner := dst.(TimeScanner) if src == nil { return scanner.ScanTime(Time{}) } - if len(src) != 8 { - return fmt.Errorf("invalid length for time: %v", len(src)) + raw, err := pgio.Uint64Exact(src) + if err != nil { + return fmt.Errorf("time: %w", err) } - usec := int64(binary.BigEndian.Uint64(src)) + usec := int64(raw) return scanner.ScanTime(Time{Microseconds: usec, Valid: true}) } @@ -176,7 +203,7 @@ func (scanPlanBinaryTimeToTimeScanner) Scan(src []byte, dst any) error { type scanPlanBinaryTimeToTextScanner struct{} func (scanPlanBinaryTimeToTextScanner) Scan(src []byte, dst any) error { - ts, ok := (dst).(TextScanner) + ts, ok := dst.(TextScanner) if !ok { return ErrScanTargetTypeChanged } @@ -185,11 +212,12 @@ func (scanPlanBinaryTimeToTextScanner) Scan(src []byte, dst any) error { return ts.ScanText(Text{}) } - if len(src) != 8 { - return fmt.Errorf("invalid length for time: %v", len(src)) + raw, err := pgio.Uint64Exact(src) + if err != nil { + return fmt.Errorf("time: %w", err) } - usec := int64(binary.BigEndian.Uint64(src)) + usec := int64(raw) tim := Time{Microseconds: usec, Valid: true} @@ -204,7 +232,7 @@ func (scanPlanBinaryTimeToTextScanner) Scan(src []byte, dst any) error { type scanPlanTextAnyToTimeScanner struct{} func (scanPlanTextAnyToTimeScanner) Scan(src []byte, dst any) error { - scanner := (dst).(TimeScanner) + scanner := dst.(TimeScanner) if src == nil { return scanner.ScanTime(Time{}) diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/timestamp.go b/vendor/github.com/jackc/pgx/v5/pgtype/timestamp.go index 405c77e..33c2b94 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/timestamp.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/timestamp.go @@ -2,18 +2,16 @@ package pgtype import ( "database/sql/driver" - "encoding/binary" "encoding/json" "fmt" - "strings" "time" + "github.com/jackc/pgx/v5/internal/pgdatetime" "github.com/jackc/pgx/v5/internal/pgio" ) const ( - pgTimestampFormat = "2006-01-02 15:04:05.999999999" - jsonISO8601 = "2006-01-02T15:04:05.999999999" + jsonISO8601 = "2006-01-02T15:04:05.999999999" ) type TimestampScanner interface { @@ -201,33 +199,17 @@ func (encodePlanTimestampCodecText) Encode(value any, buf []byte) (newBuf []byte return nil, nil } - var s string - switch ts.InfinityModifier { case Finite: - t := discardTimeZone(ts.Time) - - // Year 0000 is 1 BC - bc := false - if year := t.Year(); year <= 0 { - year = -year + 1 - t = time.Date(year, t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), t.Nanosecond(), time.UTC) - bc = true - } - - s = t.Truncate(time.Microsecond).Format(pgTimestampFormat) - - if bc { - s += " BC" - } + // The fields are read in ts.Time's own location, so there is no zone to discard + // and nothing to append after the time. + buf = pgdatetime.AppendTimestamp(buf, ts.Time, "") case Infinity: - s = "infinity" + buf = append(buf, "infinity"...) case NegativeInfinity: - s = "-infinity" + buf = append(buf, "-infinity"...) } - buf = append(buf, s...) - return buf, nil } @@ -257,18 +239,19 @@ func (c *TimestampCodec) PlanScan(m *Map, oid uint32, format int16, target any) type scanPlanBinaryTimestampToTimestampScanner struct{ location *time.Location } func (plan *scanPlanBinaryTimestampToTimestampScanner) Scan(src []byte, dst any) error { - scanner := (dst).(TimestampScanner) + scanner := dst.(TimestampScanner) if src == nil { return scanner.ScanTimestamp(Timestamp{}) } - if len(src) != 8 { - return fmt.Errorf("invalid length for timestamp: %v", len(src)) + raw, err := pgio.Uint64Exact(src) + if err != nil { + return fmt.Errorf("timestamp: %w", err) } var ts Timestamp - microsecSinceY2K := int64(binary.BigEndian.Uint64(src)) + microsecSinceY2K := int64(raw) switch microsecSinceY2K { case infinityMicrosecondOffset: @@ -280,6 +263,9 @@ func (plan *scanPlanBinaryTimestampToTimestampScanner) Scan(src []byte, dst any) microsecFromUnixEpochToY2K/1_000_000+microsecSinceY2K/1_000_000, (microsecFromUnixEpochToY2K%1_000_000*1_000)+(microsecSinceY2K%1_000_000*1000), ).UTC() + if tim.Before(minDateTime) || !tim.Before(endTimestamp) { + return fmt.Errorf("timestamp %d microseconds from 2000-01-01 is out of range", microsecSinceY2K) + } if plan.location != nil { tim = time.Date(tim.Year(), tim.Month(), tim.Day(), tim.Hour(), tim.Minute(), tim.Second(), tim.Nanosecond(), plan.location) } @@ -292,37 +278,34 @@ func (plan *scanPlanBinaryTimestampToTimestampScanner) Scan(src []byte, dst any) type scanPlanTextTimestampToTimestampScanner struct{ location *time.Location } func (plan *scanPlanTextTimestampToTimestampScanner) Scan(src []byte, dst any) error { - scanner := (dst).(TimestampScanner) + scanner := dst.(TimestampScanner) if src == nil { return scanner.ScanTimestamp(Timestamp{}) } + dt, err := parseTextDateTime(src) + if err != nil { + return err + } + var ts Timestamp - sbuf := string(src) - switch sbuf { - case "infinity": - ts = Timestamp{Valid: true, InfinityModifier: Infinity} - case "-infinity": - ts = Timestamp{Valid: true, InfinityModifier: -Infinity} - default: - bc := false - if strings.HasSuffix(sbuf, " BC") { - sbuf = sbuf[:len(sbuf)-3] - bc = true + if dt.infinity != Finite { + ts = Timestamp{Valid: true, InfinityModifier: dt.infinity} + } else { + if !dt.hasTime || dt.hasOffset { + return badDateTime(src) } - tim, err := time.Parse(pgTimestampFormat, sbuf) + + tim, err := dt.toTime(src, "timestamp", endTimestamp) if err != nil { return err } - if bc { - year := -tim.Year() + 1 - tim = time.Date(year, tim.Month(), tim.Day(), tim.Hour(), tim.Minute(), tim.Second(), tim.Nanosecond(), tim.Location()) - } - + // timestamp has no time zone, so ScanLocation reinterprets the same wall clock + // reading rather than converting the instant. if plan.location != nil { - tim = time.Date(tim.Year(), tim.Month(), tim.Day(), tim.Hour(), tim.Minute(), tim.Second(), tim.Nanosecond(), plan.location) + tim = dt.in(plan.location) } ts = Timestamp{Time: tim, Valid: true} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/timestamptz.go b/vendor/github.com/jackc/pgx/v5/pgtype/timestamptz.go index 139312a..f05e384 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/timestamptz.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/timestamptz.go @@ -2,19 +2,15 @@ package pgtype import ( "database/sql/driver" - "encoding/binary" "encoding/json" "fmt" - "strings" "time" + "github.com/jackc/pgx/v5/internal/pgdatetime" "github.com/jackc/pgx/v5/internal/pgio" ) const ( - pgTimestamptzHourFormat = "2006-01-02 15:04:05.999999999Z07" - pgTimestamptzMinuteFormat = "2006-01-02 15:04:05.999999999Z07:00" - pgTimestamptzSecondFormat = "2006-01-02 15:04:05.999999999Z07:00:00" microsecFromUnixEpochToY2K = 946_684_800 * 1_000_000 ) @@ -199,34 +195,15 @@ func (encodePlanTimestamptzCodecText) Encode(value any, buf []byte) (newBuf []by return nil, nil } - var s string - switch ts.InfinityModifier { case Finite: - - t := ts.Time.UTC().Truncate(time.Microsecond) - - // Year 0000 is 1 BC - bc := false - if year := t.Year(); year <= 0 { - year = -year + 1 - t = time.Date(year, t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), t.Nanosecond(), time.UTC) - bc = true - } - - s = t.Format(pgTimestamptzSecondFormat) - - if bc { - s += " BC" - } + buf = pgdatetime.AppendTimestamp(buf, ts.Time.UTC(), "Z") case Infinity: - s = "infinity" + buf = append(buf, "infinity"...) case NegativeInfinity: - s = "-infinity" + buf = append(buf, "-infinity"...) } - buf = append(buf, s...) - return buf, nil } @@ -248,18 +225,19 @@ func (c *TimestamptzCodec) PlanScan(m *Map, oid uint32, format int16, target any type scanPlanBinaryTimestamptzToTimestamptzScanner struct{ location *time.Location } func (plan *scanPlanBinaryTimestamptzToTimestamptzScanner) Scan(src []byte, dst any) error { - scanner := (dst).(TimestamptzScanner) + scanner := dst.(TimestamptzScanner) if src == nil { return scanner.ScanTimestamptz(Timestamptz{}) } - if len(src) != 8 { - return fmt.Errorf("invalid length for timestamptz: %v", len(src)) + raw, err := pgio.Uint64Exact(src) + if err != nil { + return fmt.Errorf("timestamptz: %w", err) } var tstz Timestamptz - microsecSinceY2K := int64(binary.BigEndian.Uint64(src)) + microsecSinceY2K := int64(raw) switch microsecSinceY2K { case infinityMicrosecondOffset: @@ -271,6 +249,9 @@ func (plan *scanPlanBinaryTimestamptzToTimestamptzScanner) Scan(src []byte, dst microsecFromUnixEpochToY2K/1_000_000+microsecSinceY2K/1_000_000, (microsecFromUnixEpochToY2K%1_000_000*1_000)+(microsecSinceY2K%1_000_000*1_000), ) + if tim.Before(minDateTime) || !tim.Before(endTimestamp) { + return fmt.Errorf("timestamptz %d microseconds from 2000-01-01 is out of range", microsecSinceY2K) + } if plan.location != nil { tim = tim.In(plan.location) } @@ -283,51 +264,38 @@ func (plan *scanPlanBinaryTimestamptzToTimestamptzScanner) Scan(src []byte, dst type scanPlanTextTimestamptzToTimestamptzScanner struct{ location *time.Location } func (plan *scanPlanTextTimestamptzToTimestamptzScanner) Scan(src []byte, dst any) error { - scanner := (dst).(TimestamptzScanner) + scanner := dst.(TimestamptzScanner) if src == nil { return scanner.ScanTimestamptz(Timestamptz{}) } + dt, err := parseTextDateTime(src) + if err != nil { + return err + } + var tstz Timestamptz - sbuf := string(src) - switch sbuf { - case "infinity": - tstz = Timestamptz{Valid: true, InfinityModifier: Infinity} - case "-infinity": - tstz = Timestamptz{Valid: true, InfinityModifier: -Infinity} - default: - bc := false - if strings.HasSuffix(sbuf, " BC") { - sbuf = sbuf[:len(sbuf)-3] - bc = true + if dt.infinity != Finite { + tstz = Timestamptz{Valid: true, InfinityModifier: dt.infinity} + } else { + if !dt.hasTime || !dt.hasOffset { + return badDateTime(src) } - var format string - switch { - case len(sbuf) >= 9 && (sbuf[len(sbuf)-9] == '-' || sbuf[len(sbuf)-9] == '+'): - format = pgTimestamptzSecondFormat - case len(sbuf) >= 6 && (sbuf[len(sbuf)-6] == '-' || sbuf[len(sbuf)-6] == '+'): - format = pgTimestamptzMinuteFormat - default: - format = pgTimestamptzHourFormat - } - - tim, err := time.Parse(format, sbuf) + tim, err := dt.toTime(src, "timestamptz", endTimestamp) if err != nil { return err } - if bc { - year := -tim.Year() + 1 - tim = time.Date(year, tim.Month(), tim.Day(), tim.Hour(), tim.Minute(), tim.Second(), tim.Nanosecond(), tim.Location()) - } - + // The binary path builds its value with time.Unix, which returns time.Local. Match + // it, so that the same value scanned in either format produces the same time.Time. + loc := time.Local if plan.location != nil { - tim = tim.In(plan.location) + loc = plan.location } - tstz = Timestamptz{Time: tim, Valid: true} + tstz = Timestamptz{Time: tim.In(loc), Valid: true} } return scanner.ScanTimestamptz(tstz) diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/tsvector.go b/vendor/github.com/jackc/pgx/v5/pgtype/tsvector.go index cc7b831..195481b 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/tsvector.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/tsvector.go @@ -1,9 +1,7 @@ package pgtype import ( - "bytes" "database/sql/driver" - "encoding/binary" "fmt" "strconv" "strings" @@ -184,33 +182,20 @@ func (encodePlanTSVectorCodecBinary) Encode(value any, buf []byte) ([]byte, erro type scanPlanBinaryTSVectorToTSVectorScanner struct{} func (scanPlanBinaryTSVectorToTSVectorScanner) Scan(src []byte, dst any) error { - scanner := (dst).(TSVectorScanner) + scanner := dst.(TSVectorScanner) if src == nil { return scanner.ScanTSVector(TSVector{}) } - rp := 0 + r := pgio.NewReader(src) - const ( - uint16Len = 2 - uint32Len = 4 - ) - - if len(src[rp:]) < uint32Len { - return fmt.Errorf("tsvector incomplete %v", src) - } - entryCount := int(int32(binary.BigEndian.Uint32(src[rp:]))) - rp += uint32Len - - if entryCount < 0 { - return fmt.Errorf("tsvector invalid lexeme count: %d", entryCount) - } - // Each lexeme carries at minimum a 1-byte NUL terminator and a 2-byte position count, so - // entryCount cannot exceed remaining/3. This bounds the up-front make() against a malicious - // server claiming a huge lexeme count in a small message. - if maxEntries := len(src[rp:]) / 3; entryCount > maxEntries { - return fmt.Errorf("tsvector invalid lexeme count %d for %d remaining bytes", entryCount, len(src[rp:])) + // Each lexeme carries at minimum a 1-byte NUL terminator and a 2-byte position count. This + // bounds the up-front make() against a malicious server claiming a huge lexeme count in a + // small message. + entryCount := r.Count(3) + if err := r.Err(); err != nil { + return fmt.Errorf("tsvector: %w", err) } var tsv TSVector @@ -219,41 +204,35 @@ func (scanPlanBinaryTSVectorToTSVectorScanner) Scan(src []byte, dst any) error { } for i := range entryCount { - nullIndex := bytes.IndexByte(src[rp:], 0x00) - if nullIndex == -1 { - return fmt.Errorf("invalid tsvector binary format: missing null terminator") - } + lexeme := TSVectorLexeme{Word: string(r.CString())} - lexeme := TSVectorLexeme{Word: string(src[rp : rp+nullIndex])} - rp += nullIndex + 1 // skip past null terminator - - // Read position count. - if len(src[rp:]) < uint16Len { - return fmt.Errorf("invalid tsvector binary format: incomplete position count") - } - - numPositions := int(binary.BigEndian.Uint16(src[rp:])) - rp += uint16Len - - // Read each packed position: weight (2 bits) | position (14 bits) - if len(src[rp:]) < numPositions*uint16Len { - return fmt.Errorf("invalid tsvector binary format: incomplete positions") + numPositions := int(r.Uint16()) + if err := r.Err(); err != nil { + return fmt.Errorf("invalid tsvector binary format: lexeme %d: %w", i, err) } + // Each packed position is weight (2 bits) | position (14 bits). numPositions came from a + // uint16, so it cannot ask for an unreasonable allocation here. if numPositions > 0 { lexeme.Positions = make([]TSVectorPosition, numPositions) for pos := range numPositions { - packed := binary.BigEndian.Uint16(src[rp:]) - rp += uint16Len + packed := r.Uint16() lexeme.Positions[pos] = TSVectorPosition{ Position: packed & 0x3FFF, Weight: tsvectorWeightFromBinary(packed >> 14), } } + if err := r.Err(); err != nil { + return fmt.Errorf("invalid tsvector binary format: lexeme %d positions: %w", i, err) + } } tsv.Lexemes[i] = lexeme } + + if err := r.Finish(); err != nil { + return fmt.Errorf("tsvector: %w", err) + } tsv.Valid = true return scanner.ScanTSVector(tsv) @@ -318,7 +297,7 @@ func (TSVectorCodec) PlanScan(m *Map, oid uint32, format int16, target any) Scan type scanPlanTextAnyToTSVectorScanner struct{} func (s scanPlanTextAnyToTSVectorScanner) Scan(src []byte, dst any) error { - scanner := (dst).(TSVectorScanner) + scanner := dst.(TSVectorScanner) if src == nil { return scanner.ScanTSVector(TSVector{}) diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/uint32.go b/vendor/github.com/jackc/pgx/v5/pgtype/uint32.go index e6d4b1c..c97ea36 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/uint32.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/uint32.go @@ -2,7 +2,6 @@ package pgtype import ( "database/sql/driver" - "encoding/binary" "encoding/json" "fmt" "math" @@ -184,7 +183,7 @@ type encodePlanUint32CodecTextUint32 struct{} func (encodePlanUint32CodecTextUint32) Encode(value any, buf []byte) (newBuf []byte, err error) { v := value.(uint32) - return append(buf, strconv.FormatUint(uint64(v), 10)...), nil + return strconv.AppendUint(buf, uint64(v), 10), nil } type encodePlanUint32CodecTextUint32Valuer struct{} @@ -221,7 +220,7 @@ func (encodePlanUint32CodecTextInt64Valuer) Encode(value any, buf []byte) (newBu return nil, fmt.Errorf("%d is greater than maximum value for uint32", v.Int64) } - return append(buf, strconv.FormatInt(v.Int64, 10)...), nil + return strconv.AppendInt(buf, v.Int64, 10), nil } func (Uint32Codec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { @@ -280,12 +279,13 @@ func (scanPlanBinaryUint32ToUint32) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 4 { - return fmt.Errorf("invalid length for uint32: %v", len(src)) + raw, err := pgio.Uint32Exact(src) + if err != nil { + return fmt.Errorf("uint32: %w", err) } - p := (dst).(*uint32) - *p = binary.BigEndian.Uint32(src) + p := dst.(*uint32) + *p = raw return nil } @@ -293,7 +293,7 @@ func (scanPlanBinaryUint32ToUint32) Scan(src []byte, dst any) error { type scanPlanBinaryUint32ToUint32Scanner struct{} func (scanPlanBinaryUint32ToUint32Scanner) Scan(src []byte, dst any) error { - s, ok := (dst).(Uint32Scanner) + s, ok := dst.(Uint32Scanner) if !ok { return ErrScanTargetTypeChanged } @@ -302,19 +302,18 @@ func (scanPlanBinaryUint32ToUint32Scanner) Scan(src []byte, dst any) error { return s.ScanUint32(Uint32{}) } - if len(src) != 4 { - return fmt.Errorf("invalid length for uint32: %v", len(src)) + n, err := pgio.Uint32Exact(src) + if err != nil { + return fmt.Errorf("uint32: %w", err) } - n := binary.BigEndian.Uint32(src) - return s.ScanUint32(Uint32{Uint32: n, Valid: true}) } type scanPlanBinaryUint32ToTextScanner struct{} func (scanPlanBinaryUint32ToTextScanner) Scan(src []byte, dst any) error { - s, ok := (dst).(TextScanner) + s, ok := dst.(TextScanner) if !ok { return ErrScanTargetTypeChanged } @@ -323,18 +322,19 @@ func (scanPlanBinaryUint32ToTextScanner) Scan(src []byte, dst any) error { return s.ScanText(Text{}) } - if len(src) != 4 { - return fmt.Errorf("invalid length for uint32: %v", len(src)) + raw, err := pgio.Uint32Exact(src) + if err != nil { + return fmt.Errorf("uint32: %w", err) } - n := uint64(binary.BigEndian.Uint32(src)) + n := uint64(raw) return s.ScanText(Text{String: strconv.FormatUint(n, 10), Valid: true}) } type scanPlanTextAnyToUint32Scanner struct{} func (scanPlanTextAnyToUint32Scanner) Scan(src []byte, dst any) error { - s, ok := (dst).(Uint32Scanner) + s, ok := dst.(Uint32Scanner) if !ok { return ErrScanTargetTypeChanged } diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/uint64.go b/vendor/github.com/jackc/pgx/v5/pgtype/uint64.go index fc407bd..4566988 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/uint64.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/uint64.go @@ -2,7 +2,6 @@ package pgtype import ( "database/sql/driver" - "encoding/binary" "fmt" "math" "strconv" @@ -158,7 +157,7 @@ type encodePlanUint64CodecTextUint64 struct{} func (encodePlanUint64CodecTextUint64) Encode(value any, buf []byte) (newBuf []byte, err error) { v := value.(uint64) - return append(buf, strconv.FormatUint(v, 10)...), nil + return strconv.AppendUint(buf, v, 10), nil } type encodePlanUint64CodecTextUint64Valuer struct{} @@ -192,7 +191,7 @@ func (encodePlanUint64CodecTextInt64Valuer) Encode(value any, buf []byte) (newBu return nil, fmt.Errorf("%d is less than minimum value for uint64", v.Int64) } - return append(buf, strconv.FormatInt(v.Int64, 10)...), nil + return strconv.AppendInt(buf, v.Int64, 10), nil } func (Uint64Codec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { @@ -228,7 +227,7 @@ func (c Uint64Codec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, sr if err != nil { return nil, err } - return int64(n), nil + return (Uint64{Uint64: n, Valid: true}).Value() } func (c Uint64Codec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { @@ -251,12 +250,13 @@ func (scanPlanBinaryUint64ToUint64) Scan(src []byte, dst any) error { return fmt.Errorf("cannot scan NULL into %T", dst) } - if len(src) != 8 { - return fmt.Errorf("invalid length for uint64: %v", len(src)) + raw, err := pgio.Uint64Exact(src) + if err != nil { + return fmt.Errorf("uint64: %w", err) } - p := (dst).(*uint64) - *p = binary.BigEndian.Uint64(src) + p := dst.(*uint64) + *p = raw return nil } @@ -264,7 +264,7 @@ func (scanPlanBinaryUint64ToUint64) Scan(src []byte, dst any) error { type scanPlanBinaryUint64ToUint64Scanner struct{} func (scanPlanBinaryUint64ToUint64Scanner) Scan(src []byte, dst any) error { - s, ok := (dst).(Uint64Scanner) + s, ok := dst.(Uint64Scanner) if !ok { return ErrScanTargetTypeChanged } @@ -273,19 +273,18 @@ func (scanPlanBinaryUint64ToUint64Scanner) Scan(src []byte, dst any) error { return s.ScanUint64(Uint64{}) } - if len(src) != 8 { - return fmt.Errorf("invalid length for uint64: %v", len(src)) + n, err := pgio.Uint64Exact(src) + if err != nil { + return fmt.Errorf("uint64: %w", err) } - n := binary.BigEndian.Uint64(src) - return s.ScanUint64(Uint64{Uint64: n, Valid: true}) } type scanPlanBinaryUint64ToTextScanner struct{} func (scanPlanBinaryUint64ToTextScanner) Scan(src []byte, dst any) error { - s, ok := (dst).(TextScanner) + s, ok := dst.(TextScanner) if !ok { return ErrScanTargetTypeChanged } @@ -294,18 +293,18 @@ func (scanPlanBinaryUint64ToTextScanner) Scan(src []byte, dst any) error { return s.ScanText(Text{}) } - if len(src) != 8 { - return fmt.Errorf("invalid length for uint64: %v", len(src)) + n, err := pgio.Uint64Exact(src) + if err != nil { + return fmt.Errorf("uint64: %w", err) } - n := binary.BigEndian.Uint64(src) return s.ScanText(Text{String: strconv.FormatUint(n, 10), Valid: true}) } type scanPlanTextAnyToUint64Scanner struct{} func (scanPlanTextAnyToUint64Scanner) Scan(src []byte, dst any) error { - s, ok := (dst).(Uint64Scanner) + s, ok := dst.(Uint64Scanner) if !ok { return ErrScanTargetTypeChanged } diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/uuid.go b/vendor/github.com/jackc/pgx/v5/pgtype/uuid.go index 476889a..725defe 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/uuid.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/uuid.go @@ -211,7 +211,7 @@ func (UUIDCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan type scanPlanBinaryUUIDToUUIDScanner struct{} func (scanPlanBinaryUUIDToUUIDScanner) Scan(src []byte, dst any) error { - scanner := (dst).(UUIDScanner) + scanner := dst.(UUIDScanner) if src == nil { return scanner.ScanUUID(UUID{}) @@ -230,7 +230,7 @@ func (scanPlanBinaryUUIDToUUIDScanner) Scan(src []byte, dst any) error { type scanPlanBinaryUUIDToTextScanner struct{} func (scanPlanBinaryUUIDToTextScanner) Scan(src []byte, dst any) error { - scanner := (dst).(TextScanner) + scanner := dst.(TextScanner) if src == nil { return scanner.ScanText(Text{}) @@ -249,7 +249,7 @@ func (scanPlanBinaryUUIDToTextScanner) Scan(src []byte, dst any) error { type scanPlanTextAnyToUUIDScanner struct{} func (scanPlanTextAnyToUUIDScanner) Scan(src []byte, dst any) error { - scanner := (dst).(UUIDScanner) + scanner := dst.(UUIDScanner) if src == nil { return scanner.ScanUUID(UUID{}) diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/xml.go b/vendor/github.com/jackc/pgx/v5/pgtype/xml.go index 66e6dff..7536e2b 100644 --- a/vendor/github.com/jackc/pgx/v5/pgtype/xml.go +++ b/vendor/github.com/jackc/pgx/v5/pgtype/xml.go @@ -104,23 +104,6 @@ func (c *XMLCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPl switch target.(type) { case *string: return scanPlanAnyToString{} - - case **string: - // This is to fix **string scanning. It seems wrong to special case **string, but it's not clear what a better - // solution would be. - // - // https://github.com/jackc/pgx/issues/1470 -- **string - // https://github.com/jackc/pgx/issues/1691 -- ** anything else - - if wrapperPlan, nextDst, ok := TryPointerPointerScanPlan(target); ok { - if nextPlan := m.planScan(oid, format, nextDst, 0); nextPlan != nil { - if _, failed := nextPlan.(*scanPlanFail); !failed { - wrapperPlan.SetNext(nextPlan) - return wrapperPlan - } - } - } - case *[]byte: return scanPlanXMLToByteSlice{} case BytesScanner: @@ -133,6 +116,17 @@ func (c *XMLCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPl return &scanPlanSQLScanner{formatCode: format} } + // Map.planScan only tries the wrap scan plan funcs when the codec returns nil, and the fallback below is never nil. + // So explicitly return nil for a pointer to a pointer to let TryPointerPointerScanPlan handle it. It sets the target + // to nil for SQL NULL and otherwise allocates through any amount of pointer indirection before scanning. + // + // https://github.com/jackc/pgx/issues/1470 -- **string + // https://github.com/jackc/pgx/issues/1691 -- ** anything else + if targetType := reflect.TypeOf(target); targetType != nil && targetType.Kind() == reflect.Pointer && + targetType.Elem().Kind() == reflect.Pointer { + return nil + } + return &scanPlanXMLToXMLUnmarshal{ unmarshal: c.Unmarshal, } diff --git a/vendor/github.com/jackc/pgx/v5/pgxpool/batch_results.go b/vendor/github.com/jackc/pgx/v5/pgxpool/batch_results.go index 5d5c681..e212617 100644 --- a/vendor/github.com/jackc/pgx/v5/pgxpool/batch_results.go +++ b/vendor/github.com/jackc/pgx/v5/pgxpool/batch_results.go @@ -5,29 +5,10 @@ import ( "github.com/jackc/pgx/v5/pgconn" ) -type errBatchResults struct { - err error -} - -func (br errBatchResults) Exec() (pgconn.CommandTag, error) { - return pgconn.CommandTag{}, br.err -} - -func (br errBatchResults) Query() (pgx.Rows, error) { - return errRows{err: br.err}, br.err -} - -func (br errBatchResults) QueryRow() pgx.Row { - return errRow{err: br.err} -} - -func (br errBatchResults) Close() error { - return br.err -} - type poolBatchResults struct { br pgx.BatchResults c *Conn + tx *Tx // owns c instead when the batch began a transaction } func (br *poolBatchResults) Exec() (pgconn.CommandTag, error) { @@ -50,3 +31,10 @@ func (br *poolBatchResults) Close() error { } return err } + +func (br *poolBatchResults) Tx() pgx.Tx { + if br.tx == nil { + return nil + } + return br.tx +} diff --git a/vendor/github.com/jackc/pgx/v5/pgxpool/pool.go b/vendor/github.com/jackc/pgx/v5/pgxpool/pool.go index 5c740b1..3988ebd 100644 --- a/vendor/github.com/jackc/pgx/v5/pgxpool/pool.go +++ b/vendor/github.com/jackc/pgx/v5/pgxpool/pool.go @@ -22,6 +22,7 @@ var ( defaultMaxConnLifetime = time.Hour defaultMaxConnIdleTime = time.Minute * 30 defaultHealthCheckPeriod = time.Minute + defaultPingTimeout = time.Duration(0) ) type connResource struct { @@ -159,6 +160,7 @@ type Config struct { ShouldPing func(context.Context, ShouldPingParams) bool // MaxConnLifetime is the duration since creation after which a connection will be automatically closed. + // The default is 1 hour. MaxConnLifetime time.Duration // MaxConnLifetimeJitter is the duration after MaxConnLifetime to randomly decide to close a connection. @@ -166,10 +168,15 @@ type Config struct { MaxConnLifetimeJitter time.Duration // MaxConnIdleTime is the duration after which an idle connection will be automatically closed by the health check. + // The default is 30 minutes. MaxConnIdleTime time.Duration // PingTimeout is the maximum amount of time to wait for a connection to pong before considering it as unhealthy and - // destroying it. If zero, the default is no timeout. + // destroying it. If zero (the default), there is no separate ping timeout. A stalled ping can then use the acquiring + // caller's full deadline, leaving no time to retry acquisition with another pooled connection. Set a positive timeout + // when that retry should have time to run; a shorter timeout can also discard healthy connections during overload or + // network latency. After the acquiring caller cancels, a ping is allowed at most one more minute to complete before + // it is canceled. PingTimeout time.Duration // MaxConns is the maximum size of the pool. The default is the greater of 4 or runtime.NumCPU(). @@ -178,6 +185,7 @@ type Config struct { // MinConns is the minimum size of the pool. After connection closes, the pool might dip below MinConns. A low // number of MinConns might mean the pool is empty after MaxConnLifetime until the health check has a chance // to create new connections. + // Each background attempt to satisfy MinConns and MinIdleConns has a 60-second timeout, including connection hooks. MinConns int32 // MinIdleConns is the minimum number of idle connections in the pool. You can increase this to ensure that @@ -188,6 +196,7 @@ type Config struct { MinIdleConns int32 // HealthCheckPeriod is the duration between checks of the health of idle connections. + // The default is 1 minute. HealthCheckPeriod time.Duration createdByParseConfig bool // Used to enforce created by ParseConfig rule. @@ -206,7 +215,8 @@ func (c *Config) Copy() *Config { // ConnString returns the connection string as parsed by pgxpool.ParseConfig into pgxpool.Config. func (c *Config) ConnString() string { return c.ConnConfig.ConnString() } -// New creates a new Pool. See [ParseConfig] for information on connString format. +// New creates a new Pool. See [ParseConfig] for information on connString format and +// [NewWithConfig] for how connections are established in the background. func New(ctx context.Context, connString string) (*Pool, error) { config, err := ParseConfig(connString) if err != nil { @@ -217,6 +227,10 @@ func New(ctx context.Context, connString string) (*Pool, error) { } // NewWithConfig creates a new [Pool]. config must have been created by [ParseConfig]. +// Connections to satisfy MinConns and MinIdleConns are established in the background. +// The startup attempt uses ctx's values but ignores its cancellation and deadline. +// Connection errors are not returned by NewWithConfig. Acquire a connection to check if a +// connection can be established. func NewWithConfig(ctx context.Context, config *Config) (*Pool, error) { // Default values are set in ParseConfig. Enforce initial creation by ParseConfig rather than setting defaults from // zero values. @@ -332,7 +346,7 @@ func NewWithConfig(ctx context.Context, config *Config) (*Pool, error) { go func() { targetIdleResources := max(int(p.minConns), int(p.minIdleConns)) - p.createIdleResources(ctx, targetIdleResources) + p.createIdleResources(context.WithoutCancel(ctx), targetIdleResources) p.backgroundHealthCheck() }() @@ -342,20 +356,22 @@ func NewWithConfig(ctx context.Context, config *Config) (*Pool, error) { // ParseConfig builds a Config from connString. It parses connString with the same behavior as [pgx.ParseConfig] with the // addition of the following variables: // -// - pool_max_conns: integer greater than 0 (default 4) +// - pool_max_conns: integer greater than 0 (default is the greater of 4 or runtime.NumCPU()) // - pool_min_conns: integer 0 or greater (default 0) +// - pool_min_idle_conns: integer 0 or greater (default 0) // - pool_max_conn_lifetime: duration string (default 1 hour) // - pool_max_conn_idle_time: duration string (default 30 minutes) // - pool_health_check_period: duration string (default 1 minute) // - pool_max_conn_lifetime_jitter: duration string (default 0) +// - pool_ping_timeout: duration string (default 0, meaning no timeout) // // See Config for definitions of these arguments. // // # Example Keyword/Value -// user=jack password=secret host=pg.example.com port=5432 dbname=mydb sslmode=verify-ca pool_max_conns=10 pool_max_conn_lifetime=1h30m +// user=jack password=secret host=pg.example.com port=5432 dbname=mydb sslmode=verify-full pool_max_conns=10 pool_max_conn_lifetime=1h30m // // # Example URL -// postgres://jack:secret@pg.example.com:5432/mydb?sslmode=verify-ca&pool_max_conns=10&pool_max_conn_lifetime=1h30m +// postgres://jack:secret@pg.example.com:5432/mydb?sslmode=verify-full&pool_max_conns=10&pool_max_conn_lifetime=1h30m func ParseConfig(connString string) (*Config, error) { connConfig, err := pgx.ParseConfig(connString) if err != nil { @@ -448,6 +464,17 @@ func ParseConfig(connString string) (*Config, error) { config.MaxConnLifetimeJitter = d } + if s, ok := config.ConnConfig.Config.RuntimeParams["pool_ping_timeout"]; ok { + delete(connConfig.Config.RuntimeParams, "pool_ping_timeout") + d, err := time.ParseDuration(s) + if err != nil { + return nil, pgconn.NewParseConfigError(connString, "cannot parse pool_ping_timeout", err) + } + config.PingTimeout = d + } else { + config.PingTimeout = defaultPingTimeout + } + return config, nil } @@ -461,6 +488,9 @@ func (p *Pool) Close() { } func (p *Pool) isExpired(res *puddle.Resource[*connResource]) bool { + if p.maxConnLifetime <= 0 { + return false + } return time.Now().After(res.Value().maxAgeTime) } @@ -566,7 +596,7 @@ func (p *Pool) checkMinConns() error { } func (p *Pool) createIdleResources(parentCtx context.Context, targetResources int) error { - ctx, cancel := context.WithCancel(parentCtx) + ctx, cancel := context.WithTimeout(parentCtx, time.Minute) defer cancel() errs := make(chan error, targetResources) @@ -629,18 +659,42 @@ func (p *Pool) Acquire(ctx context.Context) (c *Conn, err error) { shouldPingParams := ShouldPingParams{Conn: cr.conn, IdleDuration: res.IdleDuration()} if p.shouldPing(ctx, shouldPingParams) { - err := func() error { - pingCtx := ctx - if p.pingTimeout > 0 { + pingErrChan := make(chan error, 1) + pingCtx, cancelPing := context.WithCancel(context.WithoutCancel(ctx)) + go func() { + defer cancelPing() + if deadline, ok := ctx.Deadline(); ok { var cancel context.CancelFunc - pingCtx, cancel = context.WithTimeout(ctx, p.pingTimeout) + pingCtx, cancel = context.WithDeadline(pingCtx, deadline) defer cancel() } - return cr.conn.Ping(pingCtx) + if p.pingTimeout > 0 { + var cancel context.CancelFunc + pingCtx, cancel = context.WithTimeout(pingCtx, p.pingTimeout) + defer cancel() + } + pingErrChan <- cr.conn.Ping(pingCtx) }() - if err != nil { - res.Destroy() - continue + + select { + case err := <-pingErrChan: + if err != nil { + res.Destroy() + continue + } + case <-ctx.Done(): + go func() { + // Let a healthy ping finish, but do not retain an abandoned + // resource forever when neither context has a deadline. + timer := time.AfterFunc(time.Minute, cancelPing) + defer timer.Stop() + if err := <-pingErrChan; err != nil { + res.Destroy() + } else { + res.Release() + } + }() + return nil, ctx.Err() } } @@ -781,13 +835,20 @@ func (p *Pool) QueryRow(ctx context.Context, sql string, args ...any) pgx.Row { return c.getPoolRow(row) } +// SendBatch acquires a connection from the Pool and sends the batch on it. The connection is released when the returned +// [pgx.BatchResults] is closed, unless the batch begins a transaction with [pgx.Batch.BeginTx]: then it is released when +// the transaction returned by [pgx.BatchResults.Tx] is committed or rolled back. func (p *Pool) SendBatch(ctx context.Context, b *pgx.Batch) pgx.BatchResults { c, err := p.Acquire(ctx) if err != nil { - return errBatchResults{err: err} + return pgx.FailedBatchResults(b, err) } br := c.SendBatch(ctx, b) + if tx := br.Tx(); tx != nil { + return &poolBatchResults{br: br, tx: &Tx{t: tx, c: c}} + } + return &poolBatchResults{br: br, c: c} } diff --git a/vendor/github.com/jackc/pgx/v5/pgxpool/rows.go b/vendor/github.com/jackc/pgx/v5/pgxpool/rows.go index f834b7e..8425116 100644 --- a/vendor/github.com/jackc/pgx/v5/pgxpool/rows.go +++ b/vendor/github.com/jackc/pgx/v5/pgxpool/rows.go @@ -3,6 +3,7 @@ package pgxpool import ( "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgtype" ) type errRows struct { @@ -18,6 +19,7 @@ func (e errRows) Scan(dest ...any) error { return e.err } func (e errRows) Values() ([]any, error) { return nil, e.err } func (e errRows) RawValues() [][]byte { return nil } func (e errRows) Conn() *pgx.Conn { return nil } +func (e errRows) TypeMap() *pgtype.Map { return nil } type errRow struct { err error @@ -90,6 +92,10 @@ func (rows *poolRows) Conn() *pgx.Conn { return rows.r.Conn() } +func (rows *poolRows) TypeMap() *pgtype.Map { + return rows.r.TypeMap() +} + type poolRow struct { r pgx.Row c *Conn diff --git a/vendor/github.com/jackc/pgx/v5/port-tamer.toml b/vendor/github.com/jackc/pgx/v5/port-tamer.toml new file mode 100644 index 0000000..2931519 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/port-tamer.toml @@ -0,0 +1,70 @@ +# port-tamer — this project's TCP port allocation (https://github.com/jackc/port-tamer). +# +# WHY. pgx's test matrix is five PostgreSQL majors plus CockroachDB running at once. In the +# devcontainer every database service sat in the app container's network namespace, so each could +# own a well-known port (5414..5417, 5432, 26257) and a second devcontainer instance was simply a +# second namespace. Natively there is one network stack, and a git worktree is the equivalent of +# that second instance — two checkouts would collide on all six. +# +# port-tamer assigns each checkout one consecutive group of free ports and writes it to a dotenv +# file (.dev/ports.env — gitignored, per-checkout state). mise loads that file, which is how a +# plain shell, process-compose, and ./test.sh all see the same numbers. THIS file is the committed +# declaration of which ports a checkout needs; the allocation itself is not committed. +# +# The devcontainer uses it too. It has its own network namespace and so does not NEED distinct +# ports, but it runs the same per-checkout clusters, so the allocation is the single description +# of where this checkout's servers are, on either platform. +# +# mise run dev:ports show the allocation and whether each port is listening +# mise run dev:ports:ensure allocate on first use; idempotent afterwards +# mise run dev:ports:overwrite deliberately move to a different group (stop services first) +# +# A listening port does NOT move an existing allocation — it may well belong to this checkout's +# own running services. Moving is always the explicit `--overwrite` above. +# +# APPEND new entries at the END. Ports are assigned consecutively in the order below, so inserting +# or reordering renumbers the existing ones — which invalidates every saved allocation and forces +# each checkout to overwrite. Appending is compatible and costs nothing. + +version = 1 + +# The default range (10000..44999) overlaps the ephemeral ports Linux hands out for client sockets +# (32768..60999), so the kernel could occupy a port inside an allocated group while its service is +# down and then break the restart. This range clears both platforms' ephemeral ranges (macOS +# starts at 49152). +[allocation] +minimum = 16000 +maximum = 31000 +bind_address = "127.0.0.1" + +# One PostgreSQL cluster per major (scripts/devdb.rb). All five share one Unix socket directory — +# sockets are named .s.PGSQL., so the port is what distinguishes them, exactly as the +# devcontainer's shared /var/run/postgresql volume worked. +[[ports]] +name = "PGPORT_14" + +[[ports]] +name = "PGPORT_15" + +[[ports]] +name = "PGPORT_16" + +[[ports]] +name = "PGPORT_17" + +[[ports]] +name = "PGPORT_18" + +# CockroachDB (scripts/devcrdb.rb): SQL and the admin HTTP UI. The HTTP port must be allocated +# even though no test uses it — cockroach binds it unconditionally, and letting it pick its own +# default (8080) would collide between checkouts. +[[ports]] +name = "CRDB_PORT" + +[[ports]] +name = "CRDB_HTTP_PORT" + +# process-compose control API. The name is process-compose's own: every `process-compose ...` +# command in this checkout then targets THIS checkout's stack with no flags. +[[ports]] +name = "PC_PORT_NUM" diff --git a/vendor/github.com/jackc/pgx/v5/process-compose.yaml b/vendor/github.com/jackc/pgx/v5/process-compose.yaml new file mode 100644 index 0000000..8a1b18b --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/process-compose.yaml @@ -0,0 +1,189 @@ +# process-compose — the long-running half of this checkout's development environment. +# +# The division of labour (identical natively and in the devcontainer): +# +# mise one-shot work: bootstrap, ports, initdb, test, format +# process-compose long-running work: the five PostgreSQL servers and CockroachDB +# +# These are exactly the services .devcontainer/docker-compose.yml used to run as containers. They +# now run as ordinary processes against this checkout's own clusters under .dev, so the same +# command set works on macOS, on Linux, and inside the container. +# +# Note what this file does NOT contain: no ports, no resolved paths, no per-process environment +# blocks, no database bootstrap. Ports arrive through the environment (.dev/, exported by the +# launcher — scripts/dev.rb); data directories, binary locations and the socket directory are +# resolved once inside scripts/devdb.rb, so a server and its readiness probe cannot disagree; and +# one-shot work (initdb, creating pgx_test) stays in scripts this file merely sequences. +# +# Two kinds of environment variable ARE read here, both set by scripts/dev.rb and both with a +# default that makes a direct `process-compose up` start only PostgreSQL 18: +# +# PGX_LOGS_DIR DevPaths::LOGS_DIR — the layout belongs to that module, not to ten literals +# PGX_DISABLE_* "true" for an on-demand target, or for a PostgreSQL major whose binaries are +# missing. Disabled processes remain available for `db:start` and lazy tests. +# +# The five servers are identical apart from their major, so pg14 carries the YAML anchors and the +# rest alias them. Anchors are resolved by the YAML parser before process-compose sees the +# document, so a probe threshold or a shutdown signal is now one edit rather than five that can +# drift apart. +# +# mise run dev start PostgreSQL 18 and the supervisor +# mise run dev:all start every database +# mise run db:start pg16 crdb prewarm selected targets +# process-compose process list status, scriptable +# process-compose process logs pg16 logs for one server +# process-compose down stop this checkout's stack only +# +# Each checkout runs its own instance on its own control port (PC_PORT_NUM, from this checkout's +# allocation), which process-compose reads from the environment — so the commands above need no +# flags and never reach another checkout's stack. +version: "0.5" + +# A process whose dependency failed should not be reported as merely skipped, and shutdown should +# unwind in dependency order rather than all at once. +is_strict: true +ordered_shutdown: true + +processes: + # PostgreSQL 14, and the template for 15-18. `serve` initdb's the cluster if this checkout has + # none, then execs the server in the foreground — so a fresh checkout goes straight to + # `mise run dev` with no documented prerequisite step, and process-compose supervises the real + # postmaster. + pg14: &pg + disabled: ${PGX_DISABLE_PG14:-true} + command: ruby scripts/devdb.rb serve 14 + readiness_probe: &pg-probe + exec: + command: ruby scripts/devdb.rb ready 14 + initial_delay_seconds: 1 + period_seconds: 1 + failure_threshold: 30 + # SIGINT is PostgreSQL's fast shutdown: roll back open transactions and exit, rather than + # waiting for clients to disconnect. + shutdown: + signal: 2 + timeout_seconds: 20 + availability: + restart: on_failure + # Bounded: `on_failure` alone retries a PERMANENT error forever (a cluster built by the other + # platform, a corrupt PGDATA), burying the real message under a restart loop. Five attempts + # then stop, so the cause stays on screen. + max_restarts: 5 + log_location: ${PGX_LOGS_DIR:-.dev/logs}/pg14.log + + # Creates pgx_test with its extensions and its md5/scram/password/cert roles once the server is + # up, then exits. A no-op when the database already exists, so restarting the stack is free. + # + # This is a one-shot, and process-compose does not re-run one when its dependency restarts. + # On-demand starts therefore run the same idempotent setup through scripts/dev_services.rb. + # CockroachDB, whose store is in memory, creates its database from its readiness probe instead. + pg14-setup: &pg-setup + disabled: ${PGX_DISABLE_PG14:-true} + command: ruby scripts/devdb.rb setup 14 + depends_on: + pg14: + condition: process_healthy + availability: + restart: "no" + log_location: ${PGX_LOGS_DIR:-.dev/logs}/pg14-setup.log + + pg15: + <<: *pg + disabled: ${PGX_DISABLE_PG15:-true} + command: ruby scripts/devdb.rb serve 15 + readiness_probe: + <<: *pg-probe + exec: + command: ruby scripts/devdb.rb ready 15 + log_location: ${PGX_LOGS_DIR:-.dev/logs}/pg15.log + + pg15-setup: + <<: *pg-setup + disabled: ${PGX_DISABLE_PG15:-true} + command: ruby scripts/devdb.rb setup 15 + depends_on: + pg15: + condition: process_healthy + log_location: ${PGX_LOGS_DIR:-.dev/logs}/pg15-setup.log + + pg16: + <<: *pg + disabled: ${PGX_DISABLE_PG16:-true} + command: ruby scripts/devdb.rb serve 16 + readiness_probe: + <<: *pg-probe + exec: + command: ruby scripts/devdb.rb ready 16 + log_location: ${PGX_LOGS_DIR:-.dev/logs}/pg16.log + + pg16-setup: + <<: *pg-setup + disabled: ${PGX_DISABLE_PG16:-true} + command: ruby scripts/devdb.rb setup 16 + depends_on: + pg16: + condition: process_healthy + log_location: ${PGX_LOGS_DIR:-.dev/logs}/pg16-setup.log + + pg17: + <<: *pg + disabled: ${PGX_DISABLE_PG17:-true} + command: ruby scripts/devdb.rb serve 17 + readiness_probe: + <<: *pg-probe + exec: + command: ruby scripts/devdb.rb ready 17 + log_location: ${PGX_LOGS_DIR:-.dev/logs}/pg17.log + + pg17-setup: + <<: *pg-setup + disabled: ${PGX_DISABLE_PG17:-true} + command: ruby scripts/devdb.rb setup 17 + depends_on: + pg17: + condition: process_healthy + log_location: ${PGX_LOGS_DIR:-.dev/logs}/pg17-setup.log + + pg18: + <<: *pg + disabled: ${PGX_DISABLE_PG18:-false} + command: ruby scripts/devdb.rb serve 18 + readiness_probe: + <<: *pg-probe + exec: + command: ruby scripts/devdb.rb ready 18 + log_location: ${PGX_LOGS_DIR:-.dev/logs}/pg18.log + + pg18-setup: + <<: *pg-setup + disabled: ${PGX_DISABLE_PG18:-false} + command: ruby scripts/devdb.rb setup 18 + depends_on: + pg18: + condition: process_healthy + log_location: ${PGX_LOGS_DIR:-.dev/logs}/pg18-setup.log + + # CockroachDB, the `crdb` test target. Insecure, single-node and entirely in memory — the same + # configuration the cockroachdb/cockroach container ran with. + # + # It has NO setup process, deliberately. The store is in memory, so every restart of this node is + # an empty cluster, and a completed one-shot is not re-run when its dependency restarts: after a + # crash-restart the node reported Ready with no pgx_test in it and `./test.sh crdb` failed every + # test. `devcrdb.rb ready` therefore creates the database itself, which makes the probe true on + # the first start and on every restart alike. + crdb: + disabled: ${PGX_DISABLE_CRDB:-true} + command: ruby scripts/devcrdb.rb serve + readiness_probe: + exec: + command: ruby scripts/devcrdb.rb ready + initial_delay_seconds: 2 + period_seconds: 1 + failure_threshold: 45 + shutdown: + signal: 15 + timeout_seconds: 20 + availability: + restart: on_failure + max_restarts: 5 + log_location: ${PGX_LOGS_DIR:-.dev/logs}/crdb.log diff --git a/vendor/github.com/jackc/pgx/v5/rows.go b/vendor/github.com/jackc/pgx/v5/rows.go index 4e5cf95..33ceb25 100644 --- a/vendor/github.com/jackc/pgx/v5/rows.go +++ b/vendor/github.com/jackc/pgx/v5/rows.go @@ -54,6 +54,9 @@ type Rows interface { // Scan reads the values from the current row into dest values positionally. dest can include pointers to core types, // values implementing the Scanner interface, and nil. nil will skip the value entirely. It is an error to call Scan // without first calling Next() and checking that it returned true. Rows is automatically closed upon error. + // + // As a special case, if dest is a single value implementing [RowScanner], the whole row is given to its ScanRow + // method instead of being scanned positionally. Scan(dest ...any) error // Values returns the decoded row values. As with Scan(), it is an error to @@ -68,6 +71,11 @@ type Rows interface { // Conn returns the underlying *Conn on which the query was executed. This may return nil if Rows did not come from a // *Conn (e.g. if it was created by RowsFromResultReader) Conn() *Conn + + // TypeMap returns the [pgtype.Map] the values of this Rows are decoded with. It is available even when [Rows.Conn] + // is nil, such as for a Rows created by [RowsFromResultReader]. It may return nil if the Rows carries no values, + // such as one representing only an error. + TypeMap() *pgtype.Map } // Row is a convenience wrapper over [Rows] that is returned by [Conn.QueryRow]. @@ -83,7 +91,21 @@ type Row interface { Scan(dest ...any) error } -// RowScanner scans an entire row at a time into the RowScanner. +// RowScanner scans an entire row at a time into the RowScanner. It is only used when it is the sole destination passed +// to [Rows.Scan] or [Row.Scan]. When passed alongside other destinations it is scanned as an ordinary single value. +// +// ScanRow always takes precedence over the destination's other scanning interfaces, such as +// [pgtype.CompositeIndexScanner]. A type implementing both must therefore dispatch within ScanRow, because the number of +// columns is not known until the row arrives: +// +// func (p *Person) ScanRow(rows pgx.Rows) error { +// if fds := rows.FieldDescriptions(); len(fds) == 1 { +// // Scan the single column via p's pgtype.CompositeIndexScanner implementation. rows.Scan(p) would +// // call ScanRow again. +// return rows.TypeMap().Scan(fds[0].DataTypeOID, fds[0].Format, rows.RawValues()[0], p) +// } +// return rows.Scan(&p.Name, &p.Age) +// } type RowScanner interface { // ScanRows scans the row. ScanRow(rows Rows) error @@ -181,7 +203,7 @@ func (rows *baseRows) Close() { } if rows.batchTracer != nil { - rows.batchTracer.TraceBatchQuery(rows.ctx, rows.conn, TraceBatchQueryData{SQL: rows.sql, Args: rows.args, CommandTag: rows.commandTag, Err: rows.err}) + rows.batchTracer.TraceBatchQuery(rows.ctx, rows.conn, TraceBatchQueryData{SQL: rows.sql, Args: rows.args, CommandTag: rows.commandTag, Err: rows.err, ReadStartTime: rows.startTime}) } else if rows.queryTracer != nil { rows.queryTracer.TraceQueryEnd(rows.ctx, rows.conn, TraceQueryEndData{rows.commandTag, rows.err}) } @@ -294,11 +316,18 @@ func (rows *baseRows) Values() ([]any, error) { return nil, errors.New("rows is closed") } - values := make([]any, 0, len(rows.FieldDescriptions())) + fieldDescriptions := rows.FieldDescriptions() + if len(fieldDescriptions) != len(rows.values) { + err := fmt.Errorf("number of field descriptions must equal number of values, got %d and %d", len(fieldDescriptions), len(rows.values)) + rows.fatal(err) + return nil, err + } - for i := range rows.FieldDescriptions() { + values := make([]any, 0, len(fieldDescriptions)) + + for i := range fieldDescriptions { buf := rows.values[i] - fd := &rows.FieldDescriptions()[i] + fd := &fieldDescriptions[i] if buf == nil { values = append(values, nil) @@ -336,6 +365,10 @@ func (rows *baseRows) RawValues() [][]byte { return rows.values } +func (rows *baseRows) TypeMap() *pgtype.Map { + return rows.typeMap +} + func (rows *baseRows) Conn() *Conn { return rows.conn } @@ -836,6 +869,13 @@ func fieldPosByName(fldDescs []pgconn.FieldDescription, field string, normalize if normalize { field = strings.ReplaceAll(field, "_", "") + } else { + // Explicit db tags can distinguish quoted identifiers that differ only by case. + for i, desc := range fldDescs { + if desc.Name == field { + return i + } + } } for i, desc := range fldDescs { if normalize { @@ -843,7 +883,7 @@ func fieldPosByName(fldDescs []pgconn.FieldDescription, field string, normalize return i } } else { - if desc.Name == field { + if strings.EqualFold(desc.Name, field) { return i } } diff --git a/vendor/github.com/jackc/pgx/v5/stdlib/sql.go b/vendor/github.com/jackc/pgx/v5/stdlib/sql.go index 576d3c6..6f696d5 100644 --- a/vendor/github.com/jackc/pgx/v5/stdlib/sql.go +++ b/vendor/github.com/jackc/pgx/v5/stdlib/sql.go @@ -57,12 +57,25 @@ // // # PostgreSQL Specific Data Types // -// The pgtype package provides support for PostgreSQL specific types. *pgtype.Map.SQLScanner is an adapter that makes -// these types usable as a sql.Scanner. +// As of Go 1.27, database/sql allows drivers to implement their own scanning logic by implementing the +// driver.RowsColumnScanner interface. This allows PostgreSQL types such as arrays to be scanned directly into Go +// values such as slices. +// +// var a []int64 +// err := db.QueryRow("select '{1,2,3}'::bigint[]").Scan(&a) +// +// In older versions of Go, *pgtype.Map.SQLScanner can be used as an adapter that makes these types usable as a +// sql.Scanner. // // m := pgtype.NewMap() // var a []int64 // err := db.QueryRow("select '{1,2,3}'::bigint[]").Scan(m.SQLScanner(&a)) +// +// The pgtype package provides support for PostgreSQL specific types. These types can be used directly in Go 1.27 and +// with *pgtype.Map.SQLScanner in older Go versions. +// +// var r pgtype.Range[pgtype.Int4] +// err := db.QueryRow("select int4range(1, 5)").Scan(&r) package stdlib import ( @@ -659,6 +672,10 @@ func (r *Rows) ColumnTypeDatabaseTypeName(index int) string { const varHeaderSize = 4 +// noTypeModifier is the type modifier PostgreSQL reports for a column whose type +// was used without a precision or length specifier. +const noTypeModifier = -1 + // ColumnTypeLength returns the length of the column type if the column is a // variable length type. If the column is not a variable length type ok // should return false. @@ -669,25 +686,59 @@ func (r *Rows) ColumnTypeLength(index int) (int64, bool) { case pgtype.TextOID, pgtype.ByteaOID: return math.MaxInt64, true case pgtype.VarcharOID, pgtype.BPCharOID: + // An unconstrained varchar or bpchar is not limited, which + // database/sql represents as math.MaxInt64. + if fd.TypeModifier == -1 { + return math.MaxInt64, true + } return int64(fd.TypeModifier - varHeaderSize), true case pgtype.VarbitOID: + if fd.TypeModifier == -1 { + return math.MaxInt64, true + } return int64(fd.TypeModifier), true default: return 0, false } } -// ColumnTypePrecisionScale should return the precision and scale for decimal -// types. If not applicable, ok should be false. +// ColumnTypePrecisionScale returns the precision and scale for numeric types +// with a declared precision. For timestamp, timestamptz, time, timetz, and interval, +// it returns a precision of 0 and the fractional seconds precision as the scale, +// defaulting to 6 when no fractional seconds precision was declared. +// For unconstrained numeric and other types, ok is false. func (r *Rows) ColumnTypePrecisionScale(index int) (precision, scale int64, ok bool) { fd := r.rows.FieldDescriptions()[index] switch fd.DataTypeOID { case pgtype.NumericOID: + // numeric without a precision specifier accepts any precision and scale, + // so there is nothing to report. + if fd.TypeModifier == noTypeModifier { + return 0, 0, false + } mod := fd.TypeModifier - varHeaderSize precision = int64((mod >> 16) & 0xffff) scale = int64(mod & 0xffff) return precision, scale, true + case pgtype.TimestampOID, pgtype.TimestamptzOID, pgtype.TimeOID, pgtype.TimetzOID: + // The type modifier of these types is their fractional seconds precision: + // the number of digits kept after the decimal point, which is the scale. + // Numeric precision does not apply to these types, so it is reported as 0. + // Without a precision specifier they keep microseconds, the maximum + // PostgreSQL supports. + if fd.TypeModifier == noTypeModifier { + return 0, 6, true + } + return 0, int64(fd.TypeModifier), true + case pgtype.IntervalOID: + // An interval's type modifier packs the field range it was declared with in + // its high bits and its fractional seconds precision in its low 16 bits, + // which are all set when only a range was specified. + if fd.TypeModifier == noTypeModifier || fd.TypeModifier&0xffff == 0xffff { + return 0, 6, true + } + return 0, int64(fd.TypeModifier & 0xffff), true default: return 0, 0, false } @@ -726,7 +777,9 @@ func (r *Rows) Close() error { return r.rows.Err() } -func (r *Rows) Next(dest []driver.Value) error { +// initValueFuncs prepares the database/sql representation of each column. Both +// Next and ScanColumn use these conversions so their driver.Values agree. +func (r *Rows) initValueFuncs() { m := r.conn.conn.TypeMap() fieldDescriptions := r.rows.FieldDescriptions() @@ -857,6 +910,10 @@ func (r *Rows) Next(dest []driver.Value) error { } } } +} + +func (r *Rows) Next(dest []driver.Value) error { + r.initValueFuncs() var more bool if r.skipNext { diff --git a/vendor/github.com/jackc/pgx/v5/stdlib/sql_go1.27.go b/vendor/github.com/jackc/pgx/v5/stdlib/sql_go1.27.go new file mode 100644 index 0000000..ed8c707 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/stdlib/sql_go1.27.go @@ -0,0 +1,129 @@ +//go:build go1.27 + +package stdlib + +import ( + "database/sql" + "database/sql/driver" + "errors" + "io" + "reflect" + "sync" + "time" + + "github.com/jackc/pgx/v5/pgtype" +) + +// Rows implements driver.RowsColumnScanner as of Go 1.27. +var _ driver.RowsColumnScanner = (*Rows)(nil) + +// NextRow implements the driver.RowsColumnScanner interface. It advances to the +// next row of data and returns io.EOF when there are no more rows. +func (r *Rows) NextRow() error { + var more bool + if r.skipNext { + more = r.skipNextMore + r.skipNext = false + } else { + more = r.rows.Next() + } + + if !more { + if err := r.rows.Err(); err != nil { + return err + } + return io.EOF + } + + return nil +} + +// ScanColumn implements the driver.RowsColumnScanner interface. It preserves +// database/sql conversions for scalar destinations and sql.Scanner implementations. +// Other destinations, such as Go slices, pgtype.Array, and pgtype.Range, are +// scanned directly using the pgx type map. +func (r *Rows) ScanColumn(scanCtx driver.ScanContext, index int, dest any) error { + if dest == nil { + return errors.New("destination not a pointer") + } + rv := reflect.ValueOf(dest) + if rv.Kind() == reflect.Pointer && rv.IsNil() { + return errors.New("destination pointer is nil") + } + + src := r.rows.RawValues()[index] + if isSQLScanDestination(rv.Type()) { + var value driver.Value + if src != nil { + r.initValueFuncs() + var err error + value, err = r.valueFuncs[index](src) + if err != nil { + return err + } + } + return sql.ConvertAssign(scanCtx, dest, value) + } + + m := r.conn.conn.TypeMap() + fd := r.rows.FieldDescriptions()[index] + return m.Scan(fd.DataTypeOID, fd.Format, src, dest) +} + +// Map from reflect.Type -> bool. +var sqlScanDestinationCache sync.Map + +// isSQLScanDestination includes named scalar types and nullable pointers to +// database/sql destinations. Select the conversion before scanning: retrying a +// failed scan could call user code twice or discard its error. +func isSQLScanDestination(t reflect.Type) bool { + if cached, ok := sqlScanDestinationCache.Load(t); ok { + return cached.(bool) + } + + result := isSQLScanDestinationUncached(t) + sqlScanDestinationCache.Store(t, result) + return result +} + +func isSQLScanDestinationUncached(t reflect.Type) bool { + var namedPointers map[reflect.Type]bool + for { + if t.Implements(reflect.TypeFor[sql.Scanner]()) { + return true + } + // These interfaces distinguish native byte slices, such as + // FlatArray[byte] and PreallocBytes, from ordinary []byte destinations. + if t.Implements(reflect.TypeFor[pgtype.ArraySetter]()) || t.Implements(reflect.TypeFor[pgtype.BytesScanner]()) { + return false + } + if t.Kind() != reflect.Pointer { + break + } + // Only defined pointer types can form a cycle without reaching a + // non-pointer type. Leave those to pgx's bounded scan planning. + if t.Name() != "" { + if namedPointers[t] { + return false + } + if namedPointers == nil { + namedPointers = make(map[reflect.Type]bool) + } + namedPointers[t] = true + } + t = t.Elem() + } + + switch t.Kind() { + case reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, + reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, + reflect.Float32, reflect.Float64, reflect.String, reflect.Interface: + return true + case reflect.Slice: + return t.Elem().Kind() == reflect.Uint8 + case reflect.Struct: + return t.ConvertibleTo(reflect.TypeFor[time.Time]()) + default: + return false + } +} diff --git a/vendor/github.com/jackc/pgx/v5/test.sh b/vendor/github.com/jackc/pgx/v5/test.sh index 8bab2d2..254217e 100644 --- a/vendor/github.com/jackc/pgx/v5/test.sh +++ b/vendor/github.com/jackc/pgx/v5/test.sh @@ -1,170 +1,35 @@ #!/usr/bin/env bash +# test.sh - Run the pgx test suite against a database target. +# +# ./test.sh PostgreSQL 18 (default) +# ./test.sh pg14 PostgreSQL 14 +# ./test.sh crdb CockroachDB +# ./test.sh all every target, sequentially +# ./test.sh pg16 -run TestConnect trailing arguments are passed to `go test` +# +# `mise run dev` starts PostgreSQL 18 and the supervisor. Other targets start for a test and stop +# afterwards unless they were explicitly prewarmed with `mise run db:start`. See DEVELOPMENT.md. +# +# The logic lives in scripts/runtests.rb, which builds each target's PGX_TEST_* environment from +# scripts/lib/test_targets.rb — the one place those connection strings are defined. This wrapper +# exists so `./test.sh` keeps working; `mise run test` is equivalent. set -euo pipefail -# test.sh - Run pgx tests against specific database targets -# -# Usage: -# ./test.sh [target] [go test flags...] -# -# Targets: -# pg14 - PostgreSQL 14 (port 5414) -# pg15 - PostgreSQL 15 (port 5415) -# pg16 - PostgreSQL 16 (port 5416) -# pg17 - PostgreSQL 17 (port 5417) -# pg18 - PostgreSQL 18 (port 5432) [default] -# crdb - CockroachDB (port 26257) -# all - Run against all targets sequentially -# -# Examples: -# ./test.sh # Test against PG18 -# ./test.sh pg14 # Test against PG14 -# ./test.sh crdb # Test against CockroachDB -# ./test.sh all # Test against all targets -# ./test.sh pg16 -run TestConnect # Test specific test against PG16 -# ./test.sh pg18 -count=1 -v # Verbose, no cache, PG18 +root="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +runtests="$root/scripts/runtests.rb" -# Color output (disabled if not a terminal) -if [ -t 1 ]; then - GREEN='\033[0;32m' - RED='\033[0;31m' - BLUE='\033[0;34m' - NC='\033[0m' +# `mise exec` is not only how this wrapper gets the pinned Ruby. It also puts process-compose, Go, +# and CockroachDB on PATH and loads this checkout's .dev/*.env files. Prefer it whenever it is +# available, including when the shell has a new-enough system Ruby but mise has not been activated. +# Invoking it from `mise run test` is harmless: this execs Ruby directly, so there is no task +# recursion. +if command -v mise > /dev/null 2>&1; then + exec mise exec -- ruby "$runtests" "$@" +elif ruby -e 'exit(RUBY_VERSION.split(".")[0].to_i >= 3 ? 0 : 1)' > /dev/null 2>&1; then + exec ruby "$runtests" "$@" else - GREEN='' - RED='' - BLUE='' - NC='' + echo "test.sh: needs Ruby 3.0 or newer (mise.toml pins one)." >&2 + echo " Install mise (https://mise.jdx.dev), then: mise install" >&2 + echo " See DEVELOPMENT.md." >&2 + exit 1 fi - -log_info() { echo -e "${BLUE}==> $*${NC}"; } -log_ok() { echo -e "${GREEN}==> $*${NC}"; } -log_err() { echo -e "${RED}==> $*${NC}" >&2; } - -# Wait for a database to accept connections -wait_for_ready() { - local connstr="$1" - local label="$2" - local max_attempts=30 - local attempt=0 - - log_info "Waiting for $label to be ready..." - while ! psql "$connstr" -c "SELECT 1" > /dev/null 2>&1; do - attempt=$((attempt + 1)) - if [ "$attempt" -ge "$max_attempts" ]; then - log_err "$label did not become ready after $max_attempts attempts" - return 1 - fi - sleep 1 - done - log_ok "$label is ready" -} - -# Directory containing this script (used to locate testsetup/) -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -CERTS_DIR="$SCRIPT_DIR/testsetup/certs" - -# Copy client certificates to /tmp for TLS tests -setup_client_certs() { - if [ -d "$CERTS_DIR" ]; then - base64 -d "$CERTS_DIR/ca.pem.b64" > /tmp/ca.pem - base64 -d "$CERTS_DIR/pgx_sslcert.crt.b64" > /tmp/pgx_sslcert.crt - base64 -d "$CERTS_DIR/pgx_sslcert.key.b64" > /tmp/pgx_sslcert.key - fi -} - -# Initialize CockroachDB (create database if not exists) -init_crdb() { - local connstr="postgresql://root@localhost:26257/?sslmode=disable" - wait_for_ready "$connstr" "CockroachDB" - log_info "Ensuring pgx_test database exists on CockroachDB..." - psql "$connstr" -c "CREATE DATABASE IF NOT EXISTS pgx_test" 2>/dev/null || true -} - -# Run tests against a single target -run_tests() { - local target="$1" - shift - local extra_args=("$@") - - local label="" - local port="" - - case "$target" in - pg14) label="PostgreSQL 14"; port=5414 ;; - pg15) label="PostgreSQL 15"; port=5415 ;; - pg16) label="PostgreSQL 16"; port=5416 ;; - pg17) label="PostgreSQL 17"; port=5417 ;; - pg18) label="PostgreSQL 18"; port=5432 ;; - crdb) - label="CockroachDB (port 26257)" - init_crdb - log_info "Testing against $label" - if ! PGX_TEST_DATABASE="postgresql://root@localhost:26257/pgx_test?sslmode=disable&experimental_enable_temp_tables=on" \ - go test -count=1 "${extra_args[@]}" ./...; then - log_err "Tests FAILED against $label" - return 1 - fi - log_ok "Tests passed against $label" - return 0 - ;; - *) - log_err "Unknown target: $target" - log_err "Valid targets: pg14, pg15, pg16, pg17, pg18, crdb, all" - return 1 - ;; - esac - - setup_client_certs - - log_info "Testing against $label (port $port)" - if ! PGX_TEST_DATABASE="host=localhost port=$port user=postgres password=postgres dbname=pgx_test" \ - PGX_TEST_UNIX_SOCKET_CONN_STRING="host=/var/run/postgresql port=$port user=postgres dbname=pgx_test" \ - PGX_TEST_TCP_CONN_STRING="host=127.0.0.1 port=$port user=pgx_md5 password=secret dbname=pgx_test" \ - PGX_TEST_MD5_PASSWORD_CONN_STRING="host=127.0.0.1 port=$port user=pgx_md5 password=secret dbname=pgx_test" \ - PGX_TEST_SCRAM_PASSWORD_CONN_STRING="host=127.0.0.1 port=$port user=pgx_scram password=secret dbname=pgx_test channel_binding=disable" \ - PGX_TEST_SCRAM_PLUS_CONN_STRING="host=localhost port=$port user=pgx_ssl password=secret sslmode=verify-full sslrootcert=/tmp/ca.pem dbname=pgx_test channel_binding=require" \ - PGX_TEST_PLAIN_PASSWORD_CONN_STRING="host=127.0.0.1 port=$port user=pgx_pw password=secret dbname=pgx_test" \ - PGX_TEST_TLS_CONN_STRING="host=localhost port=$port user=pgx_ssl password=secret sslmode=verify-full sslrootcert=/tmp/ca.pem dbname=pgx_test channel_binding=disable" \ - PGX_TEST_TLS_CLIENT_CONN_STRING="host=localhost port=$port user=pgx_sslcert sslmode=verify-full sslrootcert=/tmp/ca.pem sslcert=/tmp/pgx_sslcert.crt sslkey=/tmp/pgx_sslcert.key dbname=pgx_test" \ - PGX_SSL_PASSWORD=certpw \ - go test -count=1 "${extra_args[@]}" ./...; then - log_err "Tests FAILED against $label" - return 1 - fi - log_ok "Tests passed against $label" -} - -# Main -main() { - local target="${1:-pg18}" - - if [ "$target" = "all" ]; then - shift || true - local targets=(pg14 pg15 pg16 pg17 pg18 crdb) - local failed=() - - for t in "${targets[@]}"; do - echo "" - log_info "==========================================" - log_info "Target: $t" - log_info "==========================================" - if ! run_tests "$t" "$@"; then - failed+=("$t") - log_err "FAILED: $t" - fi - done - - echo "" - if [ ${#failed[@]} -gt 0 ]; then - log_err "Failed targets: ${failed[*]}" - return 1 - else - log_ok "All targets passed" - fi - else - shift || true - run_tests "$target" "$@" - fi -} - -main "$@" diff --git a/vendor/github.com/jackc/pgx/v5/tracer.go b/vendor/github.com/jackc/pgx/v5/tracer.go index 58ca99f..ce786bd 100644 --- a/vendor/github.com/jackc/pgx/v5/tracer.go +++ b/vendor/github.com/jackc/pgx/v5/tracer.go @@ -2,6 +2,7 @@ package pgx import ( "context" + "time" "github.com/jackc/pgx/v5/pgconn" ) @@ -44,6 +45,16 @@ type TraceBatchQueryData struct { Args []any CommandTag pgconn.CommandTag Err error + + // ReadStartTime is when pgx began reading this query's result from the server -- i.e. when it requested the next + // result in the batch, not when SendBatch was called or when this query's turn in the batch started. + // + // The interval from ReadStartTime to when TraceBatchQuery is called is not a pure network or server measurement. + // It excludes any time the query spent waiting for earlier queries in the batch to be consumed, but it does + // include network waits, server-side buffering, and -- for a query consumed via [QueuedQuery.Query] or + // [BatchResults.Query] -- however long the calling application takes to read and close the returned Rows, since + // TraceBatchQuery for that query is not called until Rows is closed. + ReadStartTime time.Time } type TraceBatchEndData struct { diff --git a/vendor/github.com/jackc/pgx/v5/tx.go b/vendor/github.com/jackc/pgx/v5/tx.go index 3f93a6f..e8e9e4f 100644 --- a/vendor/github.com/jackc/pgx/v5/tx.go +++ b/vendor/github.com/jackc/pgx/v5/tx.go @@ -3,6 +3,7 @@ package pgx import ( "context" "errors" + "slices" "strconv" "strings" @@ -51,32 +52,58 @@ type TxOptions struct { CommitQuery string } -var emptyTxOptions TxOptions +// The standard values of each transaction option, unset first. beginSQLs is indexed by the position of a value in +// these lists. +var ( + txIsoLevels = [...]TxIsoLevel{"", Serializable, RepeatableRead, ReadCommitted, ReadUncommitted} + txAccessModes = [...]TxAccessMode{"", ReadWrite, ReadOnly} + txDeferrableModes = [...]TxDeferrableMode{"", Deferrable, NotDeferrable} +) + +// beginSQLs holds the begin statement for every combination of the standard transaction option values, so that +// beginning a transaction with them does not allocate. +var beginSQLs = func() (sqls [len(txIsoLevels)][len(txAccessModes)][len(txDeferrableModes)]string) { + for i, isoLevel := range txIsoLevels { + for a, accessMode := range txAccessModes { + for d, deferrableMode := range txDeferrableModes { + sqls[i][a][d] = renderBeginSQL(isoLevel, accessMode, deferrableMode) + } + } + } + return sqls +}() func (txOptions TxOptions) beginSQL() string { - if txOptions == emptyTxOptions { - return "begin" - } - if txOptions.BeginQuery != "" { return txOptions.BeginQuery } + i := slices.Index(txIsoLevels[:], txOptions.IsoLevel) + a := slices.Index(txAccessModes[:], txOptions.AccessMode) + d := slices.Index(txDeferrableModes[:], txOptions.DeferrableMode) + if i < 0 || a < 0 || d < 0 { + return renderBeginSQL(txOptions.IsoLevel, txOptions.AccessMode, txOptions.DeferrableMode) + } + + return beginSQLs[i][a][d] +} + +func renderBeginSQL(isoLevel TxIsoLevel, accessMode TxAccessMode, deferrableMode TxDeferrableMode) string { var buf strings.Builder buf.Grow(64) // 64 - maximum length of string with available options buf.WriteString("begin") - if txOptions.IsoLevel != "" { + if isoLevel != "" { buf.WriteString(" isolation level ") - buf.WriteString(string(txOptions.IsoLevel)) + buf.WriteString(string(isoLevel)) } - if txOptions.AccessMode != "" { + if accessMode != "" { buf.WriteByte(' ') - buf.WriteString(string(txOptions.AccessMode)) + buf.WriteString(string(accessMode)) } - if txOptions.DeferrableMode != "" { + if deferrableMode != "" { buf.WriteByte(' ') - buf.WriteString(string(txOptions.DeferrableMode)) + buf.WriteString(string(deferrableMode)) } return buf.String() @@ -100,9 +127,12 @@ func (c *Conn) Begin(ctx context.Context) (Tx, error) { func (c *Conn) BeginTx(ctx context.Context, txOptions TxOptions) (Tx, error) { _, err := c.Exec(ctx, txOptions.beginSQL()) if err != nil { - // begin should never fail unless there is an underlying connection issue or - // a context timeout. In either case, the connection is possibly broken. - c.die() + // begin kills the connection upon receiving fatal, panic or non PGError errors, + // but does not otherwise as the connection should be reusable. + var pgErr *pgconn.PgError + if !errors.As(err, &pgErr) || isConnectionFatal(pgErr) { + c.die() + } return nil, err } @@ -112,6 +142,14 @@ func (c *Conn) BeginTx(ctx context.Context, txOptions TxOptions) (Tx, error) { }, nil } +func isConnectionFatal(pgErr *pgconn.PgError) bool { + severity := pgErr.SeverityUnlocalized + if severity == "" { + severity = pgErr.Severity + } + return severity == "FATAL" || severity == "PANIC" +} + // Tx represents a database transaction. // // Tx is an interface instead of a struct to enable connection pools to be implemented without relying on internal pgx @@ -269,7 +307,10 @@ func (tx *dbTx) CopyFrom(ctx context.Context, tableName Identifier, columnNames // SendBatch delegates to the underlying *Conn func (tx *dbTx) SendBatch(ctx context.Context, b *Batch) BatchResults { if tx.closed { - return &batchResults{err: ErrTxClosed} + return FailedBatchResults(b, ErrTxClosed) + } + if b.txOptions != nil { + return FailedBatchResults(b, errors.New("Batch.BeginTx cannot be used within a transaction")) } return tx.conn.SendBatch(ctx, b) @@ -371,7 +412,7 @@ func (sp *dbSimulatedNestedTx) CopyFrom(ctx context.Context, tableName Identifie // SendBatch delegates to the underlying *Conn func (sp *dbSimulatedNestedTx) SendBatch(ctx context.Context, b *Batch) BatchResults { if sp.closed { - return &batchResults{err: ErrTxClosed} + return FailedBatchResults(b, ErrTxClosed) } return sp.tx.SendBatch(ctx, b) diff --git a/vendor/github.com/jackc/pgx/v5/values.go b/vendor/github.com/jackc/pgx/v5/values.go index 6e2ff30..e7dde89 100644 --- a/vendor/github.com/jackc/pgx/v5/values.go +++ b/vendor/github.com/jackc/pgx/v5/values.go @@ -53,6 +53,17 @@ func tryScanStringCopyValueThenEncode(m *pgtype.Map, buf []byte, oid uint32, arg s = string(textBuf) } + // Check if this is an array type. If so, use an ArraySetter to preserve + // array dimensions during CopyFrom. + if typ, ok := m.TypeForOID(oid); ok { + if _, ok := typ.Codec.(*pgtype.ArrayCodec); ok { + var arr pgtype.Array[any] + if err := m.Scan(oid, TextFormatCode, []byte(s), &arr); err == nil { + return m.Encode(oid, BinaryFormatCode, arr, buf) + } + } + } + var v any err := m.Scan(oid, TextFormatCode, []byte(s), &v) if err != nil { diff --git a/vendor/github.com/jackc/puddle/v2/CHANGELOG.md b/vendor/github.com/jackc/puddle/v2/CHANGELOG.md index d0d202c..b5db506 100644 --- a/vendor/github.com/jackc/puddle/v2/CHANGELOG.md +++ b/vendor/github.com/jackc/puddle/v2/CHANGELOG.md @@ -1,3 +1,14 @@ +# 2.2.4 (November 16, 2026) + +* Fix: Destroy resources when construction started by CreateResource finishes after Close or Reset. + Previously, Close could leave a resource counted in pool statistics and Reset could allow a stale resource to be reused. (Harrison Crosse) + +# 2.2.3 (October 5, 2026) + +* Fix: Destroy resources when background construction started by TryAcquire finishes after Close or Reset. + Previously, Close could wait indefinitely and Reset could allow a stale resource to be reused. (bensynapse) +* Replace custom logarithm calculation with math/bits. (Andy Walker) + # 2.2.2 (September 10, 2024) * Add empty acquire time to stats (Maxim Ivanov) diff --git a/vendor/github.com/jackc/puddle/v2/README.md b/vendor/github.com/jackc/puddle/v2/README.md index fa82a9d..47d1acf 100644 --- a/vendor/github.com/jackc/puddle/v2/README.md +++ b/vendor/github.com/jackc/puddle/v2/README.md @@ -73,7 +73,23 @@ Puddle is stable and feature complete. ## Supported Go Versions -puddle supports the same versions of Go that are supported by the Go project. For [Go](https://golang.org/doc/devel/release.html#policy) that is the two most recent major releases. This means puddle supports Go 1.19 and higher. +puddle supports the same versions of Go that are supported by the Go project: the [two most recent major releases](https://go.dev/doc/devel/release#policy). The minimum Go version declared in `go.mod` is 1.19, which is also tested in CI as a compatibility baseline. + +## Differences with Go sync.Pool + +They are intended for entirely different types of resources: + +* [sync.Pool](https://pkg.go.dev/sync#Pool) would generally be used for in memory objects. +* Puddle would generally be used for handles to external objects such as connections, file handles, etc. + +Specific differences: + +* sync.Pool does not have a way to limit max resources in pool. +* sync.Pool does not have a way to ensure at least min resources in pool. +* sync.Pool can drop resources in pool at any time - not ideal for expensive to create connections. +* sync.Pool does not have a cleanup / release function. Resources are GCed without a chance to close cleanly. +* sync.Pool does not have a way to handle errors creating the resource +* sync.Pool does not support context to limit time to wait creating a resource ## License diff --git a/vendor/github.com/jackc/puddle/v2/log.go b/vendor/github.com/jackc/puddle/v2/log.go deleted file mode 100644 index b21b946..0000000 --- a/vendor/github.com/jackc/puddle/v2/log.go +++ /dev/null @@ -1,32 +0,0 @@ -package puddle - -import "unsafe" - -type ints interface { - int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64 -} - -// log2Int returns log2 of an integer. This function panics if val < 0. For val -// == 0, returns 0. -func log2Int[T ints](val T) uint8 { - if val <= 0 { - panic("log2 of non-positive number does not exist") - } - - return log2IntRange(val, 0, uint8(8*unsafe.Sizeof(val))) -} - -func log2IntRange[T ints](val T, begin, end uint8) uint8 { - length := end - begin - if length == 1 { - return begin - } - - delim := begin + length/2 - mask := T(1) << delim - if mask > val { - return log2IntRange(val, begin, delim) - } else { - return log2IntRange(val, delim, end) - } -} diff --git a/vendor/github.com/jackc/puddle/v2/mise.toml b/vendor/github.com/jackc/puddle/v2/mise.toml new file mode 100644 index 0000000..a015672 --- /dev/null +++ b/vendor/github.com/jackc/puddle/v2/mise.toml @@ -0,0 +1,2 @@ +[tools] +go = "1.27.1" diff --git a/vendor/github.com/jackc/puddle/v2/pool.go b/vendor/github.com/jackc/puddle/v2/pool.go index c411d2f..4bb3a75 100644 --- a/vendor/github.com/jackc/puddle/v2/pool.go +++ b/vendor/github.com/jackc/puddle/v2/pool.go @@ -3,6 +3,7 @@ package puddle import ( "context" "errors" + "math/bits" "sync" "sync/atomic" "time" @@ -513,6 +514,11 @@ func (p *Pool[T]) TryAcquire(ctx context.Context) (*Resource[T], error) { } res.value = value + if p.closed || res.poolResetCount != p.resetCount { + p.allResources.remove(res) + go p.destructResourceValue(value) + return + } res.status = resourceStatusIdle p.idleResources.Push(res) }() @@ -543,12 +549,14 @@ func (p *Pool[T]) TryAcquire(ctx context.Context) (*Resource[T], error) { // TODO: Replace this with acquireSem.TryAcquireAll() if it gets to // upstream. https://github.com/golang/sync/pull/19 func acquireSemAll(sem *semaphore.Weighted, num int) int { + if num <= 0 { + panic("aquireSemAll: num <= 0") + } if sem.TryAcquire(int64(num)) { return num } - var acquired int - for i := int(log2Int(num)); i >= 0; i-- { + for i := bits.Len64(uint64(num)) - 1; i >= 0; i-- { val := 1 << i if sem.TryAcquire(int64(val)) { acquired += val @@ -638,10 +646,14 @@ func (p *Pool[T]) CreateResource(ctx context.Context) error { res.value = value res.status = resourceStatusIdle - // If closed while constructing resource then destroy it and return an error - if p.closed { + // If closed or reset while constructing resource then destroy it + if p.closed || res.poolResetCount != p.resetCount { + p.allResources.remove(res) go p.destructResourceValue(res.value) - return ErrClosedPool + if p.closed { + return ErrClosedPool + } + return nil } p.idleResources.Push(res) diff --git a/vendor/github.com/klauspost/compress/.gitignore b/vendor/github.com/klauspost/compress/.gitignore index d31b378..fb06aaf 100644 --- a/vendor/github.com/klauspost/compress/.gitignore +++ b/vendor/github.com/klauspost/compress/.gitignore @@ -30,3 +30,6 @@ perf.data.old # gdb history .gdb_history + +# Silesia corpus, fetched by testdata/fetch_silesia.sh +**/testdata/silesia.tar* diff --git a/vendor/github.com/klauspost/compress/AGENTS.md b/vendor/github.com/klauspost/compress/AGENTS.md new file mode 100644 index 0000000..e14bc14 --- /dev/null +++ b/vendor/github.com/klauspost/compress/AGENTS.md @@ -0,0 +1,106 @@ +# AGENTS.md + +Guidance for people and coding agents changing this repository. It records +conventions and traps learned while working on the decoders and encoders; the +README describes the packages themselves. + +## Checks before sending a change + +- `gofmt`, `go vet ./...` and `go fix -diff ./...` (which should report + nothing). Code written for specific platforms must be vetted for them too: + run `go vet` with `GOOS`/`GOARCH` set to each platform it targets. `go vet` + caches results per package and does not notice edits to files excluded by + build tags; use a fresh `GOCACHE` to confirm a stale-looking error. +- `go test ./...` with and without `-tags=noasm` (and `nounsafe` if you + touched `unsafe` code), on every architecture whose assembly changed. +- Decoder changes: run the fuzzers CI runs (see `.github/workflows/go.yml`), + also with `-tags=noasm`, `-tags=nounsafe` and `-asan`, for longer than CI + does, and for zstd both `FuzzDecodeAll` and the `NoBMI2` variants. +- Raising the Go version in the root `go.mod` breaks the nested modules + (`*/_generate`, `s2/cmd/_s2sx`) until they are updated too. In a `go` + directive, `1.25` sorts before `1.25.0`, so a dependency that needs + `1.25.0` forces the full form. + +## Tests + +- Put a new test in the existing test file for the code it exercises + (`decoder_test.go` for Reader/DecodeAll behaviour, `seqdec_test.go` for + sequence execution, and so on), and reuse its helpers. Use table tests for + three or more similar cases. +- Extend the existing fuzzers (`func Fuzz…`) rather than adding parallel + harnesses; if a new harness supersedes an old one, remove the old one in + the same change. +- Prove which path a test or benchmark exercises. A benchmark once ran the + pure-Go sequence decoder instead of the assembly because of how its buffers + were set up. A `panic` planted in the path is a quick check; `println` + output is easy to miss. +- `sync.Pool` drops about a quarter of `Put`s under `-race` by design; never + assume `Get` returns the last `Put`. +- Don't add tests whose only purpose is to catch someone deliberately undoing + a performance pin (an alignment, say); a comment explaining it is enough. + +## Performance claims + +- Use real data. The maintainer's corpora are at + https://klauspost.com/files/compress/ (logs, JSON, CSV, serialized data, + tar files); put `.zst` files in `zstd/testdata/benchmark-custom/` and run + `BenchmarkDecoderWithCustomFiles`. Silesia, enwik and generated data are + fine for correctness but are not accepted as evidence for a speed-up. +- When a result depends on how the data was compressed, report the levels + separately (for example `SpeedDefault` and `SpeedBestCompression`). +- Anchor `-bench` patterns at every level with `$`: `-bench 'BenchmarkFoo$'` + also runs `BenchmarkFooBar` otherwise, which has produced fake gains and + regressions. +- Code placement alone moves results by about ±2%. For an A/B, insert + `PCALIGN $64` before every `TEXT` in the `.s` files of *both* builds + (measurement only, not committed). +- Build both variants as test binaries up front, then run them in turns: one + short `-count 1` run of each, repeated for ten or more rounds, swapping + which goes first every round (AB, BA, AB, …) so neither build always gets + the warmer or colder slot. Never run all of A and then all of B. Clock + speed, temperature, cache and page-cache state, and background load drift + over a session; alternating spreads that drift over both builds instead of + turning it into a difference between them. Pin to one core, use an + otherwise idle machine, and compare the pooled results with `benchstat`. +- Report the number of regressed cases next to the geomean; a small win with + no regressions is a different result from a larger one with some. +- No CPU-model-specific code paths or thresholds. A gate for arm64 must be + measured on several Neoverse generations (N1, V1, V2, V3), not one core. + +## Pull requests + +- One commit per independent change, with fixups squashed in. Number the + changes in the description as "(1) … (sha)" and name the test file for + each test. +- Mention each `#NNN` once in prose; refer back in words. +- Don't open many PRs against the same area at once; reviewer time is the + scarce resource. +- Keep Go comments short; generator and assembly comments can explain in + detail. +- Keep private or company-internal references (internal service names, + private links, chat or agent-session URLs) out of code, commit messages and + PR text. + +## Assembly is generated + +- zstd, huff0 and s2 assembly is generated with the + [honeycombio/avo](https://github.com/honeycombio/avo) fork of avo from + `zstd/_generate`, `huff0/_generate` and `s2/_generate`. Never edit the + `.s` files by hand: change the generator, run `go generate -v -x` in the + `_generate` directory, and commit the regenerated output. CI's `generate` job + fails if the committed files differ from the generator's output. +- The arm64 files are lowered from the same amd64 program by the fork, which + the `_generate` modules import as `github.com/honeycombio/avo`; keep all + three on the same fork commit. A change to the generator changes both + architectures; build and test both. +- When moving the avo pin, regenerate and check the output is byte-identical + unless a change is intended, so unrelated printer changes don't slip into a + review. +- Never put a label directly on a `PCALIGN` (emit the `PCALIGN` before the + label). A jump to it makes the amd64 assembler jump to the wrong place + (Go ≤ 1.25, golang/go#74648) or loop forever when it has to widen a branch + (Go ≥ 1.26, golang/go#81792). Current versions of the avo fork reject it. +- Build tags: `noasm` selects the pure-Go code and `nounsafe` the code without + `unsafe`. Every assembly or `unsafe` path needs a portable fallback, and CI + runs the default, `noasm`, `nounsafe` and `nounsafe,noasm` builds. The + library doesn't use cgo. diff --git a/vendor/github.com/klauspost/compress/README.md b/vendor/github.com/klauspost/compress/README.md index 0e9f170..1f5dbe9 100644 --- a/vendor/github.com/klauspost/compress/README.md +++ b/vendor/github.com/klauspost/compress/README.md @@ -6,7 +6,10 @@ This package provides various compression algorithms. * [S2](https://github.com/klauspost/compress/tree/master/s2#s2-compression) is a high performance replacement for Snappy. * Optimized [deflate](https://godoc.org/github.com/klauspost/compress/flate) packages which can be used as a dropin replacement for [gzip](https://godoc.org/github.com/klauspost/compress/gzip), [zip](https://godoc.org/github.com/klauspost/compress/zip) and [zlib](https://godoc.org/github.com/klauspost/compress/zlib). * [snappy](https://github.com/klauspost/compress/tree/master/snappy) is a drop-in replacement for `github.com/golang/snappy` offering better compression and concurrent streams. +* [lzw](https://github.com/klauspost/compress/tree/master/lzw) is a drop-in replacement for `compress/lzw` with 1.4-4x faster decompression and 1.1-2.7x faster compression, depending on the data. * [huff0](https://github.com/klauspost/compress/tree/master/huff0) and [FSE](https://github.com/klauspost/compress/tree/master/fse) implementations for raw entropy encoding. +* [Xpress](https://github.com/klauspost/compress/tree/master/xpress) decompression of the Microsoft XPRESS (MS-XCA) plain LZ77 and LZ77+Huffman formats (the LZ77+Huffman variant is the one used in WIM images and Windows Compact OS / WOF data). +* [dict](https://github.com/klauspost/compress/tree/master/dict) is an experimental dictionary builder for Zstandard, S2, LZ4, deflate and more. * [gzhttp](https://github.com/klauspost/compress/tree/master/gzhttp) Provides client and server wrappers for handling gzipped/zstd HTTP requests efficiently. * [pgzip](https://github.com/klauspost/pgzip) is a separate package that provides a very fast parallel gzip implementation. @@ -27,8 +30,41 @@ Use the links above for more information on each. # changelog +* Sep 25th, 2026 [1.20.1](https://github.com/klauspost/compress/releases/tag/v1.20.1) + * zstd: Apply reset options to reused frame decoders by @pellared in https://github.com/klauspost/compress/pull/1226 + * flate: Report unexpected EOF for truncated Huffman extra bits by @rupayon123 in https://github.com/klauspost/compress/pull/1229 + * flate: Avoid FMA in EstimatedBits for portable rounding by @malt3 in https://github.com/klauspost/compress/pull/1224 + * gzhttp: Preserve caller request headers in Transport by @jakezwang in https://github.com/klauspost/compress/pull/1225 + * gzhttp: Only decompress a request when gzip is the outermost coding by @youdie006 in https://github.com/klauspost/compress/pull/1223 + * zstd/huff0: Optimizations by @lizthegrey in https://github.com/klauspost/compress/pull/1203 https://github.com/klauspost/compress/pull/1205 https://github.com/klauspost/compress/pull/1207 https://github.com/klauspost/compress/pull/1204 https://github.com/klauspost/compress/pull/1208 https://github.com/klauspost/compress/pull/1211 https://github.com/klauspost/compress/pull/1209 https://github.com/klauspost/compress/pull/1210 + * flate: Speed improvements by @alex in https://github.com/klauspost/compress/pull/1220 https://github.com/klauspost/compress/pull/1218 https://github.com/klauspost/compress/pull/1216 https://github.com/klauspost/compress/pull/1215 https://github.com/klauspost/compress/pull/1214 https://github.com/klauspost/compress/pull/1217 + +* Sep 2nd, 2026 [1.20.0](https://github.com/klauspost/compress/releases/tag/v1.20.0) + * lzw: Add lzw reader/writer in https://github.com/klauspost/compress/pull/1189 + * xpress: Add Microsoft XPRESS (MS-XCA) decompression by @MP-GOWTHAM in https://github.com/klauspost/compress/pull/1195 + * s2: arm64 assembly encoders by @lizthegrey in https://github.com/klauspost/compress/pull/1187 + * zstd, huff0: Improved arm64 assembly by @lizthegrey in https://github.com/klauspost/compress/pull/1175 https://github.com/klauspost/compress/pull/1199 https://github.com/klauspost/compress/pull/1197 + * flate: Writer L7-9 with dictionary can emit the dictionary to stream in https://github.com/klauspost/compress/pull/1201 + * gzhttp: Limit jitter hash to jitterBuffer bytes by @VedantMadane in https://github.com/klauspost/compress/pull/1192 + * s2: Clamp the Go EncodeBetter skip to match the assembly by @lizthegrey in https://github.com/klauspost/compress/pull/1190 + * xxhash: Bound input of non-preemptive assembly by @AskAlexSharov in https://github.com/klauspost/compress/pull/1196 + +* Aug 6th, 2026 [1.19.2](https://github.com/klauspost/compress/releases/tag/v1.19.2) + * huff0: Add arm64 assembly for Decompress4X/1X by @lizthegrey in https://github.com/klauspost/compress/pull/1172 + * zstd: Re-enable unsafe decodeSync memory copies by @lizthegrey in https://github.com/klauspost/compress/pull/1171 + * zstd: Fix arm64 asm frame offsets placing locals on the saved LR slot by @lizthegrey in https://github.com/klauspost/compress/pull/1176 + * zstd: Avoid racing MaxDecodedSize write on shared dict litEnc by @zanarellidev in https://github.com/klauspost/compress/pull/1182 + * zstd: Keep BuildDict recent-offsets positive and loadable by @zanarellidev in https://github.com/klauspost/compress/pull/1184 + * zstd: Handle zero-literal BuildDict corpus by @cyphercodes in https://github.com/klauspost/compress/pull/1178 + * zstd: Don't clear the registered dictionary when decoding past the window by @sueun-dev in https://github.com/klauspost/compress/pull/1177 + +* Jul 20th, 2026 [1.19.1](https://github.com/klauspost/compress/releases/tag/v1.19.1) + * zstd: Validate SnappyConverter literal copies in https://github.com/klauspost/compress/pull/1170 + * flate: Use `Peek` instead of `ReadByte` for the `bufio.Reader` decode path by @joechenrh in https://github.com/klauspost/compress/pull/1169 + * zstd: Bump avo pin, regenerate arm64 asm by @lizthegrey in https://github.com/klauspost/compress/pull/1167 + * Jul 1st, 2026 [1.19.0](https://github.com/klauspost/compress/releases/tag/v1.19.0) - * zstd: Add true concurrent stream encodingin https://github.com/klauspost/compress/pull/1136 + * zstd: Add true concurrent stream encoding in https://github.com/klauspost/compress/pull/1136 * zstd: arm64 decoder asm by @lizthegrey in https://github.com/klauspost/compress/pull/1160 * flate: Add inflate checkpoints in https://github.com/klauspost/compress/pull/1154 * zstd: avoid unused BuildDict encoder allocation by @snissn in https://github.com/klauspost/compress/pull/1147 @@ -39,6 +75,22 @@ Use the links above for more information on each. * huff0: Allow building table from oversized histogram in https://github.com/klauspost/compress/pull/1156 * s2sx: Clean symlink targets in https://github.com/klauspost/compress/pull/1163 +
+ See changes to v1.18.x + +* Jun 30th, 2026 [1.18.7](https://github.com/klauspost/compress/releases/tag/v1.18.7) + * s2: Fix `NewDict` out-of-bounds read. Security release without other changes. + +* Apr 30th, 2026 [1.18.6](https://github.com/klauspost/compress/releases/tag/v1.18.6) + * s2: Fix amd64 stack frame corruption in https://github.com/klauspost/compress/pull/1145 + * gzhttp: Canonicalize ETag header by @justinmayhew in https://github.com/klauspost/compress/pull/1139 + * Pool hash tables in Go encode paths to reduce allocations by @huynhanx03 in https://github.com/klauspost/compress/pull/1143 + +* Mar 20th, 2026 [1.18.5](https://github.com/klauspost/compress/releases/tag/v1.18.5) + * zstd: Fix crash when changing encoder dictionary with same ID in https://github.com/klauspost/compress/pull/1135 + * zstd: Default to full zero frames in https://github.com/klauspost/compress/pull/1134 + * flate: Clean up histogram order in https://github.com/klauspost/compress/pull/1133 + * Feb 9th, 2026 [1.18.4](https://github.com/klauspost/compress/releases/tag/v1.18.4) * gzhttp: Add zstandard to server handler wrapper https://github.com/klauspost/compress/pull/1121 * zstd: Add ResetWithOptions to encoder/decoder https://github.com/klauspost/compress/pull/1122 @@ -70,6 +122,8 @@ Use the links above for more information on each. * flate: Fix matchlen L5+L6 https://github.com/klauspost/compress/pull/1049 * flate: Cleanup & reduce casts https://github.com/klauspost/compress/pull/1050 +
+
See changes to v1.17.x diff --git a/vendor/github.com/klauspost/compress/fse/compress.go b/vendor/github.com/klauspost/compress/fse/compress.go index 8c8baa4..9d6885e 100644 --- a/vendor/github.com/klauspost/compress/fse/compress.go +++ b/vendor/github.com/klauspost/compress/fse/compress.go @@ -26,6 +26,7 @@ func Compress(in []byte, s *Scratch) ([]byte, error) { if err != nil { return nil, err } + defer s.cleanup() // Create histogram, if none was provided. maxCount := s.maxCount @@ -659,7 +660,8 @@ func (s *Scratch) validateNorm() (err error) { if v >= 0 { total += int(v) } else { - total -= int(v) + // -1 takes one cell. Adding -v would let a wrapped -32768 pass. + total++ } } defer func() { diff --git a/vendor/github.com/klauspost/compress/fse/decompress.go b/vendor/github.com/klauspost/compress/fse/decompress.go index 0c7dd4f..f8ee7f6 100644 --- a/vendor/github.com/klauspost/compress/fse/decompress.go +++ b/vendor/github.com/klauspost/compress/fse/decompress.go @@ -3,6 +3,7 @@ package fse import ( "errors" "fmt" + "math" ) const ( @@ -21,6 +22,7 @@ func Decompress(b []byte, s *Scratch) ([]byte, error) { if err != nil { return nil, err } + defer s.cleanup() s.Out = s.Out[:0] err = s.readNCount() if err != nil { @@ -123,6 +125,11 @@ func (s *Scratch) readNCount() error { remaining -= count gotTotal += count } + if count > math.MaxInt16 { + // Only one symbol filling a tableLog 15 table, which cannot be decoded. + // Truncated, it would leave the decoding table unwritten. + return fmt.Errorf("corruption detected (count %d > %d)", count, math.MaxInt16) + } s.norm[charnum&0xff] = int16(count) charnum++ previous0 = count == 0 diff --git a/vendor/github.com/klauspost/compress/fse/fse.go b/vendor/github.com/klauspost/compress/fse/fse.go index 535cbad..99d8012 100644 --- a/vendor/github.com/klauspost/compress/fse/fse.go +++ b/vendor/github.com/klauspost/compress/fse/fse.go @@ -134,6 +134,12 @@ func (s *Scratch) prepare(in []byte) (*Scratch, error) { return s, nil } +// cleanup clears any pointers to user supplied buffers. +func (s *Scratch) cleanup() { + s.br.b = nil + s.bits.in = nil +} + // tableStep returns the next table index. func tableStep(tableSize uint32) uint32 { return (tableSize >> 1) + (tableSize >> 3) + 3 diff --git a/vendor/github.com/klauspost/compress/huff0/bitreader.go b/vendor/github.com/klauspost/compress/huff0/bitreader.go index bfc7a52..1d9ab6a 100644 --- a/vendor/github.com/klauspost/compress/huff0/bitreader.go +++ b/vendor/github.com/klauspost/compress/huff0/bitreader.go @@ -9,8 +9,10 @@ import ( "errors" "fmt" "io" + "math/bits" "github.com/klauspost/compress/internal/le" + "github.com/klauspost/compress/internal/regmask" ) // bitReader reads a bitstream in reverse. @@ -206,10 +208,107 @@ func (b *bitReaderShifted) fill() { } } +// shiftedState is the part of a bitReaderShifted that changes while +// reading. Decode loops hold it by value so it stays in registers. +// value is always le.Load64(in, off) << bitsRead. +type shiftedState struct { + value uint64 + off uint + bitsRead uint8 +} + +func (b *bitReaderShifted) state() shiftedState { + return shiftedState{value: b.value, off: b.off, bitsRead: b.bitsRead} +} + +func (b *bitReaderShifted) setState(s shiftedState) { + b.value, b.off, b.bitsRead = s.value, s.off, s.bitsRead +} + +// refill reloads the whole container with one load and no branch, +// leaving at least 57 bits. off must be at least bitsRead/8. +func (s shiftedState) refill(in []byte) shiftedState { + s.off -= uint(s.bitsRead >> 3) + s.bitsRead &= 7 + s.value = le.Load64(in, s.off) << (s.bitsRead & regmask.Shift64ByUint8) + return s +} + +// decode reads one symbol from a table indexed by the top bits of the +// container, value >> peek. +func (s shiftedState) decode(single *[1 << tableLogMax]dEntrySingle, peek uint8) (shiftedState, uint8) { + v := single[(s.value>>(peek®mask.Shift64ByUint8))&(1<> 8) +} + func (b *bitReaderShifted) remaining() uint { return b.off*8 + uint(64-b.bitsRead) } +// canUseAsm reports whether the reader has a full 8-byte window ahead of +// its read pointer, which the Decompress4X asm loops need to take over. +func (b *bitReaderShifted) canUseAsm() bool { + return b.off >= 8 +} + +// prepareForAsm establishes the invariant the Decompress4X asm loops rely +// on: value == load64(in[off:off+8]) << bitsRead with bitsRead <= 7, so +// that a full group of symbols can never shift their sentinel bit out of +// the container. init leaves bitsRead == 8 when the final byte of the +// stream is exactly 0x01; that whole byte is consumed, so the same position +// is the window one byte lower with nothing consumed. Requires canUseAsm. +func (b *bitReaderShifted) prepareForAsm() { + if b.bitsRead >= 8 { + b.off-- + b.value = le.Load64(b.in, b.off) + b.bitsRead -= 8 + } +} + +// restoreFromAsm converts the state left behind by the Decompress4X asm +// loops back to the invariant the Go code relies on: value holds the 8 +// bytes at in[off:off+8] shifted left by bitsRead, with the low bitsRead +// bits zero. +// +// The asm keeps a sentinel bit in value just below the unread bits, so its +// trailing zero count is the number of consumed bits. The sentinel is ORed +// over the lowest bit of the window, which the loop never consumes before +// re-reading memory, so the window is re-read here too rather than taken +// from value. The asm reports off as the signed distance from the start of +// the stream, and it can be negative: a reload always reads a whole 8-byte +// window, so a stream that is nearly drained ends with up to 7 bytes of the +// previous stream (or the jump table) below its start inside the window. +// Those bytes sit below the stream's own bits and count as consumed. +// Anything further below, or more bits consumed than the stream holds, is +// corruption. +func (b *bitReaderShifted) restoreFromAsm() error { + off := int(b.off) + consumed := uint(bits.TrailingZeros64(b.value)) + if off < 0 { + if off < -7 { + return errors.New("corruption detected: stream underrun") + } + consumed += uint(-off) * 8 + if consumed > 64 { + return errors.New("corruption detected: stream underrun") + } + off = 0 + } + if off+8 > len(b.in) { + return errors.New("corruption detected: stream overrun") + } + b.off = uint(off) + b.bitsRead = uint8(consumed) + if consumed >= 64 { + b.value = 0 + } else { + b.value = le.Load64(b.in, b.off) << consumed + } + return nil +} + // close the bitstream and returns an error if out-of-buffer reads occurred. func (b *bitReaderShifted) close() error { // Release reference. diff --git a/vendor/github.com/klauspost/compress/huff0/bitwriter.go b/vendor/github.com/klauspost/compress/huff0/bitwriter.go index 41db94c..c48e7ea 100644 --- a/vendor/github.com/klauspost/compress/huff0/bitwriter.go +++ b/vendor/github.com/klauspost/compress/huff0/bitwriter.go @@ -5,6 +5,50 @@ package huff0 +import ( + "github.com/klauspost/compress/internal/le" + "github.com/klauspost/compress/internal/regmask" +) + +// bitState is a bit writer that stays in registers when passed and +// returned by value. It writes into a buffer owned by the caller. +type bitState struct { + c uint64 + nb uint + pos int +} + +// flush writes the whole bytes with one 8-byte store at pos, leaving +// at most 7 bits. buf must have 8 bytes of room at pos. +func (s bitState) flush(buf []byte) bitState { + le.Store64(buf, s.pos, s.c) + s.pos += int(s.nb >> 3) + s.c >>= (s.nb &^ 7) & regmask.Shift64ByUint + s.nb &= 7 + return s +} + +// add adds n bits from v, which must have no bits set above them. +// There must be room for them. +func (s bitState) add(v uint64, n uint) bitState { + s.c |= v << (s.nb & regmask.Shift64ByUint) + s.nb += n + return s +} + +// fourSymbols returns the codes for a, b, c and d packed in that order +// from the LSB, and their total length. +func fourSymbols(a, b, c, d cTableEntry) (uint64, uint) { + bitsA := uint(a.nBits) + bitsB := bitsA + uint(b.nBits) + bitsC := bitsB + uint(c.nBits) + v := uint64(a.val) | + uint64(b.val)<<(bitsA®mask.Shift64ByUint) | + uint64(c.val)<<(bitsB®mask.Shift64ByUint) | + uint64(d.val)<<(bitsC®mask.Shift64ByUint) + return v, bitsC + uint(d.nBits) +} + // bitWriter will write bits. // First bit will be LSB of the first byte of output. type bitWriter struct { @@ -33,55 +77,6 @@ func (b *bitWriter) encSymbol(ct cTable, symbol byte) { b.nBits += enc.nBits } -// encTwoSymbols will add up to 32 bits. value may not contain more set bits than indicated. -// It will not check if there is space for them, so the caller must ensure that it has flushed recently. -func (b *bitWriter) encTwoSymbols(ct cTable, av, bv byte) { - encA := ct[av] - encB := ct[bv] - sh := b.nBits & 63 - combined := uint64(encA.val) | (uint64(encB.val) << (encA.nBits & 63)) - b.bitContainer |= combined << sh - if false { - if encA.nBits == 0 { - panic("nbitsA 0") - } - if encB.nBits == 0 { - panic("nbitsB 0") - } - } - b.nBits += encA.nBits + encB.nBits -} - -// encFourSymbols adds up to 32 bits from four symbols. -// It will not check if there is space for them, -// so the caller must ensure that b has been flushed recently. -func (b *bitWriter) encFourSymbols(encA, encB, encC, encD cTableEntry) { - bitsA := encA.nBits - bitsB := bitsA + encB.nBits - bitsC := bitsB + encC.nBits - bitsD := bitsC + encD.nBits - combined := uint64(encA.val) | - (uint64(encB.val) << (bitsA & 63)) | - (uint64(encC.val) << (bitsB & 63)) | - (uint64(encD.val) << (bitsC & 63)) - b.bitContainer |= combined << (b.nBits & 63) - b.nBits += bitsD -} - -// flush32 will flush out, so there are at least 32 bits available for writing. -func (b *bitWriter) flush32() { - if b.nBits < 32 { - return - } - b.out = append(b.out, - byte(b.bitContainer), - byte(b.bitContainer>>8), - byte(b.bitContainer>>16), - byte(b.bitContainer>>24)) - b.nBits -= 32 - b.bitContainer >>= 32 -} - // flushAlign will flush remaining full bytes and align to next byte boundary. func (b *bitWriter) flushAlign() { nbBytes := (b.nBits + 7) >> 3 diff --git a/vendor/github.com/klauspost/compress/huff0/compress.go b/vendor/github.com/klauspost/compress/huff0/compress.go index a97cf1b..1406b76 100644 --- a/vendor/github.com/klauspost/compress/huff0/compress.go +++ b/vendor/github.com/klauspost/compress/huff0/compress.go @@ -4,6 +4,7 @@ import ( "fmt" "math" "runtime" + "slices" "sync" ) @@ -243,23 +244,27 @@ func (s *Scratch) compress1xDo(dst, src []byte) []byte { bw.encSymbol(cTable, src[n+i-1]) } n -= 4 - if s.actualTableLog <= 8 { - for ; n >= 0; n -= 4 { - tmp := src[n : n+4] - // tmp should be len 4 - bw.flush32() - bw.encFourSymbols(cTable[tmp[3]], cTable[tmp[2]], cTable[tmp[1]], cTable[tmp[0]]) + + // flush leaves at most 7 bits, so four symbols (at most 4*tableLogMax + // bits) always fit. Each chunk checks room for bytesPer4 per four + // symbols plus the 8-byte store. + const bytesPer4 = (7 + 4*tableLogMax) / 8 + w := bitState{c: bw.bitContainer, nb: uint(bw.nBits), pos: len(bw.out)} + buf := bw.out[:cap(bw.out)] + for n >= 0 { + k := (len(buf) - w.pos - 8) / bytesPer4 + if k <= 0 { + buf = slices.Grow(buf[:w.pos], (n/4+1)*bytesPer4+8) + buf = buf[:cap(buf)] + continue } - } else { - for ; n >= 0; n -= 4 { + for stop := max(n-4*k, -4); n > stop; n -= 4 { + w = w.flush(buf) tmp := src[n : n+4] - // tmp should be len 4 - bw.flush32() - bw.encTwoSymbols(cTable, tmp[3], tmp[2]) - bw.flush32() - bw.encTwoSymbols(cTable, tmp[1], tmp[0]) + w = w.add(fourSymbols(cTable[tmp[3]], cTable[tmp[2]], cTable[tmp[1]], cTable[tmp[0]])) } } + bw.bitContainer, bw.nBits, bw.out = w.c, uint8(w.nb), buf[:w.pos] bw.close() return bw.out } diff --git a/vendor/github.com/klauspost/compress/huff0/decompress.go b/vendor/github.com/klauspost/compress/huff0/decompress.go index 7d0efa8..9358784 100644 --- a/vendor/github.com/klauspost/compress/huff0/decompress.go +++ b/vendor/github.com/klauspost/compress/huff0/decompress.go @@ -54,6 +54,10 @@ func ReadTable(in []byte, s *Scratch) (s2 *Scratch, remain []byte, err error) { if len(in) < int(iSize) { return s, nil, fmt.Errorf("input too small for table, want %d bytes, have %d", iSize, len(in)) } + // The low nibble is the weights' FSE tableLog - 5, which the format limits to 6. + if in[0]&15+5 > 6 { + return s, nil, errors.New("corrupt input: weights tableLog too big") + } // FSE compressed weights s.fse.DecompressLimit = 255 hw := s.huffWeight[:] @@ -70,17 +74,32 @@ func ReadTable(in []byte, s *Scratch) (s2 *Scratch, remain []byte, err error) { in = in[iSize:] } - // collect weight stats + // collect weight stats. Weights repeat, so four histograms keep each + // increment from waiting on the previous store to the same counter. + var hist [4][16]uint32 + var seen uint8 + w := s.huffWeight[:s.symbolLen] + for ; len(w) >= 4; w = w[4:] { + hist[0][w[0]&15]++ + hist[1][w[1]&15]++ + hist[2][w[2]&15]++ + hist[3][w[3]&15]++ + seen |= w[0] | w[1] | w[2] | w[3] + } + for _, v := range w { + hist[0][v&15]++ + seen |= v + } var rankStats [16]uint32 weightTotal := uint32(0) - for _, v := range s.huffWeight[:s.symbolLen] { - if v > tableLogMax { - return s, nil, errors.New("corrupt input: weight too large") - } - v2 := v & 15 - rankStats[v2]++ - // (1 << (v2-1)) is slower since the compiler cannot prove that v2 isn't 0. - weightTotal += (1 << v2) >> 1 + for i := range rankStats { + rankStats[i] = hist[0][i] + hist[1][i] + hist[2][i] + hist[3][i] + } + for i := 1; i < len(rankStats); i++ { + weightTotal += rankStats[i] << (i - 1) + } + if seen > 15 || rankStats[tableLogMax+1]|rankStats[tableLogMax+2]|rankStats[tableLogMax+3]|rankStats[tableLogMax+4] != 0 { + return s, nil, errors.New("corrupt input: weight too large") } if weightTotal == 0 { return s, nil, errors.New("corrupt input: weights zero") @@ -158,9 +177,17 @@ func ReadTable(in []byte, s *Scratch) (s2 *Scratch, remain []byte, err error) { nBits: uint8(d.entry), } + // length is a power of two; runs of 4 or more are filled 4 at a time. single := s.dt.single[*rank : *rank+length] - for i := range single { - single[i] = d + if length >= 4 { + for i := 0; i < len(single); i += 4 { + s4 := single[i : i+4 : i+4] + s4[0], s4[1], s4[2], s4[3] = d, d, d, d + } + } else { + for i := range single { + single[i] = d + } } *rank += length } diff --git a/vendor/github.com/klauspost/compress/huff0/decompress_amd64.go b/vendor/github.com/klauspost/compress/huff0/decompress_amd64.go index 7035d65..169cf10 100644 --- a/vendor/github.com/klauspost/compress/huff0/decompress_amd64.go +++ b/vendor/github.com/klauspost/compress/huff0/decompress_amd64.go @@ -1,4 +1,4 @@ -//go:build amd64 && !appengine && !noasm && gc +//go:build amd64 && !noasm && gc // amd64 stubs and dispatch for the asm loops used by decompress_asm.go. package huff0 @@ -8,36 +8,99 @@ import ( ) // decompress4x_main_loop_amd64 is an x86 assembler implementation -// of Decompress4X when tablelog > 8. +// of Decompress4X when tablelog > 8, decoding fastSymbols symbols per +// stream between bit container reloads. // //go:noescape func decompress4x_main_loop_amd64(ctx *decompress4xContext) // decompress4x_8b_main_loop_amd64 is an x86 assembler implementation -// of Decompress4X when tablelog <= 8 which decodes 4 entries -// per loop. +// of Decompress4X when tablelog <= 8, decoding fast8bSymbols symbols +// per stream between bit container reloads. // //go:noescape func decompress4x_8b_main_loop_amd64(ctx *decompress4xContext) +// decompress4x_4b_main_loop_amd64 is an x86 assembler implementation +// of Decompress4X when tablelog <= 4, decoding fast4bSymbols symbols +// per stream between bit container reloads. +// +//go:noescape +func decompress4x_4b_main_loop_amd64(ctx *decompress4xContext) + +// decompress4x_4b_main_loop_bmi2 is the BMI2 twin of decompress4x_4b_main_loop_amd64. +// +//go:noescape +func decompress4x_4b_main_loop_bmi2(ctx *decompress4xContext) + +// decompress4x_main_loop_bmi2 is the BMI2 twin of decompress4x_main_loop_amd64. +// +//go:noescape +func decompress4x_main_loop_bmi2(ctx *decompress4xContext) + +// decompress4x_8b_main_loop_bmi2 is the BMI2 twin of decompress4x_8b_main_loop_amd64. +// +//go:noescape +func decompress4x_8b_main_loop_bmi2(ctx *decompress4xContext) + // decompress1x_main_loop_amd64 is an x86 assembler implementation -// of Decompress1X when tablelog > 8. +// of Decompress1X when tablelog > 8, decoding fastSymbols symbols +// between bit container reloads. // //go:noescape func decompress1x_main_loop_amd64(ctx *decompress1xContext) -// decompress1x_main_loop_bmi2 is an x86 with BMI2 assembler implementation -// of Decompress1X when tablelog > 8. +// decompress1x_8b_main_loop_amd64 is an x86 assembler implementation +// of Decompress1X when tablelog <= 8, decoding fast8bSymbols symbols +// between bit container reloads. +// +//go:noescape +func decompress1x_8b_main_loop_amd64(ctx *decompress1xContext) + +// decompress1x_4b_main_loop_amd64 is an x86 assembler implementation +// of Decompress1X when tablelog <= 4, decoding fast4bSymbols symbols +// between bit container reloads. +// +//go:noescape +func decompress1x_4b_main_loop_amd64(ctx *decompress1xContext) + +// decompress1x_main_loop_bmi2 is the BMI2 twin of decompress1x_main_loop_amd64. // //go:noescape func decompress1x_main_loop_bmi2(ctx *decompress1xContext) +// decompress1x_8b_main_loop_bmi2 is the BMI2 twin of decompress1x_8b_main_loop_amd64. +// +//go:noescape +func decompress1x_8b_main_loop_bmi2(ctx *decompress1xContext) + +// decompress1x_4b_main_loop_bmi2 is the BMI2 twin of decompress1x_4b_main_loop_amd64. +// +//go:noescape +func decompress1x_4b_main_loop_bmi2(ctx *decompress1xContext) + func decompress4x_main_loop_asm(ctx *decompress4xContext) { - decompress4x_main_loop_amd64(ctx) + if cpuinfo.HasBMI2() { + decompress4x_main_loop_bmi2(ctx) + } else { + decompress4x_main_loop_amd64(ctx) + } } func decompress4x_8b_main_loop_asm(ctx *decompress4xContext) { - decompress4x_8b_main_loop_amd64(ctx) + if cpuinfo.HasBMI2() { + decompress4x_8b_main_loop_bmi2(ctx) + } else { + decompress4x_8b_main_loop_amd64(ctx) + } +} + +func decompress4x_4b_main_loop_asm(ctx *decompress4xContext) { + if cpuinfo.HasBMI2() { + decompress4x_4b_main_loop_bmi2(ctx) + } else { + decompress4x_4b_main_loop_amd64(ctx) + } } func decompress1x_main_loop_asm(ctx *decompress1xContext) { @@ -47,3 +110,19 @@ func decompress1x_main_loop_asm(ctx *decompress1xContext) { decompress1x_main_loop_amd64(ctx) } } + +func decompress1x_8b_main_loop_asm(ctx *decompress1xContext) { + if cpuinfo.HasBMI2() { + decompress1x_8b_main_loop_bmi2(ctx) + } else { + decompress1x_8b_main_loop_amd64(ctx) + } +} + +func decompress1x_4b_main_loop_asm(ctx *decompress1xContext) { + if cpuinfo.HasBMI2() { + decompress1x_4b_main_loop_bmi2(ctx) + } else { + decompress1x_4b_main_loop_amd64(ctx) + } +} diff --git a/vendor/github.com/klauspost/compress/huff0/decompress_amd64.s b/vendor/github.com/klauspost/compress/huff0/decompress_amd64.s index c5d4a71..30dfa87 100644 --- a/vendor/github.com/klauspost/compress/huff0/decompress_amd64.s +++ b/vendor/github.com/klauspost/compress/huff0/decompress_amd64.s @@ -1,830 +1,3476 @@ -// Code generated by command: go run gen.go -out ../decompress.s -arch amd64,arm64 -pkg=huff0. DO NOT EDIT. +// Code generated by command: go run gen.go -out ../decompress.s -arch amd64,arm64 -arm64-promote-stack-slots -pkg=huff0. DO NOT EDIT. -//go:build !appengine && !noasm && gc +//go:build !noasm && gc // func decompress4x_main_loop_amd64(ctx *decompress4xContext) -TEXT ·decompress4x_main_loop_amd64(SB), $0-8 +// Requires: BMI, CMOV +TEXT ·decompress4x_main_loop_amd64(SB), $40-8 + MOVQ ctx+0(FP), CX + // Preload values - MOVQ ctx+0(FP), AX - MOVBQZX 8(AX), DI - MOVQ 16(AX), BX - MOVQ 48(AX), SI - MOVQ 24(AX), R8 - MOVQ 32(AX), R9 - MOVQ (AX), R10 + MOVBQZX 8(CX), AX + MOVQ 32(CX), DX + MOVQ 16(CX), BX + MOVQ 24(CX), SI + LEAQ (BX)(SI*1), DI + LEAQ (BX)(SI*2), R9 + LEAQ (SI)(SI*2), R11 + ADDQ BX, R11 - // Main loop -main_loop: - XORL DX, DX - CMPQ BX, SI - SETGE DL + // Copy the input pointers to their stack slots + MOVQ 64(CX), SI + MOVQ SI, (SP) + MOVQ 72(CX), SI + MOVQ SI, 8(SP) + MOVQ 80(CX), SI + MOVQ SI, 16(SP) + MOVQ 88(CX), SI + MOVQ SI, 24(SP) - // br0.fillFast32() - MOVQ 32(R10), R11 - MOVBQZX 40(R10), R12 - CMPQ R12, $0x20 - JBE skip_fill0 - MOVQ 24(R10), AX - SUBQ $0x20, R12 - SUBQ $0x04, AX - MOVQ (R10), R13 + // Convert each bit reader to sentinel form: bits = value | 1<> 8) - // out[id * dstEvery + 1] = uint8(v1.entry >> 8) - MOVW AX, (BX) + // stream 1, symbol 1 + MOVQ AX, CX + MOVQ R8, R13 + SHRQ CL, R13 + MOVWQZX (DX)(R13*2), CX + SHLQ CL, R8 + SHRQ $0x08, CX + MOVB CL, 1(DI) - // update the bitreader structure - MOVQ R11, 32(R10) - MOVB R12, 40(R10) + // stream 2, symbol 1 + MOVQ AX, CX + MOVQ R10, R13 + SHRQ CL, R13 + MOVWQZX (DX)(R13*2), CX + SHLQ CL, R10 + SHRQ $0x08, CX + MOVB CL, 1(R9) - // br1.fillFast32() - MOVQ 80(R10), R11 - MOVBQZX 88(R10), R12 - CMPQ R12, $0x20 - JBE skip_fill1 - MOVQ 72(R10), AX - SUBQ $0x20, R12 - SUBQ $0x04, AX - MOVQ 48(R10), R13 + // stream 3, symbol 1 + MOVQ AX, CX + MOVQ R12, R13 + SHRQ CL, R13 + MOVWQZX (DX)(R13*2), CX + SHLQ CL, R12 + SHRQ $0x08, CX + MOVB CL, 1(R11) - // b.value |= uint64(low) << (b.bitsRead & 63) - MOVL (AX)(R13*1), R13 - MOVQ R12, CX - SHLQ CL, R13 - MOVQ AX, 72(R10) - ORQ R13, R11 + // stream 0, symbol 2 + MOVQ AX, CX + MOVQ SI, R13 + SHRQ CL, R13 + MOVWQZX (DX)(R13*2), CX + SHLQ CL, SI + SHRQ $0x08, CX + MOVB CL, 2(BX) - // exhausted += (br1.off < 4) - CMPQ AX, $0x04 - ADCB $+0, DL + // stream 1, symbol 2 + MOVQ AX, CX + MOVQ R8, R13 + SHRQ CL, R13 + MOVWQZX (DX)(R13*2), CX + SHLQ CL, R8 + SHRQ $0x08, CX + MOVB CL, 2(DI) -skip_fill1: - // val0 := br1.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 + // stream 2, symbol 2 + MOVQ AX, CX + MOVQ R10, R13 + SHRQ CL, R13 + MOVWQZX (DX)(R13*2), CX + SHLQ CL, R10 + SHRQ $0x08, CX + MOVB CL, 2(R9) - // v0 := table[val0&mask] - MOVW (R9)(R13*2), CX + // stream 3, symbol 2 + MOVQ AX, CX + MOVQ R12, R13 + SHRQ CL, R13 + MOVWQZX (DX)(R13*2), CX + SHLQ CL, R12 + SHRQ $0x08, CX + MOVB CL, 2(R11) - // br1.advance(uint8(v0.entry) - MOVB CH, AL - SHLQ CL, R11 - ADDB CL, R12 + // stream 0, symbol 3 + MOVQ AX, CX + MOVQ SI, R13 + SHRQ CL, R13 + MOVWQZX (DX)(R13*2), CX + SHLQ CL, SI + SHRQ $0x08, CX + MOVB CL, 3(BX) - // val1 := br1.peekTopBits(peekBits) - MOVQ DI, CX - MOVQ R11, R13 - SHRQ CL, R13 + // stream 1, symbol 3 + MOVQ AX, CX + MOVQ R8, R13 + SHRQ CL, R13 + MOVWQZX (DX)(R13*2), CX + SHLQ CL, R8 + SHRQ $0x08, CX + MOVB CL, 3(DI) - // v1 := table[val1&mask] - MOVW (R9)(R13*2), CX + // stream 2, symbol 3 + MOVQ AX, CX + MOVQ R10, R13 + SHRQ CL, R13 + MOVWQZX (DX)(R13*2), CX + SHLQ CL, R10 + SHRQ $0x08, CX + MOVB CL, 3(R9) - // br1.advance(uint8(v1.entry)) - MOVB CH, AH - SHLQ CL, R11 - ADDB CL, R12 + // stream 3, symbol 3 + MOVQ AX, CX + MOVQ R12, R13 + SHRQ CL, R13 + MOVWQZX (DX)(R13*2), CX + SHLQ CL, R12 + SHRQ $0x08, CX + MOVB CL, 3(R11) - // these two writes get coalesced - // out[id * dstEvery + 0] = uint8(v0.entry >> 8) - // out[id * dstEvery + 1] = uint8(v1.entry >> 8) - MOVW AX, (BX)(R8*1) + // stream 0, symbol 4 + MOVQ AX, CX + MOVQ SI, R13 + SHRQ CL, R13 + MOVWQZX (DX)(R13*2), CX + SHLQ CL, SI + SHRQ $0x08, CX + MOVB CL, 4(BX) - // update the bitreader structure - MOVQ R11, 80(R10) - MOVB R12, 88(R10) + // stream 1, symbol 4 + MOVQ AX, CX + MOVQ R8, R13 + SHRQ CL, R13 + MOVWQZX (DX)(R13*2), CX + SHLQ CL, R8 + SHRQ $0x08, CX + MOVB CL, 4(DI) - // br2.fillFast32() - MOVQ 128(R10), R11 - MOVBQZX 136(R10), R12 - CMPQ R12, $0x20 - JBE skip_fill2 - MOVQ 120(R10), AX - SUBQ $0x20, R12 - SUBQ $0x04, AX - MOVQ 96(R10), R13 + // stream 2, symbol 4 + MOVQ AX, CX + MOVQ R10, R13 + SHRQ CL, R13 + MOVWQZX (DX)(R13*2), CX + SHLQ CL, R10 + SHRQ $0x08, CX + MOVB CL, 4(R9) - // b.value |= uint64(low) << (b.bitsRead & 63) - MOVL (AX)(R13*1), R13 - MOVQ R12, CX - SHLQ CL, R13 - MOVQ AX, 120(R10) - ORQ R13, R11 + // stream 3, symbol 4 + MOVQ AX, CX + MOVQ R12, R13 + SHRQ CL, R13 + MOVWQZX (DX)(R13*2), CX + SHLQ CL, R12 + SHRQ $0x08, CX + MOVB CL, 4(R11) - // exhausted += (br2.off < 4) - CMPQ AX, $0x04 - ADCB $+0, DL + // Reload the four bit containers + TZCNTQ SI, SI + MOVQ SI, CX + ANDQ $0x07, CX + SHRQ $0x03, SI + MOVQ (SP), R13 + SUBQ SI, R13 + MOVQ R13, (SP) + MOVQ (R13), SI + ORQ $0x01, SI + SHLQ CL, SI + TZCNTQ R8, R8 + MOVQ R8, CX + ANDQ $0x07, CX + SHRQ $0x03, R8 + MOVQ 8(SP), R13 + SUBQ R8, R13 + MOVQ R13, 8(SP) + MOVQ (R13), R8 + ORQ $0x01, R8 + SHLQ CL, R8 + TZCNTQ R10, R10 + MOVQ R10, CX + ANDQ $0x07, CX + SHRQ $0x03, R10 + MOVQ 16(SP), R13 + SUBQ R10, R13 + MOVQ R13, 16(SP) + MOVQ (R13), R10 + ORQ $0x01, R10 + SHLQ CL, R10 + TZCNTQ R12, R12 + MOVQ R12, CX + ANDQ $0x07, CX + SHRQ $0x03, R12 + MOVQ 24(SP), R13 + SUBQ R12, R13 + MOVQ R13, 24(SP) + MOVQ (R13), R12 + ORQ $0x01, R12 + SHLQ CL, R12 + ADDQ $0x05, BX + ADDQ $0x05, DI + ADDQ $0x05, R9 + ADDQ $0x05, R11 + CMPQ BX, 32(SP) + JB inner_loop + JMP outer_loop -skip_fill2: - // val0 := br2.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v0 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br2.advance(uint8(v0.entry) - MOVB CH, AL - SHLQ CL, R11 - ADDB CL, R12 - - // val1 := br2.peekTopBits(peekBits) - MOVQ DI, CX - MOVQ R11, R13 - SHRQ CL, R13 - - // v1 := table[val1&mask] - MOVW (R9)(R13*2), CX - - // br2.advance(uint8(v1.entry)) - MOVB CH, AH - SHLQ CL, R11 - ADDB CL, R12 - - // these two writes get coalesced - // out[id * dstEvery + 0] = uint8(v0.entry >> 8) - // out[id * dstEvery + 1] = uint8(v1.entry >> 8) - MOVW AX, (BX)(R8*2) - - // update the bitreader structure - MOVQ R11, 128(R10) - MOVB R12, 136(R10) - - // br3.fillFast32() - MOVQ 176(R10), R11 - MOVBQZX 184(R10), R12 - CMPQ R12, $0x20 - JBE skip_fill3 - MOVQ 168(R10), AX - SUBQ $0x20, R12 - SUBQ $0x04, AX - MOVQ 144(R10), R13 - - // b.value |= uint64(low) << (b.bitsRead & 63) - MOVL (AX)(R13*1), R13 - MOVQ R12, CX - SHLQ CL, R13 - MOVQ AX, 168(R10) - ORQ R13, R11 - - // exhausted += (br3.off < 4) - CMPQ AX, $0x04 - ADCB $+0, DL - -skip_fill3: - // val0 := br3.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v0 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br3.advance(uint8(v0.entry) - MOVB CH, AL - SHLQ CL, R11 - ADDB CL, R12 - - // val1 := br3.peekTopBits(peekBits) - MOVQ DI, CX - MOVQ R11, R13 - SHRQ CL, R13 - - // v1 := table[val1&mask] - MOVW (R9)(R13*2), CX - - // br3.advance(uint8(v1.entry)) - MOVB CH, AH - SHLQ CL, R11 - ADDB CL, R12 - - // these two writes get coalesced - // out[id * dstEvery + 0] = uint8(v0.entry >> 8) - // out[id * dstEvery + 1] = uint8(v1.entry >> 8) - LEAQ (R8)(R8*2), CX - MOVW AX, (BX)(CX*1) - - // update the bitreader structure - MOVQ R11, 176(R10) - MOVB R12, 184(R10) - ADDQ $0x02, BX - TESTB DL, DL - JZ main_loop - MOVQ ctx+0(FP), AX - SUBQ 16(AX), BX - SHLQ $0x02, BX - MOVQ BX, 40(AX) +done: + // Hand the state back: off = ip - in (negative when the window reached below the stream start), + // value = the sentinel-form container. bitReaderShifted.restoreFromAsm normalizes both. + MOVQ ctx+0(FP), AX + MOVQ (AX), CX + MOVQ (SP), DX + SUBQ (CX), DX + MOVQ DX, 24(CX) + MOVQ SI, 32(CX) + MOVQ 8(SP), DX + SUBQ 48(CX), DX + MOVQ DX, 72(CX) + MOVQ R8, 80(CX) + MOVQ 16(SP), DX + SUBQ 96(CX), DX + MOVQ DX, 120(CX) + MOVQ R10, 128(CX) + MOVQ 24(SP), DX + SUBQ 144(CX), DX + MOVQ DX, 168(CX) + MOVQ R12, 176(CX) + SUBQ 16(AX), BX + SHLQ $0x02, BX + MOVQ BX, 40(AX) RET // func decompress4x_8b_main_loop_amd64(ctx *decompress4xContext) -TEXT ·decompress4x_8b_main_loop_amd64(SB), $0-8 +// Requires: BMI, CMOV +TEXT ·decompress4x_8b_main_loop_amd64(SB), $40-8 + MOVQ ctx+0(FP), CX + // Preload values - MOVQ ctx+0(FP), CX - MOVBQZX 8(CX), DI + MOVBQZX 8(CX), AX + MOVQ 32(CX), DX MOVQ 16(CX), BX - MOVQ 48(CX), SI - MOVQ 24(CX), R8 - MOVQ 32(CX), R9 - MOVQ (CX), R10 - - // Main loop -main_loop: - XORL DX, DX - CMPQ BX, SI - SETGE DL - - // br0.fillFast32() - MOVQ 32(R10), R11 - MOVBQZX 40(R10), R12 - CMPQ R12, $0x20 - JBE skip_fill0 - MOVQ 24(R10), R13 - SUBQ $0x20, R12 - SUBQ $0x04, R13 - MOVQ (R10), R14 - - // b.value |= uint64(low) << (b.bitsRead & 63) - MOVL (R13)(R14*1), R14 - MOVQ R12, CX - SHLQ CL, R14 - MOVQ R13, 24(R10) - ORQ R14, R11 - - // exhausted += (br0.off < 4) - CMPQ R13, $0x04 - ADCB $+0, DL - -skip_fill0: - // val0 := br0.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v0 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br0.advance(uint8(v0.entry) - MOVB CH, AL - SHLQ CL, R11 - ADDB CL, R12 - - // val1 := br0.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v1 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br0.advance(uint8(v1.entry) - MOVB CH, AH - SHLQ CL, R11 - ADDB CL, R12 - BSWAPL AX - - // val2 := br0.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v2 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br0.advance(uint8(v2.entry) - MOVB CH, AH - SHLQ CL, R11 - ADDB CL, R12 - - // val3 := br0.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v3 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br0.advance(uint8(v3.entry) - MOVB CH, AL - SHLQ CL, R11 - ADDB CL, R12 - BSWAPL AX - - // these four writes get coalesced - // out[id * dstEvery + 0] = uint8(v0.entry >> 8) - // out[id * dstEvery + 1] = uint8(v1.entry >> 8) - // out[id * dstEvery + 3] = uint8(v2.entry >> 8) - // out[id * dstEvery + 4] = uint8(v3.entry >> 8) - MOVL AX, (BX) - - // update the bitreader structure - MOVQ R11, 32(R10) - MOVB R12, 40(R10) - - // br1.fillFast32() - MOVQ 80(R10), R11 - MOVBQZX 88(R10), R12 - CMPQ R12, $0x20 - JBE skip_fill1 - MOVQ 72(R10), R13 - SUBQ $0x20, R12 - SUBQ $0x04, R13 - MOVQ 48(R10), R14 - - // b.value |= uint64(low) << (b.bitsRead & 63) - MOVL (R13)(R14*1), R14 - MOVQ R12, CX - SHLQ CL, R14 - MOVQ R13, 72(R10) - ORQ R14, R11 - - // exhausted += (br1.off < 4) - CMPQ R13, $0x04 - ADCB $+0, DL - -skip_fill1: - // val0 := br1.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v0 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br1.advance(uint8(v0.entry) - MOVB CH, AL - SHLQ CL, R11 - ADDB CL, R12 - - // val1 := br1.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v1 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br1.advance(uint8(v1.entry) - MOVB CH, AH - SHLQ CL, R11 - ADDB CL, R12 - BSWAPL AX - - // val2 := br1.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v2 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br1.advance(uint8(v2.entry) - MOVB CH, AH - SHLQ CL, R11 - ADDB CL, R12 - - // val3 := br1.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v3 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br1.advance(uint8(v3.entry) - MOVB CH, AL - SHLQ CL, R11 - ADDB CL, R12 - BSWAPL AX - - // these four writes get coalesced - // out[id * dstEvery + 0] = uint8(v0.entry >> 8) - // out[id * dstEvery + 1] = uint8(v1.entry >> 8) - // out[id * dstEvery + 3] = uint8(v2.entry >> 8) - // out[id * dstEvery + 4] = uint8(v3.entry >> 8) - MOVL AX, (BX)(R8*1) - - // update the bitreader structure - MOVQ R11, 80(R10) - MOVB R12, 88(R10) - - // br2.fillFast32() - MOVQ 128(R10), R11 - MOVBQZX 136(R10), R12 - CMPQ R12, $0x20 - JBE skip_fill2 - MOVQ 120(R10), R13 - SUBQ $0x20, R12 - SUBQ $0x04, R13 - MOVQ 96(R10), R14 - - // b.value |= uint64(low) << (b.bitsRead & 63) - MOVL (R13)(R14*1), R14 - MOVQ R12, CX - SHLQ CL, R14 - MOVQ R13, 120(R10) - ORQ R14, R11 - - // exhausted += (br2.off < 4) - CMPQ R13, $0x04 - ADCB $+0, DL - -skip_fill2: - // val0 := br2.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v0 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br2.advance(uint8(v0.entry) - MOVB CH, AL - SHLQ CL, R11 - ADDB CL, R12 - - // val1 := br2.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v1 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br2.advance(uint8(v1.entry) - MOVB CH, AH - SHLQ CL, R11 - ADDB CL, R12 - BSWAPL AX - - // val2 := br2.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v2 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br2.advance(uint8(v2.entry) - MOVB CH, AH - SHLQ CL, R11 - ADDB CL, R12 - - // val3 := br2.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v3 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br2.advance(uint8(v3.entry) - MOVB CH, AL - SHLQ CL, R11 - ADDB CL, R12 - BSWAPL AX - - // these four writes get coalesced - // out[id * dstEvery + 0] = uint8(v0.entry >> 8) - // out[id * dstEvery + 1] = uint8(v1.entry >> 8) - // out[id * dstEvery + 3] = uint8(v2.entry >> 8) - // out[id * dstEvery + 4] = uint8(v3.entry >> 8) - MOVL AX, (BX)(R8*2) - - // update the bitreader structure - MOVQ R11, 128(R10) - MOVB R12, 136(R10) - - // br3.fillFast32() - MOVQ 176(R10), R11 - MOVBQZX 184(R10), R12 - CMPQ R12, $0x20 - JBE skip_fill3 - MOVQ 168(R10), R13 - SUBQ $0x20, R12 - SUBQ $0x04, R13 - MOVQ 144(R10), R14 - - // b.value |= uint64(low) << (b.bitsRead & 63) - MOVL (R13)(R14*1), R14 - MOVQ R12, CX - SHLQ CL, R14 - MOVQ R13, 168(R10) - ORQ R14, R11 - - // exhausted += (br3.off < 4) - CMPQ R13, $0x04 - ADCB $+0, DL - -skip_fill3: - // val0 := br3.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v0 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br3.advance(uint8(v0.entry) - MOVB CH, AL - SHLQ CL, R11 - ADDB CL, R12 - - // val1 := br3.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v1 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br3.advance(uint8(v1.entry) - MOVB CH, AH - SHLQ CL, R11 - ADDB CL, R12 - BSWAPL AX - - // val2 := br3.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v2 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br3.advance(uint8(v2.entry) - MOVB CH, AH - SHLQ CL, R11 - ADDB CL, R12 - - // val3 := br3.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v3 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br3.advance(uint8(v3.entry) - MOVB CH, AL - SHLQ CL, R11 - ADDB CL, R12 - BSWAPL AX - - // these four writes get coalesced - // out[id * dstEvery + 0] = uint8(v0.entry >> 8) - // out[id * dstEvery + 1] = uint8(v1.entry >> 8) - // out[id * dstEvery + 3] = uint8(v2.entry >> 8) - // out[id * dstEvery + 4] = uint8(v3.entry >> 8) - LEAQ (R8)(R8*2), CX - MOVL AX, (BX)(CX*1) - - // update the bitreader structure - MOVQ R11, 176(R10) - MOVB R12, 184(R10) - ADDQ $0x04, BX - TESTB DL, DL - JZ main_loop - MOVQ ctx+0(FP), AX - SUBQ 16(AX), BX - SHLQ $0x02, BX - MOVQ BX, 40(AX) + MOVQ 24(CX), SI + LEAQ (BX)(SI*1), DI + LEAQ (BX)(SI*2), R9 + LEAQ (SI)(SI*2), R11 + ADDQ BX, R11 + + // Copy the input pointers to their stack slots + MOVQ 64(CX), SI + MOVQ SI, (SP) + MOVQ 72(CX), SI + MOVQ SI, 8(SP) + MOVQ 80(CX), SI + MOVQ SI, 16(SP) + MOVQ 88(CX), SI + MOVQ SI, 24(SP) + + // Convert each bit reader to sentinel form: bits = value | 1< 8. +// of Decompress4X when tablelog > 8, decoding fastSymbols symbols per +// stream between bit container reloads. // //go:noescape func decompress4x_main_loop_arm64(ctx *decompress4xContext) // decompress4x_8b_main_loop_arm64 is an arm64 assembler implementation -// of Decompress4X when tablelog <= 8 which decodes 4 entries -// per loop. +// of Decompress4X when tablelog <= 8, decoding fast8bSymbols symbols +// per stream between bit container reloads. // //go:noescape func decompress4x_8b_main_loop_arm64(ctx *decompress4xContext) +// decompress4x_4b_main_loop_arm64 is an arm64 assembler implementation +// of Decompress4X when tablelog <= 4, decoding fast4bSymbols symbols +// per stream between bit container reloads. +// +//go:noescape +func decompress4x_4b_main_loop_arm64(ctx *decompress4xContext) + // decompress1x_main_loop_arm64 is an arm64 assembler implementation -// of Decompress1X when tablelog > 8. +// of Decompress1X when tablelog > 8, decoding fastSymbols symbols +// between bit container reloads. // //go:noescape func decompress1x_main_loop_arm64(ctx *decompress1xContext) +// decompress1x_8b_main_loop_arm64 is an arm64 assembler implementation +// of Decompress1X when tablelog <= 8, decoding fast8bSymbols symbols +// between bit container reloads. +// +//go:noescape +func decompress1x_8b_main_loop_arm64(ctx *decompress1xContext) + +// decompress1x_4b_main_loop_arm64 is an arm64 assembler implementation +// of Decompress1X when tablelog <= 4, decoding fast4bSymbols symbols +// between bit container reloads. +// +//go:noescape +func decompress1x_4b_main_loop_arm64(ctx *decompress1xContext) + func decompress4x_main_loop_asm(ctx *decompress4xContext) { decompress4x_main_loop_arm64(ctx) } @@ -32,6 +55,18 @@ func decompress4x_8b_main_loop_asm(ctx *decompress4xContext) { decompress4x_8b_main_loop_arm64(ctx) } +func decompress4x_4b_main_loop_asm(ctx *decompress4xContext) { + decompress4x_4b_main_loop_arm64(ctx) +} + func decompress1x_main_loop_asm(ctx *decompress1xContext) { decompress1x_main_loop_arm64(ctx) } + +func decompress1x_8b_main_loop_asm(ctx *decompress1xContext) { + decompress1x_8b_main_loop_arm64(ctx) +} + +func decompress1x_4b_main_loop_asm(ctx *decompress1xContext) { + decompress1x_4b_main_loop_arm64(ctx) +} diff --git a/vendor/github.com/klauspost/compress/huff0/decompress_arm64.s b/vendor/github.com/klauspost/compress/huff0/decompress_arm64.s index e160127..d853dee 100644 --- a/vendor/github.com/klauspost/compress/huff0/decompress_arm64.s +++ b/vendor/github.com/klauspost/compress/huff0/decompress_arm64.s @@ -1,295 +1,302 @@ -// Code generated by command: go run gen.go -out ../decompress.s -arch amd64,arm64 -pkg=huff0. DO NOT EDIT. +// Code generated by command: go run gen.go -out ../decompress.s -arch amd64,arm64 -arm64-promote-stack-slots -pkg=huff0. DO NOT EDIT. // EXPERIMENTAL arm64 output lowered from an amd64 avo program. -//go:build arm64 && !appengine && !noasm && gc +//go:build arm64 && (!noasm && gc) // func decompress4x_main_loop_amd64(ctx *decompress4xContext) -TEXT ·decompress4x_main_loop_arm64(SB), $0-8 +// Requires: BMI, CMOV +TEXT ·decompress4x_main_loop_arm64(SB), $40-8 + MOVD ctx+0(FP), R1 + // Preload values - MOVD ctx+0(FP), R0 - MOVBU 8(R0), R6 - MOVD 16(R0), R3 - MOVD 48(R0), R5 - MOVD 24(R0), R7 - MOVD 32(R0), R8 - MOVD (R0), R9 + MOVBU 8(R1), R0 + MOVD 32(R1), R2 + MOVD 16(R1), R3 + MOVD 24(R1), R5 + ADD R5, R3, R6 + ADD R5<<1, R3, R8 + ADD R5<<1, R5, R10 + ADD R3, R10, R10 - // Main loop -main_loop: - MOVD $0, R2 - CMP R5, R3 - CSET GE, R16 - BFI $0, R16, $8, R2 + // Copy the input pointers to their stack slots + MOVD 64(R1), R19 + MOVD 72(R1), R20 + MOVD 80(R1), R21 + MOVD 88(R1), R22 - // br0.fillFast32() - MOVD 32(R9), R10 - MOVBU 40(R9), R11 - CMP $0x20, R11 - BLS skip_fill0 - MOVD 24(R9), R0 - SUB $0x20, R11, R11 - SUB $0x04, R0, R0 - MOVD (R9), R12 + // Convert each bit reader to sentinel form: bits = value | 1<> 8) - // out[id * dstEvery + 1] = uint8(v1.entry >> 8) - MOVH R0, (R3) + // stream 1, symbol 1 + LSR R0, R7, R12 + MOVHU (R2)(R12<<1), R1 + LSL R1, R7, R7 + LSR $0x08, R1, R1 + MOVB R1, 1(R6) - // update the bitreader structure - MOVD R10, 32(R9) - MOVB R11, 40(R9) + // stream 2, symbol 1 + LSR R0, R9, R12 + MOVHU (R2)(R12<<1), R1 + LSL R1, R9, R9 + LSR $0x08, R1, R1 + MOVB R1, 1(R8) - // br1.fillFast32() - MOVD 80(R9), R10 - MOVBU 88(R9), R11 - CMP $0x20, R11 - BLS skip_fill1 - MOVD 72(R9), R0 - SUB $0x20, R11, R11 - SUB $0x04, R0, R0 - MOVD 48(R9), R12 + // stream 3, symbol 1 + LSR R0, R11, R12 + MOVHU (R2)(R12<<1), R1 + LSL R1, R11, R11 + LSR $0x08, R1, R1 + MOVB R1, 1(R10) - // b.value |= uint64(low) << (b.bitsRead & 63) - ADD R12, R0, R15 - MOVWU (R15), R12 - MOVD R11, R1 - LSL R1, R12, R12 - MOVD R0, 72(R9) - ORR R12, R10, R10 + // stream 0, symbol 2 + LSR R0, R5, R12 + MOVHU (R2)(R12<<1), R1 + LSL R1, R5, R5 + LSR $0x08, R1, R1 + MOVB R1, 2(R3) - // exhausted += (br1.off < 4) - CMP $0x04, R0 - CSINC HS, R2, R2, R16 - BFI $0, R16, $8, R2 + // stream 1, symbol 2 + LSR R0, R7, R12 + MOVHU (R2)(R12<<1), R1 + LSL R1, R7, R7 + LSR $0x08, R1, R1 + MOVB R1, 2(R6) -skip_fill1: - // val0 := br1.peekTopBits(peekBits) - MOVD R10, R12 - MOVD R6, R1 - LSR R1, R12, R12 + // stream 2, symbol 2 + LSR R0, R9, R12 + MOVHU (R2)(R12<<1), R1 + LSL R1, R9, R9 + LSR $0x08, R1, R1 + MOVB R1, 2(R8) - // v0 := table[val0&mask] - ADD R12<<1, R8, R15 - MOVHU (R15), R1 + // stream 3, symbol 2 + LSR R0, R11, R12 + MOVHU (R2)(R12<<1), R1 + LSL R1, R11, R11 + LSR $0x08, R1, R1 + MOVB R1, 2(R10) - // br1.advance(uint8(v0.entry) - UBFX $8, R1, $8, R16 - BFI $0, R16, $8, R0 - LSL R1, R10, R10 - ADD R1, R11, R15 - BFI $0, R15, $8, R11 + // stream 0, symbol 3 + LSR R0, R5, R12 + MOVHU (R2)(R12<<1), R1 + LSL R1, R5, R5 + LSR $0x08, R1, R1 + MOVB R1, 3(R3) - // val1 := br1.peekTopBits(peekBits) - MOVD R6, R1 - MOVD R10, R12 - LSR R1, R12, R12 + // stream 1, symbol 3 + LSR R0, R7, R12 + MOVHU (R2)(R12<<1), R1 + LSL R1, R7, R7 + LSR $0x08, R1, R1 + MOVB R1, 3(R6) - // v1 := table[val1&mask] - ADD R12<<1, R8, R15 - MOVHU (R15), R1 + // stream 2, symbol 3 + LSR R0, R9, R12 + MOVHU (R2)(R12<<1), R1 + LSL R1, R9, R9 + LSR $0x08, R1, R1 + MOVB R1, 3(R8) - // br1.advance(uint8(v1.entry)) - UBFX $8, R1, $8, R16 - BFI $8, R16, $8, R0 - LSL R1, R10, R10 - ADD R1, R11, R15 - BFI $0, R15, $8, R11 + // stream 3, symbol 3 + LSR R0, R11, R12 + MOVHU (R2)(R12<<1), R1 + LSL R1, R11, R11 + LSR $0x08, R1, R1 + MOVB R1, 3(R10) - // these two writes get coalesced - // out[id * dstEvery + 0] = uint8(v0.entry >> 8) - // out[id * dstEvery + 1] = uint8(v1.entry >> 8) - ADD R7, R3, R15 - MOVH R0, (R15) + // stream 0, symbol 4 + LSR R0, R5, R12 + MOVHU (R2)(R12<<1), R1 + LSL R1, R5, R5 + LSR $0x08, R1, R1 + MOVB R1, 4(R3) - // update the bitreader structure - MOVD R10, 80(R9) - MOVB R11, 88(R9) + // stream 1, symbol 4 + LSR R0, R7, R12 + MOVHU (R2)(R12<<1), R1 + LSL R1, R7, R7 + LSR $0x08, R1, R1 + MOVB R1, 4(R6) - // br2.fillFast32() - MOVD 128(R9), R10 - MOVBU 136(R9), R11 - CMP $0x20, R11 - BLS skip_fill2 - MOVD 120(R9), R0 - SUB $0x20, R11, R11 - SUB $0x04, R0, R0 - MOVD 96(R9), R12 + // stream 2, symbol 4 + LSR R0, R9, R12 + MOVHU (R2)(R12<<1), R1 + LSL R1, R9, R9 + LSR $0x08, R1, R1 + MOVB R1, 4(R8) - // b.value |= uint64(low) << (b.bitsRead & 63) - ADD R12, R0, R15 - MOVWU (R15), R12 - MOVD R11, R1 - LSL R1, R12, R12 - MOVD R0, 120(R9) - ORR R12, R10, R10 + // stream 3, symbol 4 + LSR R0, R11, R12 + MOVHU (R2)(R12<<1), R1 + LSL R1, R11, R11 + LSR $0x08, R1, R1 + MOVB R1, 4(R10) - // exhausted += (br2.off < 4) - CMP $0x04, R0 - CSINC HS, R2, R2, R16 - BFI $0, R16, $8, R2 + // Reload the four bit containers + RBIT R5, R5 + CLZ R5, R5 + MOVD R5, R1 + AND $0x07, R1, R1 + LSR $0x03, R5, R5 + SUB R5, R19, R19 + MOVD (R19), R5 + ORR $0x01, R5, R5 + LSL R1, R5, R5 + RBIT R7, R7 + CLZ R7, R7 + MOVD R7, R1 + AND $0x07, R1, R1 + LSR $0x03, R7, R7 + SUB R7, R20, R20 + MOVD (R20), R7 + ORR $0x01, R7, R7 + LSL R1, R7, R7 + RBIT R9, R9 + CLZ R9, R9 + MOVD R9, R1 + AND $0x07, R1, R1 + LSR $0x03, R9, R9 + SUB R9, R21, R21 + MOVD (R21), R9 + ORR $0x01, R9, R9 + LSL R1, R9, R9 + RBIT R11, R11 + CLZ R11, R11 + MOVD R11, R1 + AND $0x07, R1, R1 + LSR $0x03, R11, R11 + SUB R11, R22, R22 + MOVD (R22), R11 + ORR $0x01, R11, R11 + LSL R1, R11, R11 + ADD $0x05, R3, R3 + ADD $0x05, R6, R6 + ADD $0x05, R8, R8 + ADD $0x05, R10, R10 + CMP R23, R3 + BLO inner_loop + JMP outer_loop -skip_fill2: - // val0 := br2.peekTopBits(peekBits) - MOVD R10, R12 - MOVD R6, R1 - LSR R1, R12, R12 - - // v0 := table[val0&mask] - ADD R12<<1, R8, R15 - MOVHU (R15), R1 - - // br2.advance(uint8(v0.entry) - UBFX $8, R1, $8, R16 - BFI $0, R16, $8, R0 - LSL R1, R10, R10 - ADD R1, R11, R15 - BFI $0, R15, $8, R11 - - // val1 := br2.peekTopBits(peekBits) - MOVD R6, R1 - MOVD R10, R12 - LSR R1, R12, R12 - - // v1 := table[val1&mask] - ADD R12<<1, R8, R15 - MOVHU (R15), R1 - - // br2.advance(uint8(v1.entry)) - UBFX $8, R1, $8, R16 - BFI $8, R16, $8, R0 - LSL R1, R10, R10 - ADD R1, R11, R15 - BFI $0, R15, $8, R11 - - // these two writes get coalesced - // out[id * dstEvery + 0] = uint8(v0.entry >> 8) - // out[id * dstEvery + 1] = uint8(v1.entry >> 8) - ADD R7<<1, R3, R15 - MOVH R0, (R15) - - // update the bitreader structure - MOVD R10, 128(R9) - MOVB R11, 136(R9) - - // br3.fillFast32() - MOVD 176(R9), R10 - MOVBU 184(R9), R11 - CMP $0x20, R11 - BLS skip_fill3 - MOVD 168(R9), R0 - SUB $0x20, R11, R11 - SUB $0x04, R0, R0 - MOVD 144(R9), R12 - - // b.value |= uint64(low) << (b.bitsRead & 63) - ADD R12, R0, R15 - MOVWU (R15), R12 - MOVD R11, R1 - LSL R1, R12, R12 - MOVD R0, 168(R9) - ORR R12, R10, R10 - - // exhausted += (br3.off < 4) - CMP $0x04, R0 - CSINC HS, R2, R2, R16 - BFI $0, R16, $8, R2 - -skip_fill3: - // val0 := br3.peekTopBits(peekBits) - MOVD R10, R12 - MOVD R6, R1 - LSR R1, R12, R12 - - // v0 := table[val0&mask] - ADD R12<<1, R8, R15 - MOVHU (R15), R1 - - // br3.advance(uint8(v0.entry) - UBFX $8, R1, $8, R16 - BFI $0, R16, $8, R0 - LSL R1, R10, R10 - ADD R1, R11, R15 - BFI $0, R15, $8, R11 - - // val1 := br3.peekTopBits(peekBits) - MOVD R6, R1 - MOVD R10, R12 - LSR R1, R12, R12 - - // v1 := table[val1&mask] - ADD R12<<1, R8, R15 - MOVHU (R15), R1 - - // br3.advance(uint8(v1.entry)) - UBFX $8, R1, $8, R16 - BFI $8, R16, $8, R0 - LSL R1, R10, R10 - ADD R1, R11, R15 - BFI $0, R15, $8, R11 - - // these two writes get coalesced - // out[id * dstEvery + 0] = uint8(v0.entry >> 8) - // out[id * dstEvery + 1] = uint8(v1.entry >> 8) - ADD R7<<1, R7, R1 - ADD R1, R3, R15 - MOVH R0, (R15) - - // update the bitreader structure - MOVD R10, 176(R9) - MOVB R11, 184(R9) - ADD $0x02, R3, R3 - AND $0xff, R2, R15 - AND $0xff, R2, R16 - TST R16, R15 - BEQ main_loop +done: + // Hand the state back: off = ip - in (negative when the window reached below the stream start), + // value = the sentinel-form container. bitReaderShifted.restoreFromAsm normalizes both. MOVD ctx+0(FP), R0 + MOVD (R0), R1 + MOVD (R1), R16 + SUB R16, R19, R19 + MOVD R19, 24(R1) + MOVD R5, 32(R1) + MOVD 48(R1), R16 + SUB R16, R20, R20 + MOVD R20, 72(R1) + MOVD R7, 80(R1) + MOVD 96(R1), R16 + SUB R16, R21, R21 + MOVD R21, 120(R1) + MOVD R9, 128(R1) + MOVD 144(R1), R16 + SUB R16, R22, R22 + MOVD R22, 168(R1) + MOVD R11, 176(R1) MOVD 16(R0), R16 SUB R16, R3, R3 LSL $0x02, R3, R3 @@ -297,555 +304,1345 @@ skip_fill3: RET // func decompress4x_8b_main_loop_amd64(ctx *decompress4xContext) -TEXT ·decompress4x_8b_main_loop_arm64(SB), $0-8 +// Requires: BMI, CMOV +TEXT ·decompress4x_8b_main_loop_arm64(SB), $40-8 + MOVD ctx+0(FP), R1 + // Preload values - MOVD ctx+0(FP), R1 - MOVBU 8(R1), R6 + MOVBU 8(R1), R0 + MOVD 32(R1), R2 MOVD 16(R1), R3 - MOVD 48(R1), R5 - MOVD 24(R1), R7 - MOVD 32(R1), R8 - MOVD (R1), R9 - - // Main loop -main_loop: - MOVD $0, R2 - CMP R5, R3 - CSET GE, R16 - BFI $0, R16, $8, R2 - - // br0.fillFast32() - MOVD 32(R9), R10 - MOVBU 40(R9), R11 - CMP $0x20, R11 - BLS skip_fill0 - MOVD 24(R9), R12 - SUB $0x20, R11, R11 - SUB $0x04, R12, R12 - MOVD (R9), R13 - - // b.value |= uint64(low) << (b.bitsRead & 63) - ADD R13, R12, R15 - MOVWU (R15), R13 - MOVD R11, R1 - LSL R1, R13, R13 - MOVD R12, 24(R9) - ORR R13, R10, R10 - - // exhausted += (br0.off < 4) - CMP $0x04, R12 - CSINC HS, R2, R2, R16 - BFI $0, R16, $8, R2 - -skip_fill0: - // val0 := br0.peekTopBits(peekBits) - MOVD R10, R12 - MOVD R6, R1 - LSR R1, R12, R12 - - // v0 := table[val0&mask] - ADD R12<<1, R8, R15 - MOVHU (R15), R1 - - // br0.advance(uint8(v0.entry) - UBFX $8, R1, $8, R16 - BFI $0, R16, $8, R0 - LSL R1, R10, R10 - ADD R1, R11, R15 - BFI $0, R15, $8, R11 - - // val1 := br0.peekTopBits(peekBits) - MOVD R10, R12 - MOVD R6, R1 - LSR R1, R12, R12 - - // v1 := table[val0&mask] - ADD R12<<1, R8, R15 - MOVHU (R15), R1 - - // br0.advance(uint8(v1.entry) - UBFX $8, R1, $8, R16 - BFI $8, R16, $8, R0 - LSL R1, R10, R10 - ADD R1, R11, R15 - BFI $0, R15, $8, R11 - REVW R0, R0 - - // val2 := br0.peekTopBits(peekBits) - MOVD R10, R12 - MOVD R6, R1 - LSR R1, R12, R12 - - // v2 := table[val0&mask] - ADD R12<<1, R8, R15 - MOVHU (R15), R1 - - // br0.advance(uint8(v2.entry) - UBFX $8, R1, $8, R16 - BFI $8, R16, $8, R0 - LSL R1, R10, R10 - ADD R1, R11, R15 - BFI $0, R15, $8, R11 - - // val3 := br0.peekTopBits(peekBits) - MOVD R10, R12 - MOVD R6, R1 - LSR R1, R12, R12 - - // v3 := table[val0&mask] - ADD R12<<1, R8, R15 - MOVHU (R15), R1 - - // br0.advance(uint8(v3.entry) - UBFX $8, R1, $8, R16 - BFI $0, R16, $8, R0 - LSL R1, R10, R10 - ADD R1, R11, R15 - BFI $0, R15, $8, R11 - REVW R0, R0 - - // these four writes get coalesced - // out[id * dstEvery + 0] = uint8(v0.entry >> 8) - // out[id * dstEvery + 1] = uint8(v1.entry >> 8) - // out[id * dstEvery + 3] = uint8(v2.entry >> 8) - // out[id * dstEvery + 4] = uint8(v3.entry >> 8) - MOVW R0, (R3) - - // update the bitreader structure - MOVD R10, 32(R9) - MOVB R11, 40(R9) - - // br1.fillFast32() - MOVD 80(R9), R10 - MOVBU 88(R9), R11 - CMP $0x20, R11 - BLS skip_fill1 - MOVD 72(R9), R12 - SUB $0x20, R11, R11 - SUB $0x04, R12, R12 - MOVD 48(R9), R13 - - // b.value |= uint64(low) << (b.bitsRead & 63) - ADD R13, R12, R15 - MOVWU (R15), R13 - MOVD R11, R1 - LSL R1, R13, R13 - MOVD R12, 72(R9) - ORR R13, R10, R10 - - // exhausted += (br1.off < 4) - CMP $0x04, R12 - CSINC HS, R2, R2, R16 - BFI $0, R16, $8, R2 - -skip_fill1: - // val0 := br1.peekTopBits(peekBits) - MOVD R10, R12 - MOVD R6, R1 - LSR R1, R12, R12 - - // v0 := table[val0&mask] - ADD R12<<1, R8, R15 - MOVHU (R15), R1 - - // br1.advance(uint8(v0.entry) - UBFX $8, R1, $8, R16 - BFI $0, R16, $8, R0 - LSL R1, R10, R10 - ADD R1, R11, R15 - BFI $0, R15, $8, R11 - - // val1 := br1.peekTopBits(peekBits) - MOVD R10, R12 - MOVD R6, R1 - LSR R1, R12, R12 - - // v1 := table[val0&mask] - ADD R12<<1, R8, R15 - MOVHU (R15), R1 - - // br1.advance(uint8(v1.entry) - UBFX $8, R1, $8, R16 - BFI $8, R16, $8, R0 - LSL R1, R10, R10 - ADD R1, R11, R15 - BFI $0, R15, $8, R11 - REVW R0, R0 - - // val2 := br1.peekTopBits(peekBits) - MOVD R10, R12 - MOVD R6, R1 - LSR R1, R12, R12 - - // v2 := table[val0&mask] - ADD R12<<1, R8, R15 - MOVHU (R15), R1 - - // br1.advance(uint8(v2.entry) - UBFX $8, R1, $8, R16 - BFI $8, R16, $8, R0 - LSL R1, R10, R10 - ADD R1, R11, R15 - BFI $0, R15, $8, R11 - - // val3 := br1.peekTopBits(peekBits) - MOVD R10, R12 - MOVD R6, R1 - LSR R1, R12, R12 - - // v3 := table[val0&mask] - ADD R12<<1, R8, R15 - MOVHU (R15), R1 - - // br1.advance(uint8(v3.entry) - UBFX $8, R1, $8, R16 - BFI $0, R16, $8, R0 - LSL R1, R10, R10 - ADD R1, R11, R15 - BFI $0, R15, $8, R11 - REVW R0, R0 - - // these four writes get coalesced - // out[id * dstEvery + 0] = uint8(v0.entry >> 8) - // out[id * dstEvery + 1] = uint8(v1.entry >> 8) - // out[id * dstEvery + 3] = uint8(v2.entry >> 8) - // out[id * dstEvery + 4] = uint8(v3.entry >> 8) - ADD R7, R3, R15 - MOVW R0, (R15) - - // update the bitreader structure - MOVD R10, 80(R9) - MOVB R11, 88(R9) - - // br2.fillFast32() - MOVD 128(R9), R10 - MOVBU 136(R9), R11 - CMP $0x20, R11 - BLS skip_fill2 - MOVD 120(R9), R12 - SUB $0x20, R11, R11 - SUB $0x04, R12, R12 - MOVD 96(R9), R13 - - // b.value |= uint64(low) << (b.bitsRead & 63) - ADD R13, R12, R15 - MOVWU (R15), R13 - MOVD R11, R1 - LSL R1, R13, R13 - MOVD R12, 120(R9) - ORR R13, R10, R10 - - // exhausted += (br2.off < 4) - CMP $0x04, R12 - CSINC HS, R2, R2, R16 - BFI $0, R16, $8, R2 - -skip_fill2: - // val0 := br2.peekTopBits(peekBits) - MOVD R10, R12 - MOVD R6, R1 - LSR R1, R12, R12 - - // v0 := table[val0&mask] - ADD R12<<1, R8, R15 - MOVHU (R15), R1 - - // br2.advance(uint8(v0.entry) - UBFX $8, R1, $8, R16 - BFI $0, R16, $8, R0 - LSL R1, R10, R10 - ADD R1, R11, R15 - BFI $0, R15, $8, R11 - - // val1 := br2.peekTopBits(peekBits) - MOVD R10, R12 - MOVD R6, R1 - LSR R1, R12, R12 - - // v1 := table[val0&mask] - ADD R12<<1, R8, R15 - MOVHU (R15), R1 - - // br2.advance(uint8(v1.entry) - UBFX $8, R1, $8, R16 - BFI $8, R16, $8, R0 - LSL R1, R10, R10 - ADD R1, R11, R15 - BFI $0, R15, $8, R11 - REVW R0, R0 - - // val2 := br2.peekTopBits(peekBits) - MOVD R10, R12 - MOVD R6, R1 - LSR R1, R12, R12 - - // v2 := table[val0&mask] - ADD R12<<1, R8, R15 - MOVHU (R15), R1 - - // br2.advance(uint8(v2.entry) - UBFX $8, R1, $8, R16 - BFI $8, R16, $8, R0 - LSL R1, R10, R10 - ADD R1, R11, R15 - BFI $0, R15, $8, R11 - - // val3 := br2.peekTopBits(peekBits) - MOVD R10, R12 - MOVD R6, R1 - LSR R1, R12, R12 - - // v3 := table[val0&mask] - ADD R12<<1, R8, R15 - MOVHU (R15), R1 - - // br2.advance(uint8(v3.entry) - UBFX $8, R1, $8, R16 - BFI $0, R16, $8, R0 - LSL R1, R10, R10 - ADD R1, R11, R15 - BFI $0, R15, $8, R11 - REVW R0, R0 - - // these four writes get coalesced - // out[id * dstEvery + 0] = uint8(v0.entry >> 8) - // out[id * dstEvery + 1] = uint8(v1.entry >> 8) - // out[id * dstEvery + 3] = uint8(v2.entry >> 8) - // out[id * dstEvery + 4] = uint8(v3.entry >> 8) - ADD R7<<1, R3, R15 - MOVW R0, (R15) - - // update the bitreader structure - MOVD R10, 128(R9) - MOVB R11, 136(R9) - - // br3.fillFast32() - MOVD 176(R9), R10 - MOVBU 184(R9), R11 - CMP $0x20, R11 - BLS skip_fill3 - MOVD 168(R9), R12 - SUB $0x20, R11, R11 - SUB $0x04, R12, R12 - MOVD 144(R9), R13 - - // b.value |= uint64(low) << (b.bitsRead & 63) - ADD R13, R12, R15 - MOVWU (R15), R13 - MOVD R11, R1 - LSL R1, R13, R13 - MOVD R12, 168(R9) - ORR R13, R10, R10 - - // exhausted += (br3.off < 4) - CMP $0x04, R12 - CSINC HS, R2, R2, R16 - BFI $0, R16, $8, R2 - -skip_fill3: - // val0 := br3.peekTopBits(peekBits) - MOVD R10, R12 - MOVD R6, R1 - LSR R1, R12, R12 - - // v0 := table[val0&mask] - ADD R12<<1, R8, R15 - MOVHU (R15), R1 - - // br3.advance(uint8(v0.entry) - UBFX $8, R1, $8, R16 - BFI $0, R16, $8, R0 - LSL R1, R10, R10 - ADD R1, R11, R15 - BFI $0, R15, $8, R11 - - // val1 := br3.peekTopBits(peekBits) - MOVD R10, R12 - MOVD R6, R1 - LSR R1, R12, R12 - - // v1 := table[val0&mask] - ADD R12<<1, R8, R15 - MOVHU (R15), R1 - - // br3.advance(uint8(v1.entry) - UBFX $8, R1, $8, R16 - BFI $8, R16, $8, R0 - LSL R1, R10, R10 - ADD R1, R11, R15 - BFI $0, R15, $8, R11 - REVW R0, R0 - - // val2 := br3.peekTopBits(peekBits) - MOVD R10, R12 - MOVD R6, R1 - LSR R1, R12, R12 - - // v2 := table[val0&mask] - ADD R12<<1, R8, R15 - MOVHU (R15), R1 - - // br3.advance(uint8(v2.entry) - UBFX $8, R1, $8, R16 - BFI $8, R16, $8, R0 - LSL R1, R10, R10 - ADD R1, R11, R15 - BFI $0, R15, $8, R11 - - // val3 := br3.peekTopBits(peekBits) - MOVD R10, R12 - MOVD R6, R1 - LSR R1, R12, R12 - - // v3 := table[val0&mask] - ADD R12<<1, R8, R15 - MOVHU (R15), R1 - - // br3.advance(uint8(v3.entry) - UBFX $8, R1, $8, R16 - BFI $0, R16, $8, R0 - LSL R1, R10, R10 - ADD R1, R11, R15 - BFI $0, R15, $8, R11 - REVW R0, R0 - - // these four writes get coalesced - // out[id * dstEvery + 0] = uint8(v0.entry >> 8) - // out[id * dstEvery + 1] = uint8(v1.entry >> 8) - // out[id * dstEvery + 3] = uint8(v2.entry >> 8) - // out[id * dstEvery + 4] = uint8(v3.entry >> 8) - ADD R7<<1, R7, R1 - ADD R1, R3, R15 - MOVW R0, (R15) - - // update the bitreader structure - MOVD R10, 176(R9) - MOVB R11, 184(R9) - ADD $0x04, R3, R3 - AND $0xff, R2, R15 - AND $0xff, R2, R16 - TST R16, R15 - BEQ main_loop + MOVD 24(R1), R5 + ADD R5, R3, R6 + ADD R5<<1, R3, R8 + ADD R5<<1, R5, R10 + ADD R3, R10, R10 + + // Copy the input pointers to their stack slots + MOVD 64(R1), R19 + MOVD 72(R1), R20 + MOVD 80(R1), R21 + MOVD 88(R1), R22 + + // Convert each bit reader to sentinel form: bits = value | 1< 4*4 && !(br[0].off < 4 || br[1].off < 4 || br[2].off < 4 || br[3].off < 4) { + nSyms := fastSymbols + if d.actualTableLog <= 4 { + nSyms = fast4bSymbols + } else if use8BitTables { + nSyms = fast8bSymbols + } + // The asm writes nSyms bytes per stream per iteration and only re-checks + // its bounds between batches of iterations (the batch size is derived + // from limit in _generate/gen.go), so stream 0 must stop early enough + // that stream 3 (which may be up to 3 bytes shorter than dstEvery) + // never writes past the end of out. Every stream needs a full 8-byte + // window ahead of its read pointer to enter the loop. + if limit := dstEvery - nSyms - 2; limit > 0 && br[0].canUseAsm() && br[1].canUseAsm() && br[2].canUseAsm() && br[3].canUseAsm() { + for i := range br { + br[i].prepareForAsm() + } ctx := decompress4xContext{ pbr: &br, peekBits: uint8((64 - d.actualTableLog) & 63), // see: bitReaderShifted.peekBitsFast() out: &out[0], dstEvery: dstEvery, tbl: &single[0], - limit: &out[dstEvery-4], // Always stop decoding when first buffer gets here to avoid writing OOB on last. + limit: &out[limit], + // The 6-byte jump table sits below stream 0 inside src, so the + // lowest window may reach into it; restoreFromAsm accounts for + // bytes below a stream's start. Bounding by src rather than by + // stream 0 keeps the asm running about six bytes longer, which + // matters for streams with very short codes. + ilowest: &src[0], } - if use8BitTables { + for i := range br { + ctx.ip[i] = &br[i].in[br[i].off] + } + switch nSyms { + case fast4bSymbols: + decompress4x_4b_main_loop_asm(&ctx) + case fast8bSymbols: decompress4x_8b_main_loop_asm(&ctx) - } else { + default: decompress4x_main_loop_asm(&ctx) } decoded = ctx.decoded out = out[decoded/4:] + for i := range br { + if err := br[i].restoreFromAsm(); err != nil { + return nil, err + } + } } // Decode remaining. @@ -128,18 +174,20 @@ func (d *Decoder) Decompress4X(dst, src []byte) ([]byte, error) { return dst, nil } +// decompress1xContext is the argument block of the Decompress1X asm loops. +// Go fills every field but decoded; the asm advances ip, and on return +// leaves the bit reader in the form bitReaderShifted.restoreFromAsm expects. type decompress1xContext struct { pbr *bitReaderShifted peekBits uint8 out *byte - outCap int + outCap int // no write reaches out[outCap] tbl *dEntrySingle decoded int + ilowest *byte // start of the stream; no read goes below it + ip *byte // the 8-byte input window, advanced by the asm } -// Error reported by asm implementations -const error_max_decoded_size_exeeded = -1 - // Decompress1X will decompress a 1X encoded stream. // The cap of the output buffer will be the maximum decompressed size. // The length of the supplied input must match the end of a block exactly. @@ -158,25 +206,36 @@ func (d *Decoder) Decompress1X(dst, src []byte) ([]byte, error) { const tlSize = 1 << tableLogMax const tlMask = tlSize - 1 - if maxDecodedSize >= 4 { + // The asm decodes whole batches of symbols and only re-checks its + // bounds between them, so it needs at least one batch of room (the + // output bound rounds nSyms up to 16, see _generate/gen.go) and a full + // 8-byte window ahead of the read pointer to enter the loop. It also + // needs at most 7 bits consumed on entry so that a batch cannot run + // the container dry, which prepareForAsm establishes. + decoded := 0 + if maxDecodedSize >= 16 && br.canUseAsm() { + br.prepareForAsm() ctx := decompress1xContext{ pbr: &br, out: &dst[0], outCap: maxDecodedSize, peekBits: uint8((64 - d.actualTableLog) & 63), // see: bitReaderShifted.peekBitsFast() tbl: &d.dt.single[0], + ilowest: &src[0], + ip: &br.in[br.off], } - - decompress1x_main_loop_asm(&ctx) - if ctx.decoded == error_max_decoded_size_exeeded { - return nil, ErrMaxDecodedSizeExceeded + if d.actualTableLog <= 4 { + decompress1x_4b_main_loop_asm(&ctx) + } else if d.actualTableLog <= 8 { + decompress1x_8b_main_loop_asm(&ctx) + } else { + decompress1x_main_loop_asm(&ctx) } - - dst = dst[:ctx.decoded] + decoded = ctx.decoded } + dst = dst[:decoded] - // br < 8, so uint8 is fine - bitsLeft := uint8(br.off)*8 + 64 - br.bitsRead + bitsLeft := br.remaining() for bitsLeft > 0 { br.fill() if len(dst) >= maxDecodedSize { @@ -186,7 +245,7 @@ func (d *Decoder) Decompress1X(dst, src []byte) ([]byte, error) { v := d.dt.single[br.peekBitsFast(d.actualTableLog)&tlMask] nBits := uint8(v.entry) br.advance(nBits) - bitsLeft -= nBits + bitsLeft -= uint(nBits) dst = append(dst, uint8(v.entry>>8)) } return dst, br.close() diff --git a/vendor/github.com/klauspost/compress/huff0/decompress_generic.go b/vendor/github.com/klauspost/compress/huff0/decompress_generic.go index e1bca5c..d258786 100644 --- a/vendor/github.com/klauspost/compress/huff0/decompress_generic.go +++ b/vendor/github.com/klauspost/compress/huff0/decompress_generic.go @@ -1,4 +1,4 @@ -//go:build (!amd64 && !arm64) || appengine || !gc || noasm +//go:build (!amd64 && !arm64) || !gc || noasm // This file contains a generic implementation of Decoder.Decompress4X. package huff0 @@ -57,64 +57,44 @@ func (d *Decoder) Decompress4X(dst, src []byte) ([]byte, error) { var off uint8 var decoded int - // Decode 2 values from each decoder/loop. + // Decode 4 values from each stream per loop. Each stream is refilled + // with one branch-free load, which leaves at least 57 bits: enough for + // 4 symbols of up to tableLogMax bits. A refill moves back at most + // 6 bytes, so off >= 8 keeps it in range. const bufoff = 256 - for { - if br[0].off < 4 || br[1].off < 4 || br[2].off < 4 || br[3].off < 4 { - break - } + tab := (*[tlSize]dEntrySingle)(single) + peek := 64 - d.actualTableLog + in0, in1, in2, in3 := br[0].in, br[1].in, br[2].in, br[3].in + s0, s1, s2, s3 := br[0].state(), br[1].state(), br[2].state(), br[3].state() + for s0.off >= 8 && s1.off >= 8 && s2.off >= 8 && s3.off >= 8 { + s0, s1, s2, s3 = s0.refill(in0), s1.refill(in1), s2.refill(in2), s3.refill(in3) + var v0, v1, v2, v3 uint8 - { - const stream = 0 - const stream2 = 1 - br[stream].fillFast() - br[stream2].fillFast() + s0, v0 = s0.decode(tab, peek) + s1, v1 = s1.decode(tab, peek) + s2, v2 = s2.decode(tab, peek) + s3, v3 = s3.decode(tab, peek) + buf[0][off], buf[1][off], buf[2][off], buf[3][off] = v0, v1, v2, v3 - val := br[stream].peekBitsFast(d.actualTableLog) - val2 := br[stream2].peekBitsFast(d.actualTableLog) - v := single[val&tlMask] - v2 := single[val2&tlMask] - br[stream].advance(uint8(v.entry)) - br[stream2].advance(uint8(v2.entry)) - buf[stream][off] = uint8(v.entry >> 8) - buf[stream2][off] = uint8(v2.entry >> 8) + s0, v0 = s0.decode(tab, peek) + s1, v1 = s1.decode(tab, peek) + s2, v2 = s2.decode(tab, peek) + s3, v3 = s3.decode(tab, peek) + buf[0][off+1], buf[1][off+1], buf[2][off+1], buf[3][off+1] = v0, v1, v2, v3 - val = br[stream].peekBitsFast(d.actualTableLog) - val2 = br[stream2].peekBitsFast(d.actualTableLog) - v = single[val&tlMask] - v2 = single[val2&tlMask] - br[stream].advance(uint8(v.entry)) - br[stream2].advance(uint8(v2.entry)) - buf[stream][off+1] = uint8(v.entry >> 8) - buf[stream2][off+1] = uint8(v2.entry >> 8) - } + s0, v0 = s0.decode(tab, peek) + s1, v1 = s1.decode(tab, peek) + s2, v2 = s2.decode(tab, peek) + s3, v3 = s3.decode(tab, peek) + buf[0][off+2], buf[1][off+2], buf[2][off+2], buf[3][off+2] = v0, v1, v2, v3 - { - const stream = 2 - const stream2 = 3 - br[stream].fillFast() - br[stream2].fillFast() + s0, v0 = s0.decode(tab, peek) + s1, v1 = s1.decode(tab, peek) + s2, v2 = s2.decode(tab, peek) + s3, v3 = s3.decode(tab, peek) + buf[0][off+3], buf[1][off+3], buf[2][off+3], buf[3][off+3] = v0, v1, v2, v3 - val := br[stream].peekBitsFast(d.actualTableLog) - val2 := br[stream2].peekBitsFast(d.actualTableLog) - v := single[val&tlMask] - v2 := single[val2&tlMask] - br[stream].advance(uint8(v.entry)) - br[stream2].advance(uint8(v2.entry)) - buf[stream][off] = uint8(v.entry >> 8) - buf[stream2][off] = uint8(v2.entry >> 8) - - val = br[stream].peekBitsFast(d.actualTableLog) - val2 = br[stream2].peekBitsFast(d.actualTableLog) - v = single[val&tlMask] - v2 = single[val2&tlMask] - br[stream].advance(uint8(v.entry)) - br[stream2].advance(uint8(v2.entry)) - buf[stream][off+1] = uint8(v.entry >> 8) - buf[stream2][off+1] = uint8(v2.entry >> 8) - } - - off += 2 + off += 4 if off == 0 { if bufoff > dstEvery { @@ -126,10 +106,6 @@ func (d *Decoder) Decompress4X(dst, src []byte) ([]byte, error) { d.bufs.Put(buf) return nil, errors.New("corruption detected: stream overrun 2") } - //copy(out, buf[0][:]) - //copy(out[dstEvery:], buf[1][:]) - //copy(out[dstEvery*2:], buf[2][:]) - //copy(out[dstEvery*3:], buf[3][:]) *(*[bufoff]byte)(out) = buf[0] *(*[bufoff]byte)(out[dstEvery:]) = buf[1] *(*[bufoff]byte)(out[dstEvery*2:]) = buf[2] @@ -138,6 +114,10 @@ func (d *Decoder) Decompress4X(dst, src []byte) ([]byte, error) { decoded += bufoff * 4 } } + br[0].setState(s0) + br[1].setState(s1) + br[2].setState(s2) + br[3].setState(s3) if off > 0 { ioff := int(off) if len(out) < dstEvery*3+ioff { diff --git a/vendor/github.com/klauspost/compress/internal/cpuinfo/cpuinfo_amd64.go b/vendor/github.com/klauspost/compress/internal/cpuinfo/cpuinfo_amd64.go index b97f905..3d9e20f 100644 --- a/vendor/github.com/klauspost/compress/internal/cpuinfo/cpuinfo_amd64.go +++ b/vendor/github.com/klauspost/compress/internal/cpuinfo/cpuinfo_amd64.go @@ -1,4 +1,4 @@ -//go:build amd64 && !appengine && !noasm && gc +//go:build amd64 && !noasm && gc package cpuinfo diff --git a/vendor/github.com/klauspost/compress/internal/cpuinfo/cpuinfo_amd64.s b/vendor/github.com/klauspost/compress/internal/cpuinfo/cpuinfo_amd64.s index 4465fbe..f128c10 100644 --- a/vendor/github.com/klauspost/compress/internal/cpuinfo/cpuinfo_amd64.s +++ b/vendor/github.com/klauspost/compress/internal/cpuinfo/cpuinfo_amd64.s @@ -1,6 +1,4 @@ -// +build !appengine -// +build gc -// +build !noasm +//go:build !noasm && gc #include "textflag.h" #include "funcdata.h" diff --git a/vendor/github.com/klauspost/compress/internal/le/unsafe_disabled.go b/vendor/github.com/klauspost/compress/internal/le/unsafe_disabled.go index 4f2a0d8..787ec9e 100644 --- a/vendor/github.com/klauspost/compress/internal/le/unsafe_disabled.go +++ b/vendor/github.com/klauspost/compress/internal/le/unsafe_disabled.go @@ -1,4 +1,4 @@ -//go:build !(amd64 || arm64 || ppc64le || riscv64) || nounsafe || purego || appengine +//go:build !(amd64 || arm64 || ppc64le || riscv64) || nounsafe || purego package le diff --git a/vendor/github.com/klauspost/compress/internal/le/unsafe_enabled.go b/vendor/github.com/klauspost/compress/internal/le/unsafe_enabled.go index 218a38b..e60be81 100644 --- a/vendor/github.com/klauspost/compress/internal/le/unsafe_enabled.go +++ b/vendor/github.com/klauspost/compress/internal/le/unsafe_enabled.go @@ -1,6 +1,6 @@ // We enable 64 bit LE platforms: -//go:build (amd64 || arm64 || ppc64le || riscv64) && !nounsafe && !purego && !appengine +//go:build (amd64 || arm64 || ppc64le || riscv64) && !nounsafe && !purego package le diff --git a/vendor/github.com/klauspost/compress/internal/regmask/regmask.go b/vendor/github.com/klauspost/compress/internal/regmask/regmask.go new file mode 100644 index 0000000..3da49d1 --- /dev/null +++ b/vendor/github.com/klauspost/compress/internal/regmask/regmask.go @@ -0,0 +1,50 @@ +//go:build !386 + +// Package regmask provides masks for variable shift counts. +// +// Go defines a shift by more than the width of the shifted value as producing +// zero, so the compiler has to guard every variable shift against that: on +// amd64 with a CMP and an SBB, on arm64 with a CMP and a CSEL, and so on. When +// the count is known to be smaller than the width anyway, masking it with the +// width minus one lets the compiler drop the guard. The mask itself costs +// nothing on the architectures whose shift instructions already use only the +// low bits of the count, which the compiler knows about. +// +// Each constant is named for the width of the value being shifted and the type +// of the shift count, and may only be used where the count is always smaller +// than that width: +// +// x := y >> (n & regmask.Shift64ByUint) // y is 64 bits, n is a uint below 64 +package regmask + +const ( + // ShiftNByUint8 - shifting an N bit value by a uint8 + Shift8ByUint8 = 7 + Shift16ByUint8 = 15 + Shift32ByUint8 = 31 + Shift64ByUint8 = 63 + + // ShiftNByUint16 - shifting an N bit value by a uint16 + Shift8ByUint16 = Shift8ByUint8 + Shift16ByUint16 = Shift16ByUint8 + Shift32ByUint16 = Shift32ByUint8 + Shift64ByUint16 = Shift64ByUint8 + + // ShiftNByUint32 - shifting an N bit value by a uint32 + Shift8ByUint32 = Shift8ByUint8 + Shift16ByUint32 = Shift16ByUint8 + Shift32ByUint32 = Shift32ByUint8 + Shift64ByUint32 = Shift64ByUint8 + + // ShiftNByUint64 - shifting an N bit value by a uint64 + Shift8ByUint64 = Shift8ByUint8 + Shift16ByUint64 = Shift16ByUint8 + Shift32ByUint64 = Shift32ByUint8 + Shift64ByUint64 = Shift64ByUint8 + + // ShiftNByUint - shifting an N bit value by a uint + Shift8ByUint = Shift8ByUint8 + Shift16ByUint = Shift16ByUint8 + Shift32ByUint = Shift32ByUint8 + Shift64ByUint = Shift64ByUint8 +) diff --git a/vendor/github.com/klauspost/compress/internal/regmask/regmask_386.go b/vendor/github.com/klauspost/compress/internal/regmask/regmask_386.go new file mode 100644 index 0000000..ff15f7c --- /dev/null +++ b/vendor/github.com/klauspost/compress/internal/regmask/regmask_386.go @@ -0,0 +1,39 @@ +//go:build 386 + +package regmask + +// A 64 bit shift on 386 is synthesized from 32 bit instructions, and masking its +// count makes the compiler emit more code rather than less, so those masks are +// no-ops here: each is the largest value its count type can hold, which the +// compiler folds away. Shifts of narrower values behave as elsewhere. +const ( + // ShiftNByUint8 - shifting an N bit value by a uint8 + Shift8ByUint8 = 7 + Shift16ByUint8 = 15 + Shift32ByUint8 = 31 + Shift64ByUint8 = 0xff + + // ShiftNByUint16 - shifting an N bit value by a uint16 + Shift8ByUint16 = Shift8ByUint8 + Shift16ByUint16 = Shift16ByUint8 + Shift32ByUint16 = Shift32ByUint8 + Shift64ByUint16 = 0xffff + + // ShiftNByUint32 - shifting an N bit value by a uint32 + Shift8ByUint32 = Shift8ByUint8 + Shift16ByUint32 = Shift16ByUint8 + Shift32ByUint32 = Shift32ByUint8 + Shift64ByUint32 = 0xffffffff + + // ShiftNByUint64 - shifting an N bit value by a uint64 + Shift8ByUint64 = Shift8ByUint8 + Shift16ByUint64 = Shift16ByUint8 + Shift32ByUint64 = Shift32ByUint8 + Shift64ByUint64 = 0xffffffffffffffff + + // ShiftNByUint - shifting an N bit value by a uint + Shift8ByUint = Shift8ByUint8 + Shift16ByUint = Shift16ByUint8 + Shift32ByUint = Shift32ByUint8 + Shift64ByUint = ^uint(0) +) diff --git a/vendor/github.com/klauspost/compress/zstd/README.md b/vendor/github.com/klauspost/compress/zstd/README.md index a5aeeae..9687b42 100644 --- a/vendor/github.com/klauspost/compress/zstd/README.md +++ b/vendor/github.com/klauspost/compress/zstd/README.md @@ -102,6 +102,15 @@ Each non-first job receives an overlap prefix from the previous job for match co so compression ratio is only marginally affected. Output is flushed in order, producing a valid single-frame zstd stream. +A job is four windows long, at least 512 KiB and at most 256 MiB, so even +large windows (`WithWindowSize`) split the input into several jobs. For windows +of 128 MiB and up this trades some total CPU time and a little ratio for much +lower wall time and peak memory. On the benchmark corpora, output at the best +level with a 256 MiB window grew by under 0.5%; the loss depends on the input. +The overlap is at most half a job, so at the best level with windows over +256 MiB each job sees less of the previous data than the window allows, and the +loss may be larger. + Benchmark on 1.8GB GOB stream (AMD Ryzen 9 9950X): | Level | 1 thread | 4 threads | 16 threads | 1T ratio | 16T ratio | @@ -359,7 +368,7 @@ It is possible to use `WithDecoderConcurrency(0)` to create GOMAXPROCS decoders. Data compressed with [dictionaries](https://github.com/facebook/zstd#the-case-for-small-data-compression) can be decompressed. Dictionaries are added individually to Decoders. -Dictionaries are generated by the `zstd --train` command and contains an initial state for the decoder. +Dictionaries are generated by the `zstd --train` command or `dict.BuildZstdDict` and contain an initial state for the decoder. To add a dictionary use the `WithDecoderDicts(dicts ...[]byte)` option with the dictionary data. Several dictionaries can be added at once. @@ -375,9 +384,13 @@ and it will likely be used even if it doesn't improve compression. The used dictionary must be used to decompress the content. +Arbitrary content can be used as a raw dictionary with `WithEncoderDictRaw(id uint32, content []byte)` and `WithDecoderDictRaw(id uint32, content []byte)`. +The content is used as initial history, and the decoder must register the same ID and content. + For any real gains, the dictionary should be built with similar data. If an unsuitable dictionary is used the output may be slightly larger than using no dictionary. Use the [zstd commandline tool](https://github.com/facebook/zstd/releases) to build a dictionary from sample data. +The *experimental* [dictionary builder](https://github.com/klauspost/compress/tree/master/dict) can also build one in Go with `dict.BuildZstdDict`, or a raw dictionary with `dict.BuildRawDict`. For information see [zstd dictionary information](https://github.com/facebook/zstd#the-case-for-small-data-compression). For now there is a fixed startup performance penalty for compressing content with dictionaries. diff --git a/vendor/github.com/klauspost/compress/zstd/bitreader.go b/vendor/github.com/klauspost/compress/zstd/bitreader.go index d41e3e1..10cece3 100644 --- a/vendor/github.com/klauspost/compress/zstd/bitreader.go +++ b/vendor/github.com/klauspost/compress/zstd/bitreader.go @@ -11,6 +11,7 @@ import ( "math/bits" "github.com/klauspost/compress/internal/le" + "github.com/klauspost/compress/internal/regmask" ) // bitReader reads a bitstream in reverse. @@ -64,17 +65,6 @@ func (b *bitReader) get32BitsFast(n uint8) uint32 { return v } -// fillFast() will make sure at least 32 bits are available. -// There must be at least 4 bytes available. -func (b *bitReader) fillFast() { - if b.bitsRead < 32 { - return - } - b.cursor -= 4 - b.value = (b.value << 32) | uint64(le.Load32(b.in, b.cursor)) - b.bitsRead -= 32 -} - // fillFastStart() assumes the bitreader is empty and there is at least 8 bytes to read. func (b *bitReader) fillFastStart() { b.cursor -= 8 @@ -101,6 +91,57 @@ func (b *bitReader) fill() { } } +// bitReadState is the part of a bitReader that changes while reading. +// Decode loops hold it by value so it stays in registers. +type bitReadState struct { + value uint64 + cursor int + bitsRead uint8 +} + +func (b *bitReader) state() bitReadState { + return bitReadState{value: b.value, cursor: b.cursor, bitsRead: b.bitsRead} +} + +func (b *bitReader) setState(s bitReadState) { + b.value, b.cursor, b.bitsRead = s.value, s.cursor, s.bitsRead +} + +// getBits is bitReader.getBits. +func (s bitReadState) getBits(n uint8) (bitReadState, int) { + if n == 0 { + return s, 0 + } + s, v := s.get32BitsFast(n) + return s, int(v) +} + +// get32BitsFast is bitReader.get32BitsFast. +func (s bitReadState) get32BitsFast(n uint8) (bitReadState, uint32) { + v := uint32((s.value << (s.bitsRead & regmask.Shift64ByUint8)) >> ((64 - n) & regmask.Shift64ByUint8)) + s.bitsRead += n + return s, v +} + +// fill is bitReader.fill reading from in. +func (s bitReadState) fill(in []byte) bitReadState { + if s.bitsRead < 32 { + return s + } + if s.cursor >= 4 { + s.cursor -= 4 + s.value = (s.value << 32) | uint64(le.Load32(in, s.cursor)) + s.bitsRead -= 32 + return s + } + s.bitsRead -= uint8(8 * s.cursor) + for s.cursor > 0 { + s.cursor-- + s.value = (s.value << 8) | uint64(in[s.cursor]) + } + return s +} + // finished returns true if all bits have been read from the bit stream. func (b *bitReader) finished() bool { return b.cursor == 0 && b.bitsRead >= 64 diff --git a/vendor/github.com/klauspost/compress/zstd/bitwriter.go b/vendor/github.com/klauspost/compress/zstd/bitwriter.go index b22b297..668ac26 100644 --- a/vendor/github.com/klauspost/compress/zstd/bitwriter.go +++ b/vendor/github.com/klauspost/compress/zstd/bitwriter.go @@ -5,6 +5,45 @@ package zstd +import ( + "github.com/klauspost/compress/internal/le" + "github.com/klauspost/compress/internal/regmask" +) + +// bitState is a bit writer that stays in registers when passed and +// returned by value. It writes into a buffer owned by the caller. +type bitState struct { + c uint64 + nb uint + pos int +} + +// flush writes the whole bytes with one 8-byte store at pos, leaving +// at most 7 bits. buf must have 8 bytes of room at pos. +func (s bitState) flush(buf []byte) bitState { + le.Store64(buf, s.pos, s.c) + s.pos += int(s.nb >> 3) + s.c >>= (s.nb &^ 7) & regmask.Shift64ByUint + s.nb &= 7 + return s +} + +// add adds n bits from v, which must have no bits set above them. +// There must be room for them. +func (s bitState) add(v uint64, n uint) bitState { + s.c |= v << (s.nb & regmask.Shift64ByUint) + s.nb += n + return s +} + +// addState adds the bits that FSE-encode tt from state, and returns +// the next state from tab. +func (s bitState) addState(state uint16, tab []uint16, tt symbolTransform) (bitState, uint16) { + nbBitsOut := (uint32(state) + tt.deltaNbBits) >> 16 + s = s.add(uint64(state&bitMask16[nbBitsOut&31]), uint(nbBitsOut)) + return s, tab[int32(state>>(nbBitsOut®mask.Shift16ByUint32))+int32(tt.deltaFindState)] +} + // bitWriter will write bits. // First bit will be LSB of the first byte of output. type bitWriter struct { diff --git a/vendor/github.com/klauspost/compress/zstd/blockdec.go b/vendor/github.com/klauspost/compress/zstd/blockdec.go index 51f9da0..ba85a2e 100644 --- a/vendor/github.com/klauspost/compress/zstd/blockdec.go +++ b/vendor/github.com/klauspost/compress/zstd/blockdec.go @@ -39,7 +39,10 @@ const ( // maxCompressedBlockSize is the biggest allowed compressed block size (128KB) maxCompressedBlockSize = 128 << 10 - compressedBlockOverAlloc = 16 + // compressedBlockOverAlloc is the slack past the logical end that the + // assembly's extended copies may read and write. It must match the + // constant of the same name in _generate/gen.go. + compressedBlockOverAlloc = 32 maxCompressedBlockSizeAlloc = 128<<10 + compressedBlockOverAlloc // Maximum possible block size (all Raw+Uncompressed). @@ -240,9 +243,11 @@ func (b *blockDec) decodeBuf(hist *history) error { b.dst[i] = v } hist.appendKeep(b.dst) + hist.decoders.consumeSyncLen(len(b.dst)) return nil case blockTypeRaw: hist.appendKeep(b.data) + hist.decoders.consumeSyncLen(len(b.data)) return nil case blockTypeCompressed: saved := b.dst @@ -416,6 +421,8 @@ func (b *blockDec) decodeLiterals(in []byte, hist *history) (remain []byte, err if len(literals) != litRegenSize { return in, fmt.Errorf("literal output size mismatch want %d, got %d", litRegenSize, len(literals)) } + // Re-cap to get extra size. + literals = b.literalBuf[:len(literals)] case literalsBlockCompressed: if len(in) < litCompSize { @@ -487,10 +494,24 @@ func (b *blockDec) decodeCompressed(hist *history) error { } if hist.decoders.nSeqs == 0 { b.dst = append(b.dst, hist.decoders.literals...) + hist.decoders.consumeSyncLen(len(hist.decoders.literals)) return nil } before := len(hist.decoders.out) - err = hist.decoders.decodeSync(hist.b[hist.ignoreBuffer:]) + h := hist.b[hist.ignoreBuffer:] + if hist.ext != nil { + h = hist.ext + } + if hist.dict == nil && hist.decoders.useTwoPass() { + // Two passes, as the concurrent decoder does: knowing the offsets + // up front lets executeSimple prefetch match sources. + if err := b.decodeSequences(hist); err != nil { + return err + } + err = hist.decoders.executeSimple(b.sequence, h) + } else { + err = hist.decoders.decodeSync(h) + } if err != nil { return err } @@ -601,16 +622,11 @@ func (b *blockDec) prepareSequences(in []byte, hist *history) (err error) { if seq.fse == nil || seq.fse.preDefined { seq.fse = fseDecoderPool.Get().(*fseDecoder) } - err := seq.fse.readNCount(&br, uint16(maxTableSymbol[i])) + err := seq.fse.readNCount(&br, tableIndex(i)) if err != nil { println("Read table error:", err) return err } - err = seq.fse.transform(symbolTableX[i]) - if err != nil { - println("Transform table error:", err) - return err - } if debugDecoder { println("Read table ok", "symbolLen:", seq.fse.symbolLen) } @@ -670,38 +686,41 @@ func (b *blockDec) decodeSequences(hist *history) error { return err } +// executeSequences executes the block's sequences straight into the history +// ring, as decodeCompressed does, and copies the result to b.dst for output. func (b *blockDec) executeSequences(hist *history) error { - hbytes := hist.b - if len(hbytes) > hist.windowSize { - hbytes = hbytes[len(hbytes)-hist.windowSize:] - } + hist.ensureBlockRing() + start := len(hist.b) hist.decoders.windowSize = hist.windowSize - hist.decoders.out = b.dst[:0] - err := hist.decoders.execute(b.sequence, hbytes) + hist.decoders.out = hist.b + err := hist.decoders.execute(b.sequence, hist.ext) if err != nil { return err } - return b.updateHistory(hist) + return b.updateHistory(hist, start) } -func (b *blockDec) updateHistory(hist *history) error { +// updateHistory copies the block's output, which starts at out[start], to +// b.dst and keeps it as history. +func (b *blockDec) updateHistory(hist *history, start int) error { if len(b.data) > maxCompressedBlockSize { return fmt.Errorf("compressed block size too large (%d)", len(b.data)) } - // Set output and release references. - b.dst = hist.decoders.out + out := hist.decoders.out + b.dst = append(b.dst[:0], out[start:]...) hist.recentOffsets = hist.decoders.prevOffset if b.Last { // if last block we don't care about history. - println("Last block, no history returned") + if debugDecoder { + println("Last block, no history returned") + } hist.b = hist.b[:0] return nil - } else { - hist.append(b.dst) - if debugDecoder { - println("Finished block with ", len(b.sequence), "sequences. Added", len(b.dst), "to history, now length", len(hist.b)) - } + } + hist.b = out + if debugDecoder { + println("Finished block with ", len(b.sequence), "sequences. Added", len(b.dst), "to history, now length", len(hist.b)) } hist.decoders.out, hist.decoders.literals = nil, nil diff --git a/vendor/github.com/klauspost/compress/zstd/blockenc.go b/vendor/github.com/klauspost/compress/zstd/blockenc.go index 0e33aea..c8f833f 100644 --- a/vendor/github.com/klauspost/compress/zstd/blockenc.go +++ b/vendor/github.com/klauspost/compress/zstd/blockenc.go @@ -376,6 +376,7 @@ func (b *blockEnc) encodeLits(lits []byte, raw bool) error { lh.setSizes(len(out), len(lits), single) if len(out)+lh.size() >= len(lits) { err = huff0.ErrIncompressible + b.dropUnwrittenTable(reUsed) } } switch err { @@ -429,6 +430,15 @@ func (b *blockEnc) encodeLits(lits []byte, raw bool) error { return nil } +// dropUnwrittenTable stops later blocks reusing the literal table after +// compressed literals are written raw: a new table became the previous one, +// but the decoder never gets it. +func (b *blockEnc) dropUnwrittenTable(reUsed bool) { + if !reUsed { + b.litEnc.Reuse = huff0.ReusePolicyNone + } +} + // encodeRLE will encode an RLE block. func (b *blockEnc) encodeRLE(val byte, length uint32) { var bh blockHeader @@ -540,6 +550,7 @@ func (b *blockEnc) encode(org []byte, raw, rawAllLits bool) error { szComp := lh.size() if len(out)+szComp >= len(b.literals)+szRaw { err = huff0.ErrIncompressible + b.dropUnwrittenTable(reUsed) } } switch err { @@ -628,38 +639,6 @@ func (b *blockEnc) encode(org []byte, raw, rawAllLits bool) error { return err } - // Choose the best compression mode for each type. - // Will evaluate the new vs predefined and previous. - chooseComp := func(cur, prev, preDef *fseEncoder) (*fseEncoder, seqCompMode) { - // See if predefined/previous is better - hist := cur.count[:cur.symbolLen] - nSize := cur.approxSize(hist) + cur.maxHeaderSize() - predefSize := preDef.approxSize(hist) - prevSize := prev.approxSize(hist) - - // Add a small penalty for new encoders. - // Don't bother with extremely small (<2 byte gains). - nSize = nSize + (nSize+2*8*16)>>4 - switch { - case predefSize <= prevSize && predefSize <= nSize || forcePreDef: - if debugEncoder { - println("Using predefined", predefSize>>3, "<=", nSize>>3) - } - return preDef, compModePredefined - case prevSize <= nSize: - if debugEncoder { - println("Using previous", prevSize>>3, "<=", nSize>>3) - } - return prev, compModeRepeat - default: - if debugEncoder { - println("Using new, predef", predefSize>>3, ". previous:", prevSize>>3, ">", nSize>>3, "header max:", cur.maxHeaderSize()>>3, "bytes") - println("tl:", cur.actualTableLog, "symbolLen:", cur.symbolLen, "norm:", cur.norm[:cur.symbolLen], "hist", cur.count[:cur.symbolLen]) - } - return cur, compModeFSE - } - } - // Write compression mode var mode uint8 if llEnc.useRLE { @@ -670,7 +649,7 @@ func (b *blockEnc) encode(org []byte, raw, rawAllLits bool) error { } } else { var m seqCompMode - llEnc, m = chooseComp(llEnc, b.coders.llPrev, &fsePredefEnc[tableLiteralLengths]) + llEnc, m = b.chooseComp(llEnc, b.coders.llPrev, &fsePredefEnc[tableLiteralLengths]) mode |= uint8(m) << 6 } if ofEnc.useRLE { @@ -681,7 +660,7 @@ func (b *blockEnc) encode(org []byte, raw, rawAllLits bool) error { } } else { var m seqCompMode - ofEnc, m = chooseComp(ofEnc, b.coders.ofPrev, &fsePredefEnc[tableOffsets]) + ofEnc, m = b.chooseComp(ofEnc, b.coders.ofPrev, &fsePredefEnc[tableOffsets]) mode |= uint8(m) << 4 } @@ -693,7 +672,7 @@ func (b *blockEnc) encode(org []byte, raw, rawAllLits bool) error { } } else { var m seqCompMode - mlEnc, m = chooseComp(mlEnc, b.coders.mlPrev, &fsePredefEnc[tableMatchLengths]) + mlEnc, m = b.chooseComp(mlEnc, b.coders.mlPrev, &fsePredefEnc[tableMatchLengths]) mode |= uint8(m) << 2 } b.output = append(b.output, mode) @@ -753,54 +732,57 @@ func (b *blockEnc) encode(org []byte, raw, rawAllLits bool) error { println("Encoded seq", seq, s, "codes:", s.llCode, s.mlCode, s.ofCode, "states:", ll.state, ml.state, of.state, "bits:", llB, mlB, ofB) } seq-- - // Store sequences in reverse... + wr.flush32() + + // Store sequences in reverse, with the bit writer and states in locals. + // flush stores 8 bytes and advances by whole bytes, so each chunk + // checks room for seqMaxBytes per sequence plus the store's slack. + const seqMaxBytes = 12 // 26 state bits + 63 extra bits. + w := bitState{c: wr.bitContainer, nb: uint(wr.nBits), pos: len(wr.out)} + buf := wr.out[:cap(wr.out)] + ofState, mlState, llState := of.state, ml.state, ll.state + ofTab, mlTab, llTab := of.stateTable, ml.stateTable, ll.stateTable + seqs := b.sequences for seq >= 0 { - s = b.sequences[seq] - - ofB := ofTT[s.ofCode] - wr.flush32() // tablelog max is below 8 for each, so it will fill max 24 bits. - //of.encode(ofB) - nbBitsOut := (uint32(of.state) + ofB.deltaNbBits) >> 16 - dstState := int32(of.state>>(nbBitsOut&15)) + int32(ofB.deltaFindState) - wr.addBits16NC(of.state, uint8(nbBitsOut)) - of.state = of.stateTable[dstState] - - // Accumulate extra bits. - outBits := ofB.outBits & 31 - extraBits := uint64(s.offset & bitMask32[outBits]) - extraBitsN := outBits - - mlB := mlTT[s.mlCode] - //ml.encode(mlB) - nbBitsOut = (uint32(ml.state) + mlB.deltaNbBits) >> 16 - dstState = int32(ml.state>>(nbBitsOut&15)) + int32(mlB.deltaFindState) - wr.addBits16NC(ml.state, uint8(nbBitsOut)) - ml.state = ml.stateTable[dstState] - - outBits = mlB.outBits & 31 - extraBits = extraBits<> 16 - dstState = int32(ll.state>>(nbBitsOut&15)) + int32(llB.deltaFindState) - wr.addBits16NC(ll.state, uint8(nbBitsOut)) - ll.state = ll.stateTable[dstState] - - outBits = llB.outBits & 31 - extraBits = extraBits< stop; seq-- { + s := seqs[seq] + ofB, mlB, llB := ofTT[s.ofCode], mlTT[s.mlCode], llTT[s.llCode] - seq-- + // w.nb <= 37 here, and the states add at most 26 bits. + w, ofState = w.addState(ofState, ofTab, ofB) + w, mlState = w.addState(mlState, mlTab, mlB) + w, llState = w.addState(llState, llTab, llB) + + ofBits, mlBits, llBits := ofB.outBits&31, mlB.outBits&31, llB.outBits&31 + extra := uint64(s.offset&bitMask32[ofBits])<<(mlBits+llBits) | + uint64(s.matchLen&bitMask32[mlBits])< 63 { + w = w.flush(buf) + if extraN > 56 { + // Only offsets over 24 bits get here. + low := uint(mlBits + llBits) + w = w.add(extra&(1<>= low + extraN -= low + } + } + w = w.add(extra, extraN).flush(buf) + + if debugSequences { + println("Encoded seq", seq, s) + } + } } + wr.bitContainer, wr.nBits, wr.out = w.c, uint8(w.nb), buf[:w.pos] + of.state, ml.state, ll.state = ofState, mlState, llState ml.flush(mlEnc.actualTableLog) of.flush(ofEnc.actualTableLog) ll.flush(llEnc.actualTableLog) @@ -826,6 +808,54 @@ func (b *blockEnc) encode(org []byte, raw, rawAllLits bool) error { return nil } +// chooseComp chooses the cheapest of the new, predefined and previous table. +func (b *blockEnc) chooseComp(cur, prev, preDef *fseEncoder) (*fseEncoder, seqCompMode) { + hist := cur.count[:cur.symbolLen] + nSize := cur.approxSize(hist) + cur.maxHeaderSize() + predefSize := preDef.approxSize(hist) + prevSize := prev.approxSize(hist) + + // Add a small penalty for new encoders. + // Don't bother with extremely small (<2 byte gains). + nSize = nSize + (nSize+2*8*16)>>4 + // The previous table may come from a dictionary and fit poorly, + // so it is compared against the exact header size, without penalty. + nSizePrev := nSize + if prevSize != math.MaxUint32 { + // Written to spare capacity; the real header goes there later. + if hdr, err := cur.writeCount(b.output[len(b.output):]); err == nil { + nSizePrev = cur.approxSize(hist) + uint32(len(hdr))*8 + } + } + // Each stream ends with a flush of tableLog bits. + nSize += uint32(cur.actualTableLog) + nSizePrev += uint32(cur.actualTableLog) + if predefSize != math.MaxUint32 { + predefSize += uint32(preDef.actualTableLog) + } + if prevSize != math.MaxUint32 { + prevSize += uint32(prev.actualTableLog) + } + switch { + case predefSize <= prevSize && predefSize <= nSize || forcePreDef: + if debugEncoder { + println("Using predefined", predefSize>>3, "<=", nSize>>3) + } + return preDef, compModePredefined + case prevSize <= nSizePrev: + if debugEncoder { + println("Using previous", prevSize>>3, "<=", nSizePrev>>3) + } + return prev, compModeRepeat + default: + if debugEncoder { + println("Using new, predef", predefSize>>3, ". previous:", prevSize>>3, ">", nSize>>3, "header max:", cur.maxHeaderSize()>>3, "bytes") + println("tl:", cur.actualTableLog, "symbolLen:", cur.symbolLen, "norm:", cur.norm[:cur.symbolLen], "hist", cur.count[:cur.symbolLen]) + } + return cur, compModeFSE + } +} + var errIncompressible = errors.New("incompressible") func (b *blockEnc) genCodes() { diff --git a/vendor/github.com/klauspost/compress/zstd/decoder.go b/vendor/github.com/klauspost/compress/zstd/decoder.go index c7e500f..a830713 100644 --- a/vendor/github.com/klauspost/compress/zstd/decoder.go +++ b/vendor/github.com/klauspost/compress/zstd/decoder.go @@ -7,8 +7,12 @@ package zstd import ( "context" "encoding/binary" + "errors" "io" + "maps" + "math" "sync" + "sync/atomic" "github.com/klauspost/compress/zstd/internal/xxhash" ) @@ -20,7 +24,8 @@ import ( // A decoder can safely be re-used even if the previous stream failed. // To release the resources, you must call the Close() function on a decoder. type Decoder struct { - o decoderOptions + // publishedOptions contains the current immutable decoder options. + publishedOptions atomic.Pointer[decoderOptions] // Unreferenced decoders, ready for use. decoders chan *blockDec @@ -84,9 +89,10 @@ var ( func NewReader(r io.Reader, opts ...DOption) (*Decoder, error) { initPredefined() var d Decoder - d.o.setDefault() - for _, o := range opts { - err := o(&d.o) + var o decoderOptions + o.setDefault() + for _, opt := range opts { + err := opt(&o) if err != nil { return nil, err } @@ -99,17 +105,19 @@ func NewReader(r io.Reader, opts ...DOption) (*Decoder, error) { } // Initialize dict map if needed. - if d.o.dicts == nil { - d.o.dicts = make(map[uint32]*dict) + if o.dicts == nil { + o.dicts = make(map[uint32]*dict) } // Create decoders - d.decoders = make(chan *blockDec, d.o.concurrent) - for i := 0; i < d.o.concurrent; i++ { - dec := newBlockDec(d.o.lowMem) - dec.localFrame = newFrameDec(d.o) + d.decoders = make(chan *blockDec, o.concurrent) + for i := 0; i < o.concurrent; i++ { + dec := newBlockDec(o.lowMem) + dec.localFrame = newFrameDec(o) + dec.localFrame.o.dicts = nil d.decoders <- dec } + d.publishedOptions.Store(&o) if r == nil { return &d, nil @@ -171,6 +179,9 @@ func (d *Decoder) Reset(r io.Reader) error { d.drainOutput() d.syncStream.br.r = nil + if d.frame != nil { + d.frame.o.dicts = nil + } if r == nil { d.current.err = ErrDecoderNilInput if len(d.current.b) > 0 { @@ -180,8 +191,10 @@ func (d *Decoder) Reset(r io.Reader) error { return nil } + o := *d.publishedOptions.Load() + // If bytes buffer and < 5MB, do sync decoding anyway. - if bb, ok := r.(byter); ok && bb.Len() < d.o.decodeBufsBelow && !d.o.limitToCap { + if bb, ok := r.(byter); ok && bb.Len() < o.decodeBufsBelow && !o.limitToCap { bb2 := bb if debugDecoder { println("*bytes.Buffer detected, doing sync decode, len:", bb.Len()) @@ -193,18 +206,30 @@ func (d *Decoder) Reset(r io.Reader) error { } dst, err := d.DecodeAll(b, dst) - if err == nil { - err = io.EOF + if !errors.Is(err, ErrDecoderSizeExceeded) { + if err == nil { + err = io.EOF + } + // Save output buffer + d.syncStream.dstBuf = dst + d.current.b = dst + d.current.err = err + d.current.flushed = true + if debugDecoder { + println("sync decode to", len(dst), "bytes, err:", err) + } + return nil } - // Save output buffer - d.syncStream.dstBuf = dst - d.current.b = dst - d.current.err = err - d.current.flushed = true + // The output does not fit WithDecoderMaxMemory, which caps the total + // decoded size when decoding in memory. A Reader follows the + // streaming contract, where the option caps the window instead, so + // decode this input as a stream after all; the shortcut has not + // consumed the reader. Drop the oversized buffer rather than keep it + // for reuse. if debugDecoder { - println("sync decode to", len(dst), "bytes, err:", err) + println("sync decode exceeded max memory after", len(dst), "bytes; streaming instead") } - return nil + d.syncStream.dstBuf = nil } // Remove current block. d.stashDecoder() @@ -217,14 +242,16 @@ func (d *Decoder) Reset(r io.Reader) error { // Ensure no-one else is still running... d.streamWg.Wait() if d.frame == nil { - d.frame = newFrameDec(d.o) + d.frame = newFrameDec(o) + } else { + d.frame.setOptions(o) } - if d.o.concurrent == 1 { + if o.concurrent == 1 { return d.startSyncDecoder(r) } - d.current.output = make(chan decodeOutput, d.o.concurrent) + d.current.output = make(chan decodeOutput, o.concurrent) ctx, cancel := context.WithCancel(context.Background()) d.current.cancel = cancel d.streamWg.Add(1) @@ -238,13 +265,21 @@ func (d *Decoder) Reset(r io.Reader) error { // Options are applied on top of the existing options. // Some options cannot be changed on reset and will return an error. func (d *Decoder) ResetWithOptions(r io.Reader, opts ...DOption) error { - d.o.resetOpt = true - defer func() { d.o.resetOpt = false }() + if d.current.err == ErrDecoderClosed { + return d.current.err + } + next := *d.publishedOptions.Load() + next.dicts = maps.Clone(next.dicts) + next.resetOpt = true for _, o := range opts { - if err := o(&d.o); err != nil { + if err := o(&next); err != nil { + next.resetOpt = false + d.publishedOptions.Store(&next) return err } } + next.resetOpt = false + d.publishedOptions.Store(&next) return d.Reset(r) } @@ -324,17 +359,24 @@ func (d *Decoder) DecodeAll(input, dst []byte) ([]byte, error) { // Grab a block decoder and frame decoder. block := <-d.decoders frame := block.localFrame + o := *d.publishedOptions.Load() + frame.setOptions(o) initialSize := len(dst) defer func() { if debugDecoder { printf("re-adding decoder: %p", block) } + block.data = nil frame.rawInput = nil frame.bBuf = nil + frame.history.b = nil + frame.history.decoders.literals = nil + frame.history.decoders.out = nil if frame.history.decoders.br != nil { frame.history.decoders.br.in = nil frame.history.decoders.br.cursor = 0 } + frame.o.dicts = nil d.decoders <- block }() frame.bBuf = input @@ -354,40 +396,44 @@ func (d *Decoder) DecodeAll(input, dst []byte) ([]byte, error) { if err = d.setDict(frame); err != nil { return nil, err } - if frame.WindowSize > d.o.maxWindowSize { + if frame.WindowSize > frame.o.maxWindowSize { if debugDecoder { - println("window size exceeded:", frame.WindowSize, ">", d.o.maxWindowSize) + println("window size exceeded:", frame.WindowSize, ">", frame.o.maxWindowSize) } return dst, ErrWindowSizeExceeded } if frame.FrameContentSize != fcsUnknown { - if frame.FrameContentSize > d.o.maxDecodedSize-uint64(len(dst)-initialSize) { + if frame.FrameContentSize > frame.o.maxDecodedSize-uint64(len(dst)-initialSize) { if debugDecoder { - println("decoder size exceeded; fcs:", frame.FrameContentSize, "> mcs:", d.o.maxDecodedSize-uint64(len(dst)-initialSize), "len:", len(dst)) + println("decoder size exceeded; fcs:", frame.FrameContentSize, "> mcs:", frame.o.maxDecodedSize-uint64(len(dst)-initialSize), "len:", len(dst)) } return dst, ErrDecoderSizeExceeded } - if d.o.limitToCap && frame.FrameContentSize > uint64(cap(dst)-len(dst)) { + if frame.o.limitToCap && frame.FrameContentSize > uint64(cap(dst)-len(dst)) { if debugDecoder { println("decoder size exceeded; fcs:", frame.FrameContentSize, "> (cap-len)", cap(dst)-len(dst)) } return dst, ErrDecoderSizeExceeded } - if cap(dst)-len(dst) < int(frame.FrameContentSize) { - dst2 := make([]byte, len(dst), len(dst)+int(frame.FrameContentSize)+compressedBlockOverAlloc) + // The content size is only checked once the frame is decoded, so + // allocate no more than the rest of the input can decode to (each + // block is at least 4 bytes) and only what fits in an int. + size := min(frame.FrameContentSize, uint64(len(frame.bBuf))*(maxCompressedBlockSize/4)) + if size <= math.MaxInt-compressedBlockOverAlloc-uint64(len(dst)) && cap(dst)-len(dst) < int(size) { + dst2 := make([]byte, len(dst), len(dst)+int(size)+compressedBlockOverAlloc) copy(dst2, dst) dst = dst2 } } - if cap(dst) == 0 && !d.o.limitToCap { + if cap(dst) == 0 && !frame.o.limitToCap { // Allocate len(input) * 2 by default if nothing is provided // and we didn't get frame content size. size := min( // Cap to 1 MB. len(input)*2, 1<<20) - if uint64(size) > d.o.maxDecodedSize { - size = int(d.o.maxDecodedSize) + if uint64(size) > frame.o.maxDecodedSize { + size = int(frame.o.maxDecodedSize) } dst = make([]byte, 0, size) } @@ -396,7 +442,7 @@ func (d *Decoder) DecodeAll(input, dst []byte) ([]byte, error) { if err != nil { return dst, err } - if uint64(len(dst)-initialSize) > d.o.maxDecodedSize { + if uint64(len(dst)-initialSize) > frame.o.maxDecodedSize { return dst, ErrDecoderSizeExceeded } if len(frame.bBuf) == 0 { @@ -459,7 +505,7 @@ func (d *Decoder) nextBlock(blocking bool) (ok bool) { println("got", len(d.current.b), "bytes, error:", d.current.err, "data crc:", tmp) } - if d.o.ignoreChecksum { + if d.frame.o.ignoreChecksum { return true } @@ -497,7 +543,7 @@ func (d *Decoder) nextBlockSync() (ok bool) { if d.current.err != nil { return false } - if d.frame.WindowSize > d.o.maxDecodedSize || d.frame.WindowSize > d.o.maxWindowSize { + if d.frame.WindowSize > d.frame.o.maxDecodedSize || d.frame.WindowSize > d.frame.o.maxWindowSize { d.current.err = ErrDecoderSizeExceeded return false } @@ -509,7 +555,7 @@ func (d *Decoder) nextBlockSync() (ok bool) { if d.current.err != nil { return false } - d.frame.history.ensureBlock() + d.frame.history.ensureBlockRing() if debugDecoder { println("History trimmed:", len(d.frame.history.b), "decoded already:", d.syncStream.decodedFrame) } @@ -546,11 +592,11 @@ func (d *Decoder) nextBlockSync() (ok bool) { // Update/Check CRC if d.frame.HasCheckSum { - if !d.o.ignoreChecksum { + if !d.frame.o.ignoreChecksum { d.frame.crc.Write(d.current.b) } if d.current.d.Last { - if !d.o.ignoreChecksum { + if !d.frame.o.ignoreChecksum { d.current.err = d.frame.checkCRC() } else { d.current.err = d.frame.consumeCRC() @@ -656,8 +702,8 @@ func (d *Decoder) startStreamDecoder(ctx context.Context, r io.Reader, output ch defer d.streamWg.Done() br := readerWrapper{r: r} - var seqDecode = make(chan *blockDec, d.o.concurrent) - var seqExecute = make(chan *blockDec, d.o.concurrent) + var seqDecode = make(chan *blockDec, d.frame.o.concurrent) + var seqExecute = make(chan *blockDec, d.frame.o.concurrent) // Async 1: Decode sequences... go func() { @@ -714,7 +760,8 @@ func (d *Decoder) startStreamDecoder(ctx context.Context, r io.Reader, output ch wg.Add(1) // Async 3: Execute sequences... - frameHistCache := d.frame.history.b + // Reuse the history ring across streams. + frameRing := d.frame.history.ring go func() { var hist history var decodedFrame uint64 @@ -733,20 +780,12 @@ func (d *Decoder) startStreamDecoder(ctx context.Context, r io.Reader, output ch } hist.reset() hist.windowSize = block.async.newHist.windowSize - hist.allocFrameBuffer = block.async.newHist.allocFrameBuffer if block.async.newHist.dict != nil { hist.setDict(block.async.newHist.dict) } - - if cap(hist.b) < hist.allocFrameBuffer { - if cap(frameHistCache) >= hist.allocFrameBuffer { - hist.b = frameHistCache - } else { - hist.b = make([]byte, 0, hist.allocFrameBuffer) - println("Alloc history sized", hist.allocFrameBuffer) - } + if hist.ring == nil { + hist.ring = frameRing } - hist.b = hist.b[:0] fcs = block.async.fcs decodedFrame = 0 } @@ -769,13 +808,15 @@ func (d *Decoder) startStreamDecoder(ctx context.Context, r io.Reader, output ch for i := range block.dst { block.dst[i] = v } - hist.append(block.dst) + hist.ensureBlockRing() + hist.appendKeep(block.dst) do.b = block.dst case blockTypeRaw: if debugDecoder { println("add raw block length:", len(block.data)) } - hist.append(block.data) + hist.ensureBlockRing() + hist.appendKeep(block.data) do.b = block.data case blockTypeCompressed: if debugDecoder { @@ -808,7 +849,7 @@ func (d *Decoder) startStreamDecoder(ctx context.Context, r io.Reader, output ch output <- do } close(output) - frameHistCache = hist.b + frameRing = hist.ring wg.Done() if debugDecoder { println("decoder goroutines finished") @@ -858,9 +899,9 @@ decodeStream: if err == nil { err = d.setDict(frame) } - if err == nil && d.frame.WindowSize > d.o.maxWindowSize { + if err == nil && d.frame.WindowSize > d.frame.o.maxWindowSize { if debugDecoder { - println("decoder size exceeded, fws:", d.frame.WindowSize, "> mws:", d.o.maxWindowSize) + println("decoder size exceeded, fws:", d.frame.WindowSize, "> mws:", d.frame.o.maxWindowSize) } err = ErrDecoderSizeExceeded @@ -887,9 +928,6 @@ decodeStream: err := frame.next(dec) if !historySent { h := frame.history - if debugDecoder { - println("Alloc History:", h.allocFrameBuffer) - } hist.reset() if h.dict != nil { hist.setDict(h.dict) @@ -936,11 +974,11 @@ decodeStream: close(seqDecode) wg.Wait() hist.reset() - d.frame.history.b = frameHistCache + d.frame.history.ring = frameRing } func (d *Decoder) setDict(frame *frameDec) (err error) { - dict, ok := d.o.dicts[frame.DictionaryID] + dict, ok := frame.o.dicts[frame.DictionaryID] if ok { if debugDecoder { println("setting dict", frame.DictionaryID) diff --git a/vendor/github.com/klauspost/compress/zstd/dict.go b/vendor/github.com/klauspost/compress/zstd/dict.go index 67f40e7..7fbdedf 100644 --- a/vendor/github.com/klauspost/compress/zstd/dict.go +++ b/vendor/github.com/klauspost/compress/zstd/dict.go @@ -17,6 +17,7 @@ type dict struct { litEnc *huff0.Scratch llDec, ofDec, mlDec sequenceDec + llEnc, ofEnc, mlEnc *fseEncoder offsets [3]int content []byte } @@ -99,17 +100,12 @@ func loadDict(b []byte) (*dict, error) { off: 0, } readDec := func(i tableIndex, dec *fseDecoder) error { - if err := dec.readNCount(&br, uint16(maxTableSymbol[i])); err != nil { + if err := dec.readNCount(&br, i); err != nil { return err } if br.overread() { return io.ErrUnexpectedEOF } - err = dec.transform(symbolTableX[i]) - if err != nil { - println("Transform table error:", err) - return err - } if debugDecoder || debugEncoder { println("Read table ok", "symbolLen:", dec.symbolLen) } @@ -145,6 +141,9 @@ func loadDict(b []byte) (*dict, error) { if d.offsets[0] > len(d.content) || d.offsets[1] > len(d.content) || d.offsets[2] > len(d.content) { return nil, fmt.Errorf("initial offset bigger than dictionary content size %d, offsets: %v", len(d.content), d.offsets) } + d.llEnc = newDictSeqEncoder(d.llDec.fse, tableLiteralLengths) + d.ofEnc = newDictSeqEncoder(d.ofDec.fse, tableOffsets) + d.mlEnc = newDictSeqEncoder(d.mlDec.fse, tableMatchLengths) return &d, nil } @@ -219,6 +218,9 @@ func BuildDict(o BuildDictOptions) ([]byte, error) { if len(contents) == 0 { return nil, errors.New("no content provided") } + if o.Level < speedNotSet || o.Level >= speedLast { + return nil, fmt.Errorf("unknown encoder level %d", o.Level) + } d := dict{ id: o.ID, litEnc: nil, diff --git a/vendor/github.com/klauspost/compress/zstd/enc_base.go b/vendor/github.com/klauspost/compress/zstd/enc_base.go index c4fea57..40505ce 100644 --- a/vendor/github.com/klauspost/compress/zstd/enc_base.go +++ b/vendor/github.com/klauspost/compress/zstd/enc_base.go @@ -194,6 +194,7 @@ func (e *fastBase) resetBase(d *dict, singleBlock bool) { } // Transfer litenc. e.blk.dictLitEnc = d.litEnc + e.blk.coders.seedPrevFromDict(d) e.hist = append(e.hist, d.content...) } } diff --git a/vendor/github.com/klauspost/compress/zstd/enc_best.go b/vendor/github.com/klauspost/compress/zstd/enc_best.go index c71382d..bdf0b82 100644 --- a/vendor/github.com/klauspost/compress/zstd/enc_best.go +++ b/vendor/github.com/klauspost/compress/zstd/enc_best.go @@ -205,12 +205,8 @@ encodeLoop: candidateL := e.longTable[nextHashL] candidateS := e.table[nextHashS] - // Set m to a match at offset if it looks like that will improve compression. - improve := func(m *match, offset int32, s int32, first uint32, rep int32) { - delta := s - offset - if delta >= e.maxMatchOff || delta <= 0 || load3232(src, offset) != first { - return - } + // improveSlow evaluates a candidate that passed improve's checks. + improveSlow := func(m *match, offset int32, s int32, first uint32, rep int32) { // Try to quick reject if we already have a long match. if m.length > 16 { left := len(src) - int(m.s+m.length) @@ -255,6 +251,14 @@ encodeLoop: } } + // Set m to a match at offset if it looks like that will improve compression. + // The reject path is kept small so it inlines at every call site. + improve := func(m *match, offset int32, s int32, first uint32, rep int32) { + if delta := s - offset; delta < e.maxMatchOff && delta > 0 && load3232(src, offset) == first { + improveSlow(m, offset, s, first, rep) + } + } + best := match{s: s, est: highScore} improve(&best, candidateL.offset-e.cur, s, uint32(cv), -1) improve(&best, candidateL.prev-e.cur, s, uint32(cv), -1) diff --git a/vendor/github.com/klauspost/compress/zstd/enc_better.go b/vendor/github.com/klauspost/compress/zstd/enc_better.go index 523d57f..42b46a3 100644 --- a/vendor/github.com/klauspost/compress/zstd/enc_better.go +++ b/vendor/github.com/klauspost/compress/zstd/enc_better.go @@ -26,6 +26,16 @@ const ( betterShortTableShardSize = betterShortTableSize / betterShortTableShardCnt // Size of an individual shard ) +// betterHashL is hashLen(u, betterLongTableBits, betterLongLen) with prime = prime8bytes. +func betterHashL(u, prime uint64) uint32 { + return uint32((u * prime) >> (64 - betterLongTableBits)) +} + +// betterHashS is hashLen(u, betterShortTableBits, betterShortLen) with prime = prime5bytes. +func betterHashS(u, prime uint64) uint32 { + return uint32(((u << (64 - 40)) * prime) >> (64 - betterShortTableBits)) +} + type prevEntry struct { offset int32 prev int32 @@ -126,6 +136,7 @@ func (e *betterFastEncoder) Encode(blk *blockEnc, src []byte) { // Override src src = e.hist sLimit := int32(len(src)) - inputMargin + primeL, primeS := hashPrimes8and5() // stepSize is the number of bytes to skip on every main loop iteration. // It should be >= 1. const stepSize = 1 @@ -163,8 +174,8 @@ encodeLoop: panic("offset0 was 0") } - nextHashL := hashLen(cv, betterLongTableBits, betterLongLen) - nextHashS := hashLen(cv, betterShortTableBits, betterShortLen) + nextHashL := betterHashL(cv, primeL) + nextHashS := betterHashS(cv, primeS) candidateL := e.longTable[nextHashL] candidateS := e.table[nextHashS] @@ -218,14 +229,13 @@ encodeLoop: break encodeLoop } // Index skipped... - for index0 < s-1 { + for end := s - 1; index0 < end; index0 += 2 { cv0 := load6432(src, index0) cv1 := cv0 >> 8 - h0 := hashLen(cv0, betterLongTableBits, betterLongLen) + h0 := betterHashL(cv0, primeL) off := index0 + e.cur + e.table[betterHashS(cv1, primeS)] = tableEntry{offset: off + 1, val: uint32(cv1)} e.longTable[h0] = prevEntry{offset: off, prev: e.longTable[h0].offset} - e.table[hashLen(cv1, betterShortTableBits, betterShortLen)] = tableEntry{offset: off + 1, val: uint32(cv1)} - index0 += 2 } cv = load6432(src, s) continue @@ -275,14 +285,13 @@ encodeLoop: } // Index skipped... - for index0 < s-1 { + for end := s - 1; index0 < end; index0 += 2 { cv0 := load6432(src, index0) cv1 := cv0 >> 8 - h0 := hashLen(cv0, betterLongTableBits, betterLongLen) + h0 := betterHashL(cv0, primeL) off := index0 + e.cur + e.table[betterHashS(cv1, primeS)] = tableEntry{offset: off + 1, val: uint32(cv1)} e.longTable[h0] = prevEntry{offset: off, prev: e.longTable[h0].offset} - e.table[hashLen(cv1, betterShortTableBits, betterShortLen)] = tableEntry{offset: off + 1, val: uint32(cv1)} - index0 += 2 } cv = load6432(src, s) // Swap offsets @@ -356,7 +365,7 @@ encodeLoop: // See if we can find a long match at s+1 const checkAt = 1 cv := load6432(src, s+checkAt) - nextHashL = hashLen(cv, betterLongTableBits, betterLongLen) + nextHashL = betterHashL(cv, primeL) candidateL = e.longTable[nextHashL] coffsetL = candidateL.offset - e.cur @@ -423,7 +432,7 @@ encodeLoop: // and still picked up as part of the match if they do. const skipBeginning = 3 - nextHashL := hashLen(load6432(src, s+matched), betterLongTableBits, betterLongLen) + nextHashL := betterHashL(load6432(src, s+matched), primeL) s2 := s + skipBeginning cv := load3232(src, s2) candidateL := e.longTable[nextHashL] @@ -501,13 +510,12 @@ encodeLoop: // Index match start+1 (long) -> s - 1 off := index0 + e.cur - for index0 < s-1 { + for end := s - 1; index0 < end; index0 += 2 { cv0 := load6432(src, index0) cv1 := cv0 >> 8 - h0 := hashLen(cv0, betterLongTableBits, betterLongLen) + e.table[betterHashS(cv1, primeS)] = tableEntry{offset: off + 1, val: uint32(cv1)} + h0 := betterHashL(cv0, primeL) e.longTable[h0] = prevEntry{offset: off, prev: e.longTable[h0].offset} - e.table[hashLen(cv1, betterShortTableBits, betterShortLen)] = tableEntry{offset: off + 1, val: uint32(cv1)} - index0 += 2 off += 2 } @@ -525,8 +533,8 @@ encodeLoop: } // Store this, since we have it. - nextHashL := hashLen(cv, betterLongTableBits, betterLongLen) - nextHashS := hashLen(cv, betterShortTableBits, betterShortLen) + nextHashL := betterHashL(cv, primeL) + nextHashS := betterHashS(cv, primeS) // We have at least 4 byte match. // No need to check backwards. We come straight from a match @@ -644,6 +652,7 @@ func (e *betterFastEncoderDict) Encode(blk *blockEnc, src []byte) { // Override src src = e.hist sLimit := int32(len(src)) - inputMargin + primeL, primeS := hashPrimes8and5() // stepSize is the number of bytes to skip on every main loop iteration. // It should be >= 1. const stepSize = 1 @@ -681,8 +690,8 @@ encodeLoop: panic("offset0 was 0") } - nextHashL := hashLen(cv, betterLongTableBits, betterLongLen) - nextHashS := hashLen(cv, betterShortTableBits, betterShortLen) + nextHashL := betterHashL(cv, primeL) + nextHashS := betterHashS(cv, primeS) candidateL := e.longTable[nextHashL] candidateS := e.table[nextHashS] @@ -737,17 +746,16 @@ encodeLoop: break encodeLoop } // Index skipped... - for index0 < s-1 { + for end := s - 1; index0 < end; index0 += 2 { cv0 := load6432(src, index0) cv1 := cv0 >> 8 - h0 := hashLen(cv0, betterLongTableBits, betterLongLen) + h0 := betterHashL(cv0, primeL) off := index0 + e.cur - e.longTable[h0] = prevEntry{offset: off, prev: e.longTable[h0].offset} - e.markLongShardDirty(h0) - h1 := hashLen(cv1, betterShortTableBits, betterShortLen) + h1 := betterHashS(cv1, primeS) e.table[h1] = tableEntry{offset: off + 1, val: uint32(cv1)} e.markShortShardDirty(h1) - index0 += 2 + e.longTable[h0] = prevEntry{offset: off, prev: e.longTable[h0].offset} + e.markLongShardDirty(h0) } cv = load6432(src, s) continue @@ -797,17 +805,16 @@ encodeLoop: } // Index skipped... - for index0 < s-1 { + for end := s - 1; index0 < end; index0 += 2 { cv0 := load6432(src, index0) cv1 := cv0 >> 8 - h0 := hashLen(cv0, betterLongTableBits, betterLongLen) + h0 := betterHashL(cv0, primeL) off := index0 + e.cur - e.longTable[h0] = prevEntry{offset: off, prev: e.longTable[h0].offset} - e.markLongShardDirty(h0) - h1 := hashLen(cv1, betterShortTableBits, betterShortLen) + h1 := betterHashS(cv1, primeS) e.table[h1] = tableEntry{offset: off + 1, val: uint32(cv1)} e.markShortShardDirty(h1) - index0 += 2 + e.longTable[h0] = prevEntry{offset: off, prev: e.longTable[h0].offset} + e.markLongShardDirty(h0) } cv = load6432(src, s) // Swap offsets @@ -881,7 +888,7 @@ encodeLoop: // See if we can find a long match at s+1 const checkAt = 1 cv := load6432(src, s+checkAt) - nextHashL = hashLen(cv, betterLongTableBits, betterLongLen) + nextHashL = betterHashL(cv, primeL) candidateL = e.longTable[nextHashL] coffsetL = candidateL.offset - e.cur @@ -942,7 +949,7 @@ encodeLoop: } // Try to find a better match by searching for a long match at the end of the current best match if s+matched < sLimit { - nextHashL := hashLen(load6432(src, s+matched), betterLongTableBits, betterLongLen) + nextHashL := betterHashL(load6432(src, s+matched), primeL) cv := load3232(src, s) candidateL := e.longTable[nextHashL] coffsetL := candidateL.offset - e.cur - matched @@ -1017,16 +1024,15 @@ encodeLoop: // Index match start+1 (long) -> s - 1 off := index0 + e.cur - for index0 < s-1 { + for end := s - 1; index0 < end; index0 += 2 { cv0 := load6432(src, index0) cv1 := cv0 >> 8 - h0 := hashLen(cv0, betterLongTableBits, betterLongLen) - e.longTable[h0] = prevEntry{offset: off, prev: e.longTable[h0].offset} - e.markLongShardDirty(h0) - h1 := hashLen(cv1, betterShortTableBits, betterShortLen) + h1 := betterHashS(cv1, primeS) e.table[h1] = tableEntry{offset: off + 1, val: uint32(cv1)} e.markShortShardDirty(h1) - index0 += 2 + h0 := betterHashL(cv0, primeL) + e.longTable[h0] = prevEntry{offset: off, prev: e.longTable[h0].offset} + e.markLongShardDirty(h0) off += 2 } @@ -1044,8 +1050,8 @@ encodeLoop: } // Store this, since we have it. - nextHashL := hashLen(cv, betterLongTableBits, betterLongLen) - nextHashS := hashLen(cv, betterShortTableBits, betterShortLen) + nextHashL := betterHashL(cv, primeL) + nextHashS := betterHashS(cv, primeS) // We have at least 4 byte match. // No need to check backwards. We come straight from a match diff --git a/vendor/github.com/klauspost/compress/zstd/enc_dfast.go b/vendor/github.com/klauspost/compress/zstd/enc_dfast.go index 712ba7a..aae5986 100644 --- a/vendor/github.com/klauspost/compress/zstd/enc_dfast.go +++ b/vendor/github.com/klauspost/compress/zstd/enc_dfast.go @@ -22,6 +22,16 @@ const ( ) +// dFastHashL is hashLen(u, dFastLongTableBits, dFastLongLen) with prime = prime8bytes. +func dFastHashL(u, prime uint64) uint32 { + return uint32((u * prime) >> (64 - dFastLongTableBits)) +} + +// dFastHashS is hashLen(u, dFastShortTableBits, dFastShortLen) with prime = prime5bytes. +func dFastHashS(u, prime uint64) uint32 { + return uint32(((u << (64 - 40)) * prime) >> (64 - dFastShortTableBits)) +} + type doubleFastEncoder struct { fastEncoder longTable [dFastLongTableSize]tableEntry @@ -87,6 +97,7 @@ func (e *doubleFastEncoder) Encode(blk *blockEnc, src []byte) { // Override src src = e.hist sLimit := int32(len(src)) - inputMargin + primeL, primeS := hashPrimes8and5() // stepSize is the number of bytes to skip on every main loop iteration. // It should be >= 1. const stepSize = 1 @@ -123,8 +134,8 @@ encodeLoop: panic("offset0 was 0") } - nextHashL := hashLen(cv, dFastLongTableBits, dFastLongLen) - nextHashS := hashLen(cv, dFastShortTableBits, dFastShortLen) + nextHashL := dFastHashL(cv, primeL) + nextHashS := dFastHashS(cv, primeS) candidateL := e.longTable[nextHashL] candidateS := e.table[nextHashS] @@ -204,7 +215,7 @@ encodeLoop: // See if we can find a long match at s+1 const checkAt = 1 cv := load6432(src, s+checkAt) - nextHashL = hashLen(cv, dFastLongTableBits, dFastLongLen) + nextHashL = dFastHashL(cv, primeL) candidateL = e.longTable[nextHashL] coffsetL = s - (candidateL.offset - e.cur) + checkAt @@ -297,16 +308,16 @@ encodeLoop: cv1 := load6432(src, index1) te0 := tableEntry{offset: index0 + e.cur, val: uint32(cv0)} te1 := tableEntry{offset: index1 + e.cur, val: uint32(cv1)} - e.longTable[hashLen(cv0, dFastLongTableBits, dFastLongLen)] = te0 - e.longTable[hashLen(cv1, dFastLongTableBits, dFastLongLen)] = te1 + e.longTable[dFastHashL(cv0, primeL)] = te0 + e.longTable[dFastHashL(cv1, primeL)] = te1 cv0 >>= 8 cv1 >>= 8 te0.offset++ te1.offset++ te0.val = uint32(cv0) te1.val = uint32(cv1) - e.table[hashLen(cv0, dFastShortTableBits, dFastShortLen)] = te0 - e.table[hashLen(cv1, dFastShortTableBits, dFastShortLen)] = te1 + e.table[dFastHashS(cv0, primeS)] = te0 + e.table[dFastHashS(cv1, primeS)] = te1 cv = load6432(src, s) @@ -323,8 +334,8 @@ encodeLoop: } // Store this, since we have it. - nextHashS := hashLen(cv, dFastShortTableBits, dFastShortLen) - nextHashL := hashLen(cv, dFastLongTableBits, dFastLongLen) + nextHashS := dFastHashS(cv, primeS) + nextHashL := dFastHashL(cv, primeL) // We have at least 4 byte match. // No need to check backwards. We come straight from a match @@ -399,6 +410,7 @@ func (e *doubleFastEncoder) EncodeNoHist(blk *blockEnc, src []byte) { // Override src sLimit := int32(len(src)) - inputMargin + primeL, primeS := hashPrimes8and5() // stepSize is the number of bytes to skip on every main loop iteration. // It should be >= 1. const stepSize = 1 @@ -429,8 +441,8 @@ encodeLoop: var t int32 for { - nextHashL := hashLen(cv, dFastLongTableBits, dFastLongLen) - nextHashS := hashLen(cv, dFastShortTableBits, dFastShortLen) + nextHashL := dFastHashL(cv, primeL) + nextHashS := dFastHashS(cv, primeS) candidateL := e.longTable[nextHashL] candidateS := e.table[nextHashS] @@ -511,7 +523,7 @@ encodeLoop: // See if we can find a long match at s+1 const checkAt = 1 cv := load6432(src, s+checkAt) - nextHashL = hashLen(cv, dFastLongTableBits, dFastLongLen) + nextHashL = dFastHashL(cv, primeL) candidateL = e.longTable[nextHashL] coffsetL = s - (candidateL.offset - e.cur) + checkAt @@ -601,16 +613,16 @@ encodeLoop: cv1 := load6432(src, index1) te0 := tableEntry{offset: index0 + e.cur, val: uint32(cv0)} te1 := tableEntry{offset: index1 + e.cur, val: uint32(cv1)} - e.longTable[hashLen(cv0, dFastLongTableBits, dFastLongLen)] = te0 - e.longTable[hashLen(cv1, dFastLongTableBits, dFastLongLen)] = te1 + e.longTable[dFastHashL(cv0, primeL)] = te0 + e.longTable[dFastHashL(cv1, primeL)] = te1 cv0 >>= 8 cv1 >>= 8 te0.offset++ te1.offset++ te0.val = uint32(cv0) te1.val = uint32(cv1) - e.table[hashLen(cv0, dFastShortTableBits, dFastShortLen)] = te0 - e.table[hashLen(cv1, dFastShortTableBits, dFastShortLen)] = te1 + e.table[dFastHashS(cv0, primeS)] = te0 + e.table[dFastHashS(cv1, primeS)] = te1 cv = load6432(src, s) @@ -627,8 +639,8 @@ encodeLoop: } // Store this, since we have it. - nextHashS := hashLen(cv1>>8, dFastShortTableBits, dFastShortLen) - nextHashL := hashLen(cv, dFastLongTableBits, dFastLongLen) + nextHashS := dFastHashS(cv1>>8, primeS) + nextHashL := dFastHashL(cv, primeL) // We have at least 4 byte match. // No need to check backwards. We come straight from a match @@ -733,6 +745,7 @@ func (e *doubleFastEncoderDict) Encode(blk *blockEnc, src []byte) { // Override src src = e.hist sLimit := int32(len(src)) - inputMargin + primeL, primeS := hashPrimes8and5() // stepSize is the number of bytes to skip on every main loop iteration. // It should be >= 1. const stepSize = 1 @@ -769,8 +782,8 @@ encodeLoop: panic("offset0 was 0") } - nextHashL := hashLen(cv, dFastLongTableBits, dFastLongLen) - nextHashS := hashLen(cv, dFastShortTableBits, dFastShortLen) + nextHashL := dFastHashL(cv, primeL) + nextHashS := dFastHashS(cv, primeS) candidateL := e.longTable[nextHashL] candidateS := e.table[nextHashS] @@ -852,7 +865,7 @@ encodeLoop: // See if we can find a long match at s+1 const checkAt = 1 cv := load6432(src, s+checkAt) - nextHashL = hashLen(cv, dFastLongTableBits, dFastLongLen) + nextHashL = dFastHashL(cv, primeL) candidateL = e.longTable[nextHashL] coffsetL = s - (candidateL.offset - e.cur) + checkAt @@ -946,8 +959,8 @@ encodeLoop: cv1 := load6432(src, index1) te0 := tableEntry{offset: index0 + e.cur, val: uint32(cv0)} te1 := tableEntry{offset: index1 + e.cur, val: uint32(cv1)} - longHash1 := hashLen(cv0, dFastLongTableBits, dFastLongLen) - longHash2 := hashLen(cv1, dFastLongTableBits, dFastLongLen) + longHash1 := dFastHashL(cv0, primeL) + longHash2 := dFastHashL(cv1, primeL) e.longTable[longHash1] = te0 e.longTable[longHash2] = te1 e.markLongShardDirty(longHash1) @@ -958,8 +971,8 @@ encodeLoop: te1.offset++ te0.val = uint32(cv0) te1.val = uint32(cv1) - hashVal1 := hashLen(cv0, dFastShortTableBits, dFastShortLen) - hashVal2 := hashLen(cv1, dFastShortTableBits, dFastShortLen) + hashVal1 := dFastHashS(cv0, primeS) + hashVal2 := dFastHashS(cv1, primeS) e.table[hashVal1] = te0 e.markShardDirty(hashVal1) e.table[hashVal2] = te1 @@ -980,8 +993,8 @@ encodeLoop: } // Store this, since we have it. - nextHashL := hashLen(cv, dFastLongTableBits, dFastLongLen) - nextHashS := hashLen(cv, dFastShortTableBits, dFastShortLen) + nextHashL := dFastHashL(cv, primeL) + nextHashS := dFastHashS(cv, primeS) // We have at least 4 byte match. // No need to check backwards. We come straight from a match diff --git a/vendor/github.com/klauspost/compress/zstd/encoder.go b/vendor/github.com/klauspost/compress/zstd/encoder.go index 6ee96d8..25dd316 100644 --- a/vendor/github.com/klauspost/compress/zstd/encoder.go +++ b/vendor/github.com/klauspost/compress/zstd/encoder.go @@ -109,7 +109,7 @@ func (e *Encoder) Reset(w io.Writer) { js.jobSize = e.o.jobSize() js.overlapSize = e.o.overlapSize() // js.filling is allocated lazily on first Write/ReadFrom so callers - // that only use EncodeAll don't pay the (up to ~32 MB) jobSize cost. + // that only use EncodeAll don't pay the jobSize cost (up to maxJobSize). js.filling = js.filling[:0] if js.nextPrefix != nil { js.putOverlapBuf(js.nextPrefix) @@ -161,15 +161,23 @@ func (e *Encoder) Reset(w io.Writer) { // as a new, independent stream. // Options are applied on top of the existing options. // Some options cannot be changed on reset and will return an error. +// If an option fails, the encoder is left unchanged. func (e *Encoder) ResetWithOptions(w io.Writer, opts ...EOption) error { - e.o.resetOpt = true - defer func() { e.o.resetOpt = false }() - hadDict := e.o.dict != nil + next := e.o + next.resetOpt = true for _, o := range opts { - if err := o(&e.o); err != nil { + if err := o(&next); err != nil { return err } } + next.resetOpt = false + + e.shutdownJobWorkers() + e.state.wg.Wait() + e.state.wWg.Wait() + + hadDict := e.o.dict != nil + e.o = next hasDict := e.o.dict != nil if e.o.concurrentBlocks && hasDict { e.o.concurrentBlocks = false diff --git a/vendor/github.com/klauspost/compress/zstd/encoder_options.go b/vendor/github.com/klauspost/compress/zstd/encoder_options.go index a808149..f0fd674 100644 --- a/vendor/github.com/klauspost/compress/zstd/encoder_options.go +++ b/vendor/github.com/klauspost/compress/zstd/encoder_options.go @@ -352,22 +352,29 @@ func WithConcurrentBlocks(b bool) EOption { } } +// maxJobSize caps the job size, so large windows still give several jobs. +// A variable so tests can exercise the cap with small inputs. +var maxJobSize = 256 << 20 + // jobSize returns the input section size per parallel job. func (o *encoderOptions) jobSize() int { - s := max(o.windowSize*4, 512<<10) - return s + // Clamp before multiplying: windowSize*4 overflows a 32-bit int for + // windows of 512 MiB. + return max(min(o.windowSize, maxJobSize/4)*4, 512<<10) } // overlapSize returns the overlap prefix size for parallel jobs. func (o *encoderOptions) overlapSize() int { + var s int switch o.level { case SpeedBestCompression: - return o.windowSize / 2 + s = o.windowSize / 2 case SpeedBetterCompression: - return o.windowSize / 4 + s = o.windowSize / 4 default: - return o.windowSize / 8 + s = o.windowSize / 8 } + return min(s, o.jobSize()/2) } // WithEncoderDict allows to register a dictionary that will be used for the encode. diff --git a/vendor/github.com/klauspost/compress/zstd/framedec.go b/vendor/github.com/klauspost/compress/zstd/framedec.go index d88f067..fb836c4 100644 --- a/vendor/github.com/klauspost/compress/zstd/framedec.go +++ b/vendor/github.com/klauspost/compress/zstd/framedec.go @@ -49,13 +49,16 @@ const ( ) func newFrameDec(o decoderOptions) *frameDec { + d := frameDec{} + d.setOptions(o) + return &d +} + +func (d *frameDec) setOptions(o decoderOptions) { if o.maxWindowSize > o.maxDecodedSize { o.maxWindowSize = o.maxDecodedSize } - d := frameDec{ - o: o, - } - return &d + d.o = o } // reset will read the frame header and prepare for block decoding. @@ -255,18 +258,6 @@ func (d *frameDec) reset(br byteBuffer) error { return ErrWindowSizeTooSmall } d.history.windowSize = int(d.WindowSize) - if !d.o.lowMem || d.history.windowSize < maxBlockSize { - // Alloc 2x window size if not low-mem, or window size below 2MB. - d.history.allocFrameBuffer = d.history.windowSize * 2 - } else { - if d.o.lowMem { - // Alloc with 1MB extra. - d.history.allocFrameBuffer = d.history.windowSize + maxBlockSize/2 - } else { - // Alloc with 2MB extra. - d.history.allocFrameBuffer = d.history.windowSize + maxBlockSize - } - } if debugDecoder { println("Frame: Dict:", d.DictionaryID, "FrameContentSize:", d.FrameContentSize, "singleseg:", d.SingleSegment, "window:", d.WindowSize, "crc:", d.HasCheckSum) @@ -352,14 +343,12 @@ func (d *frameDec) runDecoder(dst []byte, dec *blockDec) ([]byte, error) { if debugDecoder { println("maxSyncLen:", d.history.decoders.maxSyncLen) } - if !d.o.limitToCap && uint64(cap(dst)) < d.history.decoders.maxSyncLen { - // Alloc for output - dst2 := make([]byte, len(dst), d.history.decoders.maxSyncLen+compressedBlockOverAlloc) - copy(dst2, dst) - dst = dst2 - } } var err error + // Hash each block while it is still in cache rather than the whole + // frame at the end. + hashCRC := d.HasCheckSum && !d.o.ignoreChecksum + crcDone := crcStart for { err = dec.reset(d.rawInput, d.WindowSize) if err != nil { @@ -372,6 +361,10 @@ func (d *frameDec) runDecoder(dst []byte, dec *blockDec) ([]byte, error) { if err != nil { break } + if hashCRC { + d.crc.Write(d.history.b[crcDone:]) + crcDone = len(d.history.b) + } if uint64(len(d.history.b)-crcStart) > d.o.maxDecodedSize { println("runDecoder: maxDecodedSize exceeded", uint64(len(d.history.b)-crcStart), ">", d.o.maxDecodedSize) err = ErrDecoderSizeExceeded @@ -402,7 +395,6 @@ func (d *frameDec) runDecoder(dst []byte, dec *blockDec) ([]byte, error) { if d.o.ignoreChecksum { err = d.consumeCRC() } else { - d.crc.Write(dst[crcStart:]) err = d.checkCRC() } } diff --git a/vendor/github.com/klauspost/compress/zstd/fse_decoder.go b/vendor/github.com/klauspost/compress/zstd/fse_decoder.go index 2f8860a..12ac2b5 100644 --- a/vendor/github.com/klauspost/compress/zstd/fse_decoder.go +++ b/vendor/github.com/klauspost/compress/zstd/fse_decoder.go @@ -43,13 +43,36 @@ type fseDecoder struct { preDefined bool } +// codeShare returns, in 1/256ths, the table's probability mass on symbols +// minCode and above: for a table read from the block, the share of its +// sequences with those codes. The predefined tables describe the format's +// defaults, not the block, and RLE tables have no distribution; both +// report -1. +func (s *fseDecoder) codeShare(minCode int) int { + if s == nil || s.preDefined || s.actualTableLog == 0 { + return -1 + } + n := 0 + for c := minCode; c < int(s.symbolLen); c++ { + switch v := int(s.norm[c]); { + case v > 0: + n += v + case v < 0: + n++ // -1 marks a probability below one slot; it occupies one + } + } + return n * 256 >> s.actualTableLog +} + // tableStep returns the next table index. func tableStep(tableSize uint32) uint32 { return (tableSize >> 1) + (tableSize >> 3) + 3 } -// readNCount will read the symbol distribution so decoding tables can be constructed. -func (s *fseDecoder) readNCount(b *byteReader, maxSymbol uint16) error { +// readNCount will read the symbol distribution for table t and build its +// decoding table. +func (s *fseDecoder) readNCount(b *byteReader, t tableIndex) error { + maxSymbol := uint16(maxTableSymbol[t]) var ( charnum uint16 previous0 bool @@ -167,7 +190,8 @@ func (s *fseDecoder) readNCount(b *byteReader, maxSymbol uint16) error { if s.symbolLen <= 1 { return fmt.Errorf("symbolLen (%d) too small", s.symbolLen) } - if s.symbolLen > maxSymbolValue+1 { + // A run of zero counts can step past maxSymbol, so check the total. + if s.symbolLen > maxSymbol+1 { return fmt.Errorf("symbolLen (%d) too big", s.symbolLen) } if remaining != 1 { @@ -180,7 +204,30 @@ func (s *fseDecoder) readNCount(b *byteReader, maxSymbol uint16) error { return fmt.Errorf("corruption detected (total %d != %d)", gotTotal, 1<> 3) - return s.buildDtable() + return s.buildDtable(&symbolExtX[t]) +} + +// symbolExt holds, per symbol, a decSymbol with only addBits and baseline set. +type symbolExt [maxMatchLengthSymbol + 1]decSymbol + +// buildDtable builds the decoding table, taking each state's addBits and +// baseline from its symbol's entry in ext. +func (s *fseDecoder) buildDtable(ext *symbolExt) error { + if int(s.symbolLen) > len(ext) { + return fmt.Errorf("symbolLen (%d) too big", s.symbolLen) + } + if err := s.fillDtable(ext); err != nil { + return err + } + // addBits never decreases with the symbol (checked in initPredefined), + // so the last symbol has the most. It may exceed the table's actual + // maximum only if the last symbol has no states, which just costs an + // extra bitreader fill. + s.maxBits = 0 + if s.symbolLen > 0 { + s.maxBits = ext[s.symbolLen-1].addBits() + } + return nil } func (s *fseDecoder) mustReadFrom(r io.Reader) { @@ -268,27 +315,6 @@ func (s *fseDecoder) setRLE(symbol decSymbol) { s.dt[0] = symbol } -// transform will transform the decoder table into a table usable for -// decoding without having to apply the transformation while decoding. -// The state will contain the base value and the number of bits to read. -func (s *fseDecoder) transform(t []baseOffset) error { - tableSize := uint16(1 << s.actualTableLog) - s.maxBits = 0 - for i, v := range s.dt[:tableSize] { - add := v.addBits() - if int(add) >= len(t) { - return fmt.Errorf("invalid decoding table entry %d, symbol %d >= max (%d)", i, v.addBits(), len(t)) - } - lu := t[add] - if lu.addBits > s.maxBits { - s.maxBits = lu.addBits - } - v.setExt(lu.addBits, lu.baseLine) - s.dt[i] = v - } - return nil -} - type fseState struct { dt []decSymbol state decSymbol diff --git a/vendor/github.com/klauspost/compress/zstd/fse_decoder_amd64.s b/vendor/github.com/klauspost/compress/zstd/fse_decoder_amd64.s index deeadc4..786e317 100644 --- a/vendor/github.com/klauspost/compress/zstd/fse_decoder_amd64.s +++ b/vendor/github.com/klauspost/compress/zstd/fse_decoder_amd64.s @@ -1,126 +1,132 @@ -// Code generated by command: go run gen_fse.go -out ../fse_decoder.s -arch amd64,arm64 -pkg=zstd. DO NOT EDIT. +// Code generated by command: go run gen_fse.go -out ../fse_decoder.s -arch amd64,arm64 -arm64-promote-stack-slots -pkg=zstd. DO NOT EDIT. -//go:build !appengine && !noasm && gc && !noasm +//go:build !noasm && gc // func buildDtable_asm(s *fseDecoder, ctx *buildDtableAsmContext) int TEXT ·buildDtable_asm(SB), $0-24 MOVQ ctx+8(FP), CX - MOVQ s+0(FP), DI + MOVQ s+0(FP), R8 // Load values - MOVBQZX 4098(DI), DX + MOVBQZX 4098(R8), DX XORQ AX, AX BTSQ DX, AX MOVQ (CX), BX MOVQ 16(CX), SI - LEAQ -1(AX), R8 + MOVQ 24(CX), DI + LEAQ -1(AX), R9 MOVQ 8(CX), CX - MOVWQZX 4096(DI), DI + MOVWQZX 4096(R8), R8 // End load values // Init, lay down lowprob symbols - XORQ R9, R9 + XORQ R10, R10 JMP init_main_loop_condition init_main_loop: - MOVWQSX (CX)(R9*2), R10 - CMPW R10, $-1 + MOVWQSX (CX)(R10*2), R11 + CMPW R11, $-1 JNE do_not_update_high_threshold - MOVB R9, 1(SI)(R8*8) - DECQ R8 - MOVQ $0x0000000000000001, R10 + MOVB R10, 1(SI)(R9*8) + DECQ R9 + MOVQ $0x0000000000000001, R11 do_not_update_high_threshold: - MOVW R10, (BX)(R9*2) - INCQ R9 + MOVW R11, (BX)(R10*2) + INCQ R10 init_main_loop_condition: - CMPQ R9, DI + CMPQ R10, R8 JL init_main_loop // Spread symbols // Calculate table step - MOVQ AX, R9 - SHRQ $0x01, R9 MOVQ AX, R10 - SHRQ $0x03, R10 - LEAQ 3(R9)(R10*1), R9 + SHRQ $0x01, R10 + MOVQ AX, R11 + SHRQ $0x03, R11 + LEAQ 3(R10)(R11*1), R10 // Fill add bits values - LEAQ -1(AX), R10 - XORQ R11, R11 + LEAQ -1(AX), R11 XORQ R12, R12 + XORQ R13, R13 JMP spread_main_loop_condition spread_main_loop: - XORQ R13, R13 - MOVWQSX (CX)(R12*2), R14 + XORQ R14, R14 + MOVWQSX (CX)(R13*2), R15 JMP spread_inner_loop_condition spread_inner_loop: - MOVB R12, 1(SI)(R11*8) + MOVB R13, 1(SI)(R12*8) adjust_position: - ADDQ R9, R11 - ANDQ R10, R11 - CMPQ R11, R8 + ADDQ R10, R12 + ANDQ R11, R12 + CMPQ R12, R9 JG adjust_position - INCQ R13 + INCQ R14 spread_inner_loop_condition: - CMPQ R13, R14 + CMPQ R14, R15 JL spread_inner_loop - INCQ R12 + INCQ R13 spread_main_loop_condition: - CMPQ R12, DI + CMPQ R13, R8 JL spread_main_loop - TESTQ R11, R11 + TESTQ R12, R12 JZ spread_check_ok MOVQ ctx+8(FP), AX - MOVQ R11, 24(AX) + MOVQ R12, 32(AX) MOVQ $+1, ret+16(FP) RET spread_check_ok: // Build Decoding table - XORQ DI, DI + XORQ R8, R8 build_table_main_table: - MOVBQZX 1(SI)(DI*8), CX - MOVWQZX (BX)(CX*2), R8 - LEAQ 1(R8), R9 - MOVW R9, (BX)(CX*2) - MOVQ R8, R9 - BSRQ R9, R9 + MOVBQZX 1(SI)(R8*8), R9 + MOVWQZX (BX)(R9*2), R10 + LEAQ 1(R10), CX + MOVW CX, (BX)(R9*2) + MOVQ R10, R11 + BSRQ R11, R11 MOVQ DX, CX - SUBQ R9, CX - SHLQ CL, R8 - SUBQ AX, R8 - MOVB CL, (SI)(DI*8) - MOVW R8, 2(SI)(DI*8) - CMPQ R8, AX + SUBQ R11, CX + SHLQ CL, R10 + SUBQ AX, R10 + MOVQ (DI)(R9*8), R9 + ORQ CX, R9 + MOVQ R10, R11 + ANDQ $0x0000ffff, R11 + SHLQ $0x10, R11 + ORQ R11, R9 + MOVQ R9, (SI)(R8*8) + CMPQ R10, AX JLE build_table_check1_ok MOVQ ctx+8(FP), CX - MOVQ R8, 24(CX) - MOVQ AX, 32(CX) + MOVQ R10, 32(CX) + MOVQ AX, 40(CX) MOVQ $+2, ret+16(FP) RET build_table_check1_ok: TESTB CL, CL JNZ build_table_check2_ok - CMPW R8, DI + CMPW R10, R8 JNE build_table_check2_ok MOVQ ctx+8(FP), AX - MOVQ R8, 24(AX) - MOVQ DI, 32(AX) + MOVQ R10, 32(AX) + MOVQ R8, 40(AX) MOVQ $+3, ret+16(FP) RET build_table_check2_ok: - INCQ DI - CMPQ DI, AX + INCQ R8 + CMPQ R8, AX JL build_table_main_table MOVQ $+0, ret+16(FP) RET diff --git a/vendor/github.com/klauspost/compress/zstd/fse_decoder_arm64.s b/vendor/github.com/klauspost/compress/zstd/fse_decoder_arm64.s index 77ee391..c37cb15 100644 --- a/vendor/github.com/klauspost/compress/zstd/fse_decoder_arm64.s +++ b/vendor/github.com/klauspost/compress/zstd/fse_decoder_arm64.s @@ -1,152 +1,147 @@ -// Code generated by command: go run gen_fse.go -out ../fse_decoder.s -arch amd64,arm64 -pkg=zstd. DO NOT EDIT. +// Code generated by command: go run gen_fse.go -out ../fse_decoder.s -arch amd64,arm64 -arm64-promote-stack-slots -pkg=zstd. DO NOT EDIT. // EXPERIMENTAL arm64 output lowered from an amd64 avo program. -//go:build arm64 && !appengine && !noasm && gc && !noasm +//go:build arm64 && (!noasm && gc) // func buildDtable_asm(s *fseDecoder, ctx *buildDtableAsmContext) int TEXT ·buildDtable_asm(SB), $0-24 MOVD ctx+8(FP), R1 - MOVD s+0(FP), R6 + MOVD s+0(FP), R7 // Load values - MOVBU 4098(R6), R2 + MOVBU 4098(R7), R2 MOVD $0, R0 MOVD $1, R16 LSL R2, R16, R16 ORR R16, R0, R0 MOVD (R1), R3 MOVD 16(R1), R5 - SUB $1, R0, R7 + MOVD 24(R1), R6 + SUB $1, R0, R8 MOVD 8(R1), R1 - MOVHU 4096(R6), R6 + MOVHU 4096(R7), R7 // End load values // Init, lay down lowprob symbols - MOVD $0, R8 + MOVD $0, R9 JMP init_main_loop_condition init_main_loop: - ADD R8<<1, R1, R15 - MOVH (R15), R9 - AND $0xffff, R9, R15 + MOVH (R1)(R9<<1), R10 MOVD $-1, R16 AND $0xffff, R16, R16 + AND $0xffff, R10, R15 CMP R16, R15 BNE do_not_update_high_threshold - ADD R7<<3, R5, R15 - MOVB R8, 1(R15) - SUB $1, R7, R7 - MOVD $0x0000000000000001, R9 + ADD R8<<3, R5, R15 + MOVB R9, 1(R15) + SUB $1, R8, R8 + MOVD $0x0000000000000001, R10 do_not_update_high_threshold: - ADD R8<<1, R3, R15 - MOVH R9, (R15) - ADD $1, R8, R8 + MOVH R10, (R3)(R9<<1) + ADD $1, R9, R9 init_main_loop_condition: - CMP R6, R8 + CMP R7, R9 BLT init_main_loop // Spread symbols // Calculate table step - MOVD R0, R8 - LSR $0x01, R8, R8 - MOVD R0, R9 - LSR $0x03, R9, R9 - ADD R9, R8, R8 - ADD $3, R8, R8 + LSR $0x01, R0, R9 + LSR $0x03, R0, R10 + ADD R10, R9, R9 + ADD $3, R9, R9 // Fill add bits values - SUB $1, R0, R9 - MOVD $0, R10 + SUB $1, R0, R10 MOVD $0, R11 + MOVD $0, R12 JMP spread_main_loop_condition spread_main_loop: - MOVD $0, R12 - ADD R11<<1, R1, R15 - MOVH (R15), R13 + MOVD $0, R13 + MOVH (R1)(R12<<1), R14 JMP spread_inner_loop_condition spread_inner_loop: - ADD R10<<3, R5, R15 - MOVB R11, 1(R15) + ADD R11<<3, R5, R15 + MOVB R12, 1(R15) adjust_position: - ADD R8, R10, R10 - AND R9, R10, R10 - CMP R7, R10 + ADD R9, R11, R11 + AND R10, R11, R11 + CMP R8, R11 BGT adjust_position - ADD $1, R12, R12 + ADD $1, R13, R13 spread_inner_loop_condition: - CMP R13, R12 + CMP R14, R13 BLT spread_inner_loop - ADD $1, R11, R11 + ADD $1, R12, R12 spread_main_loop_condition: - CMP R6, R11 + CMP R7, R12 BLT spread_main_loop - TST R10, R10 + TST R11, R11 BEQ spread_check_ok MOVD ctx+8(FP), R0 - MOVD R10, 24(R0) + MOVD R11, 32(R0) MOVD $+1, R16 MOVD R16, ret+16(FP) RET spread_check_ok: // Build Decoding table - MOVD $0, R6 + MOVD $0, R7 build_table_main_table: - ADD R6<<3, R5, R15 - MOVBU 1(R15), R1 - ADD R1<<1, R3, R15 - MOVHU (R15), R7 - ADD $1, R7, R8 - ADD R1<<1, R3, R15 - MOVH R8, (R15) - MOVD R7, R8 - CLZ R8, R16 - MOVD $63, R8 - SUB R16, R8, R8 + ADD R7<<3, R5, R15 + MOVBU 1(R15), R8 + MOVHU (R3)(R8<<1), R9 + ADD $1, R9, R1 + MOVH R1, (R3)(R8<<1) + MOVD R9, R10 + CLZ R10, R16 + MOVD $63, R10 + SUB R16, R10, R10 MOVD R2, R1 - SUB R8, R1, R1 - LSL R1, R7, R7 - SUB R0, R7, R7 - ADD R6<<3, R5, R15 - MOVB R1, (R15) - ADD R6<<3, R5, R15 - MOVH R7, 2(R15) - CMP R0, R7 + SUB R10, R1, R1 + LSL R1, R9, R9 + SUB R0, R9, R9 + MOVD (R6)(R8<<3), R8 + ORR R1, R8, R8 + MOVD R9, R10 + AND $0x0000ffff, R10, R10 + LSL $0x10, R10, R10 + ORR R10, R8, R8 + MOVD R8, (R5)(R7<<3) + CMP R0, R9 BLE build_table_check1_ok MOVD ctx+8(FP), R1 - MOVD R7, 24(R1) - MOVD R0, 32(R1) + MOVD R9, 32(R1) + MOVD R0, 40(R1) MOVD $+2, R16 MOVD R16, ret+16(FP) RET build_table_check1_ok: - AND $0xff, R1, R15 - AND $0xff, R1, R16 - TST R16, R15 + TST $0xff, R1 BNE build_table_check2_ok - AND $0xffff, R7, R15 - AND $0xffff, R6, R16 + AND $0xffff, R7, R16 + AND $0xffff, R9, R15 CMP R16, R15 BNE build_table_check2_ok MOVD ctx+8(FP), R0 - MOVD R7, 24(R0) - MOVD R6, 32(R0) + MOVD R9, 32(R0) + MOVD R7, 40(R0) MOVD $+3, R16 MOVD R16, ret+16(FP) RET build_table_check2_ok: - ADD $1, R6, R6 - CMP R0, R6 + ADD $1, R7, R7 + CMP R0, R7 BLT build_table_main_table MOVD $+0, R16 MOVD R16, ret+16(FP) diff --git a/vendor/github.com/klauspost/compress/zstd/fse_decoder_asm.go b/vendor/github.com/klauspost/compress/zstd/fse_decoder_asm.go index 4ffc7e3..7394eef 100644 --- a/vendor/github.com/klauspost/compress/zstd/fse_decoder_asm.go +++ b/vendor/github.com/klauspost/compress/zstd/fse_decoder_asm.go @@ -1,4 +1,4 @@ -//go:build (amd64 || arm64) && !appengine && !noasm && gc +//go:build (amd64 || arm64) && !noasm && gc package zstd @@ -15,6 +15,7 @@ type buildDtableAsmContext struct { stateTable *uint16 norm *int16 dt *uint64 + ext *uint64 // outputs --- set by the procedure in the case of error; // for interpretation please see the error handling part below @@ -35,12 +36,13 @@ const ( errorNewStateNoBits = 3 ) -// buildDtable will build the decoding table. -func (s *fseDecoder) buildDtable() error { +// fillDtable fills the decoding table; see buildDtable. +func (s *fseDecoder) fillDtable(ext *symbolExt) error { ctx := buildDtableAsmContext{ stateTable: &s.stateTable[0], norm: &s.norm[0], dt: (*uint64)(&s.dt[0]), + ext: (*uint64)(&ext[0]), } code := buildDtable_asm(s, &ctx) diff --git a/vendor/github.com/klauspost/compress/zstd/fse_decoder_generic.go b/vendor/github.com/klauspost/compress/zstd/fse_decoder_generic.go index 38fd2cc..f40353b 100644 --- a/vendor/github.com/klauspost/compress/zstd/fse_decoder_generic.go +++ b/vendor/github.com/klauspost/compress/zstd/fse_decoder_generic.go @@ -1,4 +1,4 @@ -//go:build (!amd64 && !arm64) || appengine || !gc || noasm +//go:build (!amd64 && !arm64) || !gc || noasm package zstd @@ -7,8 +7,8 @@ import ( "fmt" ) -// buildDtable will build the decoding table. -func (s *fseDecoder) buildDtable() error { +// fillDtable fills the decoding table; see buildDtable. +func (s *fseDecoder) fillDtable(ext *symbolExt) error { tableSize := uint32(1 << s.actualTableLog) highThreshold := tableSize - 1 symbolNext := s.stateTable[:256] @@ -56,7 +56,6 @@ func (s *fseDecoder) buildDtable() error { nextState := symbolNext[symbol] symbolNext[symbol] = nextState + 1 nBits := s.actualTableLog - byte(highBits(uint32(nextState))) - s.dt[u&maxTableMask].setNBits(nBits) newState := (nextState << nBits) - tableSize if newState > tableSize { return fmt.Errorf("newState (%d) outside table size (%d)", newState, tableSize) @@ -65,7 +64,7 @@ func (s *fseDecoder) buildDtable() error { // Seems weird that this is possible with nbits > 0. return fmt.Errorf("newState (%d) == oldState (%d) and no bits", newState, u) } - s.dt[u&maxTableMask].setNewState(newState) + s.dt[u&maxTableMask] = ext[symbol] | decSymbol(nBits) | decSymbol(newState)<<16 } } return nil diff --git a/vendor/github.com/klauspost/compress/zstd/fse_predefined.go b/vendor/github.com/klauspost/compress/zstd/fse_predefined.go index 474cb77..7880b6f 100644 --- a/vendor/github.com/klauspost/compress/zstd/fse_predefined.go +++ b/vendor/github.com/klauspost/compress/zstd/fse_predefined.go @@ -25,6 +25,10 @@ var ( // https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#the-codes-for-literals-lengths-match-lengths-and-offsets symbolTableX [3][]baseOffset + // symbolExtX holds symbolTableX as decSymbols carrying only addBits and + // baseline, which buildDtable merges into each state. + symbolExtX [3]symbolExt + // maxTableSymbol is the biggest supported symbol for each table type // https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#the-codes-for-literals-lengths-match-lengths-and-offsets maxTableSymbol = [3]uint8{tableLiteralLengths: maxLiteralLengthSymbol, tableOffsets: maxOffsetLengthSymbol, tableMatchLengths: maxMatchLengthSymbol} @@ -105,6 +109,15 @@ func initPredefined() { } fillBase(tmp[2:], 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30) symbolTableX[tableOffsets] = tmp + for i, t := range symbolTableX { + for j, lu := range t { + // fseDecoder.buildDtable takes maxBits from the last symbol. + if j > 0 && lu.addBits < t[j-1].addBits { + panic(fmt.Sprintf("table %v: addBits decreases at symbol %d", tableIndex(i), j)) + } + symbolExtX[i][j] = newDecSymbol(0, lu.addBits, 0, lu.baseLine) + } + } // Fill predefined tables and transform them. // https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#default-distributions @@ -135,10 +148,7 @@ func initPredefined() { -1, -1, -1, -1, -1}) f.symbolLen = 53 } - if err := f.buildDtable(); err != nil { - panic(fmt.Errorf("building table %v: %v", tableIndex(i), err)) - } - if err := f.transform(symbolTableX[i]); err != nil { + if err := f.buildDtable(&symbolExtX[i]); err != nil { panic(fmt.Errorf("building table %v: %v", tableIndex(i), err)) } f.preDefined = true diff --git a/vendor/github.com/klauspost/compress/zstd/hash.go b/vendor/github.com/klauspost/compress/zstd/hash.go index 5d73c21..2b606a3 100644 --- a/vendor/github.com/klauspost/compress/zstd/hash.go +++ b/vendor/github.com/klauspost/compress/zstd/hash.go @@ -4,6 +4,8 @@ package zstd +import "runtime" + const ( prime3bytes = 506832829 prime4bytes = 2654435761 @@ -13,6 +15,12 @@ const ( prime8bytes = 0xcf1bbcdcb7a56463 ) +// hashPrimesInRegs reports whether encoders should keep the 64-bit hash primes +// in registers rather than as constants. The compiler rebuilds a constant at +// every use: one instruction on amd64, but up to 4 on arm64, which also has +// the registers to spare. See hashPrimes8and5. +const hashPrimesInRegs = runtime.GOARCH == "arm64" + // hashLen returns a hash of the lowest mls bytes of with length output bits. // mls must be >=3 and <=8. Any other value will return hash for 4 bytes. // length should always be < 32. @@ -33,3 +41,17 @@ func hashLen(u uint64, length, mls uint8) uint32 { return (uint32(u) * prime4bytes) >> (32 - length) } } + +// hashPrimes85 is a var so arm64 keeps the primes in registers instead of +// rebuilding each 64-bit prime with up to 4 instructions per use. +var hashPrimes85 = [2]uint64{prime8bytes, prime5bytes} + +// hashPrimes8and5 returns prime8bytes and prime5bytes for encoders that hash +// 8 and 5 bytes. Where registers are too scarce to hold them, it returns the +// constants. +func hashPrimes8and5() (prime8, prime5 uint64) { + if hashPrimesInRegs { + return hashPrimes85[0], hashPrimes85[1] + } + return prime8bytes, prime5bytes +} diff --git a/vendor/github.com/klauspost/compress/zstd/history.go b/vendor/github.com/klauspost/compress/zstd/history.go index 0916485..76e4c30 100644 --- a/vendor/github.com/klauspost/compress/zstd/history.go +++ b/vendor/github.com/klauspost/compress/zstd/history.go @@ -24,16 +24,26 @@ type history struct { // when checking for matches in history ignoreBuffer int - windowSize int - allocFrameBuffer int // needed? - error bool - dict *dict + windowSize int + error bool + dict *dict + + // ring backs b when streaming (see ensureBlockRing). + // ext holds the part of the previous lap of ring still in the window, + // which precedes b[0] in the stream; nil when b holds all history. + // The previous lap is ring[extStart:extEnd]. + ring []byte + ext []byte + extStart int + extEnd int } // reset will reset the history to initial state of a frame. // The history must already have been initialized to the desired size. func (h *history) reset() { h.b = h.b[:0] + h.ext = nil + h.extStart, h.extEnd = 0, 0 h.ignoreBuffer = 0 h.error = false h.recentOffsets = [3]int{1, 4, 8} @@ -67,47 +77,40 @@ func (h *history) setDict(dict *dict) { h.huffTree = dict.litEnc } -// append bytes to history. -// This function will make sure there is space for it, -// if the buffer has been allocated with enough extra space. -func (h *history) append(b []byte) { - if len(b) >= h.windowSize { - // Discard all history by simply overwriting - h.b = h.b[:h.windowSize] - copy(h.b, b[len(b)-h.windowSize:]) - return +// ensureBlockRing makes room for the next block without moving history, +// as the reference decoder does. b is a prefix of ring capped to one block +// of space. When a block no longer fits, the data written so far becomes +// ext and writing restarts at the front of ring. ext is trimmed so the +// block space ahead of b never overlaps it; with ring sized to window plus +// two blocks of space, b and ext together always hold a full window. +func (h *history) ensureBlockRing() { + // Room for the largest block plus the overrun of the fast copies. + ringBlockSpace := min(h.windowSize, maxCompressedBlockSize) + compressedBlockOverAlloc + size := h.windowSize + 2*ringBlockSpace + pos := len(h.b) + if cap(h.ring) < size || (pos > 0 && &h.b[0] != &h.ring[0]) { + // No ring yet, or b no longer lives in it: start one, keeping up + // to a window of what was decoded so far as the previous lap. + keep := min(pos, h.windowSize) + if cap(h.ring) < size { + h.ring = make([]byte, size) + } + h.ring = h.ring[:size] + copy(h.ring[size-keep:], h.b[pos-keep:]) + h.extStart, h.extEnd = size-keep, size + pos = 0 + } else if pos+ringBlockSpace > size { + // Wrap: everything written this lap becomes the previous lap. + h.extStart, h.extEnd = 0, pos + pos = 0 } - - // If there is space, append it. - if len(b) < cap(h.b)-len(h.b) { - h.b = append(h.b, b...) - return + h.ring = h.ring[:size] + end := pos + ringBlockSpace + h.b = h.ring[:pos:end] + h.ext = nil + if start := max(end, h.extStart); start < h.extEnd { + h.ext = h.ring[start:h.extEnd] } - - // Move data down so we only have window size left. - // We know we have less than window size in b at this point. - discard := len(b) + len(h.b) - h.windowSize - copy(h.b, h.b[discard:]) - h.b = h.b[:h.windowSize] - copy(h.b[h.windowSize-len(b):], b) -} - -// ensureBlock will ensure there is space for at least one block... -func (h *history) ensureBlock() { - if cap(h.b) < h.allocFrameBuffer { - h.b = make([]byte, 0, h.allocFrameBuffer) - return - } - - avail := cap(h.b) - len(h.b) - if avail >= h.windowSize || avail > maxCompressedBlockSize { - return - } - // Move data down so we only have window size left. - // We know we have less than window size in b at this point. - discard := len(h.b) - h.windowSize - copy(h.b, h.b[discard:]) - h.b = h.b[:h.windowSize] } // append bytes to history without ever discarding anything. diff --git a/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash.go b/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash.go index fc40c82..9c0cbc1 100644 --- a/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash.go +++ b/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash.go @@ -52,6 +52,11 @@ func (d *Digest) Reset() { d.n = 0 } +// maxAsmSize bounds the input handed to a single writeBlocks call. Assembly is +// never preemptible, so an unbounded call holds every P in stop-the-world for +// its duration. Whole 32-byte blocks, so Write can feed it in pieces. +const maxAsmSize = 128 << 10 // 4096 whole 32-byte blocks + // Size always returns 8 bytes. func (d *Digest) Size() int { return 8 } @@ -83,6 +88,13 @@ func (d *Digest) Write(b []byte) (n int, err error) { d.n = 0 } + for len(b) >= maxAsmSize { + // Assembly is not preemptible, so hashing a large buffer in one call + // blocks every stop-the-world for the whole call. Feed it in chunks. + writeBlocks(d, b[:maxAsmSize]) + b = b[maxAsmSize:] + } + if len(b) >= 32 { // One or more full blocks left. nw := writeBlocks(d, b) diff --git a/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_amd64.s b/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_amd64.s index ddb63aa..95d7980 100644 --- a/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_amd64.s +++ b/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_amd64.s @@ -1,8 +1,4 @@ -//go:build !appengine && gc && !purego && !noasm -// +build !appengine -// +build gc -// +build !purego -// +build !noasm +//go:build gc && !purego && !noasm #include "textflag.h" @@ -175,7 +171,11 @@ finalize: RET // func writeBlocks(d *Digest, b []byte) int -TEXT ·writeBlocks(SB), NOSPLIT|NOFRAME, $0-40 +// +// Deliberately not NOSPLIT: the stack check is the preemption point that lets a +// stop-the-world proceed between chunks. The frame must be >= abi.StackSmall +// (128), or the assembler marks this leaf NOSPLIT anyway and drops that check. +TEXT ·writeBlocks(SB), $128-40 // Load fixed primes needed for round. MOVQ ·primes+0(SB), prime1 MOVQ ·primes+8(SB), prime2 diff --git a/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_arm64.s b/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_arm64.s index ae7d4d3..a09d43b 100644 --- a/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_arm64.s +++ b/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_arm64.s @@ -1,8 +1,4 @@ -//go:build !appengine && gc && !purego && !noasm -// +build !appengine -// +build gc -// +build !purego -// +build !noasm +//go:build gc && !purego && !noasm #include "textflag.h" @@ -163,7 +159,11 @@ finalize: RET // func writeBlocks(s *Digest, b []byte) int -TEXT ·writeBlocks(SB), NOSPLIT|NOFRAME, $0-40 +// +// Deliberately not NOSPLIT: the stack check is the preemption point that lets a +// stop-the-world proceed between chunks. The frame must be >= abi.StackSmall +// (128), or the assembler marks this leaf NOSPLIT anyway and drops that check. +TEXT ·writeBlocks(SB), $128-40 LDP ·primes+0(SB), (prime1, prime2) // Load state. Assume v[1-4] are stored contiguously. diff --git a/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_asm.go b/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_asm.go index d4221ed..8a0170d 100644 --- a/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_asm.go +++ b/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_asm.go @@ -1,9 +1,4 @@ -//go:build (amd64 || arm64) && !appengine && gc && !purego && !noasm -// +build amd64 arm64 -// +build !appengine -// +build gc -// +build !purego -// +build !noasm +//go:build (amd64 || arm64) && gc && !purego && !noasm package xxhash diff --git a/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_other.go b/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_other.go index 9576426..83fd719 100644 --- a/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_other.go +++ b/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_other.go @@ -1,4 +1,4 @@ -//go:build (!amd64 && !arm64) || appengine || !gc || purego || noasm +//go:build (!amd64 && !arm64) || !gc || purego || noasm package xxhash diff --git a/vendor/github.com/klauspost/compress/zstd/matchlen_amd64.go b/vendor/github.com/klauspost/compress/zstd/matchlen_amd64.go index 1ed1892..1d89a60 100644 --- a/vendor/github.com/klauspost/compress/zstd/matchlen_amd64.go +++ b/vendor/github.com/klauspost/compress/zstd/matchlen_amd64.go @@ -1,4 +1,4 @@ -//go:build amd64 && !appengine && !noasm && gc +//go:build amd64 && !noasm && gc // Copyright 2019+ Klaus Post. All rights reserved. // License information can be found in the LICENSE file. diff --git a/vendor/github.com/klauspost/compress/zstd/matchlen_amd64.s b/vendor/github.com/klauspost/compress/zstd/matchlen_amd64.s index 0782b86..760046f 100644 --- a/vendor/github.com/klauspost/compress/zstd/matchlen_amd64.s +++ b/vendor/github.com/klauspost/compress/zstd/matchlen_amd64.s @@ -1,6 +1,6 @@ // Copied from S2 implementation. -//go:build !appengine && !noasm && gc && !noasm +//go:build !noasm && gc #include "textflag.h" diff --git a/vendor/github.com/klauspost/compress/zstd/matchlen_generic.go b/vendor/github.com/klauspost/compress/zstd/matchlen_generic.go index 379746c..ec47656 100644 --- a/vendor/github.com/klauspost/compress/zstd/matchlen_generic.go +++ b/vendor/github.com/klauspost/compress/zstd/matchlen_generic.go @@ -1,4 +1,4 @@ -//go:build !amd64 || appengine || !gc || noasm +//go:build !amd64 || !gc || noasm // Copyright 2019+ Klaus Post. All rights reserved. // License information can be found in the LICENSE file. diff --git a/vendor/github.com/klauspost/compress/zstd/seqdec.go b/vendor/github.com/klauspost/compress/zstd/seqdec.go index 0bfb0e4..3963b86 100644 --- a/vendor/github.com/klauspost/compress/zstd/seqdec.go +++ b/vendor/github.com/klauspost/compress/zstd/seqdec.go @@ -76,6 +76,31 @@ type sequenceDecs struct { maxSyncLen uint64 } +// twoPassFarCode is the offset code from which a match counts as far: 20 is +// 1 MiB, the distance every measured arm64 core gains from. A Neoverse N1 +// (Graviton2, Ampere Altra) gains from 128 KiB too, but that needs a +// per-core threshold override; not worth the CPU-specific special case for +// a core class already being phased out of the fleet. +const twoPassFarCode = 20 + +// useTwoPass reports whether the block is decoded in two passes with the +// match-source prefetch (seqdec_arm64.go): a window of at least +// decodeTwoPassMinWindow and, unless the offset table is predefined or +// RLE, a share of at least twoPassMinFarShare of codes twoPassFarCode+. +func (s *sequenceDecs) useTwoPass() bool { + if s.windowSize < decodeTwoPassMinWindow { + return false + } + fse := s.offsets.fse + if fse != nil && !fse.preDefined && fse.actualTableLog != 0 && int(fse.symbolLen) <= twoPassFarCode { + // No symbol reaches twoPassFarCode, so codeShare can only return 0: + // skip finding it. + return false + } + share := fse.codeShare(twoPassFarCode) + return share < 0 || share >= twoPassMinFarShare +} + // initialize all 3 decoders from the stream input. func (s *sequenceDecs) initialize(br *bitReader, hist *history, out []byte) error { if err := s.litLengths.init(br); err != nil { @@ -99,6 +124,29 @@ func (s *sequenceDecs) initialize(br *bitReader, hist *history, out []byte) erro return nil } +// consumeSyncLen accounts for n bytes of frame output produced outside +// decodeSync. maxSyncLen bounds how much the frame may still produce and +// decodeSyncSimple compares it with the output buffer's slack to decide +// whether the extended 16-byte copies are safe. Blocks with sequences +// subtracted their output; raw blocks, RLE blocks and compressed blocks +// holding only literals did not, so a frame that opened with a raw block +// overstated its remaining size for every block after it and ran the +// bounds-exact copies for the rest of the frame. +// +// Zero means "no bound" and selects the conservative paths, so a block that +// meets or exceeds the bound lands there; the frame-size checks in +// runDecoder reject the excess afterwards. +func (s *sequenceDecs) consumeSyncLen(n int) { + if s.maxSyncLen == 0 { + return + } + if uint64(n) >= s.maxSyncLen { + s.maxSyncLen = 0 + return + } + s.maxSyncLen -= uint64(n) +} + func (s *sequenceDecs) freeDecoders() { if f := s.litLengths.fse; f != nil && !f.preDefined { fseDecoderPool.Put(f) @@ -134,15 +182,30 @@ func (s *sequenceDecs) execute(seqs []seqVals, hist []byte) error { var t = len(s.out) out := s.out[:t+s.seqSize] + literals := s.literals + windowSize := s.windowSize + dict := s.dict for _, seq := range seqs { + // Short sequences copy 16 bytes for each part. + if seq.ll <= 16 && seq.ml <= 16 && t+seq.ll+16 <= cap(out) && cap(literals) >= 16 { + if src := matchSource(out, hist, dict, t+seq.ll, seq.mo, 16, windowSize); src != nil { + *(*[16]byte)(out[t : t+16]) = *(*[16]byte)(literals[:16]) + t += seq.ll + *(*[16]byte)(out[t : t+16]) = *(*[16]byte)(src) + t += seq.ml + literals = literals[seq.ll:] + continue + } + } + // Add literals - copy(out[t:], s.literals[:seq.ll]) + copy(out[t:], literals[:seq.ll]) t += seq.ll - s.literals = s.literals[seq.ll:] + literals = literals[seq.ll:] // Copy from dictionary... - if seq.mo > t+len(hist) || seq.mo > s.windowSize { + if seq.mo > t+len(hist) || seq.mo > windowSize { if len(s.dict) == 0 { return fmt.Errorf("match offset (%d) bigger than current history (%d)", seq.mo, t+len(hist)) } @@ -191,23 +254,17 @@ func (s *sequenceDecs) execute(seqs []seqVals, hist []byte) error { continue } else { // Overlapping copy - // Extend destination slice and copy one byte at the time. - src := out[start : start+seq.ml] - dst := out[t:] - dst = dst[:len(src)] - t += len(src) - // Destination is the space we just added. - for i := range src { - dst[i] = src[i] - } + overlapCopy(out, start, t, seq.ml) + t += seq.ml } } } // Add final literals - copy(out[t:], s.literals) + copy(out[t:], literals) + s.literals = literals if debugDecoder { - t += len(s.literals) + t += len(literals) if t != len(out) { panic(fmt.Errorf("length mismatch, want %d, got %d, ss: %d", len(out), t, s.seqSize)) } @@ -217,184 +274,148 @@ func (s *sequenceDecs) execute(seqs []seqVals, hist []byte) error { return nil } +// decodeSyncGoOnly makes decodeSync skip the assembly decoder, so tests can +// compare it with the Go one in the same binary. +var decodeSyncGoOnly bool + // decode sequences from the stream with the provided history. func (s *sequenceDecs) decodeSync(hist []byte) error { - supported, err := s.decodeSyncSimple(hist) - if supported { - return err + if !decodeSyncGoOnly { + supported, err := s.decodeSyncSimple(hist) + if supported { + return err + } } + // The bit reader, repeat offsets and literals are held in locals so + // they stay in registers; they are written back on success. br := s.br + in, bs := br.in, br.state() + prev0, prev1, prev2 := s.prevOffset[0], s.prevOffset[1], s.prevOffset[2] + literals := s.literals + maxBits := s.maxBits + windowSize := s.windowSize + dict := s.dict seqs := s.nSeqs startSize := len(s.out) // Grab full sizes tables, to avoid bounds checks. llTable, mlTable, ofTable := s.litLengths.fse.dt[:maxTablesize], s.matchLengths.fse.dt[:maxTablesize], s.offsets.fse.dt[:maxTablesize] llState, mlState, ofState := s.litLengths.state.state, s.matchLengths.state.state, s.offsets.state.state out := s.out - maxBlockSize := min(s.windowSize, maxCompressedBlockSize) + maxBlockSize := min(windowSize, maxCompressedBlockSize) if debugDecoder { println("decodeSync: decoding", seqs, "sequences", br.remain(), "bits remain on stream") } for i := seqs - 1; i >= 0; i-- { - if br.overread() { + if bs.bitsRead > 64 { + br.setState(bs) printf("reading sequence %d, exceeded available data. Overread by %d\n", seqs-i, -br.remain()) return io.ErrUnexpectedEOF } var ll, mo, ml int - if br.cursor > 4+((maxOffsetBits+16+16)>>3) { - // inlined function: - // ll, mo, ml = s.nextFast(br, llState, mlState, ofState) + // Final will not read from stream. + var llB, mlB, moB uint8 + ll, llB = llState.final() + ml, mlB = mlState.final() + mo, moB = ofState.final() - // Final will not read from stream. - var llB, mlB, moB uint8 - ll, llB = llState.final() - ml, mlB = mlState.final() - mo, moB = ofState.final() - - // extra bits are stored in reverse order. - br.fillFast() - mo += br.getBits(moB) - if s.maxBits > 32 { - br.fillFast() - } - ml += br.getBits(mlB) - ll += br.getBits(llB) - - if moB > 1 { - s.prevOffset[2] = s.prevOffset[1] - s.prevOffset[1] = s.prevOffset[0] - s.prevOffset[0] = mo - } else { - // mo = s.adjustOffset(mo, ll, moB) - // Inlined for rather big speedup - if ll == 0 { - // There is an exception though, when current sequence's literals_length = 0. - // In this case, repeated offsets are shifted by one, so an offset_value of 1 means Repeated_Offset2, - // an offset_value of 2 means Repeated_Offset3, and an offset_value of 3 means Repeated_Offset1 - 1_byte. - mo++ - } - - if mo == 0 { - mo = s.prevOffset[0] - } else { - var temp int - if mo == 3 { - temp = s.prevOffset[0] - 1 - } else { - temp = s.prevOffset[mo] - } - - if temp == 0 { - // 0 is not valid; input is corrupted; force offset to 1 - println("WARNING: temp was 0") - temp = 1 - } - - if mo != 1 { - s.prevOffset[2] = s.prevOffset[1] - } - s.prevOffset[1] = s.prevOffset[0] - s.prevOffset[0] = temp - mo = temp - } - } - br.fillFast() - } else { - ll, mo, ml = s.next(br, llState, mlState, ofState) - br.fill() + // extra bits are stored in reverse order. + var v int + bs = bs.fill(in) + bs, v = bs.getBits(moB) + mo += v + if maxBits > 32 { + bs = bs.fill(in) } + bs, v = bs.getBits(mlB) + ml += v + bs, v = bs.getBits(llB) + ll += v + + if moB > 1 { + prev2 = prev1 + prev1 = prev0 + prev0 = mo + } else { + // mo = s.adjustOffset(mo, ll, moB) + // Inlined for rather big speedup + if ll == 0 { + // There is an exception though, when current sequence's literals_length = 0. + // In this case, repeated offsets are shifted by one, so an offset_value of 1 means Repeated_Offset2, + // an offset_value of 2 means Repeated_Offset3, and an offset_value of 3 means Repeated_Offset1 - 1_byte. + mo++ + } + + if mo == 0 { + mo = prev0 + } else { + var temp int + switch mo { + case 1: + temp = prev1 + case 2: + temp = prev2 + default: + temp = prev0 - 1 + } + + if temp == 0 { + // 0 is not valid; input is corrupted; force offset to 1 + println("WARNING: temp was 0") + temp = 1 + } + + if mo != 1 { + prev2 = prev1 + } + prev1 = prev0 + prev0 = temp + mo = temp + } + } + bs = bs.fill(in) if debugSequences { println("Seq", seqs-i-1, "Litlen:", ll, "mo:", mo, "(abs) ml:", ml) } - if ll > len(s.literals) { - return fmt.Errorf("unexpected literal count, want %d bytes, but only %d is available", ll, len(s.literals)) + if ll > len(literals) { + return fmt.Errorf("unexpected literal count, want %d bytes, but only %d is available", ll, len(literals)) } size := ll + ml + len(out) if size-startSize > maxBlockSize { return fmt.Errorf("output bigger than max block size (%d)", maxBlockSize) } - if size > cap(out) { - // Not enough size, which can happen under high volume block streaming conditions - // but could be if destination slice is too small for sync operations. - // over-allocating here can create a large amount of GC pressure so we try to keep - // it as contained as possible - used := len(out) - startSize - addBytes := 256 + ll + ml + used>>2 - // Clamp to max block size. - if used+addBytes > maxBlockSize { - addBytes = maxBlockSize - used - } - out = append(out, make([]byte, addBytes)...) - out = out[:len(out)-addBytes] + // Matches from earlier output, the history or the dictionary are + // copied without calling executeSeq; short ones with fixed 16-byte copies, with no + // calls so the loop state stays in registers. + t := len(out) + p := t + ll + short := ll <= 16 && ml <= 16 && p+16 <= cap(out) && cap(literals) >= 16 + var src []byte + if short { + src = matchSource(out, hist, dict, p, mo, 16, windowSize) } - if ml > maxMatchLen { - return fmt.Errorf("match len (%d) bigger than max allowed length", ml) + if src == nil && p+ml <= cap(out) { + short = false + src = matchSource(out, hist, dict, p, mo, ml, windowSize) } - - // Add literals - out = append(out, s.literals[:ll]...) - s.literals = s.literals[ll:] - - if mo == 0 && ml > 0 { - return fmt.Errorf("zero matchoff and matchlen (%d) > 0", ml) - } - - if mo > len(out)+len(hist) || mo > s.windowSize { - if len(s.dict) == 0 { - return fmt.Errorf("match offset (%d) bigger than current history (%d)", mo, len(out)+len(hist)-startSize) - } - - // we may be in dictionary. - dictO := len(s.dict) - (mo - (len(out) + len(hist))) - if dictO < 0 || dictO >= len(s.dict) { - return fmt.Errorf("match offset (%d) bigger than current history (%d)", mo, len(out)+len(hist)-startSize) - } - end := dictO + ml - if end > len(s.dict) { - out = append(out, s.dict[dictO:]...) - ml -= len(s.dict) - dictO - } else { - out = append(out, s.dict[dictO:end]...) - mo = 0 - ml = 0 - } - } - - // Copy from history. - // TODO: Blocks without history could be made to ignore this completely. - if v := mo - len(out); v > 0 { - // v is the start position in history from end. - start := len(hist) - v - if ml > v { - // Some goes into current block. - // Copy remainder of history - out = append(out, hist[start:]...) - ml -= v - } else { - out = append(out, hist[start:start+ml]...) - ml = 0 - } - } - // We must be in current buffer now - if ml > 0 { - start := len(out) - mo - if ml <= len(out)-start { - // No overlap - out = append(out, out[start:start+ml]...) - } else { - // Overlapping copy - // Extend destination slice and copy one byte at the time. - out = out[:len(out)+ml] - src := out[start : start+ml] - // Destination is the space we just added. - dst := out[len(out)-ml:] - dst = dst[:len(src)] - for i := range src { - dst[i] = src[i] - } + if short { + *(*[16]byte)(out[t : t+16]) = *(*[16]byte)(literals[:16]) + *(*[16]byte)(out[p : p+16]) = *(*[16]byte)(src) + out = out[:p+ml] + literals = literals[ll:] + } else if src != nil { + out = out[:p+ml] + copy(out[t:p], literals[:ll]) + copy(out[p:], src) + literals = literals[ll:] + } else { + var err error + out, literals, err = s.executeSeq(out, literals, hist, ll, mo, ml, startSize, maxBlockSize) + if err != nil { + return err } } if i == 0 { @@ -410,7 +431,8 @@ func (s *sequenceDecs) decodeSync(hist []byte) error { mlState = mlTable[mlState.newState()&maxTableMask] ofState = ofTable[ofState.newState()&maxTableMask] } else { - bits := br.get32BitsFast(nBits) + var bits uint32 + bs, bits = bs.get32BitsFast(nBits) lowBits := uint16(bits >> ((ofState.nbBits() + mlState.nbBits()) & 31)) llState = llTable[(llState.newState()+lowBits)&maxTableMask] @@ -424,15 +446,132 @@ func (s *sequenceDecs) decodeSync(hist []byte) error { } } - if size := len(s.literals) + len(out) - startSize; size > maxBlockSize { + if size := len(literals) + len(out) - startSize; size > maxBlockSize { return fmt.Errorf("output bigger than max block size (%d)", maxBlockSize) } // Add final literals - s.out = append(out, s.literals...) + s.out = append(out, literals...) + s.literals = literals + s.prevOffset = [3]int{prev0, prev1, prev2} + br.setState(bs) return br.close() } +// overlapCopy writes n bytes at out[t:] repeating out[start:t], which +// overlaps the destination. Each copy doubles the repeated span, so it takes +// about log2(n/(t-start)) copies instead of n byte moves. +func overlapCopy(out []byte, start, t, n int) { + if start >= t { + // Nothing to repeat; callers reject a zero offset. + return + } + for end := t + n; t < end; { + t += copy(out[t:end], out[start:t]) + } +} + +// matchSource returns the n bytes a match of length n at p in out copies +// from: earlier output it does not overlap, the history or the dictionary. +// It returns nil when the match needs the general path. It must stay +// inlinable: a call would spill the decode loop's state. +func matchSource(out, hist, dict []byte, p, mo, n, windowSize int) []byte { + // v is how far the match starts back from the end of hist, and d how + // far it reaches past hist into dict. + if mo <= windowSize { + if mo >= n && mo <= p { + return out[p-mo : p-mo+n] + } + if v := mo - p; v >= n && v <= len(hist) { + return hist[len(hist)-v:][:n] + } + } + if d := mo - (p + len(hist)); d >= n && d <= len(dict) { + return dict[len(dict)-d:][:n] + } + return nil +} + +// executeSeq appends the literals and match of one sequence to out and +// returns the updated out and remaining literals. +func (s *sequenceDecs) executeSeq(out, literals, hist []byte, ll, mo, ml, startSize, maxBlockSize int) ([]byte, []byte, error) { + if ll+ml+len(out) > cap(out) { + // Not enough size, which can happen under high volume block streaming conditions + // but could be if destination slice is too small for sync operations. + // over-allocating here can create a large amount of GC pressure so we try to keep + // it as contained as possible + used := len(out) - startSize + addBytes := 256 + ll + ml + used>>2 + // Clamp to max block size. + if used+addBytes > maxBlockSize { + addBytes = maxBlockSize - used + } + out = append(out, make([]byte, addBytes)...) + out = out[:len(out)-addBytes] + } + if ml > maxMatchLen { + return nil, nil, fmt.Errorf("match len (%d) bigger than max allowed length", ml) + } + + // Add literals + out = append(out, literals[:ll]...) + literals = literals[ll:] + + if mo == 0 && ml > 0 { + return nil, nil, fmt.Errorf("zero matchoff and matchlen (%d) > 0", ml) + } + + if mo > len(out)+len(hist) || mo > s.windowSize { + if len(s.dict) == 0 { + return nil, nil, fmt.Errorf("match offset (%d) bigger than current history (%d)", mo, len(out)-startSize) + } + + // we may be in dictionary. + dictO := len(s.dict) - (mo - (len(out) + len(hist))) + if dictO < 0 || dictO >= len(s.dict) { + return nil, nil, fmt.Errorf("match offset (%d) bigger than current history (%d)", mo, len(out)-startSize) + } + end := dictO + ml + if end > len(s.dict) { + out = append(out, s.dict[dictO:]...) + ml -= len(s.dict) - dictO + } else { + out = append(out, s.dict[dictO:end]...) + mo = 0 + ml = 0 + } + } + + // Copy from history. + // TODO: Blocks without history could be made to ignore this completely. + if v := mo - len(out); v > 0 { + // v is the start position in history from end. + start := len(hist) - v + if ml > v { + // Some goes into current block. + // Copy remainder of history + out = append(out, hist[start:]...) + ml -= v + } else { + out = append(out, hist[start:start+ml]...) + ml = 0 + } + } + // We must be in current buffer now + if ml > 0 { + start := len(out) - mo + if ml <= len(out)-start { + // No overlap + out = append(out, out[start:start+ml]...) + } else { + // Overlapping copy + out = out[:len(out)+ml] + overlapCopy(out, start, len(out)-ml, ml) + } + } + return out, literals, nil +} + var bitMask [16]uint16 func init() { @@ -441,25 +580,6 @@ func init() { } } -func (s *sequenceDecs) next(br *bitReader, llState, mlState, ofState decSymbol) (ll, mo, ml int) { - // Final will not read from stream. - ll, llB := llState.final() - ml, mlB := mlState.final() - mo, moB := ofState.final() - - // extra bits are stored in reverse order. - br.fill() - mo += br.getBits(moB) - if s.maxBits > 32 { - br.fill() - } - // matchlength+literal length, max 32 bits - ml += br.getBits(mlB) - ll += br.getBits(llB) - mo = s.adjustOffset(mo, ll, moB) - return -} - func (s *sequenceDecs) adjustOffset(offset, litLen int, offsetB uint8) int { if offsetB > 1 { s.prevOffset[2] = s.prevOffset[1] diff --git a/vendor/github.com/klauspost/compress/zstd/seqdec_amd64.go b/vendor/github.com/klauspost/compress/zstd/seqdec_amd64.go index 1281da8..968f5b6 100644 --- a/vendor/github.com/klauspost/compress/zstd/seqdec_amd64.go +++ b/vendor/github.com/klauspost/compress/zstd/seqdec_amd64.go @@ -1,8 +1,10 @@ -//go:build amd64 && !appengine && !noasm && gc +//go:build amd64 && !noasm && gc package zstd import ( + "math" + "github.com/klauspost/compress/internal/cpuinfo" ) @@ -10,6 +12,14 @@ import ( // in seqdec_asm.go; this file only declares the amd64 asm routines and the // dispatch helpers that pick the BMI2 / non-BMI2 (and 56-bit / safe) variant. +// See seqdec_arm64.go. Disabled here: on Sapphire Rapids, Granite Rapids +// and Zen 4 the two-pass decode costs 7-12% on real data; their caches +// already cover the offsets involved. +var ( + twoPassMinFarShare = 257 // never: the share is at most 256 + decodeTwoPassMinWindow = math.MaxInt +) + // sequenceDecs_decode implements the main loop of sequenceDecs in x86 asm. // // Please refer to seqdec_generic.go for the reference implementation. diff --git a/vendor/github.com/klauspost/compress/zstd/seqdec_amd64.s b/vendor/github.com/klauspost/compress/zstd/seqdec_amd64.s index 4d3188f..f85fddf 100644 --- a/vendor/github.com/klauspost/compress/zstd/seqdec_amd64.s +++ b/vendor/github.com/klauspost/compress/zstd/seqdec_amd64.s @@ -1,10 +1,10 @@ -// Code generated by command: go run gen.go -out ../seqdec.s -arch amd64,arm64 -pkg=zstd. DO NOT EDIT. +// Code generated by command: go run gen.go -out ../seqdec.s -arch amd64,arm64 -arm64-promote-stack-slots -arm64-pair-vector-moves -pkg=zstd. DO NOT EDIT. -//go:build !appengine && !noasm && gc && !noasm +//go:build !noasm && gc // func sequenceDecs_decode_amd64(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int // Requires: CMOV -TEXT ·sequenceDecs_decode_amd64(SB), $8-32 +TEXT ·sequenceDecs_decode_amd64(SB), $40-32 MOVQ br+8(FP), CX MOVQ 24(CX), DX MOVBQZX 40(CX), BX @@ -16,11 +16,20 @@ TEXT ·sequenceDecs_decode_amd64(SB), $8-32 MOVQ 72(AX), DI MOVQ 80(AX), R8 MOVQ 88(AX), R9 + MOVQ (AX), CX + MOVQ CX, 8(SP) + MOVQ 24(AX), CX + MOVQ CX, 16(SP) + MOVQ 48(AX), CX + MOVQ CX, 24(SP) + MOVQ 96(AX), CX + MOVQ CX, 32(SP) MOVQ 104(AX), R10 MOVQ s+0(FP), AX MOVQ 144(AX), R11 MOVQ 152(AX), R12 MOVQ 160(AX), R13 + PCALIGN $0x40 sequenceDecs_decode_amd64_main_loop: MOVQ (SP), R14 @@ -55,46 +64,32 @@ sequenceDecs_decode_amd64_fill_check_overread: sequenceDecs_decode_amd64_fill_end: // Update offset - MOVQ R9, AX - MOVQ BX, CX - MOVQ DX, R15 - SHLQ CL, R15 - MOVB AH, CL - SHRQ $0x20, AX - TESTQ CX, CX - JZ sequenceDecs_decode_amd64_of_update_zero - ADDQ CX, BX - CMPQ BX, $0x40 - JA sequenceDecs_decode_amd64_of_update_zero - CMPQ CX, $0x40 - JAE sequenceDecs_decode_amd64_of_update_zero - NEGQ CX - SHRQ CL, R15 - ADDQ R15, AX - -sequenceDecs_decode_amd64_of_update_zero: - MOVQ AX, 16(R10) + MOVQ R9, AX + MOVQ BX, CX + MOVQ DX, R15 + SHLQ CL, R15 + SHRQ $0x01, R15 + MOVBLZX AH, CX + SHRQ $0x20, AX + ADDQ CX, BX + XORQ $0x3f, CX + SHRQ CL, R15 + ADDQ R15, AX + MOVQ AX, 16(R10) // Update match length - MOVQ R8, AX - MOVQ BX, CX - MOVQ DX, R15 - SHLQ CL, R15 - MOVB AH, CL - SHRQ $0x20, AX - TESTQ CX, CX - JZ sequenceDecs_decode_amd64_ml_update_zero - ADDQ CX, BX - CMPQ BX, $0x40 - JA sequenceDecs_decode_amd64_ml_update_zero - CMPQ CX, $0x40 - JAE sequenceDecs_decode_amd64_ml_update_zero - NEGQ CX - SHRQ CL, R15 - ADDQ R15, AX - -sequenceDecs_decode_amd64_ml_update_zero: - MOVQ AX, 8(R10) + MOVQ R8, AX + MOVQ BX, CX + MOVQ DX, R15 + SHLQ CL, R15 + SHRQ $0x01, R15 + MOVBLZX AH, CX + SHRQ $0x20, AX + ADDQ CX, BX + XORQ $0x3f, CX + SHRQ CL, R15 + ADDQ R15, AX + MOVQ AX, 8(R10) // Fill bitreader to have enough for the remaining CMPQ SI, $0x08 @@ -126,90 +121,76 @@ sequenceDecs_decode_amd64_fill_2_check_overread: sequenceDecs_decode_amd64_fill_2_end: // Update literal length - MOVQ DI, AX - MOVQ BX, CX - MOVQ DX, R15 - SHLQ CL, R15 - MOVB AH, CL - SHRQ $0x20, AX - TESTQ CX, CX - JZ sequenceDecs_decode_amd64_ll_update_zero - ADDQ CX, BX - CMPQ BX, $0x40 - JA sequenceDecs_decode_amd64_ll_update_zero - CMPQ CX, $0x40 - JAE sequenceDecs_decode_amd64_ll_update_zero - NEGQ CX - SHRQ CL, R15 - ADDQ R15, AX - -sequenceDecs_decode_amd64_ll_update_zero: - MOVQ AX, (R10) + MOVQ DI, AX + MOVQ BX, CX + MOVQ DX, R15 + SHLQ CL, R15 + SHRQ $0x01, R15 + MOVBLZX AH, CX + SHRQ $0x20, AX + ADDQ CX, BX + XORQ $0x3f, CX + SHRQ CL, R15 + ADDQ R15, AX + MOVQ AX, (R10) // Fill bitreader for state updates MOVQ R14, (SP) MOVQ R9, AX SHRQ $0x08, AX MOVBQZX AL, AX - MOVQ ctx+16(FP), CX - CMPQ 96(CX), $0x00 + CMPQ 32(SP), $0x00 JZ sequenceDecs_decode_amd64_skip_update // Update Literal Length State MOVBQZX DI, R14 SHRL $0x10, DI - LEAQ (BX)(R14*1), CX + MOVQ BX, CX MOVQ DX, R15 - MOVQ CX, BX - ROLQ CL, R15 - MOVL $0x00000001, BP - MOVB R14, CL - SHLL CL, BP - DECL BP - ANDQ BP, R15 + SHLQ CL, R15 + SHRQ $0x01, R15 + ADDQ R14, BX + XORQ $0x3f, R14 + MOVQ R14, CX + SHRQ CL, R15 ADDQ R15, DI // Load ctx.llTable - MOVQ ctx+16(FP), CX - MOVQ (CX), CX + MOVQ 8(SP), CX MOVQ (CX)(DI*8), DI // Update Match Length State MOVBQZX R8, R14 SHRL $0x10, R8 - LEAQ (BX)(R14*1), CX + MOVQ BX, CX MOVQ DX, R15 - MOVQ CX, BX - ROLQ CL, R15 - MOVL $0x00000001, BP - MOVB R14, CL - SHLL CL, BP - DECL BP - ANDQ BP, R15 + SHLQ CL, R15 + SHRQ $0x01, R15 + ADDQ R14, BX + XORQ $0x3f, R14 + MOVQ R14, CX + SHRQ CL, R15 ADDQ R15, R8 // Load ctx.mlTable - MOVQ ctx+16(FP), CX - MOVQ 24(CX), CX + MOVQ 16(SP), CX MOVQ (CX)(R8*8), R8 // Update Offset State MOVBQZX R9, R14 SHRL $0x10, R9 - LEAQ (BX)(R14*1), CX + MOVQ BX, CX MOVQ DX, R15 - MOVQ CX, BX - ROLQ CL, R15 - MOVL $0x00000001, BP - MOVB R14, CL - SHLL CL, BP - DECL BP - ANDQ BP, R15 + SHLQ CL, R15 + SHRQ $0x01, R15 + ADDQ R14, BX + XORQ $0x3f, R14 + MOVQ R14, CX + SHRQ CL, R15 ADDQ R15, R9 // Load ctx.ofTable - MOVQ ctx+16(FP), CX - MOVQ 48(CX), CX + MOVQ 24(SP), CX MOVQ (CX)(R9*8), R9 sequenceDecs_decode_amd64_skip_update: @@ -290,8 +271,7 @@ sequenceDecs_decode_amd64_after_adjust: sequenceDecs_decode_amd64_match_len_ofs_ok: ADDQ $0x18, R10 - MOVQ ctx+16(FP), AX - DECQ 96(AX) + DECQ 32(SP) JNS sequenceDecs_decode_amd64_main_loop MOVQ s+0(FP), AX MOVQ R11, 144(AX) @@ -303,36 +283,54 @@ sequenceDecs_decode_amd64_match_len_ofs_ok: MOVQ SI, 32(AX) // Return success + MOVQ 32(SP), AX + MOVQ ctx+16(FP), CX + MOVQ AX, 96(CX) MOVQ $0x00000000, ret+24(FP) RET // Return with match length error sequenceDecs_decode_amd64_error_match_len_ofs_mismatch: + MOVQ 32(SP), AX + MOVQ ctx+16(FP), CX + MOVQ AX, 96(CX) MOVQ $0x00000001, ret+24(FP) RET // Return with match too long error sequenceDecs_decode_amd64_error_match_len_too_big: + MOVQ 32(SP), AX + MOVQ ctx+16(FP), CX + MOVQ AX, 96(CX) MOVQ $0x00000002, ret+24(FP) RET // Return with match offset too long error + MOVQ 32(SP), AX + MOVQ ctx+16(FP), CX + MOVQ AX, 96(CX) MOVQ $0x00000003, ret+24(FP) RET // Return with not enough literals error error_not_enough_literals: + MOVQ 32(SP), AX + MOVQ ctx+16(FP), CX + MOVQ AX, 96(CX) MOVQ $0x00000004, ret+24(FP) RET // Return with overread error error_overread: + MOVQ 32(SP), AX + MOVQ ctx+16(FP), CX + MOVQ AX, 96(CX) MOVQ $0x00000006, ret+24(FP) RET // func sequenceDecs_decode_56_amd64(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int // Requires: CMOV -TEXT ·sequenceDecs_decode_56_amd64(SB), $8-32 +TEXT ·sequenceDecs_decode_56_amd64(SB), $40-32 MOVQ br+8(FP), CX MOVQ 24(CX), DX MOVBQZX 40(CX), BX @@ -344,11 +342,20 @@ TEXT ·sequenceDecs_decode_56_amd64(SB), $8-32 MOVQ 72(AX), DI MOVQ 80(AX), R8 MOVQ 88(AX), R9 + MOVQ (AX), CX + MOVQ CX, 8(SP) + MOVQ 24(AX), CX + MOVQ CX, 16(SP) + MOVQ 48(AX), CX + MOVQ CX, 24(SP) + MOVQ 96(AX), CX + MOVQ CX, 32(SP) MOVQ 104(AX), R10 MOVQ s+0(FP), AX MOVQ 144(AX), R11 MOVQ 152(AX), R12 MOVQ 160(AX), R13 + PCALIGN $0x40 sequenceDecs_decode_56_amd64_main_loop: MOVQ (SP), R14 @@ -383,132 +390,104 @@ sequenceDecs_decode_56_amd64_fill_check_overread: sequenceDecs_decode_56_amd64_fill_end: // Update offset - MOVQ R9, AX - MOVQ BX, CX - MOVQ DX, R15 - SHLQ CL, R15 - MOVB AH, CL - SHRQ $0x20, AX - TESTQ CX, CX - JZ sequenceDecs_decode_56_amd64_of_update_zero - ADDQ CX, BX - CMPQ BX, $0x40 - JA sequenceDecs_decode_56_amd64_of_update_zero - CMPQ CX, $0x40 - JAE sequenceDecs_decode_56_amd64_of_update_zero - NEGQ CX - SHRQ CL, R15 - ADDQ R15, AX - -sequenceDecs_decode_56_amd64_of_update_zero: - MOVQ AX, 16(R10) + MOVQ R9, AX + MOVQ BX, CX + MOVQ DX, R15 + SHLQ CL, R15 + SHRQ $0x01, R15 + MOVBLZX AH, CX + SHRQ $0x20, AX + ADDQ CX, BX + XORQ $0x3f, CX + SHRQ CL, R15 + ADDQ R15, AX + MOVQ AX, 16(R10) // Update match length - MOVQ R8, AX - MOVQ BX, CX - MOVQ DX, R15 - SHLQ CL, R15 - MOVB AH, CL - SHRQ $0x20, AX - TESTQ CX, CX - JZ sequenceDecs_decode_56_amd64_ml_update_zero - ADDQ CX, BX - CMPQ BX, $0x40 - JA sequenceDecs_decode_56_amd64_ml_update_zero - CMPQ CX, $0x40 - JAE sequenceDecs_decode_56_amd64_ml_update_zero - NEGQ CX - SHRQ CL, R15 - ADDQ R15, AX - -sequenceDecs_decode_56_amd64_ml_update_zero: - MOVQ AX, 8(R10) + MOVQ R8, AX + MOVQ BX, CX + MOVQ DX, R15 + SHLQ CL, R15 + SHRQ $0x01, R15 + MOVBLZX AH, CX + SHRQ $0x20, AX + ADDQ CX, BX + XORQ $0x3f, CX + SHRQ CL, R15 + ADDQ R15, AX + MOVQ AX, 8(R10) // Update literal length - MOVQ DI, AX - MOVQ BX, CX - MOVQ DX, R15 - SHLQ CL, R15 - MOVB AH, CL - SHRQ $0x20, AX - TESTQ CX, CX - JZ sequenceDecs_decode_56_amd64_ll_update_zero - ADDQ CX, BX - CMPQ BX, $0x40 - JA sequenceDecs_decode_56_amd64_ll_update_zero - CMPQ CX, $0x40 - JAE sequenceDecs_decode_56_amd64_ll_update_zero - NEGQ CX - SHRQ CL, R15 - ADDQ R15, AX - -sequenceDecs_decode_56_amd64_ll_update_zero: - MOVQ AX, (R10) + MOVQ DI, AX + MOVQ BX, CX + MOVQ DX, R15 + SHLQ CL, R15 + SHRQ $0x01, R15 + MOVBLZX AH, CX + SHRQ $0x20, AX + ADDQ CX, BX + XORQ $0x3f, CX + SHRQ CL, R15 + ADDQ R15, AX + MOVQ AX, (R10) // Fill bitreader for state updates MOVQ R14, (SP) MOVQ R9, AX SHRQ $0x08, AX MOVBQZX AL, AX - MOVQ ctx+16(FP), CX - CMPQ 96(CX), $0x00 + CMPQ 32(SP), $0x00 JZ sequenceDecs_decode_56_amd64_skip_update // Update Literal Length State MOVBQZX DI, R14 SHRL $0x10, DI - LEAQ (BX)(R14*1), CX + MOVQ BX, CX MOVQ DX, R15 - MOVQ CX, BX - ROLQ CL, R15 - MOVL $0x00000001, BP - MOVB R14, CL - SHLL CL, BP - DECL BP - ANDQ BP, R15 + SHLQ CL, R15 + SHRQ $0x01, R15 + ADDQ R14, BX + XORQ $0x3f, R14 + MOVQ R14, CX + SHRQ CL, R15 ADDQ R15, DI // Load ctx.llTable - MOVQ ctx+16(FP), CX - MOVQ (CX), CX + MOVQ 8(SP), CX MOVQ (CX)(DI*8), DI // Update Match Length State MOVBQZX R8, R14 SHRL $0x10, R8 - LEAQ (BX)(R14*1), CX + MOVQ BX, CX MOVQ DX, R15 - MOVQ CX, BX - ROLQ CL, R15 - MOVL $0x00000001, BP - MOVB R14, CL - SHLL CL, BP - DECL BP - ANDQ BP, R15 + SHLQ CL, R15 + SHRQ $0x01, R15 + ADDQ R14, BX + XORQ $0x3f, R14 + MOVQ R14, CX + SHRQ CL, R15 ADDQ R15, R8 // Load ctx.mlTable - MOVQ ctx+16(FP), CX - MOVQ 24(CX), CX + MOVQ 16(SP), CX MOVQ (CX)(R8*8), R8 // Update Offset State MOVBQZX R9, R14 SHRL $0x10, R9 - LEAQ (BX)(R14*1), CX + MOVQ BX, CX MOVQ DX, R15 - MOVQ CX, BX - ROLQ CL, R15 - MOVL $0x00000001, BP - MOVB R14, CL - SHLL CL, BP - DECL BP - ANDQ BP, R15 + SHLQ CL, R15 + SHRQ $0x01, R15 + ADDQ R14, BX + XORQ $0x3f, R14 + MOVQ R14, CX + SHRQ CL, R15 ADDQ R15, R9 // Load ctx.ofTable - MOVQ ctx+16(FP), CX - MOVQ 48(CX), CX + MOVQ 24(SP), CX MOVQ (CX)(R9*8), R9 sequenceDecs_decode_56_amd64_skip_update: @@ -589,8 +568,7 @@ sequenceDecs_decode_56_amd64_after_adjust: sequenceDecs_decode_56_amd64_match_len_ofs_ok: ADDQ $0x18, R10 - MOVQ ctx+16(FP), AX - DECQ 96(AX) + DECQ 32(SP) JNS sequenceDecs_decode_56_amd64_main_loop MOVQ s+0(FP), AX MOVQ R11, 144(AX) @@ -602,36 +580,54 @@ sequenceDecs_decode_56_amd64_match_len_ofs_ok: MOVQ SI, 32(AX) // Return success + MOVQ 32(SP), AX + MOVQ ctx+16(FP), CX + MOVQ AX, 96(CX) MOVQ $0x00000000, ret+24(FP) RET // Return with match length error sequenceDecs_decode_56_amd64_error_match_len_ofs_mismatch: + MOVQ 32(SP), AX + MOVQ ctx+16(FP), CX + MOVQ AX, 96(CX) MOVQ $0x00000001, ret+24(FP) RET // Return with match too long error sequenceDecs_decode_56_amd64_error_match_len_too_big: + MOVQ 32(SP), AX + MOVQ ctx+16(FP), CX + MOVQ AX, 96(CX) MOVQ $0x00000002, ret+24(FP) RET // Return with match offset too long error + MOVQ 32(SP), AX + MOVQ ctx+16(FP), CX + MOVQ AX, 96(CX) MOVQ $0x00000003, ret+24(FP) RET // Return with not enough literals error error_not_enough_literals: + MOVQ 32(SP), AX + MOVQ ctx+16(FP), CX + MOVQ AX, 96(CX) MOVQ $0x00000004, ret+24(FP) RET // Return with overread error error_overread: + MOVQ 32(SP), AX + MOVQ ctx+16(FP), CX + MOVQ AX, 96(CX) MOVQ $0x00000006, ret+24(FP) RET // func sequenceDecs_decode_bmi2(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int // Requires: BMI, BMI2, CMOV -TEXT ·sequenceDecs_decode_bmi2(SB), $8-32 +TEXT ·sequenceDecs_decode_bmi2(SB), $40-32 MOVQ br+8(FP), BX MOVQ 24(BX), AX MOVBQZX 40(BX), DX @@ -643,11 +639,20 @@ TEXT ·sequenceDecs_decode_bmi2(SB), $8-32 MOVQ 72(CX), SI MOVQ 80(CX), DI MOVQ 88(CX), R8 + MOVQ (CX), R9 + MOVQ R9, 8(SP) + MOVQ 24(CX), R9 + MOVQ R9, 16(SP) + MOVQ 48(CX), R9 + MOVQ R9, 24(SP) + MOVQ 96(CX), R9 + MOVQ R9, 32(SP) MOVQ 104(CX), R9 MOVQ s+0(FP), CX MOVQ 144(CX), R10 MOVQ 152(CX), R11 MOVQ 160(CX), R12 + PCALIGN $0x40 sequenceDecs_decode_bmi2_main_loop: MOVQ (SP), R13 @@ -753,8 +758,7 @@ sequenceDecs_decode_bmi2_fill_2_end: MOVQ R13, (SP) MOVQ $0x00000808, CX BEXTRQ CX, R8, R13 - MOVQ ctx+16(FP), CX - CMPQ 96(CX), $0x00 + CMPQ 32(SP), $0x00 JZ sequenceDecs_decode_bmi2_skip_update LEAQ (SI)(DI*1), R14 ADDQ R8, R14 @@ -772,8 +776,7 @@ sequenceDecs_decode_bmi2_fill_2_end: ADDQ CX, R8 // Load ctx.ofTable - MOVQ ctx+16(FP), CX - MOVQ 48(CX), CX + MOVQ 24(SP), CX MOVQ (CX)(R8*8), R8 // Update Match Length State @@ -783,8 +786,7 @@ sequenceDecs_decode_bmi2_fill_2_end: ADDQ CX, DI // Load ctx.mlTable - MOVQ ctx+16(FP), CX - MOVQ 24(CX), CX + MOVQ 16(SP), CX MOVQ (CX)(DI*8), DI // Update Literal Length State @@ -793,8 +795,7 @@ sequenceDecs_decode_bmi2_fill_2_end: ADDQ CX, SI // Load ctx.llTable - MOVQ ctx+16(FP), CX - MOVQ (CX), CX + MOVQ 8(SP), CX MOVQ (CX)(SI*8), SI sequenceDecs_decode_bmi2_skip_update: @@ -875,8 +876,7 @@ sequenceDecs_decode_bmi2_after_adjust: sequenceDecs_decode_bmi2_match_len_ofs_ok: ADDQ $0x18, R9 - MOVQ ctx+16(FP), CX - DECQ 96(CX) + DECQ 32(SP) JNS sequenceDecs_decode_bmi2_main_loop MOVQ s+0(FP), CX MOVQ R10, 144(CX) @@ -888,36 +888,54 @@ sequenceDecs_decode_bmi2_match_len_ofs_ok: MOVQ BX, 32(CX) // Return success + MOVQ 32(SP), AX + MOVQ ctx+16(FP), CX + MOVQ AX, 96(CX) MOVQ $0x00000000, ret+24(FP) RET // Return with match length error sequenceDecs_decode_bmi2_error_match_len_ofs_mismatch: + MOVQ 32(SP), AX + MOVQ ctx+16(FP), CX + MOVQ AX, 96(CX) MOVQ $0x00000001, ret+24(FP) RET // Return with match too long error sequenceDecs_decode_bmi2_error_match_len_too_big: + MOVQ 32(SP), AX + MOVQ ctx+16(FP), CX + MOVQ AX, 96(CX) MOVQ $0x00000002, ret+24(FP) RET // Return with match offset too long error + MOVQ 32(SP), AX + MOVQ ctx+16(FP), CX + MOVQ AX, 96(CX) MOVQ $0x00000003, ret+24(FP) RET // Return with not enough literals error error_not_enough_literals: + MOVQ 32(SP), AX + MOVQ ctx+16(FP), CX + MOVQ AX, 96(CX) MOVQ $0x00000004, ret+24(FP) RET // Return with overread error error_overread: + MOVQ 32(SP), AX + MOVQ ctx+16(FP), CX + MOVQ AX, 96(CX) MOVQ $0x00000006, ret+24(FP) RET // func sequenceDecs_decode_56_bmi2(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int // Requires: BMI, BMI2, CMOV -TEXT ·sequenceDecs_decode_56_bmi2(SB), $8-32 +TEXT ·sequenceDecs_decode_56_bmi2(SB), $40-32 MOVQ br+8(FP), BX MOVQ 24(BX), AX MOVBQZX 40(BX), DX @@ -929,11 +947,20 @@ TEXT ·sequenceDecs_decode_56_bmi2(SB), $8-32 MOVQ 72(CX), SI MOVQ 80(CX), DI MOVQ 88(CX), R8 + MOVQ (CX), R9 + MOVQ R9, 8(SP) + MOVQ 24(CX), R9 + MOVQ R9, 16(SP) + MOVQ 48(CX), R9 + MOVQ R9, 24(SP) + MOVQ 96(CX), R9 + MOVQ R9, 32(SP) MOVQ 104(CX), R9 MOVQ s+0(FP), CX MOVQ 144(CX), R10 MOVQ 152(CX), R11 MOVQ 160(CX), R12 + PCALIGN $0x40 sequenceDecs_decode_56_bmi2_main_loop: MOVQ (SP), R13 @@ -1010,8 +1037,7 @@ sequenceDecs_decode_56_bmi2_fill_end: MOVQ R13, (SP) MOVQ $0x00000808, CX BEXTRQ CX, R8, R13 - MOVQ ctx+16(FP), CX - CMPQ 96(CX), $0x00 + CMPQ 32(SP), $0x00 JZ sequenceDecs_decode_56_bmi2_skip_update LEAQ (SI)(DI*1), R14 ADDQ R8, R14 @@ -1029,8 +1055,7 @@ sequenceDecs_decode_56_bmi2_fill_end: ADDQ CX, R8 // Load ctx.ofTable - MOVQ ctx+16(FP), CX - MOVQ 48(CX), CX + MOVQ 24(SP), CX MOVQ (CX)(R8*8), R8 // Update Match Length State @@ -1040,8 +1065,7 @@ sequenceDecs_decode_56_bmi2_fill_end: ADDQ CX, DI // Load ctx.mlTable - MOVQ ctx+16(FP), CX - MOVQ 24(CX), CX + MOVQ 16(SP), CX MOVQ (CX)(DI*8), DI // Update Literal Length State @@ -1050,8 +1074,7 @@ sequenceDecs_decode_56_bmi2_fill_end: ADDQ CX, SI // Load ctx.llTable - MOVQ ctx+16(FP), CX - MOVQ (CX), CX + MOVQ 8(SP), CX MOVQ (CX)(SI*8), SI sequenceDecs_decode_56_bmi2_skip_update: @@ -1132,8 +1155,7 @@ sequenceDecs_decode_56_bmi2_after_adjust: sequenceDecs_decode_56_bmi2_match_len_ofs_ok: ADDQ $0x18, R9 - MOVQ ctx+16(FP), CX - DECQ 96(CX) + DECQ 32(SP) JNS sequenceDecs_decode_56_bmi2_main_loop MOVQ s+0(FP), CX MOVQ R10, 144(CX) @@ -1145,49 +1167,79 @@ sequenceDecs_decode_56_bmi2_match_len_ofs_ok: MOVQ BX, 32(CX) // Return success + MOVQ 32(SP), AX + MOVQ ctx+16(FP), CX + MOVQ AX, 96(CX) MOVQ $0x00000000, ret+24(FP) RET // Return with match length error sequenceDecs_decode_56_bmi2_error_match_len_ofs_mismatch: + MOVQ 32(SP), AX + MOVQ ctx+16(FP), CX + MOVQ AX, 96(CX) MOVQ $0x00000001, ret+24(FP) RET // Return with match too long error sequenceDecs_decode_56_bmi2_error_match_len_too_big: + MOVQ 32(SP), AX + MOVQ ctx+16(FP), CX + MOVQ AX, 96(CX) MOVQ $0x00000002, ret+24(FP) RET // Return with match offset too long error + MOVQ 32(SP), AX + MOVQ ctx+16(FP), CX + MOVQ AX, 96(CX) MOVQ $0x00000003, ret+24(FP) RET // Return with not enough literals error error_not_enough_literals: + MOVQ 32(SP), AX + MOVQ ctx+16(FP), CX + MOVQ AX, 96(CX) MOVQ $0x00000004, ret+24(FP) RET // Return with overread error error_overread: + MOVQ 32(SP), AX + MOVQ ctx+16(FP), CX + MOVQ AX, 96(CX) MOVQ $0x00000006, ret+24(FP) RET // func sequenceDecs_executeSimple_amd64(ctx *executeAsmContext) bool -// Requires: SSE -TEXT ·sequenceDecs_executeSimple_amd64(SB), $8-9 +// Requires: MMX+, SSE +TEXT ·sequenceDecs_executeSimple_amd64(SB), $32-9 MOVQ ctx+0(FP), R10 MOVQ 8(R10), CX TESTQ CX, CX JZ empty_seqs MOVQ (R10), AX - MOVQ 24(R10), DX - MOVQ 32(R10), BX - MOVQ 80(R10), SI - MOVQ 104(R10), DI - MOVQ 120(R10), R8 - MOVQ 56(R10), R9 - MOVQ 64(R10), R10 - ADDQ R10, R9 + + // seqsEnd = seqsBase + 24 * len(seqs) if ctx.prefetch, else seqsBase (prefetch off) + MOVQ AX, DX + MOVBQZX 128(R10), R11 + TESTQ R11, R11 + JZ prefetch_off + LEAQ (CX)(CX*2), DX + SHLQ $0x03, DX + ADDQ AX, DX + +prefetch_off: + MOVQ DX, (SP) + MOVQ 24(R10), DX + MOVQ 32(R10), BX + MOVQ 80(R10), SI + MOVQ 104(R10), DI + MOVQ 120(R10), R8 + MOVQ 56(R10), R9 + MOVQ 64(R10), R10 + ADDQ R10, R9 // seqsBase += 24 * seqIndex LEAQ (DX)(DX*2), R11 @@ -1196,16 +1248,243 @@ TEXT ·sequenceDecs_executeSimple_amd64(SB), $8-9 // outBase += outPosition ADDQ DI, BX + MOVQ BX, 8(SP) + MOVQ BX, R11 + SUBQ DI, R11 + MOVQ R11, 16(SP) + NEGQ R11 + ADDQ R9, R11 + MOVQ R11, 24(SP) + // Prime the prefetch window + MOVQ (SP), R11 + LEAQ (AX), R12 + CMPQ R12, R11 + JAE prefetch_skip_0 + MOVQ 8(SP), R12 + MOVQ (AX), R11 + ADDQ R11, R12 + MOVQ R12, R13 + MOVQ 16(AX), R11 + SUBQ R11, R13 + MOVQ 16(SP), R11 + CMPQ R13, R11 + JAE prefetch_in_out_0 + MOVQ 24(SP), R11 + ADDQ R11, R13 + +prefetch_in_out_0: + PREFETCHT0 (R13) + PREFETCHT0 64(R13) + MOVQ 8(AX), R11 + ADDQ R11, R12 + MOVQ R12, 8(SP) + +prefetch_skip_0: + MOVQ (SP), R11 + LEAQ 24(AX), R12 + CMPQ R12, R11 + JAE prefetch_skip_1 + MOVQ 8(SP), R12 + MOVQ 24(AX), R11 + ADDQ R11, R12 + MOVQ R12, R13 + MOVQ 40(AX), R11 + SUBQ R11, R13 + MOVQ 16(SP), R11 + CMPQ R13, R11 + JAE prefetch_in_out_1 + MOVQ 24(SP), R11 + ADDQ R11, R13 + +prefetch_in_out_1: + PREFETCHT0 (R13) + PREFETCHT0 64(R13) + MOVQ 32(AX), R11 + ADDQ R11, R12 + MOVQ R12, 8(SP) + +prefetch_skip_1: + MOVQ (SP), R11 + LEAQ 48(AX), R12 + CMPQ R12, R11 + JAE prefetch_skip_2 + MOVQ 8(SP), R12 + MOVQ 48(AX), R11 + ADDQ R11, R12 + MOVQ R12, R13 + MOVQ 64(AX), R11 + SUBQ R11, R13 + MOVQ 16(SP), R11 + CMPQ R13, R11 + JAE prefetch_in_out_2 + MOVQ 24(SP), R11 + ADDQ R11, R13 + +prefetch_in_out_2: + PREFETCHT0 (R13) + PREFETCHT0 64(R13) + MOVQ 56(AX), R11 + ADDQ R11, R12 + MOVQ R12, 8(SP) + +prefetch_skip_2: + MOVQ (SP), R11 + LEAQ 72(AX), R12 + CMPQ R12, R11 + JAE prefetch_skip_3 + MOVQ 8(SP), R12 + MOVQ 72(AX), R11 + ADDQ R11, R12 + MOVQ R12, R13 + MOVQ 88(AX), R11 + SUBQ R11, R13 + MOVQ 16(SP), R11 + CMPQ R13, R11 + JAE prefetch_in_out_3 + MOVQ 24(SP), R11 + ADDQ R11, R13 + +prefetch_in_out_3: + PREFETCHT0 (R13) + PREFETCHT0 64(R13) + MOVQ 80(AX), R11 + ADDQ R11, R12 + MOVQ R12, 8(SP) + +prefetch_skip_3: + MOVQ (SP), R11 + LEAQ 96(AX), R12 + CMPQ R12, R11 + JAE prefetch_skip_4 + MOVQ 8(SP), R12 + MOVQ 96(AX), R11 + ADDQ R11, R12 + MOVQ R12, R13 + MOVQ 112(AX), R11 + SUBQ R11, R13 + MOVQ 16(SP), R11 + CMPQ R13, R11 + JAE prefetch_in_out_4 + MOVQ 24(SP), R11 + ADDQ R11, R13 + +prefetch_in_out_4: + PREFETCHT0 (R13) + PREFETCHT0 64(R13) + MOVQ 104(AX), R11 + ADDQ R11, R12 + MOVQ R12, 8(SP) + +prefetch_skip_4: + MOVQ (SP), R11 + LEAQ 120(AX), R12 + CMPQ R12, R11 + JAE prefetch_skip_5 + MOVQ 8(SP), R12 + MOVQ 120(AX), R11 + ADDQ R11, R12 + MOVQ R12, R13 + MOVQ 136(AX), R11 + SUBQ R11, R13 + MOVQ 16(SP), R11 + CMPQ R13, R11 + JAE prefetch_in_out_5 + MOVQ 24(SP), R11 + ADDQ R11, R13 + +prefetch_in_out_5: + PREFETCHT0 (R13) + PREFETCHT0 64(R13) + MOVQ 128(AX), R11 + ADDQ R11, R12 + MOVQ R12, 8(SP) + +prefetch_skip_5: + MOVQ (SP), R11 + LEAQ 144(AX), R12 + CMPQ R12, R11 + JAE prefetch_skip_6 + MOVQ 8(SP), R12 + MOVQ 144(AX), R11 + ADDQ R11, R12 + MOVQ R12, R13 + MOVQ 160(AX), R11 + SUBQ R11, R13 + MOVQ 16(SP), R11 + CMPQ R13, R11 + JAE prefetch_in_out_6 + MOVQ 24(SP), R11 + ADDQ R11, R13 + +prefetch_in_out_6: + PREFETCHT0 (R13) + PREFETCHT0 64(R13) + MOVQ 152(AX), R11 + ADDQ R11, R12 + MOVQ R12, 8(SP) + +prefetch_skip_6: + MOVQ (SP), R11 + LEAQ 168(AX), R12 + CMPQ R12, R11 + JAE prefetch_skip_7 + MOVQ 8(SP), R12 + MOVQ 168(AX), R11 + ADDQ R11, R12 + MOVQ R12, R13 + MOVQ 184(AX), R11 + SUBQ R11, R13 + MOVQ 16(SP), R11 + CMPQ R13, R11 + JAE prefetch_in_out_7 + MOVQ 24(SP), R11 + ADDQ R11, R13 + +prefetch_in_out_7: + PREFETCHT0 (R13) + PREFETCHT0 64(R13) + MOVQ 176(AX), R11 + ADDQ R11, R12 + MOVQ R12, 8(SP) + PCALIGN $0x40 + +prefetch_skip_7: main_loop: + MOVQ (SP), R11 + LEAQ 192(AX), R12 + CMPQ R12, R11 + JAE prefetch_skip_8 + MOVQ 8(SP), R12 + MOVQ 192(AX), R11 + ADDQ R11, R12 + MOVQ R12, R13 + MOVQ 208(AX), R11 + SUBQ R11, R13 + MOVQ 16(SP), R11 + CMPQ R13, R11 + JAE prefetch_in_out_8 + MOVQ 24(SP), R11 + ADDQ R11, R13 + +prefetch_in_out_8: + PREFETCHT0 (R13) + PREFETCHT0 64(R13) + MOVQ 200(AX), R11 + ADDQ R11, R12 + MOVQ R12, 8(SP) + +prefetch_skip_8: MOVQ (AX), R11 MOVQ 16(AX), R12 MOVQ 8(AX), R13 // Copy literals - TESTQ R11, R11 - JZ check_offset - XORQ R14, R14 + MOVUPS (SI), X0 + MOVUPS X0, (BX) + CMPQ R11, $0x10 + JBE copy_1_end + MOVQ $0x00000010, R14 copy_1: MOVUPS (SI)(R14*1), X0 @@ -1213,12 +1492,13 @@ copy_1: ADDQ $0x10, R14 CMPQ R14, R11 JB copy_1 - ADDQ R11, SI - ADDQ R11, BX - ADDQ R11, DI + +copy_1_end: + ADDQ R11, SI + ADDQ R11, BX + ADDQ R11, DI // Malformed input if seq.mo > t+len(hist) || seq.mo > s.windowSize) -check_offset: LEAQ (DI)(R10*1), R11 CMPQ R12, R11 JG error_match_off_too_big @@ -1258,13 +1538,13 @@ copy_4_small: JMP copy_4_move_8through16 copy_4_move_3: - MOVW (R14), R11 - MOVB 2(R14), R12 - MOVW R11, (BX) - MOVB R12, 2(BX) - ADDQ R13, R14 - ADDQ R13, BX - JMP copy_4_end + MOVWQZX (R14), R11 + MOVB 2(R14), R12 + MOVW R11, (BX) + MOVB R12, 2(BX) + ADDQ R13, R14 + ADDQ R13, BX + JMP copy_4_end copy_4_move_4through7: MOVL (R14), R11 @@ -1327,13 +1607,13 @@ copy_5_move_1or2: JMP copy_5_end copy_5_move_3: - MOVW (R14), R15 - MOVB 2(R14), BP - MOVW R15, (BX) - MOVB BP, 2(BX) - ADDQ R11, R14 - ADDQ R11, BX - JMP copy_5_end + MOVWQZX (R14), R15 + MOVB 2(R14), BP + MOVW R15, (BX) + MOVB BP, 2(BX) + ADDQ R11, R14 + ADDQ R11, BX + JMP copy_5_end copy_5_move_4through7: MOVL (R14), R15 @@ -1366,30 +1646,57 @@ copy_match: JA copy_overlapping_match // Copy non-overlapping match - ADDQ R13, DI - MOVQ BX, R12 + ADDQ R13, DI + MOVUPS (R11), X0 + MOVUPS 16(R11), X1 + MOVUPS X0, (BX) + MOVUPS X1, 16(BX) + CMPQ R13, $0x20 + JA copy_2_long + ADDQ R13, BX + JMP handle_loop + +copy_2_long: + LEAQ 32(BX), R12 ADDQ R13, BX + ADDQ $0x20, R11 + SUBQ $0x20, R13 copy_2: MOVUPS (R11), X0 + MOVUPS 16(R11), X1 MOVUPS X0, (R12) - ADDQ $0x10, R11 - ADDQ $0x10, R12 - SUBQ $0x10, R13 + MOVUPS X1, 16(R12) + ADDQ $0x20, R11 + ADDQ $0x20, R12 + SUBQ $0x20, R13 JHI copy_2 JMP handle_loop // Copy overlapping match copy_overlapping_match: ADDQ R13, DI + CMPQ R12, $0x10 + JB copy_slow_3 + MOVQ BX, R12 + ADDQ R13, BX + +copy_3: + MOVUPS (R11), X0 + MOVUPS X0, (R12) + ADDQ $0x10, R11 + ADDQ $0x10, R12 + SUBQ $0x10, R13 + JHI copy_3 + JMP handle_loop copy_slow_3: - MOVB (R11), R12 - MOVB R12, (BX) - INCQ R11 - INCQ BX - DECQ R13 - JNZ copy_slow_3 + MOVBQZX (R11), R12 + MOVB R12, (BX) + INCQ R11 + INCQ BX + DECQ R13 + JNZ copy_slow_3 handle_loop: ADDQ $0x18, AX @@ -1427,21 +1734,33 @@ empty_seqs: RET // func sequenceDecs_executeSimple_safe_amd64(ctx *executeAsmContext) bool -// Requires: SSE -TEXT ·sequenceDecs_executeSimple_safe_amd64(SB), $8-9 +// Requires: MMX+, SSE +TEXT ·sequenceDecs_executeSimple_safe_amd64(SB), $32-9 MOVQ ctx+0(FP), R10 MOVQ 8(R10), CX TESTQ CX, CX JZ empty_seqs MOVQ (R10), AX - MOVQ 24(R10), DX - MOVQ 32(R10), BX - MOVQ 80(R10), SI - MOVQ 104(R10), DI - MOVQ 120(R10), R8 - MOVQ 56(R10), R9 - MOVQ 64(R10), R10 - ADDQ R10, R9 + + // seqsEnd = seqsBase + 24 * len(seqs) if ctx.prefetch, else seqsBase (prefetch off) + MOVQ AX, DX + MOVBQZX 128(R10), R11 + TESTQ R11, R11 + JZ prefetch_off + LEAQ (CX)(CX*2), DX + SHLQ $0x03, DX + ADDQ AX, DX + +prefetch_off: + MOVQ DX, (SP) + MOVQ 24(R10), DX + MOVQ 32(R10), BX + MOVQ 80(R10), SI + MOVQ 104(R10), DI + MOVQ 120(R10), R8 + MOVQ 56(R10), R9 + MOVQ 64(R10), R10 + ADDQ R10, R9 // seqsBase += 24 * seqIndex LEAQ (DX)(DX*2), R11 @@ -1450,8 +1769,233 @@ TEXT ·sequenceDecs_executeSimple_safe_amd64(SB), $8-9 // outBase += outPosition ADDQ DI, BX + MOVQ BX, 8(SP) + MOVQ BX, R11 + SUBQ DI, R11 + MOVQ R11, 16(SP) + NEGQ R11 + ADDQ R9, R11 + MOVQ R11, 24(SP) + // Prime the prefetch window + MOVQ (SP), R11 + LEAQ (AX), R12 + CMPQ R12, R11 + JAE prefetch_skip_0 + MOVQ 8(SP), R12 + MOVQ (AX), R11 + ADDQ R11, R12 + MOVQ R12, R13 + MOVQ 16(AX), R11 + SUBQ R11, R13 + MOVQ 16(SP), R11 + CMPQ R13, R11 + JAE prefetch_in_out_0 + MOVQ 24(SP), R11 + ADDQ R11, R13 + +prefetch_in_out_0: + PREFETCHT0 (R13) + PREFETCHT0 64(R13) + MOVQ 8(AX), R11 + ADDQ R11, R12 + MOVQ R12, 8(SP) + +prefetch_skip_0: + MOVQ (SP), R11 + LEAQ 24(AX), R12 + CMPQ R12, R11 + JAE prefetch_skip_1 + MOVQ 8(SP), R12 + MOVQ 24(AX), R11 + ADDQ R11, R12 + MOVQ R12, R13 + MOVQ 40(AX), R11 + SUBQ R11, R13 + MOVQ 16(SP), R11 + CMPQ R13, R11 + JAE prefetch_in_out_1 + MOVQ 24(SP), R11 + ADDQ R11, R13 + +prefetch_in_out_1: + PREFETCHT0 (R13) + PREFETCHT0 64(R13) + MOVQ 32(AX), R11 + ADDQ R11, R12 + MOVQ R12, 8(SP) + +prefetch_skip_1: + MOVQ (SP), R11 + LEAQ 48(AX), R12 + CMPQ R12, R11 + JAE prefetch_skip_2 + MOVQ 8(SP), R12 + MOVQ 48(AX), R11 + ADDQ R11, R12 + MOVQ R12, R13 + MOVQ 64(AX), R11 + SUBQ R11, R13 + MOVQ 16(SP), R11 + CMPQ R13, R11 + JAE prefetch_in_out_2 + MOVQ 24(SP), R11 + ADDQ R11, R13 + +prefetch_in_out_2: + PREFETCHT0 (R13) + PREFETCHT0 64(R13) + MOVQ 56(AX), R11 + ADDQ R11, R12 + MOVQ R12, 8(SP) + +prefetch_skip_2: + MOVQ (SP), R11 + LEAQ 72(AX), R12 + CMPQ R12, R11 + JAE prefetch_skip_3 + MOVQ 8(SP), R12 + MOVQ 72(AX), R11 + ADDQ R11, R12 + MOVQ R12, R13 + MOVQ 88(AX), R11 + SUBQ R11, R13 + MOVQ 16(SP), R11 + CMPQ R13, R11 + JAE prefetch_in_out_3 + MOVQ 24(SP), R11 + ADDQ R11, R13 + +prefetch_in_out_3: + PREFETCHT0 (R13) + PREFETCHT0 64(R13) + MOVQ 80(AX), R11 + ADDQ R11, R12 + MOVQ R12, 8(SP) + +prefetch_skip_3: + MOVQ (SP), R11 + LEAQ 96(AX), R12 + CMPQ R12, R11 + JAE prefetch_skip_4 + MOVQ 8(SP), R12 + MOVQ 96(AX), R11 + ADDQ R11, R12 + MOVQ R12, R13 + MOVQ 112(AX), R11 + SUBQ R11, R13 + MOVQ 16(SP), R11 + CMPQ R13, R11 + JAE prefetch_in_out_4 + MOVQ 24(SP), R11 + ADDQ R11, R13 + +prefetch_in_out_4: + PREFETCHT0 (R13) + PREFETCHT0 64(R13) + MOVQ 104(AX), R11 + ADDQ R11, R12 + MOVQ R12, 8(SP) + +prefetch_skip_4: + MOVQ (SP), R11 + LEAQ 120(AX), R12 + CMPQ R12, R11 + JAE prefetch_skip_5 + MOVQ 8(SP), R12 + MOVQ 120(AX), R11 + ADDQ R11, R12 + MOVQ R12, R13 + MOVQ 136(AX), R11 + SUBQ R11, R13 + MOVQ 16(SP), R11 + CMPQ R13, R11 + JAE prefetch_in_out_5 + MOVQ 24(SP), R11 + ADDQ R11, R13 + +prefetch_in_out_5: + PREFETCHT0 (R13) + PREFETCHT0 64(R13) + MOVQ 128(AX), R11 + ADDQ R11, R12 + MOVQ R12, 8(SP) + +prefetch_skip_5: + MOVQ (SP), R11 + LEAQ 144(AX), R12 + CMPQ R12, R11 + JAE prefetch_skip_6 + MOVQ 8(SP), R12 + MOVQ 144(AX), R11 + ADDQ R11, R12 + MOVQ R12, R13 + MOVQ 160(AX), R11 + SUBQ R11, R13 + MOVQ 16(SP), R11 + CMPQ R13, R11 + JAE prefetch_in_out_6 + MOVQ 24(SP), R11 + ADDQ R11, R13 + +prefetch_in_out_6: + PREFETCHT0 (R13) + PREFETCHT0 64(R13) + MOVQ 152(AX), R11 + ADDQ R11, R12 + MOVQ R12, 8(SP) + +prefetch_skip_6: + MOVQ (SP), R11 + LEAQ 168(AX), R12 + CMPQ R12, R11 + JAE prefetch_skip_7 + MOVQ 8(SP), R12 + MOVQ 168(AX), R11 + ADDQ R11, R12 + MOVQ R12, R13 + MOVQ 184(AX), R11 + SUBQ R11, R13 + MOVQ 16(SP), R11 + CMPQ R13, R11 + JAE prefetch_in_out_7 + MOVQ 24(SP), R11 + ADDQ R11, R13 + +prefetch_in_out_7: + PREFETCHT0 (R13) + PREFETCHT0 64(R13) + MOVQ 176(AX), R11 + ADDQ R11, R12 + MOVQ R12, 8(SP) + PCALIGN $0x40 + +prefetch_skip_7: main_loop: + MOVQ (SP), R11 + LEAQ 192(AX), R12 + CMPQ R12, R11 + JAE prefetch_skip_8 + MOVQ 8(SP), R12 + MOVQ 192(AX), R11 + ADDQ R11, R12 + MOVQ R12, R13 + MOVQ 208(AX), R11 + SUBQ R11, R13 + MOVQ 16(SP), R11 + CMPQ R13, R11 + JAE prefetch_in_out_8 + MOVQ 24(SP), R11 + ADDQ R11, R13 + +prefetch_in_out_8: + PREFETCHT0 (R13) + PREFETCHT0 64(R13) + MOVQ 200(AX), R11 + ADDQ R11, R12 + MOVQ R12, 8(SP) + +prefetch_skip_8: MOVQ (AX), R11 MOVQ 16(AX), R12 MOVQ 8(AX), R13 @@ -1494,13 +2038,13 @@ copy_1_move_1or2: JMP copy_1_end copy_1_move_3: - MOVW (SI), R14 - MOVB 2(SI), R15 - MOVW R14, (BX) - MOVB R15, 2(BX) - ADDQ R11, SI - ADDQ R11, BX - JMP copy_1_end + MOVWQZX (SI), R14 + MOVB 2(SI), R15 + MOVW R14, (BX) + MOVB R15, 2(BX) + ADDQ R11, SI + ADDQ R11, BX + JMP copy_1_end copy_1_move_4through7: MOVL (SI), R14 @@ -1563,13 +2107,13 @@ copy_4_small: JMP copy_4_move_8through16 copy_4_move_3: - MOVW (R14), R11 - MOVB 2(R14), R12 - MOVW R11, (BX) - MOVB R12, 2(BX) - ADDQ R13, R14 - ADDQ R13, BX - JMP copy_4_end + MOVWQZX (R14), R11 + MOVB 2(R14), R12 + MOVW R11, (BX) + MOVB R12, 2(BX) + ADDQ R13, R14 + ADDQ R13, BX + JMP copy_4_end copy_4_move_4through7: MOVL (R14), R11 @@ -1632,13 +2176,13 @@ copy_5_move_1or2: JMP copy_5_end copy_5_move_3: - MOVW (R14), R15 - MOVB 2(R14), BP - MOVW R15, (BX) - MOVB BP, 2(BX) - ADDQ R11, R14 - ADDQ R11, BX - JMP copy_5_end + MOVWQZX (R14), R15 + MOVB 2(R14), BP + MOVW R15, (BX) + MOVB BP, 2(BX) + ADDQ R11, R14 + ADDQ R11, BX + JMP copy_5_end copy_5_move_4through7: MOVL (R14), R15 @@ -1707,13 +2251,13 @@ copy_2_move_1or2: JMP copy_2_end copy_2_move_3: - MOVW (R11), R12 - MOVB 2(R11), R14 - MOVW R12, (BX) - MOVB R14, 2(BX) - ADDQ R13, R11 - ADDQ R13, BX - JMP copy_2_end + MOVWQZX (R11), R12 + MOVB 2(R11), R14 + MOVW R12, (BX) + MOVB R14, 2(BX) + ADDQ R13, R11 + ADDQ R13, BX + JMP copy_2_end copy_2_move_4through7: MOVL (R11), R12 @@ -1738,14 +2282,27 @@ copy_2_end: // Copy overlapping match copy_overlapping_match: ADDQ R13, DI + CMPQ R12, $0x10 + JB copy_slow_3 + +copy_3_blocks: + MOVUPS (R11), X0 + MOVUPS X0, (BX) + ADDQ $0x10, R11 + ADDQ $0x10, BX + SUBQ $0x10, R13 + CMPQ R13, $0x10 + JAE copy_3_blocks + TESTQ R13, R13 + JZ handle_loop copy_slow_3: - MOVB (R11), R12 - MOVB R12, (BX) - INCQ R11 - INCQ BX - DECQ R13 - JNZ copy_slow_3 + MOVBQZX (R11), R12 + MOVB R12, (BX) + INCQ R11 + INCQ BX + DECQ R13 + JNZ copy_slow_3 handle_loop: ADDQ $0x18, AX @@ -1784,7 +2341,7 @@ empty_seqs: // func sequenceDecs_decodeSync_amd64(s *sequenceDecs, br *bitReader, ctx *decodeSyncAsmContext) int // Requires: CMOV, SSE -TEXT ·sequenceDecs_decodeSync_amd64(SB), $64-32 +TEXT ·sequenceDecs_decodeSync_amd64(SB), $96-32 MOVQ br+8(FP), CX MOVQ 24(CX), DX MOVBQZX 40(CX), BX @@ -1796,29 +2353,38 @@ TEXT ·sequenceDecs_decodeSync_amd64(SB), $64-32 MOVQ 72(AX), DI MOVQ 80(AX), R8 MOVQ 88(AX), R9 - XORQ CX, CX + MOVQ (AX), CX MOVQ CX, 8(SP) + MOVQ 24(AX), CX MOVQ CX, 16(SP) + MOVQ 48(AX), CX MOVQ CX, 24(SP) + MOVQ 96(AX), CX + MOVQ CX, 32(SP) + XORQ CX, CX + MOVQ CX, 40(SP) + MOVQ CX, 48(SP) + MOVQ CX, 56(SP) MOVQ 112(AX), R10 MOVQ 128(AX), CX - MOVQ CX, 32(SP) + MOVQ CX, 64(SP) MOVQ 144(AX), R11 MOVQ 136(AX), R12 MOVQ 200(AX), CX - MOVQ CX, 56(SP) + MOVQ CX, 88(SP) MOVQ 176(AX), CX - MOVQ CX, 48(SP) + MOVQ CX, 80(SP) MOVQ 184(AX), AX - MOVQ AX, 40(SP) - MOVQ 40(SP), AX - ADDQ AX, 48(SP) + MOVQ AX, 72(SP) + MOVQ 72(SP), AX + ADDQ AX, 80(SP) // Calculate pointer to s.out[cap(s.out)] (a past-end pointer) - ADDQ R10, 32(SP) + ADDQ R10, 64(SP) // outBase += outPosition - ADDQ R12, R10 + ADDQ R12, R10 + PCALIGN $0x40 sequenceDecs_decodeSync_amd64_main_loop: MOVQ (SP), R13 @@ -1853,46 +2419,32 @@ sequenceDecs_decodeSync_amd64_fill_check_overread: sequenceDecs_decodeSync_amd64_fill_end: // Update offset - MOVQ R9, AX - MOVQ BX, CX - MOVQ DX, R14 - SHLQ CL, R14 - MOVB AH, CL - SHRQ $0x20, AX - TESTQ CX, CX - JZ sequenceDecs_decodeSync_amd64_of_update_zero - ADDQ CX, BX - CMPQ BX, $0x40 - JA sequenceDecs_decodeSync_amd64_of_update_zero - CMPQ CX, $0x40 - JAE sequenceDecs_decodeSync_amd64_of_update_zero - NEGQ CX - SHRQ CL, R14 - ADDQ R14, AX - -sequenceDecs_decodeSync_amd64_of_update_zero: - MOVQ AX, 8(SP) + MOVQ R9, AX + MOVQ BX, CX + MOVQ DX, R14 + SHLQ CL, R14 + SHRQ $0x01, R14 + MOVBLZX AH, CX + SHRQ $0x20, AX + ADDQ CX, BX + XORQ $0x3f, CX + SHRQ CL, R14 + ADDQ R14, AX + MOVQ AX, 40(SP) // Update match length - MOVQ R8, AX - MOVQ BX, CX - MOVQ DX, R14 - SHLQ CL, R14 - MOVB AH, CL - SHRQ $0x20, AX - TESTQ CX, CX - JZ sequenceDecs_decodeSync_amd64_ml_update_zero - ADDQ CX, BX - CMPQ BX, $0x40 - JA sequenceDecs_decodeSync_amd64_ml_update_zero - CMPQ CX, $0x40 - JAE sequenceDecs_decodeSync_amd64_ml_update_zero - NEGQ CX - SHRQ CL, R14 - ADDQ R14, AX - -sequenceDecs_decodeSync_amd64_ml_update_zero: - MOVQ AX, 16(SP) + MOVQ R8, AX + MOVQ BX, CX + MOVQ DX, R14 + SHLQ CL, R14 + SHRQ $0x01, R14 + MOVBLZX AH, CX + SHRQ $0x20, AX + ADDQ CX, BX + XORQ $0x3f, CX + SHRQ CL, R14 + ADDQ R14, AX + MOVQ AX, 48(SP) // Fill bitreader to have enough for the remaining CMPQ SI, $0x08 @@ -1924,96 +2476,82 @@ sequenceDecs_decodeSync_amd64_fill_2_check_overread: sequenceDecs_decodeSync_amd64_fill_2_end: // Update literal length - MOVQ DI, AX - MOVQ BX, CX - MOVQ DX, R14 - SHLQ CL, R14 - MOVB AH, CL - SHRQ $0x20, AX - TESTQ CX, CX - JZ sequenceDecs_decodeSync_amd64_ll_update_zero - ADDQ CX, BX - CMPQ BX, $0x40 - JA sequenceDecs_decodeSync_amd64_ll_update_zero - CMPQ CX, $0x40 - JAE sequenceDecs_decodeSync_amd64_ll_update_zero - NEGQ CX - SHRQ CL, R14 - ADDQ R14, AX - -sequenceDecs_decodeSync_amd64_ll_update_zero: - MOVQ AX, 24(SP) + MOVQ DI, AX + MOVQ BX, CX + MOVQ DX, R14 + SHLQ CL, R14 + SHRQ $0x01, R14 + MOVBLZX AH, CX + SHRQ $0x20, AX + ADDQ CX, BX + XORQ $0x3f, CX + SHRQ CL, R14 + ADDQ R14, AX + MOVQ AX, 56(SP) // Fill bitreader for state updates MOVQ R13, (SP) MOVQ R9, AX SHRQ $0x08, AX MOVBQZX AL, AX - MOVQ ctx+16(FP), CX - CMPQ 96(CX), $0x00 + CMPQ 32(SP), $0x00 JZ sequenceDecs_decodeSync_amd64_skip_update // Update Literal Length State MOVBQZX DI, R13 SHRL $0x10, DI - LEAQ (BX)(R13*1), CX + MOVQ BX, CX MOVQ DX, R14 - MOVQ CX, BX - ROLQ CL, R14 - MOVL $0x00000001, R15 - MOVB R13, CL - SHLL CL, R15 - DECL R15 - ANDQ R15, R14 + SHLQ CL, R14 + SHRQ $0x01, R14 + ADDQ R13, BX + XORQ $0x3f, R13 + MOVQ R13, CX + SHRQ CL, R14 ADDQ R14, DI // Load ctx.llTable - MOVQ ctx+16(FP), CX - MOVQ (CX), CX + MOVQ 8(SP), CX MOVQ (CX)(DI*8), DI // Update Match Length State MOVBQZX R8, R13 SHRL $0x10, R8 - LEAQ (BX)(R13*1), CX + MOVQ BX, CX MOVQ DX, R14 - MOVQ CX, BX - ROLQ CL, R14 - MOVL $0x00000001, R15 - MOVB R13, CL - SHLL CL, R15 - DECL R15 - ANDQ R15, R14 + SHLQ CL, R14 + SHRQ $0x01, R14 + ADDQ R13, BX + XORQ $0x3f, R13 + MOVQ R13, CX + SHRQ CL, R14 ADDQ R14, R8 // Load ctx.mlTable - MOVQ ctx+16(FP), CX - MOVQ 24(CX), CX + MOVQ 16(SP), CX MOVQ (CX)(R8*8), R8 // Update Offset State MOVBQZX R9, R13 SHRL $0x10, R9 - LEAQ (BX)(R13*1), CX + MOVQ BX, CX MOVQ DX, R14 - MOVQ CX, BX - ROLQ CL, R14 - MOVL $0x00000001, R15 - MOVB R13, CL - SHLL CL, R15 - DECL R15 - ANDQ R15, R14 + SHLQ CL, R14 + SHRQ $0x01, R14 + ADDQ R13, BX + XORQ $0x3f, R13 + MOVQ R13, CX + SHRQ CL, R14 ADDQ R14, R9 // Load ctx.ofTable - MOVQ ctx+16(FP), CX - MOVQ 48(CX), CX + MOVQ 24(SP), CX MOVQ (CX)(R9*8), R9 sequenceDecs_decodeSync_amd64_skip_update: // Adjust offset MOVQ s+0(FP), CX - MOVQ 8(SP), R13 + MOVQ 40(SP), R13 CMPQ AX, $0x01 JBE sequenceDecs_decodeSync_amd64_adjust_offsetB_1_or_0 MOVUPS 144(CX), X0 @@ -2022,7 +2560,7 @@ sequenceDecs_decodeSync_amd64_skip_update: JMP sequenceDecs_decodeSync_amd64_after_adjust sequenceDecs_decodeSync_amd64_adjust_offsetB_1_or_0: - CMPQ 24(SP), $0x00000000 + CMPQ 56(SP), $0x00000000 JNE sequenceDecs_decodeSync_amd64_adjust_offset_maybezero INCQ R13 JMP sequenceDecs_decodeSync_amd64_adjust_offset_nonzero @@ -2057,14 +2595,11 @@ sequenceDecs_decodeSync_amd64_adjust_skip: MOVQ R14, R13 sequenceDecs_decodeSync_amd64_after_adjust: - MOVQ R13, 8(SP) + MOVQ R13, 40(SP) // Check values - MOVQ 16(SP), AX - MOVQ 24(SP), CX - LEAQ (AX)(CX*1), R14 - MOVQ s+0(FP), R15 - ADDQ R14, 256(R15) + MOVQ 48(SP), AX + MOVQ 56(SP), CX MOVQ ctx+16(FP), R14 SUBQ CX, 104(R14) JS error_not_enough_literals @@ -2076,50 +2611,49 @@ sequenceDecs_decodeSync_amd64_after_adjust: JNZ sequenceDecs_decodeSync_amd64_error_match_len_ofs_mismatch sequenceDecs_decodeSync_amd64_match_len_ofs_ok: - MOVQ 24(SP), AX - MOVQ 8(SP), CX - MOVQ 16(SP), R13 - // Check if we have enough space in s.out - LEAQ 16(AX)(R13*1), R14 + LEAQ 32(CX)(AX*1), R14 ADDQ R10, R14 - CMPQ R14, 32(SP) + CMPQ R14, 64(SP) JA error_not_enough_space // Copy literals - TESTQ AX, AX - JZ check_offset - XORQ R14, R14 + MOVUPS (R11), X0 + MOVUPS X0, (R10) + CMPQ CX, $0x10 + JBE copy_1_end + MOVQ $0x00000010, R14 copy_1: MOVUPS (R11)(R14*1), X0 MOVUPS X0, (R10)(R14*1) ADDQ $0x10, R14 - CMPQ R14, AX + CMPQ R14, CX JB copy_1 - ADDQ AX, R11 - ADDQ AX, R10 - ADDQ AX, R12 + +copy_1_end: + ADDQ CX, R11 + ADDQ CX, R10 + ADDQ CX, R12 // Malformed input if seq.mo > t+len(hist) || seq.mo > s.windowSize) -check_offset: - MOVQ R12, AX - ADDQ 40(SP), AX - CMPQ CX, AX + MOVQ R12, CX + ADDQ 72(SP), CX + CMPQ R13, CX JG error_match_off_too_big - CMPQ CX, 56(SP) + CMPQ R13, 88(SP) JG error_match_off_too_big // Copy match from history - MOVQ CX, AX - SUBQ R12, AX + MOVQ R13, CX + SUBQ R12, CX JLS copy_match - MOVQ 48(SP), R14 - SUBQ AX, R14 - CMPQ R13, AX + MOVQ 80(SP), R14 + SUBQ CX, R14 + CMPQ AX, CX JG copy_all_from_history - MOVQ R13, AX - SUBQ $0x10, AX + MOVQ AX, CX + SUBQ $0x10, CX JB copy_4_small copy_4_loop: @@ -2127,54 +2661,54 @@ copy_4_loop: MOVUPS X0, (R10) ADDQ $0x10, R14 ADDQ $0x10, R10 - SUBQ $0x10, AX + SUBQ $0x10, CX JAE copy_4_loop - LEAQ 16(R14)(AX*1), R14 - LEAQ 16(R10)(AX*1), R10 + LEAQ 16(R14)(CX*1), R14 + LEAQ 16(R10)(CX*1), R10 MOVUPS -16(R14), X0 MOVUPS X0, -16(R10) JMP copy_4_end copy_4_small: - CMPQ R13, $0x03 + CMPQ AX, $0x03 JE copy_4_move_3 - CMPQ R13, $0x08 + CMPQ AX, $0x08 JB copy_4_move_4through7 JMP copy_4_move_8through16 copy_4_move_3: - MOVW (R14), AX - MOVB 2(R14), CL - MOVW AX, (R10) - MOVB CL, 2(R10) - ADDQ R13, R14 - ADDQ R13, R10 - JMP copy_4_end + MOVWQZX (R14), CX + MOVB 2(R14), R13 + MOVW CX, (R10) + MOVB R13, 2(R10) + ADDQ AX, R14 + ADDQ AX, R10 + JMP copy_4_end copy_4_move_4through7: - MOVL (R14), AX - MOVL -4(R14)(R13*1), CX - MOVL AX, (R10) - MOVL CX, -4(R10)(R13*1) - ADDQ R13, R14 - ADDQ R13, R10 + MOVL (R14), CX + MOVL -4(R14)(AX*1), R13 + MOVL CX, (R10) + MOVL R13, -4(R10)(AX*1) + ADDQ AX, R14 + ADDQ AX, R10 JMP copy_4_end copy_4_move_8through16: - MOVQ (R14), AX - MOVQ -8(R14)(R13*1), CX - MOVQ AX, (R10) - MOVQ CX, -8(R10)(R13*1) - ADDQ R13, R14 - ADDQ R13, R10 + MOVQ (R14), CX + MOVQ -8(R14)(AX*1), R13 + MOVQ CX, (R10) + MOVQ R13, -8(R10)(AX*1) + ADDQ AX, R14 + ADDQ AX, R10 copy_4_end: - ADDQ R13, R12 + ADDQ AX, R12 JMP handle_loop JMP loop_finished copy_all_from_history: - MOVQ AX, R15 + MOVQ CX, R15 SUBQ $0x10, R15 JB copy_5_small @@ -2192,90 +2726,116 @@ copy_5_loop: JMP copy_5_end copy_5_small: - CMPQ AX, $0x03 + CMPQ CX, $0x03 JE copy_5_move_3 JB copy_5_move_1or2 - CMPQ AX, $0x08 + CMPQ CX, $0x08 JB copy_5_move_4through7 JMP copy_5_move_8through16 copy_5_move_1or2: MOVB (R14), R15 - MOVB -1(R14)(AX*1), BP + MOVB -1(R14)(CX*1), BP MOVB R15, (R10) - MOVB BP, -1(R10)(AX*1) - ADDQ AX, R14 - ADDQ AX, R10 + MOVB BP, -1(R10)(CX*1) + ADDQ CX, R14 + ADDQ CX, R10 JMP copy_5_end copy_5_move_3: - MOVW (R14), R15 - MOVB 2(R14), BP - MOVW R15, (R10) - MOVB BP, 2(R10) - ADDQ AX, R14 - ADDQ AX, R10 - JMP copy_5_end + MOVWQZX (R14), R15 + MOVB 2(R14), BP + MOVW R15, (R10) + MOVB BP, 2(R10) + ADDQ CX, R14 + ADDQ CX, R10 + JMP copy_5_end copy_5_move_4through7: MOVL (R14), R15 - MOVL -4(R14)(AX*1), BP + MOVL -4(R14)(CX*1), BP MOVL R15, (R10) - MOVL BP, -4(R10)(AX*1) - ADDQ AX, R14 - ADDQ AX, R10 + MOVL BP, -4(R10)(CX*1) + ADDQ CX, R14 + ADDQ CX, R10 JMP copy_5_end copy_5_move_8through16: MOVQ (R14), R15 - MOVQ -8(R14)(AX*1), BP + MOVQ -8(R14)(CX*1), BP MOVQ R15, (R10) - MOVQ BP, -8(R10)(AX*1) - ADDQ AX, R14 - ADDQ AX, R10 + MOVQ BP, -8(R10)(CX*1) + ADDQ CX, R14 + ADDQ CX, R10 copy_5_end: - ADDQ AX, R12 - SUBQ AX, R13 + ADDQ CX, R12 + SUBQ CX, AX // Copy match from the current buffer copy_match: - MOVQ R10, AX - SUBQ CX, AX + MOVQ R10, CX + SUBQ R13, CX // ml <= mo - CMPQ R13, CX + CMPQ AX, R13 JA copy_overlapping_match // Copy non-overlapping match - ADDQ R13, R12 - MOVQ R10, CX - ADDQ R13, R10 + ADDQ AX, R12 + MOVUPS (CX), X0 + MOVUPS 16(CX), X1 + MOVUPS X0, (R10) + MOVUPS X1, 16(R10) + CMPQ AX, $0x20 + JA copy_2_long + ADDQ AX, R10 + JMP handle_loop + +copy_2_long: + LEAQ 32(R10), R13 + ADDQ AX, R10 + ADDQ $0x20, CX + SUBQ $0x20, AX copy_2: - MOVUPS (AX), X0 - MOVUPS X0, (CX) - ADDQ $0x10, AX - ADDQ $0x10, CX - SUBQ $0x10, R13 + MOVUPS (CX), X0 + MOVUPS 16(CX), X1 + MOVUPS X0, (R13) + MOVUPS X1, 16(R13) + ADDQ $0x20, CX + ADDQ $0x20, R13 + SUBQ $0x20, AX JHI copy_2 JMP handle_loop // Copy overlapping match copy_overlapping_match: - ADDQ R13, R12 + ADDQ AX, R12 + CMPQ R13, $0x10 + JB copy_slow_3 + MOVQ R10, R13 + ADDQ AX, R10 + +copy_3: + MOVUPS (CX), X0 + MOVUPS X0, (R13) + ADDQ $0x10, CX + ADDQ $0x10, R13 + SUBQ $0x10, AX + JHI copy_3 + JMP handle_loop copy_slow_3: - MOVB (AX), CL - MOVB CL, (R10) - INCQ AX - INCQ R10 - DECQ R13 - JNZ copy_slow_3 + MOVBQZX (CX), R13 + MOVB R13, (R10) + INCQ CX + INCQ R10 + DECQ AX + JNZ copy_slow_3 handle_loop: - MOVQ ctx+16(FP), AX - DECQ 96(AX) + DECQ 32(SP) JNS sequenceDecs_decodeSync_amd64_main_loop loop_finished: @@ -2284,6 +2844,13 @@ loop_finished: MOVB BL, 40(AX) MOVQ SI, 32(AX) + // s.seqSize += outPosition - ctx.outPosition + MOVQ ctx+16(FP), AX + MOVQ s+0(FP), CX + MOVQ R12, DX + SUBQ 136(AX), DX + ADDQ DX, 256(CX) + // Update the context MOVQ ctx+16(FP), AX MOVQ R12, 136(AX) @@ -2297,7 +2864,7 @@ loop_finished: // Return with match length error sequenceDecs_decodeSync_amd64_error_match_len_ofs_mismatch: - MOVQ 16(SP), AX + MOVQ 48(SP), AX MOVQ ctx+16(FP), CX MOVQ AX, 216(CX) MOVQ $0x00000001, ret+24(FP) @@ -2306,7 +2873,7 @@ sequenceDecs_decodeSync_amd64_error_match_len_ofs_mismatch: // Return with match too long error sequenceDecs_decodeSync_amd64_error_match_len_too_big: MOVQ ctx+16(FP), AX - MOVQ 16(SP), CX + MOVQ 48(SP), CX MOVQ CX, 216(AX) MOVQ $0x00000002, ret+24(FP) RET @@ -2314,7 +2881,7 @@ sequenceDecs_decodeSync_amd64_error_match_len_too_big: // Return with match offset too long error error_match_off_too_big: MOVQ ctx+16(FP), AX - MOVQ 8(SP), CX + MOVQ 40(SP), CX MOVQ CX, 224(AX) MOVQ R12, 136(AX) MOVQ $0x00000003, ret+24(FP) @@ -2323,7 +2890,7 @@ error_match_off_too_big: // Return with not enough literals error error_not_enough_literals: MOVQ ctx+16(FP), AX - MOVQ 24(SP), CX + MOVQ 56(SP), CX MOVQ CX, 208(AX) MOVQ $0x00000004, ret+24(FP) RET @@ -2336,9 +2903,9 @@ error_overread: // Return with not enough output space error error_not_enough_space: MOVQ ctx+16(FP), AX - MOVQ 24(SP), CX + MOVQ 56(SP), CX MOVQ CX, 208(AX) - MOVQ 16(SP), CX + MOVQ 48(SP), CX MOVQ CX, 216(AX) MOVQ R12, 136(AX) MOVQ $0x00000005, ret+24(FP) @@ -2346,7 +2913,7 @@ error_not_enough_space: // func sequenceDecs_decodeSync_bmi2(s *sequenceDecs, br *bitReader, ctx *decodeSyncAsmContext) int // Requires: BMI, BMI2, CMOV, SSE -TEXT ·sequenceDecs_decodeSync_bmi2(SB), $64-32 +TEXT ·sequenceDecs_decodeSync_bmi2(SB), $96-32 MOVQ br+8(FP), BX MOVQ 24(BX), AX MOVBQZX 40(BX), DX @@ -2358,29 +2925,38 @@ TEXT ·sequenceDecs_decodeSync_bmi2(SB), $64-32 MOVQ 72(CX), SI MOVQ 80(CX), DI MOVQ 88(CX), R8 - XORQ R9, R9 + MOVQ (CX), R9 MOVQ R9, 8(SP) + MOVQ 24(CX), R9 MOVQ R9, 16(SP) + MOVQ 48(CX), R9 MOVQ R9, 24(SP) + MOVQ 96(CX), R9 + MOVQ R9, 32(SP) + XORQ R9, R9 + MOVQ R9, 40(SP) + MOVQ R9, 48(SP) + MOVQ R9, 56(SP) MOVQ 112(CX), R9 MOVQ 128(CX), R10 - MOVQ R10, 32(SP) + MOVQ R10, 64(SP) MOVQ 144(CX), R10 MOVQ 136(CX), R11 MOVQ 200(CX), R12 - MOVQ R12, 56(SP) + MOVQ R12, 88(SP) MOVQ 176(CX), R12 - MOVQ R12, 48(SP) + MOVQ R12, 80(SP) MOVQ 184(CX), CX - MOVQ CX, 40(SP) - MOVQ 40(SP), CX - ADDQ CX, 48(SP) + MOVQ CX, 72(SP) + MOVQ 72(SP), CX + ADDQ CX, 80(SP) // Calculate pointer to s.out[cap(s.out)] (a past-end pointer) - ADDQ R9, 32(SP) + ADDQ R9, 64(SP) // outBase += outPosition - ADDQ R11, R9 + ADDQ R11, R9 + PCALIGN $0x40 sequenceDecs_decodeSync_bmi2_main_loop: MOVQ (SP), R12 @@ -2425,7 +3001,7 @@ sequenceDecs_decodeSync_bmi2_fill_end: MOVQ R8, CX SHRQ $0x20, CX ADDQ R14, CX - MOVQ CX, 8(SP) + MOVQ CX, 40(SP) // Update match length MOVQ $0x00000808, CX @@ -2438,7 +3014,7 @@ sequenceDecs_decodeSync_bmi2_fill_end: MOVQ DI, CX SHRQ $0x20, CX ADDQ R14, CX - MOVQ CX, 16(SP) + MOVQ CX, 48(SP) // Fill bitreader to have enough for the remaining CMPQ BX, $0x08 @@ -2480,14 +3056,13 @@ sequenceDecs_decodeSync_bmi2_fill_2_end: MOVQ SI, CX SHRQ $0x20, CX ADDQ R14, CX - MOVQ CX, 24(SP) + MOVQ CX, 56(SP) // Fill bitreader for state updates MOVQ R12, (SP) MOVQ $0x00000808, CX BEXTRQ CX, R8, R12 - MOVQ ctx+16(FP), CX - CMPQ 96(CX), $0x00 + CMPQ 32(SP), $0x00 JZ sequenceDecs_decodeSync_bmi2_skip_update LEAQ (SI)(DI*1), R13 ADDQ R8, R13 @@ -2505,8 +3080,7 @@ sequenceDecs_decodeSync_bmi2_fill_2_end: ADDQ CX, R8 // Load ctx.ofTable - MOVQ ctx+16(FP), CX - MOVQ 48(CX), CX + MOVQ 24(SP), CX MOVQ (CX)(R8*8), R8 // Update Match Length State @@ -2516,8 +3090,7 @@ sequenceDecs_decodeSync_bmi2_fill_2_end: ADDQ CX, DI // Load ctx.mlTable - MOVQ ctx+16(FP), CX - MOVQ 24(CX), CX + MOVQ 16(SP), CX MOVQ (CX)(DI*8), DI // Update Literal Length State @@ -2526,14 +3099,13 @@ sequenceDecs_decodeSync_bmi2_fill_2_end: ADDQ CX, SI // Load ctx.llTable - MOVQ ctx+16(FP), CX - MOVQ (CX), CX + MOVQ 8(SP), CX MOVQ (CX)(SI*8), SI sequenceDecs_decodeSync_bmi2_skip_update: // Adjust offset MOVQ s+0(FP), CX - MOVQ 8(SP), R13 + MOVQ 40(SP), R13 CMPQ R12, $0x01 JBE sequenceDecs_decodeSync_bmi2_adjust_offsetB_1_or_0 MOVUPS 144(CX), X0 @@ -2542,7 +3114,7 @@ sequenceDecs_decodeSync_bmi2_skip_update: JMP sequenceDecs_decodeSync_bmi2_after_adjust sequenceDecs_decodeSync_bmi2_adjust_offsetB_1_or_0: - CMPQ 24(SP), $0x00000000 + CMPQ 56(SP), $0x00000000 JNE sequenceDecs_decodeSync_bmi2_adjust_offset_maybezero INCQ R13 JMP sequenceDecs_decodeSync_bmi2_adjust_offset_nonzero @@ -2577,14 +3149,11 @@ sequenceDecs_decodeSync_bmi2_adjust_skip: MOVQ R14, R13 sequenceDecs_decodeSync_bmi2_after_adjust: - MOVQ R13, 8(SP) + MOVQ R13, 40(SP) // Check values - MOVQ 16(SP), CX - MOVQ 24(SP), R12 - LEAQ (CX)(R12*1), R14 - MOVQ s+0(FP), R15 - ADDQ R14, 256(R15) + MOVQ 48(SP), CX + MOVQ 56(SP), R12 MOVQ ctx+16(FP), R14 SUBQ R12, 104(R14) JS error_not_enough_literals @@ -2596,50 +3165,49 @@ sequenceDecs_decodeSync_bmi2_after_adjust: JNZ sequenceDecs_decodeSync_bmi2_error_match_len_ofs_mismatch sequenceDecs_decodeSync_bmi2_match_len_ofs_ok: - MOVQ 24(SP), CX - MOVQ 8(SP), R12 - MOVQ 16(SP), R13 - // Check if we have enough space in s.out - LEAQ 16(CX)(R13*1), R14 + LEAQ 32(R12)(CX*1), R14 ADDQ R9, R14 - CMPQ R14, 32(SP) + CMPQ R14, 64(SP) JA error_not_enough_space // Copy literals - TESTQ CX, CX - JZ check_offset - XORQ R14, R14 + MOVUPS (R10), X0 + MOVUPS X0, (R9) + CMPQ R12, $0x10 + JBE copy_1_end + MOVQ $0x00000010, R14 copy_1: MOVUPS (R10)(R14*1), X0 MOVUPS X0, (R9)(R14*1) ADDQ $0x10, R14 - CMPQ R14, CX + CMPQ R14, R12 JB copy_1 - ADDQ CX, R10 - ADDQ CX, R9 - ADDQ CX, R11 + +copy_1_end: + ADDQ R12, R10 + ADDQ R12, R9 + ADDQ R12, R11 // Malformed input if seq.mo > t+len(hist) || seq.mo > s.windowSize) -check_offset: - MOVQ R11, CX - ADDQ 40(SP), CX - CMPQ R12, CX + MOVQ R11, R12 + ADDQ 72(SP), R12 + CMPQ R13, R12 JG error_match_off_too_big - CMPQ R12, 56(SP) + CMPQ R13, 88(SP) JG error_match_off_too_big // Copy match from history - MOVQ R12, CX - SUBQ R11, CX + MOVQ R13, R12 + SUBQ R11, R12 JLS copy_match - MOVQ 48(SP), R14 - SUBQ CX, R14 - CMPQ R13, CX + MOVQ 80(SP), R14 + SUBQ R12, R14 + CMPQ CX, R12 JG copy_all_from_history - MOVQ R13, CX - SUBQ $0x10, CX + MOVQ CX, R12 + SUBQ $0x10, R12 JB copy_4_small copy_4_loop: @@ -2647,54 +3215,54 @@ copy_4_loop: MOVUPS X0, (R9) ADDQ $0x10, R14 ADDQ $0x10, R9 - SUBQ $0x10, CX + SUBQ $0x10, R12 JAE copy_4_loop - LEAQ 16(R14)(CX*1), R14 - LEAQ 16(R9)(CX*1), R9 + LEAQ 16(R14)(R12*1), R14 + LEAQ 16(R9)(R12*1), R9 MOVUPS -16(R14), X0 MOVUPS X0, -16(R9) JMP copy_4_end copy_4_small: - CMPQ R13, $0x03 + CMPQ CX, $0x03 JE copy_4_move_3 - CMPQ R13, $0x08 + CMPQ CX, $0x08 JB copy_4_move_4through7 JMP copy_4_move_8through16 copy_4_move_3: - MOVW (R14), CX - MOVB 2(R14), R12 - MOVW CX, (R9) - MOVB R12, 2(R9) - ADDQ R13, R14 - ADDQ R13, R9 - JMP copy_4_end + MOVWQZX (R14), R12 + MOVB 2(R14), R13 + MOVW R12, (R9) + MOVB R13, 2(R9) + ADDQ CX, R14 + ADDQ CX, R9 + JMP copy_4_end copy_4_move_4through7: - MOVL (R14), CX - MOVL -4(R14)(R13*1), R12 - MOVL CX, (R9) - MOVL R12, -4(R9)(R13*1) - ADDQ R13, R14 - ADDQ R13, R9 + MOVL (R14), R12 + MOVL -4(R14)(CX*1), R13 + MOVL R12, (R9) + MOVL R13, -4(R9)(CX*1) + ADDQ CX, R14 + ADDQ CX, R9 JMP copy_4_end copy_4_move_8through16: - MOVQ (R14), CX - MOVQ -8(R14)(R13*1), R12 - MOVQ CX, (R9) - MOVQ R12, -8(R9)(R13*1) - ADDQ R13, R14 - ADDQ R13, R9 + MOVQ (R14), R12 + MOVQ -8(R14)(CX*1), R13 + MOVQ R12, (R9) + MOVQ R13, -8(R9)(CX*1) + ADDQ CX, R14 + ADDQ CX, R9 copy_4_end: - ADDQ R13, R11 + ADDQ CX, R11 JMP handle_loop JMP loop_finished copy_all_from_history: - MOVQ CX, R15 + MOVQ R12, R15 SUBQ $0x10, R15 JB copy_5_small @@ -2712,90 +3280,116 @@ copy_5_loop: JMP copy_5_end copy_5_small: - CMPQ CX, $0x03 + CMPQ R12, $0x03 JE copy_5_move_3 JB copy_5_move_1or2 - CMPQ CX, $0x08 + CMPQ R12, $0x08 JB copy_5_move_4through7 JMP copy_5_move_8through16 copy_5_move_1or2: MOVB (R14), R15 - MOVB -1(R14)(CX*1), BP + MOVB -1(R14)(R12*1), BP MOVB R15, (R9) - MOVB BP, -1(R9)(CX*1) - ADDQ CX, R14 - ADDQ CX, R9 + MOVB BP, -1(R9)(R12*1) + ADDQ R12, R14 + ADDQ R12, R9 JMP copy_5_end copy_5_move_3: - MOVW (R14), R15 - MOVB 2(R14), BP - MOVW R15, (R9) - MOVB BP, 2(R9) - ADDQ CX, R14 - ADDQ CX, R9 - JMP copy_5_end + MOVWQZX (R14), R15 + MOVB 2(R14), BP + MOVW R15, (R9) + MOVB BP, 2(R9) + ADDQ R12, R14 + ADDQ R12, R9 + JMP copy_5_end copy_5_move_4through7: MOVL (R14), R15 - MOVL -4(R14)(CX*1), BP + MOVL -4(R14)(R12*1), BP MOVL R15, (R9) - MOVL BP, -4(R9)(CX*1) - ADDQ CX, R14 - ADDQ CX, R9 + MOVL BP, -4(R9)(R12*1) + ADDQ R12, R14 + ADDQ R12, R9 JMP copy_5_end copy_5_move_8through16: MOVQ (R14), R15 - MOVQ -8(R14)(CX*1), BP + MOVQ -8(R14)(R12*1), BP MOVQ R15, (R9) - MOVQ BP, -8(R9)(CX*1) - ADDQ CX, R14 - ADDQ CX, R9 + MOVQ BP, -8(R9)(R12*1) + ADDQ R12, R14 + ADDQ R12, R9 copy_5_end: - ADDQ CX, R11 - SUBQ CX, R13 + ADDQ R12, R11 + SUBQ R12, CX // Copy match from the current buffer copy_match: - MOVQ R9, CX - SUBQ R12, CX + MOVQ R9, R12 + SUBQ R13, R12 // ml <= mo - CMPQ R13, R12 + CMPQ CX, R13 JA copy_overlapping_match // Copy non-overlapping match - ADDQ R13, R11 - MOVQ R9, R12 - ADDQ R13, R9 + ADDQ CX, R11 + MOVUPS (R12), X0 + MOVUPS 16(R12), X1 + MOVUPS X0, (R9) + MOVUPS X1, 16(R9) + CMPQ CX, $0x20 + JA copy_2_long + ADDQ CX, R9 + JMP handle_loop + +copy_2_long: + LEAQ 32(R9), R13 + ADDQ CX, R9 + ADDQ $0x20, R12 + SUBQ $0x20, CX copy_2: - MOVUPS (CX), X0 - MOVUPS X0, (R12) - ADDQ $0x10, CX - ADDQ $0x10, R12 - SUBQ $0x10, R13 + MOVUPS (R12), X0 + MOVUPS 16(R12), X1 + MOVUPS X0, (R13) + MOVUPS X1, 16(R13) + ADDQ $0x20, R12 + ADDQ $0x20, R13 + SUBQ $0x20, CX JHI copy_2 JMP handle_loop // Copy overlapping match copy_overlapping_match: - ADDQ R13, R11 + ADDQ CX, R11 + CMPQ R13, $0x10 + JB copy_slow_3 + MOVQ R9, R13 + ADDQ CX, R9 + +copy_3: + MOVUPS (R12), X0 + MOVUPS X0, (R13) + ADDQ $0x10, R12 + ADDQ $0x10, R13 + SUBQ $0x10, CX + JHI copy_3 + JMP handle_loop copy_slow_3: - MOVB (CX), R12 - MOVB R12, (R9) - INCQ CX - INCQ R9 - DECQ R13 - JNZ copy_slow_3 + MOVBQZX (R12), R13 + MOVB R13, (R9) + INCQ R12 + INCQ R9 + DECQ CX + JNZ copy_slow_3 handle_loop: - MOVQ ctx+16(FP), CX - DECQ 96(CX) + DECQ 32(SP) JNS sequenceDecs_decodeSync_bmi2_main_loop loop_finished: @@ -2804,6 +3398,13 @@ loop_finished: MOVB DL, 40(CX) MOVQ BX, 32(CX) + // s.seqSize += outPosition - ctx.outPosition + MOVQ ctx+16(FP), AX + MOVQ s+0(FP), CX + MOVQ R11, DX + SUBQ 136(AX), DX + ADDQ DX, 256(CX) + // Update the context MOVQ ctx+16(FP), AX MOVQ R11, 136(AX) @@ -2817,7 +3418,7 @@ loop_finished: // Return with match length error sequenceDecs_decodeSync_bmi2_error_match_len_ofs_mismatch: - MOVQ 16(SP), AX + MOVQ 48(SP), AX MOVQ ctx+16(FP), CX MOVQ AX, 216(CX) MOVQ $0x00000001, ret+24(FP) @@ -2826,7 +3427,7 @@ sequenceDecs_decodeSync_bmi2_error_match_len_ofs_mismatch: // Return with match too long error sequenceDecs_decodeSync_bmi2_error_match_len_too_big: MOVQ ctx+16(FP), AX - MOVQ 16(SP), CX + MOVQ 48(SP), CX MOVQ CX, 216(AX) MOVQ $0x00000002, ret+24(FP) RET @@ -2834,7 +3435,7 @@ sequenceDecs_decodeSync_bmi2_error_match_len_too_big: // Return with match offset too long error error_match_off_too_big: MOVQ ctx+16(FP), AX - MOVQ 8(SP), CX + MOVQ 40(SP), CX MOVQ CX, 224(AX) MOVQ R11, 136(AX) MOVQ $0x00000003, ret+24(FP) @@ -2843,7 +3444,7 @@ error_match_off_too_big: // Return with not enough literals error error_not_enough_literals: MOVQ ctx+16(FP), AX - MOVQ 24(SP), CX + MOVQ 56(SP), CX MOVQ CX, 208(AX) MOVQ $0x00000004, ret+24(FP) RET @@ -2856,9 +3457,9 @@ error_overread: // Return with not enough output space error error_not_enough_space: MOVQ ctx+16(FP), AX - MOVQ 24(SP), CX + MOVQ 56(SP), CX MOVQ CX, 208(AX) - MOVQ 16(SP), CX + MOVQ 48(SP), CX MOVQ CX, 216(AX) MOVQ R11, 136(AX) MOVQ $0x00000005, ret+24(FP) @@ -2866,7 +3467,7 @@ error_not_enough_space: // func sequenceDecs_decodeSync_safe_amd64(s *sequenceDecs, br *bitReader, ctx *decodeSyncAsmContext) int // Requires: CMOV, SSE -TEXT ·sequenceDecs_decodeSync_safe_amd64(SB), $64-32 +TEXT ·sequenceDecs_decodeSync_safe_amd64(SB), $96-32 MOVQ br+8(FP), CX MOVQ 24(CX), DX MOVBQZX 40(CX), BX @@ -2878,29 +3479,38 @@ TEXT ·sequenceDecs_decodeSync_safe_amd64(SB), $64-32 MOVQ 72(AX), DI MOVQ 80(AX), R8 MOVQ 88(AX), R9 - XORQ CX, CX + MOVQ (AX), CX MOVQ CX, 8(SP) + MOVQ 24(AX), CX MOVQ CX, 16(SP) + MOVQ 48(AX), CX MOVQ CX, 24(SP) + MOVQ 96(AX), CX + MOVQ CX, 32(SP) + XORQ CX, CX + MOVQ CX, 40(SP) + MOVQ CX, 48(SP) + MOVQ CX, 56(SP) MOVQ 112(AX), R10 MOVQ 128(AX), CX - MOVQ CX, 32(SP) + MOVQ CX, 64(SP) MOVQ 144(AX), R11 MOVQ 136(AX), R12 MOVQ 200(AX), CX - MOVQ CX, 56(SP) + MOVQ CX, 88(SP) MOVQ 176(AX), CX - MOVQ CX, 48(SP) + MOVQ CX, 80(SP) MOVQ 184(AX), AX - MOVQ AX, 40(SP) - MOVQ 40(SP), AX - ADDQ AX, 48(SP) + MOVQ AX, 72(SP) + MOVQ 72(SP), AX + ADDQ AX, 80(SP) // Calculate pointer to s.out[cap(s.out)] (a past-end pointer) - ADDQ R10, 32(SP) + ADDQ R10, 64(SP) // outBase += outPosition - ADDQ R12, R10 + ADDQ R12, R10 + PCALIGN $0x40 sequenceDecs_decodeSync_safe_amd64_main_loop: MOVQ (SP), R13 @@ -2935,46 +3545,32 @@ sequenceDecs_decodeSync_safe_amd64_fill_check_overread: sequenceDecs_decodeSync_safe_amd64_fill_end: // Update offset - MOVQ R9, AX - MOVQ BX, CX - MOVQ DX, R14 - SHLQ CL, R14 - MOVB AH, CL - SHRQ $0x20, AX - TESTQ CX, CX - JZ sequenceDecs_decodeSync_safe_amd64_of_update_zero - ADDQ CX, BX - CMPQ BX, $0x40 - JA sequenceDecs_decodeSync_safe_amd64_of_update_zero - CMPQ CX, $0x40 - JAE sequenceDecs_decodeSync_safe_amd64_of_update_zero - NEGQ CX - SHRQ CL, R14 - ADDQ R14, AX - -sequenceDecs_decodeSync_safe_amd64_of_update_zero: - MOVQ AX, 8(SP) + MOVQ R9, AX + MOVQ BX, CX + MOVQ DX, R14 + SHLQ CL, R14 + SHRQ $0x01, R14 + MOVBLZX AH, CX + SHRQ $0x20, AX + ADDQ CX, BX + XORQ $0x3f, CX + SHRQ CL, R14 + ADDQ R14, AX + MOVQ AX, 40(SP) // Update match length - MOVQ R8, AX - MOVQ BX, CX - MOVQ DX, R14 - SHLQ CL, R14 - MOVB AH, CL - SHRQ $0x20, AX - TESTQ CX, CX - JZ sequenceDecs_decodeSync_safe_amd64_ml_update_zero - ADDQ CX, BX - CMPQ BX, $0x40 - JA sequenceDecs_decodeSync_safe_amd64_ml_update_zero - CMPQ CX, $0x40 - JAE sequenceDecs_decodeSync_safe_amd64_ml_update_zero - NEGQ CX - SHRQ CL, R14 - ADDQ R14, AX - -sequenceDecs_decodeSync_safe_amd64_ml_update_zero: - MOVQ AX, 16(SP) + MOVQ R8, AX + MOVQ BX, CX + MOVQ DX, R14 + SHLQ CL, R14 + SHRQ $0x01, R14 + MOVBLZX AH, CX + SHRQ $0x20, AX + ADDQ CX, BX + XORQ $0x3f, CX + SHRQ CL, R14 + ADDQ R14, AX + MOVQ AX, 48(SP) // Fill bitreader to have enough for the remaining CMPQ SI, $0x08 @@ -3006,96 +3602,82 @@ sequenceDecs_decodeSync_safe_amd64_fill_2_check_overread: sequenceDecs_decodeSync_safe_amd64_fill_2_end: // Update literal length - MOVQ DI, AX - MOVQ BX, CX - MOVQ DX, R14 - SHLQ CL, R14 - MOVB AH, CL - SHRQ $0x20, AX - TESTQ CX, CX - JZ sequenceDecs_decodeSync_safe_amd64_ll_update_zero - ADDQ CX, BX - CMPQ BX, $0x40 - JA sequenceDecs_decodeSync_safe_amd64_ll_update_zero - CMPQ CX, $0x40 - JAE sequenceDecs_decodeSync_safe_amd64_ll_update_zero - NEGQ CX - SHRQ CL, R14 - ADDQ R14, AX - -sequenceDecs_decodeSync_safe_amd64_ll_update_zero: - MOVQ AX, 24(SP) + MOVQ DI, AX + MOVQ BX, CX + MOVQ DX, R14 + SHLQ CL, R14 + SHRQ $0x01, R14 + MOVBLZX AH, CX + SHRQ $0x20, AX + ADDQ CX, BX + XORQ $0x3f, CX + SHRQ CL, R14 + ADDQ R14, AX + MOVQ AX, 56(SP) // Fill bitreader for state updates MOVQ R13, (SP) MOVQ R9, AX SHRQ $0x08, AX MOVBQZX AL, AX - MOVQ ctx+16(FP), CX - CMPQ 96(CX), $0x00 + CMPQ 32(SP), $0x00 JZ sequenceDecs_decodeSync_safe_amd64_skip_update // Update Literal Length State MOVBQZX DI, R13 SHRL $0x10, DI - LEAQ (BX)(R13*1), CX + MOVQ BX, CX MOVQ DX, R14 - MOVQ CX, BX - ROLQ CL, R14 - MOVL $0x00000001, R15 - MOVB R13, CL - SHLL CL, R15 - DECL R15 - ANDQ R15, R14 + SHLQ CL, R14 + SHRQ $0x01, R14 + ADDQ R13, BX + XORQ $0x3f, R13 + MOVQ R13, CX + SHRQ CL, R14 ADDQ R14, DI // Load ctx.llTable - MOVQ ctx+16(FP), CX - MOVQ (CX), CX + MOVQ 8(SP), CX MOVQ (CX)(DI*8), DI // Update Match Length State MOVBQZX R8, R13 SHRL $0x10, R8 - LEAQ (BX)(R13*1), CX + MOVQ BX, CX MOVQ DX, R14 - MOVQ CX, BX - ROLQ CL, R14 - MOVL $0x00000001, R15 - MOVB R13, CL - SHLL CL, R15 - DECL R15 - ANDQ R15, R14 + SHLQ CL, R14 + SHRQ $0x01, R14 + ADDQ R13, BX + XORQ $0x3f, R13 + MOVQ R13, CX + SHRQ CL, R14 ADDQ R14, R8 // Load ctx.mlTable - MOVQ ctx+16(FP), CX - MOVQ 24(CX), CX + MOVQ 16(SP), CX MOVQ (CX)(R8*8), R8 // Update Offset State MOVBQZX R9, R13 SHRL $0x10, R9 - LEAQ (BX)(R13*1), CX + MOVQ BX, CX MOVQ DX, R14 - MOVQ CX, BX - ROLQ CL, R14 - MOVL $0x00000001, R15 - MOVB R13, CL - SHLL CL, R15 - DECL R15 - ANDQ R15, R14 + SHLQ CL, R14 + SHRQ $0x01, R14 + ADDQ R13, BX + XORQ $0x3f, R13 + MOVQ R13, CX + SHRQ CL, R14 ADDQ R14, R9 // Load ctx.ofTable - MOVQ ctx+16(FP), CX - MOVQ 48(CX), CX + MOVQ 24(SP), CX MOVQ (CX)(R9*8), R9 sequenceDecs_decodeSync_safe_amd64_skip_update: // Adjust offset MOVQ s+0(FP), CX - MOVQ 8(SP), R13 + MOVQ 40(SP), R13 CMPQ AX, $0x01 JBE sequenceDecs_decodeSync_safe_amd64_adjust_offsetB_1_or_0 MOVUPS 144(CX), X0 @@ -3104,7 +3686,7 @@ sequenceDecs_decodeSync_safe_amd64_skip_update: JMP sequenceDecs_decodeSync_safe_amd64_after_adjust sequenceDecs_decodeSync_safe_amd64_adjust_offsetB_1_or_0: - CMPQ 24(SP), $0x00000000 + CMPQ 56(SP), $0x00000000 JNE sequenceDecs_decodeSync_safe_amd64_adjust_offset_maybezero INCQ R13 JMP sequenceDecs_decodeSync_safe_amd64_adjust_offset_nonzero @@ -3139,14 +3721,11 @@ sequenceDecs_decodeSync_safe_amd64_adjust_skip: MOVQ R14, R13 sequenceDecs_decodeSync_safe_amd64_after_adjust: - MOVQ R13, 8(SP) + MOVQ R13, 40(SP) // Check values - MOVQ 16(SP), AX - MOVQ 24(SP), CX - LEAQ (AX)(CX*1), R14 - MOVQ s+0(FP), R15 - ADDQ R14, 256(R15) + MOVQ 48(SP), AX + MOVQ 56(SP), CX MOVQ ctx+16(FP), R14 SUBQ CX, 104(R14) JS error_not_enough_literals @@ -3158,20 +3737,16 @@ sequenceDecs_decodeSync_safe_amd64_after_adjust: JNZ sequenceDecs_decodeSync_safe_amd64_error_match_len_ofs_mismatch sequenceDecs_decodeSync_safe_amd64_match_len_ofs_ok: - MOVQ 24(SP), AX - MOVQ 8(SP), CX - MOVQ 16(SP), R13 - // Check if we have enough space in s.out - LEAQ (AX)(R13*1), R14 + LEAQ (CX)(AX*1), R14 ADDQ R10, R14 - CMPQ R14, 32(SP) + CMPQ R14, 64(SP) JA error_not_enough_space // Copy literals - TESTQ AX, AX + TESTQ CX, CX JZ check_offset - MOVQ AX, R14 + MOVQ CX, R14 SUBQ $0x10, R14 JB copy_1_small @@ -3189,70 +3764,70 @@ copy_1_loop: JMP copy_1_end copy_1_small: - CMPQ AX, $0x03 + CMPQ CX, $0x03 JE copy_1_move_3 JB copy_1_move_1or2 - CMPQ AX, $0x08 + CMPQ CX, $0x08 JB copy_1_move_4through7 JMP copy_1_move_8through16 copy_1_move_1or2: MOVB (R11), R14 - MOVB -1(R11)(AX*1), R15 + MOVB -1(R11)(CX*1), R15 MOVB R14, (R10) - MOVB R15, -1(R10)(AX*1) - ADDQ AX, R11 - ADDQ AX, R10 + MOVB R15, -1(R10)(CX*1) + ADDQ CX, R11 + ADDQ CX, R10 JMP copy_1_end copy_1_move_3: - MOVW (R11), R14 - MOVB 2(R11), R15 - MOVW R14, (R10) - MOVB R15, 2(R10) - ADDQ AX, R11 - ADDQ AX, R10 - JMP copy_1_end + MOVWQZX (R11), R14 + MOVB 2(R11), R15 + MOVW R14, (R10) + MOVB R15, 2(R10) + ADDQ CX, R11 + ADDQ CX, R10 + JMP copy_1_end copy_1_move_4through7: MOVL (R11), R14 - MOVL -4(R11)(AX*1), R15 + MOVL -4(R11)(CX*1), R15 MOVL R14, (R10) - MOVL R15, -4(R10)(AX*1) - ADDQ AX, R11 - ADDQ AX, R10 + MOVL R15, -4(R10)(CX*1) + ADDQ CX, R11 + ADDQ CX, R10 JMP copy_1_end copy_1_move_8through16: MOVQ (R11), R14 - MOVQ -8(R11)(AX*1), R15 + MOVQ -8(R11)(CX*1), R15 MOVQ R14, (R10) - MOVQ R15, -8(R10)(AX*1) - ADDQ AX, R11 - ADDQ AX, R10 + MOVQ R15, -8(R10)(CX*1) + ADDQ CX, R11 + ADDQ CX, R10 copy_1_end: - ADDQ AX, R12 + ADDQ CX, R12 // Malformed input if seq.mo > t+len(hist) || seq.mo > s.windowSize) check_offset: - MOVQ R12, AX - ADDQ 40(SP), AX - CMPQ CX, AX + MOVQ R12, CX + ADDQ 72(SP), CX + CMPQ R13, CX JG error_match_off_too_big - CMPQ CX, 56(SP) + CMPQ R13, 88(SP) JG error_match_off_too_big // Copy match from history - MOVQ CX, AX - SUBQ R12, AX + MOVQ R13, CX + SUBQ R12, CX JLS copy_match - MOVQ 48(SP), R14 - SUBQ AX, R14 - CMPQ R13, AX + MOVQ 80(SP), R14 + SUBQ CX, R14 + CMPQ AX, CX JG copy_all_from_history - MOVQ R13, AX - SUBQ $0x10, AX + MOVQ AX, CX + SUBQ $0x10, CX JB copy_4_small copy_4_loop: @@ -3260,54 +3835,54 @@ copy_4_loop: MOVUPS X0, (R10) ADDQ $0x10, R14 ADDQ $0x10, R10 - SUBQ $0x10, AX + SUBQ $0x10, CX JAE copy_4_loop - LEAQ 16(R14)(AX*1), R14 - LEAQ 16(R10)(AX*1), R10 + LEAQ 16(R14)(CX*1), R14 + LEAQ 16(R10)(CX*1), R10 MOVUPS -16(R14), X0 MOVUPS X0, -16(R10) JMP copy_4_end copy_4_small: - CMPQ R13, $0x03 + CMPQ AX, $0x03 JE copy_4_move_3 - CMPQ R13, $0x08 + CMPQ AX, $0x08 JB copy_4_move_4through7 JMP copy_4_move_8through16 copy_4_move_3: - MOVW (R14), AX - MOVB 2(R14), CL - MOVW AX, (R10) - MOVB CL, 2(R10) - ADDQ R13, R14 - ADDQ R13, R10 - JMP copy_4_end + MOVWQZX (R14), CX + MOVB 2(R14), R13 + MOVW CX, (R10) + MOVB R13, 2(R10) + ADDQ AX, R14 + ADDQ AX, R10 + JMP copy_4_end copy_4_move_4through7: - MOVL (R14), AX - MOVL -4(R14)(R13*1), CX - MOVL AX, (R10) - MOVL CX, -4(R10)(R13*1) - ADDQ R13, R14 - ADDQ R13, R10 + MOVL (R14), CX + MOVL -4(R14)(AX*1), R13 + MOVL CX, (R10) + MOVL R13, -4(R10)(AX*1) + ADDQ AX, R14 + ADDQ AX, R10 JMP copy_4_end copy_4_move_8through16: - MOVQ (R14), AX - MOVQ -8(R14)(R13*1), CX - MOVQ AX, (R10) - MOVQ CX, -8(R10)(R13*1) - ADDQ R13, R14 - ADDQ R13, R10 + MOVQ (R14), CX + MOVQ -8(R14)(AX*1), R13 + MOVQ CX, (R10) + MOVQ R13, -8(R10)(AX*1) + ADDQ AX, R14 + ADDQ AX, R10 copy_4_end: - ADDQ R13, R12 + ADDQ AX, R12 JMP handle_loop JMP loop_finished copy_all_from_history: - MOVQ AX, R15 + MOVQ CX, R15 SUBQ $0x10, R15 JB copy_5_small @@ -3325,141 +3900,153 @@ copy_5_loop: JMP copy_5_end copy_5_small: - CMPQ AX, $0x03 + CMPQ CX, $0x03 JE copy_5_move_3 JB copy_5_move_1or2 - CMPQ AX, $0x08 + CMPQ CX, $0x08 JB copy_5_move_4through7 JMP copy_5_move_8through16 copy_5_move_1or2: MOVB (R14), R15 - MOVB -1(R14)(AX*1), BP + MOVB -1(R14)(CX*1), BP MOVB R15, (R10) - MOVB BP, -1(R10)(AX*1) - ADDQ AX, R14 - ADDQ AX, R10 + MOVB BP, -1(R10)(CX*1) + ADDQ CX, R14 + ADDQ CX, R10 JMP copy_5_end copy_5_move_3: - MOVW (R14), R15 - MOVB 2(R14), BP - MOVW R15, (R10) - MOVB BP, 2(R10) - ADDQ AX, R14 - ADDQ AX, R10 - JMP copy_5_end + MOVWQZX (R14), R15 + MOVB 2(R14), BP + MOVW R15, (R10) + MOVB BP, 2(R10) + ADDQ CX, R14 + ADDQ CX, R10 + JMP copy_5_end copy_5_move_4through7: MOVL (R14), R15 - MOVL -4(R14)(AX*1), BP + MOVL -4(R14)(CX*1), BP MOVL R15, (R10) - MOVL BP, -4(R10)(AX*1) - ADDQ AX, R14 - ADDQ AX, R10 + MOVL BP, -4(R10)(CX*1) + ADDQ CX, R14 + ADDQ CX, R10 JMP copy_5_end copy_5_move_8through16: MOVQ (R14), R15 - MOVQ -8(R14)(AX*1), BP + MOVQ -8(R14)(CX*1), BP MOVQ R15, (R10) - MOVQ BP, -8(R10)(AX*1) - ADDQ AX, R14 - ADDQ AX, R10 + MOVQ BP, -8(R10)(CX*1) + ADDQ CX, R14 + ADDQ CX, R10 copy_5_end: - ADDQ AX, R12 - SUBQ AX, R13 + ADDQ CX, R12 + SUBQ CX, AX // Copy match from the current buffer copy_match: - MOVQ R10, AX - SUBQ CX, AX + MOVQ R10, CX + SUBQ R13, CX // ml <= mo - CMPQ R13, CX + CMPQ AX, R13 JA copy_overlapping_match // Copy non-overlapping match - ADDQ R13, R12 - MOVQ R13, CX - SUBQ $0x10, CX + ADDQ AX, R12 + MOVQ AX, R13 + SUBQ $0x10, R13 JB copy_2_small copy_2_loop: - MOVUPS (AX), X0 + MOVUPS (CX), X0 MOVUPS X0, (R10) - ADDQ $0x10, AX + ADDQ $0x10, CX ADDQ $0x10, R10 - SUBQ $0x10, CX + SUBQ $0x10, R13 JAE copy_2_loop - LEAQ 16(AX)(CX*1), AX - LEAQ 16(R10)(CX*1), R10 - MOVUPS -16(AX), X0 + LEAQ 16(CX)(R13*1), CX + LEAQ 16(R10)(R13*1), R10 + MOVUPS -16(CX), X0 MOVUPS X0, -16(R10) JMP copy_2_end copy_2_small: - CMPQ R13, $0x03 + CMPQ AX, $0x03 JE copy_2_move_3 JB copy_2_move_1or2 - CMPQ R13, $0x08 + CMPQ AX, $0x08 JB copy_2_move_4through7 JMP copy_2_move_8through16 copy_2_move_1or2: - MOVB (AX), CL - MOVB -1(AX)(R13*1), R14 - MOVB CL, (R10) - MOVB R14, -1(R10)(R13*1) - ADDQ R13, AX - ADDQ R13, R10 + MOVB (CX), R13 + MOVB -1(CX)(AX*1), R14 + MOVB R13, (R10) + MOVB R14, -1(R10)(AX*1) + ADDQ AX, CX + ADDQ AX, R10 JMP copy_2_end copy_2_move_3: - MOVW (AX), CX - MOVB 2(AX), R14 - MOVW CX, (R10) - MOVB R14, 2(R10) - ADDQ R13, AX - ADDQ R13, R10 - JMP copy_2_end + MOVWQZX (CX), R13 + MOVB 2(CX), R14 + MOVW R13, (R10) + MOVB R14, 2(R10) + ADDQ AX, CX + ADDQ AX, R10 + JMP copy_2_end copy_2_move_4through7: - MOVL (AX), CX - MOVL -4(AX)(R13*1), R14 - MOVL CX, (R10) - MOVL R14, -4(R10)(R13*1) - ADDQ R13, AX - ADDQ R13, R10 + MOVL (CX), R13 + MOVL -4(CX)(AX*1), R14 + MOVL R13, (R10) + MOVL R14, -4(R10)(AX*1) + ADDQ AX, CX + ADDQ AX, R10 JMP copy_2_end copy_2_move_8through16: - MOVQ (AX), CX - MOVQ -8(AX)(R13*1), R14 - MOVQ CX, (R10) - MOVQ R14, -8(R10)(R13*1) - ADDQ R13, AX - ADDQ R13, R10 + MOVQ (CX), R13 + MOVQ -8(CX)(AX*1), R14 + MOVQ R13, (R10) + MOVQ R14, -8(R10)(AX*1) + ADDQ AX, CX + ADDQ AX, R10 copy_2_end: JMP handle_loop // Copy overlapping match copy_overlapping_match: - ADDQ R13, R12 + ADDQ AX, R12 + CMPQ R13, $0x10 + JB copy_slow_3 + +copy_3_blocks: + MOVUPS (CX), X0 + MOVUPS X0, (R10) + ADDQ $0x10, CX + ADDQ $0x10, R10 + SUBQ $0x10, AX + CMPQ AX, $0x10 + JAE copy_3_blocks + TESTQ AX, AX + JZ handle_loop copy_slow_3: - MOVB (AX), CL - MOVB CL, (R10) - INCQ AX - INCQ R10 - DECQ R13 - JNZ copy_slow_3 + MOVBQZX (CX), R13 + MOVB R13, (R10) + INCQ CX + INCQ R10 + DECQ AX + JNZ copy_slow_3 handle_loop: - MOVQ ctx+16(FP), AX - DECQ 96(AX) + DECQ 32(SP) JNS sequenceDecs_decodeSync_safe_amd64_main_loop loop_finished: @@ -3468,6 +4055,13 @@ loop_finished: MOVB BL, 40(AX) MOVQ SI, 32(AX) + // s.seqSize += outPosition - ctx.outPosition + MOVQ ctx+16(FP), AX + MOVQ s+0(FP), CX + MOVQ R12, DX + SUBQ 136(AX), DX + ADDQ DX, 256(CX) + // Update the context MOVQ ctx+16(FP), AX MOVQ R12, 136(AX) @@ -3481,7 +4075,7 @@ loop_finished: // Return with match length error sequenceDecs_decodeSync_safe_amd64_error_match_len_ofs_mismatch: - MOVQ 16(SP), AX + MOVQ 48(SP), AX MOVQ ctx+16(FP), CX MOVQ AX, 216(CX) MOVQ $0x00000001, ret+24(FP) @@ -3490,7 +4084,7 @@ sequenceDecs_decodeSync_safe_amd64_error_match_len_ofs_mismatch: // Return with match too long error sequenceDecs_decodeSync_safe_amd64_error_match_len_too_big: MOVQ ctx+16(FP), AX - MOVQ 16(SP), CX + MOVQ 48(SP), CX MOVQ CX, 216(AX) MOVQ $0x00000002, ret+24(FP) RET @@ -3498,7 +4092,7 @@ sequenceDecs_decodeSync_safe_amd64_error_match_len_too_big: // Return with match offset too long error error_match_off_too_big: MOVQ ctx+16(FP), AX - MOVQ 8(SP), CX + MOVQ 40(SP), CX MOVQ CX, 224(AX) MOVQ R12, 136(AX) MOVQ $0x00000003, ret+24(FP) @@ -3507,7 +4101,7 @@ error_match_off_too_big: // Return with not enough literals error error_not_enough_literals: MOVQ ctx+16(FP), AX - MOVQ 24(SP), CX + MOVQ 56(SP), CX MOVQ CX, 208(AX) MOVQ $0x00000004, ret+24(FP) RET @@ -3520,9 +4114,9 @@ error_overread: // Return with not enough output space error error_not_enough_space: MOVQ ctx+16(FP), AX - MOVQ 24(SP), CX + MOVQ 56(SP), CX MOVQ CX, 208(AX) - MOVQ 16(SP), CX + MOVQ 48(SP), CX MOVQ CX, 216(AX) MOVQ R12, 136(AX) MOVQ $0x00000005, ret+24(FP) @@ -3530,7 +4124,7 @@ error_not_enough_space: // func sequenceDecs_decodeSync_safe_bmi2(s *sequenceDecs, br *bitReader, ctx *decodeSyncAsmContext) int // Requires: BMI, BMI2, CMOV, SSE -TEXT ·sequenceDecs_decodeSync_safe_bmi2(SB), $64-32 +TEXT ·sequenceDecs_decodeSync_safe_bmi2(SB), $96-32 MOVQ br+8(FP), BX MOVQ 24(BX), AX MOVBQZX 40(BX), DX @@ -3542,29 +4136,38 @@ TEXT ·sequenceDecs_decodeSync_safe_bmi2(SB), $64-32 MOVQ 72(CX), SI MOVQ 80(CX), DI MOVQ 88(CX), R8 - XORQ R9, R9 + MOVQ (CX), R9 MOVQ R9, 8(SP) + MOVQ 24(CX), R9 MOVQ R9, 16(SP) + MOVQ 48(CX), R9 MOVQ R9, 24(SP) + MOVQ 96(CX), R9 + MOVQ R9, 32(SP) + XORQ R9, R9 + MOVQ R9, 40(SP) + MOVQ R9, 48(SP) + MOVQ R9, 56(SP) MOVQ 112(CX), R9 MOVQ 128(CX), R10 - MOVQ R10, 32(SP) + MOVQ R10, 64(SP) MOVQ 144(CX), R10 MOVQ 136(CX), R11 MOVQ 200(CX), R12 - MOVQ R12, 56(SP) + MOVQ R12, 88(SP) MOVQ 176(CX), R12 - MOVQ R12, 48(SP) + MOVQ R12, 80(SP) MOVQ 184(CX), CX - MOVQ CX, 40(SP) - MOVQ 40(SP), CX - ADDQ CX, 48(SP) + MOVQ CX, 72(SP) + MOVQ 72(SP), CX + ADDQ CX, 80(SP) // Calculate pointer to s.out[cap(s.out)] (a past-end pointer) - ADDQ R9, 32(SP) + ADDQ R9, 64(SP) // outBase += outPosition - ADDQ R11, R9 + ADDQ R11, R9 + PCALIGN $0x40 sequenceDecs_decodeSync_safe_bmi2_main_loop: MOVQ (SP), R12 @@ -3609,7 +4212,7 @@ sequenceDecs_decodeSync_safe_bmi2_fill_end: MOVQ R8, CX SHRQ $0x20, CX ADDQ R14, CX - MOVQ CX, 8(SP) + MOVQ CX, 40(SP) // Update match length MOVQ $0x00000808, CX @@ -3622,7 +4225,7 @@ sequenceDecs_decodeSync_safe_bmi2_fill_end: MOVQ DI, CX SHRQ $0x20, CX ADDQ R14, CX - MOVQ CX, 16(SP) + MOVQ CX, 48(SP) // Fill bitreader to have enough for the remaining CMPQ BX, $0x08 @@ -3664,14 +4267,13 @@ sequenceDecs_decodeSync_safe_bmi2_fill_2_end: MOVQ SI, CX SHRQ $0x20, CX ADDQ R14, CX - MOVQ CX, 24(SP) + MOVQ CX, 56(SP) // Fill bitreader for state updates MOVQ R12, (SP) MOVQ $0x00000808, CX BEXTRQ CX, R8, R12 - MOVQ ctx+16(FP), CX - CMPQ 96(CX), $0x00 + CMPQ 32(SP), $0x00 JZ sequenceDecs_decodeSync_safe_bmi2_skip_update LEAQ (SI)(DI*1), R13 ADDQ R8, R13 @@ -3689,8 +4291,7 @@ sequenceDecs_decodeSync_safe_bmi2_fill_2_end: ADDQ CX, R8 // Load ctx.ofTable - MOVQ ctx+16(FP), CX - MOVQ 48(CX), CX + MOVQ 24(SP), CX MOVQ (CX)(R8*8), R8 // Update Match Length State @@ -3700,8 +4301,7 @@ sequenceDecs_decodeSync_safe_bmi2_fill_2_end: ADDQ CX, DI // Load ctx.mlTable - MOVQ ctx+16(FP), CX - MOVQ 24(CX), CX + MOVQ 16(SP), CX MOVQ (CX)(DI*8), DI // Update Literal Length State @@ -3710,14 +4310,13 @@ sequenceDecs_decodeSync_safe_bmi2_fill_2_end: ADDQ CX, SI // Load ctx.llTable - MOVQ ctx+16(FP), CX - MOVQ (CX), CX + MOVQ 8(SP), CX MOVQ (CX)(SI*8), SI sequenceDecs_decodeSync_safe_bmi2_skip_update: // Adjust offset MOVQ s+0(FP), CX - MOVQ 8(SP), R13 + MOVQ 40(SP), R13 CMPQ R12, $0x01 JBE sequenceDecs_decodeSync_safe_bmi2_adjust_offsetB_1_or_0 MOVUPS 144(CX), X0 @@ -3726,7 +4325,7 @@ sequenceDecs_decodeSync_safe_bmi2_skip_update: JMP sequenceDecs_decodeSync_safe_bmi2_after_adjust sequenceDecs_decodeSync_safe_bmi2_adjust_offsetB_1_or_0: - CMPQ 24(SP), $0x00000000 + CMPQ 56(SP), $0x00000000 JNE sequenceDecs_decodeSync_safe_bmi2_adjust_offset_maybezero INCQ R13 JMP sequenceDecs_decodeSync_safe_bmi2_adjust_offset_nonzero @@ -3761,14 +4360,11 @@ sequenceDecs_decodeSync_safe_bmi2_adjust_skip: MOVQ R14, R13 sequenceDecs_decodeSync_safe_bmi2_after_adjust: - MOVQ R13, 8(SP) + MOVQ R13, 40(SP) // Check values - MOVQ 16(SP), CX - MOVQ 24(SP), R12 - LEAQ (CX)(R12*1), R14 - MOVQ s+0(FP), R15 - ADDQ R14, 256(R15) + MOVQ 48(SP), CX + MOVQ 56(SP), R12 MOVQ ctx+16(FP), R14 SUBQ R12, 104(R14) JS error_not_enough_literals @@ -3780,20 +4376,16 @@ sequenceDecs_decodeSync_safe_bmi2_after_adjust: JNZ sequenceDecs_decodeSync_safe_bmi2_error_match_len_ofs_mismatch sequenceDecs_decodeSync_safe_bmi2_match_len_ofs_ok: - MOVQ 24(SP), CX - MOVQ 8(SP), R12 - MOVQ 16(SP), R13 - // Check if we have enough space in s.out - LEAQ (CX)(R13*1), R14 + LEAQ (R12)(CX*1), R14 ADDQ R9, R14 - CMPQ R14, 32(SP) + CMPQ R14, 64(SP) JA error_not_enough_space // Copy literals - TESTQ CX, CX + TESTQ R12, R12 JZ check_offset - MOVQ CX, R14 + MOVQ R12, R14 SUBQ $0x10, R14 JB copy_1_small @@ -3811,70 +4403,70 @@ copy_1_loop: JMP copy_1_end copy_1_small: - CMPQ CX, $0x03 + CMPQ R12, $0x03 JE copy_1_move_3 JB copy_1_move_1or2 - CMPQ CX, $0x08 + CMPQ R12, $0x08 JB copy_1_move_4through7 JMP copy_1_move_8through16 copy_1_move_1or2: MOVB (R10), R14 - MOVB -1(R10)(CX*1), R15 + MOVB -1(R10)(R12*1), R15 MOVB R14, (R9) - MOVB R15, -1(R9)(CX*1) - ADDQ CX, R10 - ADDQ CX, R9 + MOVB R15, -1(R9)(R12*1) + ADDQ R12, R10 + ADDQ R12, R9 JMP copy_1_end copy_1_move_3: - MOVW (R10), R14 - MOVB 2(R10), R15 - MOVW R14, (R9) - MOVB R15, 2(R9) - ADDQ CX, R10 - ADDQ CX, R9 - JMP copy_1_end + MOVWQZX (R10), R14 + MOVB 2(R10), R15 + MOVW R14, (R9) + MOVB R15, 2(R9) + ADDQ R12, R10 + ADDQ R12, R9 + JMP copy_1_end copy_1_move_4through7: MOVL (R10), R14 - MOVL -4(R10)(CX*1), R15 + MOVL -4(R10)(R12*1), R15 MOVL R14, (R9) - MOVL R15, -4(R9)(CX*1) - ADDQ CX, R10 - ADDQ CX, R9 + MOVL R15, -4(R9)(R12*1) + ADDQ R12, R10 + ADDQ R12, R9 JMP copy_1_end copy_1_move_8through16: MOVQ (R10), R14 - MOVQ -8(R10)(CX*1), R15 + MOVQ -8(R10)(R12*1), R15 MOVQ R14, (R9) - MOVQ R15, -8(R9)(CX*1) - ADDQ CX, R10 - ADDQ CX, R9 + MOVQ R15, -8(R9)(R12*1) + ADDQ R12, R10 + ADDQ R12, R9 copy_1_end: - ADDQ CX, R11 + ADDQ R12, R11 // Malformed input if seq.mo > t+len(hist) || seq.mo > s.windowSize) check_offset: - MOVQ R11, CX - ADDQ 40(SP), CX - CMPQ R12, CX + MOVQ R11, R12 + ADDQ 72(SP), R12 + CMPQ R13, R12 JG error_match_off_too_big - CMPQ R12, 56(SP) + CMPQ R13, 88(SP) JG error_match_off_too_big // Copy match from history - MOVQ R12, CX - SUBQ R11, CX + MOVQ R13, R12 + SUBQ R11, R12 JLS copy_match - MOVQ 48(SP), R14 - SUBQ CX, R14 - CMPQ R13, CX + MOVQ 80(SP), R14 + SUBQ R12, R14 + CMPQ CX, R12 JG copy_all_from_history - MOVQ R13, CX - SUBQ $0x10, CX + MOVQ CX, R12 + SUBQ $0x10, R12 JB copy_4_small copy_4_loop: @@ -3882,54 +4474,54 @@ copy_4_loop: MOVUPS X0, (R9) ADDQ $0x10, R14 ADDQ $0x10, R9 - SUBQ $0x10, CX + SUBQ $0x10, R12 JAE copy_4_loop - LEAQ 16(R14)(CX*1), R14 - LEAQ 16(R9)(CX*1), R9 + LEAQ 16(R14)(R12*1), R14 + LEAQ 16(R9)(R12*1), R9 MOVUPS -16(R14), X0 MOVUPS X0, -16(R9) JMP copy_4_end copy_4_small: - CMPQ R13, $0x03 + CMPQ CX, $0x03 JE copy_4_move_3 - CMPQ R13, $0x08 + CMPQ CX, $0x08 JB copy_4_move_4through7 JMP copy_4_move_8through16 copy_4_move_3: - MOVW (R14), CX - MOVB 2(R14), R12 - MOVW CX, (R9) - MOVB R12, 2(R9) - ADDQ R13, R14 - ADDQ R13, R9 - JMP copy_4_end + MOVWQZX (R14), R12 + MOVB 2(R14), R13 + MOVW R12, (R9) + MOVB R13, 2(R9) + ADDQ CX, R14 + ADDQ CX, R9 + JMP copy_4_end copy_4_move_4through7: - MOVL (R14), CX - MOVL -4(R14)(R13*1), R12 - MOVL CX, (R9) - MOVL R12, -4(R9)(R13*1) - ADDQ R13, R14 - ADDQ R13, R9 + MOVL (R14), R12 + MOVL -4(R14)(CX*1), R13 + MOVL R12, (R9) + MOVL R13, -4(R9)(CX*1) + ADDQ CX, R14 + ADDQ CX, R9 JMP copy_4_end copy_4_move_8through16: - MOVQ (R14), CX - MOVQ -8(R14)(R13*1), R12 - MOVQ CX, (R9) - MOVQ R12, -8(R9)(R13*1) - ADDQ R13, R14 - ADDQ R13, R9 + MOVQ (R14), R12 + MOVQ -8(R14)(CX*1), R13 + MOVQ R12, (R9) + MOVQ R13, -8(R9)(CX*1) + ADDQ CX, R14 + ADDQ CX, R9 copy_4_end: - ADDQ R13, R11 + ADDQ CX, R11 JMP handle_loop JMP loop_finished copy_all_from_history: - MOVQ CX, R15 + MOVQ R12, R15 SUBQ $0x10, R15 JB copy_5_small @@ -3947,141 +4539,153 @@ copy_5_loop: JMP copy_5_end copy_5_small: - CMPQ CX, $0x03 + CMPQ R12, $0x03 JE copy_5_move_3 JB copy_5_move_1or2 - CMPQ CX, $0x08 + CMPQ R12, $0x08 JB copy_5_move_4through7 JMP copy_5_move_8through16 copy_5_move_1or2: MOVB (R14), R15 - MOVB -1(R14)(CX*1), BP + MOVB -1(R14)(R12*1), BP MOVB R15, (R9) - MOVB BP, -1(R9)(CX*1) - ADDQ CX, R14 - ADDQ CX, R9 + MOVB BP, -1(R9)(R12*1) + ADDQ R12, R14 + ADDQ R12, R9 JMP copy_5_end copy_5_move_3: - MOVW (R14), R15 - MOVB 2(R14), BP - MOVW R15, (R9) - MOVB BP, 2(R9) - ADDQ CX, R14 - ADDQ CX, R9 - JMP copy_5_end + MOVWQZX (R14), R15 + MOVB 2(R14), BP + MOVW R15, (R9) + MOVB BP, 2(R9) + ADDQ R12, R14 + ADDQ R12, R9 + JMP copy_5_end copy_5_move_4through7: MOVL (R14), R15 - MOVL -4(R14)(CX*1), BP + MOVL -4(R14)(R12*1), BP MOVL R15, (R9) - MOVL BP, -4(R9)(CX*1) - ADDQ CX, R14 - ADDQ CX, R9 + MOVL BP, -4(R9)(R12*1) + ADDQ R12, R14 + ADDQ R12, R9 JMP copy_5_end copy_5_move_8through16: MOVQ (R14), R15 - MOVQ -8(R14)(CX*1), BP + MOVQ -8(R14)(R12*1), BP MOVQ R15, (R9) - MOVQ BP, -8(R9)(CX*1) - ADDQ CX, R14 - ADDQ CX, R9 + MOVQ BP, -8(R9)(R12*1) + ADDQ R12, R14 + ADDQ R12, R9 copy_5_end: - ADDQ CX, R11 - SUBQ CX, R13 + ADDQ R12, R11 + SUBQ R12, CX // Copy match from the current buffer copy_match: - MOVQ R9, CX - SUBQ R12, CX + MOVQ R9, R12 + SUBQ R13, R12 // ml <= mo - CMPQ R13, R12 + CMPQ CX, R13 JA copy_overlapping_match // Copy non-overlapping match - ADDQ R13, R11 - MOVQ R13, R12 - SUBQ $0x10, R12 + ADDQ CX, R11 + MOVQ CX, R13 + SUBQ $0x10, R13 JB copy_2_small copy_2_loop: - MOVUPS (CX), X0 + MOVUPS (R12), X0 MOVUPS X0, (R9) - ADDQ $0x10, CX + ADDQ $0x10, R12 ADDQ $0x10, R9 - SUBQ $0x10, R12 + SUBQ $0x10, R13 JAE copy_2_loop - LEAQ 16(CX)(R12*1), CX - LEAQ 16(R9)(R12*1), R9 - MOVUPS -16(CX), X0 + LEAQ 16(R12)(R13*1), R12 + LEAQ 16(R9)(R13*1), R9 + MOVUPS -16(R12), X0 MOVUPS X0, -16(R9) JMP copy_2_end copy_2_small: - CMPQ R13, $0x03 + CMPQ CX, $0x03 JE copy_2_move_3 JB copy_2_move_1or2 - CMPQ R13, $0x08 + CMPQ CX, $0x08 JB copy_2_move_4through7 JMP copy_2_move_8through16 copy_2_move_1or2: - MOVB (CX), R12 - MOVB -1(CX)(R13*1), R14 - MOVB R12, (R9) - MOVB R14, -1(R9)(R13*1) - ADDQ R13, CX - ADDQ R13, R9 + MOVB (R12), R13 + MOVB -1(R12)(CX*1), R14 + MOVB R13, (R9) + MOVB R14, -1(R9)(CX*1) + ADDQ CX, R12 + ADDQ CX, R9 JMP copy_2_end copy_2_move_3: - MOVW (CX), R12 - MOVB 2(CX), R14 - MOVW R12, (R9) - MOVB R14, 2(R9) - ADDQ R13, CX - ADDQ R13, R9 - JMP copy_2_end + MOVWQZX (R12), R13 + MOVB 2(R12), R14 + MOVW R13, (R9) + MOVB R14, 2(R9) + ADDQ CX, R12 + ADDQ CX, R9 + JMP copy_2_end copy_2_move_4through7: - MOVL (CX), R12 - MOVL -4(CX)(R13*1), R14 - MOVL R12, (R9) - MOVL R14, -4(R9)(R13*1) - ADDQ R13, CX - ADDQ R13, R9 + MOVL (R12), R13 + MOVL -4(R12)(CX*1), R14 + MOVL R13, (R9) + MOVL R14, -4(R9)(CX*1) + ADDQ CX, R12 + ADDQ CX, R9 JMP copy_2_end copy_2_move_8through16: - MOVQ (CX), R12 - MOVQ -8(CX)(R13*1), R14 - MOVQ R12, (R9) - MOVQ R14, -8(R9)(R13*1) - ADDQ R13, CX - ADDQ R13, R9 + MOVQ (R12), R13 + MOVQ -8(R12)(CX*1), R14 + MOVQ R13, (R9) + MOVQ R14, -8(R9)(CX*1) + ADDQ CX, R12 + ADDQ CX, R9 copy_2_end: JMP handle_loop // Copy overlapping match copy_overlapping_match: - ADDQ R13, R11 + ADDQ CX, R11 + CMPQ R13, $0x10 + JB copy_slow_3 + +copy_3_blocks: + MOVUPS (R12), X0 + MOVUPS X0, (R9) + ADDQ $0x10, R12 + ADDQ $0x10, R9 + SUBQ $0x10, CX + CMPQ CX, $0x10 + JAE copy_3_blocks + TESTQ CX, CX + JZ handle_loop copy_slow_3: - MOVB (CX), R12 - MOVB R12, (R9) - INCQ CX - INCQ R9 - DECQ R13 - JNZ copy_slow_3 + MOVBQZX (R12), R13 + MOVB R13, (R9) + INCQ R12 + INCQ R9 + DECQ CX + JNZ copy_slow_3 handle_loop: - MOVQ ctx+16(FP), CX - DECQ 96(CX) + DECQ 32(SP) JNS sequenceDecs_decodeSync_safe_bmi2_main_loop loop_finished: @@ -4090,6 +4694,13 @@ loop_finished: MOVB DL, 40(CX) MOVQ BX, 32(CX) + // s.seqSize += outPosition - ctx.outPosition + MOVQ ctx+16(FP), AX + MOVQ s+0(FP), CX + MOVQ R11, DX + SUBQ 136(AX), DX + ADDQ DX, 256(CX) + // Update the context MOVQ ctx+16(FP), AX MOVQ R11, 136(AX) @@ -4103,7 +4714,7 @@ loop_finished: // Return with match length error sequenceDecs_decodeSync_safe_bmi2_error_match_len_ofs_mismatch: - MOVQ 16(SP), AX + MOVQ 48(SP), AX MOVQ ctx+16(FP), CX MOVQ AX, 216(CX) MOVQ $0x00000001, ret+24(FP) @@ -4112,7 +4723,7 @@ sequenceDecs_decodeSync_safe_bmi2_error_match_len_ofs_mismatch: // Return with match too long error sequenceDecs_decodeSync_safe_bmi2_error_match_len_too_big: MOVQ ctx+16(FP), AX - MOVQ 16(SP), CX + MOVQ 48(SP), CX MOVQ CX, 216(AX) MOVQ $0x00000002, ret+24(FP) RET @@ -4120,7 +4731,7 @@ sequenceDecs_decodeSync_safe_bmi2_error_match_len_too_big: // Return with match offset too long error error_match_off_too_big: MOVQ ctx+16(FP), AX - MOVQ 8(SP), CX + MOVQ 40(SP), CX MOVQ CX, 224(AX) MOVQ R11, 136(AX) MOVQ $0x00000003, ret+24(FP) @@ -4129,7 +4740,7 @@ error_match_off_too_big: // Return with not enough literals error error_not_enough_literals: MOVQ ctx+16(FP), AX - MOVQ 24(SP), CX + MOVQ 56(SP), CX MOVQ CX, 208(AX) MOVQ $0x00000004, ret+24(FP) RET @@ -4142,9 +4753,9 @@ error_overread: // Return with not enough output space error error_not_enough_space: MOVQ ctx+16(FP), AX - MOVQ 24(SP), CX + MOVQ 56(SP), CX MOVQ CX, 208(AX) - MOVQ 16(SP), CX + MOVQ 48(SP), CX MOVQ CX, 216(AX) MOVQ R11, 136(AX) MOVQ $0x00000005, ret+24(FP) diff --git a/vendor/github.com/klauspost/compress/zstd/seqdec_arm64.go b/vendor/github.com/klauspost/compress/zstd/seqdec_arm64.go index 5ad262a..5b911ab 100644 --- a/vendor/github.com/klauspost/compress/zstd/seqdec_arm64.go +++ b/vendor/github.com/klauspost/compress/zstd/seqdec_arm64.go @@ -1,4 +1,4 @@ -//go:build arm64 && !appengine && !noasm && gc +//go:build arm64 && !noasm && gc package zstd @@ -7,6 +7,17 @@ package zstd // by the avo arm64 lowering printer) and the dispatch helpers. arm64 has no // BMI2, so each helper selects only between the 56-bit / safe variants. +// The synchronous decoder takes the two-pass path, and executeSimple +// prefetches, when the window is at least decodeTwoPassMinWindow and the +// block's offset table puts at least twoPassMinFarShare/256 of its +// sequences 128 KiB or more back (sequenceDecs.useTwoPass). Thresholds +// from the per-file N1 measurement in #1212; variables so tests can force +// either path. +var ( + twoPassMinFarShare = 46 + decodeTwoPassMinWindow = 1 << 20 +) + // sequenceDecs_decode_arm64 implements the main loop of sequenceDecs in arm64 asm. // // Please refer to seqdec_generic.go for the reference implementation. diff --git a/vendor/github.com/klauspost/compress/zstd/seqdec_arm64.s b/vendor/github.com/klauspost/compress/zstd/seqdec_arm64.s index 6f54ef2..084e5df 100644 --- a/vendor/github.com/klauspost/compress/zstd/seqdec_arm64.s +++ b/vendor/github.com/klauspost/compress/zstd/seqdec_arm64.s @@ -1,38 +1,39 @@ -// Code generated by command: go run gen.go -out ../seqdec.s -arch amd64,arm64 -pkg=zstd. DO NOT EDIT. +// Code generated by command: go run gen.go -out ../seqdec.s -arch amd64,arm64 -arm64-promote-stack-slots -arm64-pair-vector-moves -pkg=zstd. DO NOT EDIT. // EXPERIMENTAL arm64 output lowered from an amd64 avo program. -//go:build arm64 && !appengine && !noasm && gc && !noasm +//go:build arm64 && (!noasm && gc) // func sequenceDecs_decode_amd64(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int // Requires: CMOV -TEXT ·sequenceDecs_decode_arm64(SB), $8-32 - MOVD br+8(FP), R1 - MOVD 24(R1), R2 - MOVBU 40(R1), R3 - MOVD (R1), R0 - MOVD 32(R1), R5 - ADD R5, R0, R0 - MOVD R0, 8(RSP) - MOVD ctx+16(FP), R0 - MOVD 72(R0), R6 - MOVD 80(R0), R7 - MOVD 88(R0), R8 - MOVD 104(R0), R9 - MOVD s+0(FP), R0 - MOVD 144(R0), R10 - MOVD 152(R0), R11 - MOVD 160(R0), R12 +TEXT ·sequenceDecs_decode_arm64(SB), $40-32 + MOVD br+8(FP), R1 + MOVD 24(R1), R2 + MOVBU 40(R1), R3 + MOVD (R1), R20 + MOVD 32(R1), R5 + ADD R5, R20, R20 + MOVD ctx+16(FP), R0 + MOVD 72(R0), R6 + MOVD 80(R0), R7 + MOVD 88(R0), R8 + MOVD (R0), R21 + MOVD 24(R0), R22 + MOVD 48(R0), R23 + MOVD 96(R0), R19 + MOVD 104(R0), R9 + MOVD s+0(FP), R0 + MOVD 144(R0), R10 + MOVD 152(R0), R11 + MOVD 160(R0), R12 + PCALIGN $0x40 sequenceDecs_decode_amd64_main_loop: - MOVD 8(RSP), R13 - // Fill bitreader to have enough for the offset and match length. CMP $0x08, R5 BLT sequenceDecs_decode_amd64_fill_byte_by_byte - MOVD R3, R0 - LSR $0x03, R0, R0 - SUB R0, R13, R13 - MOVD (R13), R2 + LSR $0x03, R3, R0 + SUB R0, R20, R20 + MOVD (R20), R2 SUB R0, R5, R5 AND $0x07, R3, R3 JMP sequenceDecs_decode_amd64_fill_end @@ -43,10 +44,10 @@ sequenceDecs_decode_amd64_fill_byte_by_byte: CMP $0x07, R3 BLE sequenceDecs_decode_amd64_fill_end LSL $0x08, R2, R2 - SUB $0x01, R13, R13 + SUB $0x01, R20, R20 SUB $0x01, R5, R5 SUB $0x08, R3, R3 - MOVBU (R13), R0 + MOVBU (R20), R0 ORR R0, R2, R2 JMP sequenceDecs_decode_amd64_fill_byte_by_byte @@ -57,55 +58,34 @@ sequenceDecs_decode_amd64_fill_check_overread: sequenceDecs_decode_amd64_fill_end: // Update offset MOVD R8, R0 - MOVD R3, R1 - MOVD R2, R14 - LSL R1, R14, R14 - UBFX $8, R0, $8, R16 - BFI $0, R16, $8, R1 + LSL R3, R2, R14 + LSR $0x01, R14, R14 + UBFX $8, R0, $8, R1 LSR $0x20, R0, R0 - TST R1, R1 - BEQ sequenceDecs_decode_amd64_of_update_zero ADD R1, R3, R3 - CMP $0x40, R3 - BHI sequenceDecs_decode_amd64_of_update_zero - CMP $0x40, R1 - BHS sequenceDecs_decode_amd64_of_update_zero - NEG R1, R1 + EOR $0x3f, R1, R1 LSR R1, R14, R14 ADD R14, R0, R0 - -sequenceDecs_decode_amd64_of_update_zero: MOVD R0, 16(R9) // Update match length MOVD R7, R0 - MOVD R3, R1 - MOVD R2, R14 - LSL R1, R14, R14 - UBFX $8, R0, $8, R16 - BFI $0, R16, $8, R1 + LSL R3, R2, R14 + LSR $0x01, R14, R14 + UBFX $8, R0, $8, R1 LSR $0x20, R0, R0 - TST R1, R1 - BEQ sequenceDecs_decode_amd64_ml_update_zero ADD R1, R3, R3 - CMP $0x40, R3 - BHI sequenceDecs_decode_amd64_ml_update_zero - CMP $0x40, R1 - BHS sequenceDecs_decode_amd64_ml_update_zero - NEG R1, R1 + EOR $0x3f, R1, R1 LSR R1, R14, R14 ADD R14, R0, R0 - -sequenceDecs_decode_amd64_ml_update_zero: MOVD R0, 8(R9) // Fill bitreader to have enough for the remaining CMP $0x08, R5 BLT sequenceDecs_decode_amd64_fill_2_byte_by_byte - MOVD R3, R0 - LSR $0x03, R0, R0 - SUB R0, R13, R13 - MOVD (R13), R2 + LSR $0x03, R3, R0 + SUB R0, R20, R20 + MOVD (R20), R2 SUB R0, R5, R5 AND $0x07, R3, R3 JMP sequenceDecs_decode_amd64_fill_2_end @@ -116,10 +96,10 @@ sequenceDecs_decode_amd64_fill_2_byte_by_byte: CMP $0x07, R3 BLE sequenceDecs_decode_amd64_fill_2_end LSL $0x08, R2, R2 - SUB $0x01, R13, R13 + SUB $0x01, R20, R20 SUB $0x01, R5, R5 SUB $0x08, R3, R3 - MOVBU (R13), R0 + MOVBU (R20), R0 ORR R0, R2, R2 JMP sequenceDecs_decode_amd64_fill_2_byte_by_byte @@ -130,98 +110,59 @@ sequenceDecs_decode_amd64_fill_2_check_overread: sequenceDecs_decode_amd64_fill_2_end: // Update literal length MOVD R6, R0 - MOVD R3, R1 - MOVD R2, R14 - LSL R1, R14, R14 - UBFX $8, R0, $8, R16 - BFI $0, R16, $8, R1 + LSL R3, R2, R14 + LSR $0x01, R14, R14 + UBFX $8, R0, $8, R1 LSR $0x20, R0, R0 - TST R1, R1 - BEQ sequenceDecs_decode_amd64_ll_update_zero ADD R1, R3, R3 - CMP $0x40, R3 - BHI sequenceDecs_decode_amd64_ll_update_zero - CMP $0x40, R1 - BHS sequenceDecs_decode_amd64_ll_update_zero - NEG R1, R1 + EOR $0x3f, R1, R1 LSR R1, R14, R14 ADD R14, R0, R0 - -sequenceDecs_decode_amd64_ll_update_zero: MOVD R0, (R9) // Fill bitreader for state updates - MOVD R13, 8(RSP) - MOVD R8, R0 - LSR $0x08, R0, R0 - MOVBU R0, R0 - MOVD ctx+16(FP), R1 - MOVD 96(R1), R16 - CMP $0x00, R16 - BEQ sequenceDecs_decode_amd64_skip_update + UBFX $8, R8, $8, R0 + CMP $0x00, R19 + BEQ sequenceDecs_decode_amd64_skip_update // Update Literal Length State MOVBU R6, R13 LSRW $0x10, R6, R6 - ADD R13, R3, R1 - MOVD R2, R14 - MOVD R1, R3 - NEG R1, R16 - ROR R16, R14, R14 - MOVD $0x00000001, R4 - BFI $0, R13, $8, R1 - LSLW R1, R4, R4 - SUBW $1, R4, R4 - AND R4, R14, R14 + LSL R3, R2, R14 + LSR $0x01, R14, R14 + ADD R13, R3, R3 + EOR $0x3f, R13, R13 + LSR R13, R14, R14 ADD R14, R6, R6 // Load ctx.llTable - MOVD ctx+16(FP), R1 - MOVD (R1), R1 - ADD R6<<3, R1, R15 - MOVD (R15), R6 + MOVD (R21)(R6<<3), R6 // Update Match Length State MOVBU R7, R13 LSRW $0x10, R7, R7 - ADD R13, R3, R1 - MOVD R2, R14 - MOVD R1, R3 - NEG R1, R16 - ROR R16, R14, R14 - MOVD $0x00000001, R4 - BFI $0, R13, $8, R1 - LSLW R1, R4, R4 - SUBW $1, R4, R4 - AND R4, R14, R14 + LSL R3, R2, R14 + LSR $0x01, R14, R14 + ADD R13, R3, R3 + EOR $0x3f, R13, R13 + LSR R13, R14, R14 ADD R14, R7, R7 // Load ctx.mlTable - MOVD ctx+16(FP), R1 - MOVD 24(R1), R1 - ADD R7<<3, R1, R15 - MOVD (R15), R7 + MOVD (R22)(R7<<3), R7 // Update Offset State MOVBU R8, R13 LSRW $0x10, R8, R8 - ADD R13, R3, R1 - MOVD R2, R14 - MOVD R1, R3 - NEG R1, R16 - ROR R16, R14, R14 - MOVD $0x00000001, R4 - BFI $0, R13, $8, R1 - LSLW R1, R4, R4 - SUBW $1, R4, R4 - AND R4, R14, R14 + LSL R3, R2, R14 + LSR $0x01, R14, R14 + ADD R13, R3, R3 + EOR $0x3f, R13, R13 + LSR R13, R14, R14 ADD R14, R8, R8 // Load ctx.ofTable - MOVD ctx+16(FP), R1 - MOVD 48(R1), R1 - ADD R8<<3, R1, R15 - MOVD (R15), R8 + MOVD (R23)(R8<<3), R8 sequenceDecs_decode_amd64_skip_update: // Adjust offset @@ -306,10 +247,7 @@ sequenceDecs_decode_amd64_after_adjust: sequenceDecs_decode_amd64_match_len_ofs_ok: ADD $0x18, R9, R9 - MOVD ctx+16(FP), R0 - MOVD 96(R0), R16 - SUBS $1, R16, R16 - MOVD R16, 96(R0) + SUBS $1, R19, R19 BPL sequenceDecs_decode_amd64_main_loop MOVD s+0(FP), R0 MOVD R10, 144(R0) @@ -321,69 +259,83 @@ sequenceDecs_decode_amd64_match_len_ofs_ok: MOVD R5, 32(R0) // Return success + MOVD ctx+16(FP), R1 + MOVD R19, 96(R1) MOVD $0x00000000, R16 MOVD R16, ret+24(FP) RET // Return with match length error sequenceDecs_decode_amd64_error_match_len_ofs_mismatch: + MOVD ctx+16(FP), R1 + MOVD R19, 96(R1) MOVD $0x00000001, R16 MOVD R16, ret+24(FP) RET // Return with match too long error sequenceDecs_decode_amd64_error_match_len_too_big: + MOVD ctx+16(FP), R1 + MOVD R19, 96(R1) MOVD $0x00000002, R16 MOVD R16, ret+24(FP) RET // Return with match offset too long error + MOVD R19, R0 + MOVD ctx+16(FP), R1 + MOVD R0, 96(R1) MOVD $0x00000003, R16 MOVD R16, ret+24(FP) RET // Return with not enough literals error error_not_enough_literals: + MOVD ctx+16(FP), R1 + MOVD R19, 96(R1) MOVD $0x00000004, R16 MOVD R16, ret+24(FP) RET // Return with overread error error_overread: + MOVD ctx+16(FP), R1 + MOVD R19, 96(R1) MOVD $0x00000006, R16 MOVD R16, ret+24(FP) RET // func sequenceDecs_decode_56_amd64(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int // Requires: CMOV -TEXT ·sequenceDecs_decode_56_arm64(SB), $8-32 - MOVD br+8(FP), R1 - MOVD 24(R1), R2 - MOVBU 40(R1), R3 - MOVD (R1), R0 - MOVD 32(R1), R5 - ADD R5, R0, R0 - MOVD R0, 8(RSP) - MOVD ctx+16(FP), R0 - MOVD 72(R0), R6 - MOVD 80(R0), R7 - MOVD 88(R0), R8 - MOVD 104(R0), R9 - MOVD s+0(FP), R0 - MOVD 144(R0), R10 - MOVD 152(R0), R11 - MOVD 160(R0), R12 +TEXT ·sequenceDecs_decode_56_arm64(SB), $40-32 + MOVD br+8(FP), R1 + MOVD 24(R1), R2 + MOVBU 40(R1), R3 + MOVD (R1), R20 + MOVD 32(R1), R5 + ADD R5, R20, R20 + MOVD ctx+16(FP), R0 + MOVD 72(R0), R6 + MOVD 80(R0), R7 + MOVD 88(R0), R8 + MOVD (R0), R21 + MOVD 24(R0), R22 + MOVD 48(R0), R23 + MOVD 96(R0), R19 + MOVD 104(R0), R9 + MOVD s+0(FP), R0 + MOVD 144(R0), R10 + MOVD 152(R0), R11 + MOVD 160(R0), R12 + PCALIGN $0x40 sequenceDecs_decode_56_amd64_main_loop: - MOVD 8(RSP), R13 - // Fill bitreader to have enough for the offset and match length. CMP $0x08, R5 BLT sequenceDecs_decode_56_amd64_fill_byte_by_byte - MOVD R3, R0 - LSR $0x03, R0, R0 - SUB R0, R13, R13 - MOVD (R13), R2 + LSR $0x03, R3, R0 + SUB R0, R20, R20 + MOVD (R20), R2 SUB R0, R5, R5 AND $0x07, R3, R3 JMP sequenceDecs_decode_56_amd64_fill_end @@ -394,10 +346,10 @@ sequenceDecs_decode_56_amd64_fill_byte_by_byte: CMP $0x07, R3 BLE sequenceDecs_decode_56_amd64_fill_end LSL $0x08, R2, R2 - SUB $0x01, R13, R13 + SUB $0x01, R20, R20 SUB $0x01, R5, R5 SUB $0x08, R3, R3 - MOVBU (R13), R0 + MOVBU (R20), R0 ORR R0, R2, R2 JMP sequenceDecs_decode_56_amd64_fill_byte_by_byte @@ -408,142 +360,83 @@ sequenceDecs_decode_56_amd64_fill_check_overread: sequenceDecs_decode_56_amd64_fill_end: // Update offset MOVD R8, R0 - MOVD R3, R1 - MOVD R2, R14 - LSL R1, R14, R14 - UBFX $8, R0, $8, R16 - BFI $0, R16, $8, R1 + LSL R3, R2, R14 + LSR $0x01, R14, R14 + UBFX $8, R0, $8, R1 LSR $0x20, R0, R0 - TST R1, R1 - BEQ sequenceDecs_decode_56_amd64_of_update_zero ADD R1, R3, R3 - CMP $0x40, R3 - BHI sequenceDecs_decode_56_amd64_of_update_zero - CMP $0x40, R1 - BHS sequenceDecs_decode_56_amd64_of_update_zero - NEG R1, R1 + EOR $0x3f, R1, R1 LSR R1, R14, R14 ADD R14, R0, R0 - -sequenceDecs_decode_56_amd64_of_update_zero: MOVD R0, 16(R9) // Update match length MOVD R7, R0 - MOVD R3, R1 - MOVD R2, R14 - LSL R1, R14, R14 - UBFX $8, R0, $8, R16 - BFI $0, R16, $8, R1 + LSL R3, R2, R14 + LSR $0x01, R14, R14 + UBFX $8, R0, $8, R1 LSR $0x20, R0, R0 - TST R1, R1 - BEQ sequenceDecs_decode_56_amd64_ml_update_zero ADD R1, R3, R3 - CMP $0x40, R3 - BHI sequenceDecs_decode_56_amd64_ml_update_zero - CMP $0x40, R1 - BHS sequenceDecs_decode_56_amd64_ml_update_zero - NEG R1, R1 + EOR $0x3f, R1, R1 LSR R1, R14, R14 ADD R14, R0, R0 - -sequenceDecs_decode_56_amd64_ml_update_zero: MOVD R0, 8(R9) // Update literal length MOVD R6, R0 - MOVD R3, R1 - MOVD R2, R14 - LSL R1, R14, R14 - UBFX $8, R0, $8, R16 - BFI $0, R16, $8, R1 + LSL R3, R2, R14 + LSR $0x01, R14, R14 + UBFX $8, R0, $8, R1 LSR $0x20, R0, R0 - TST R1, R1 - BEQ sequenceDecs_decode_56_amd64_ll_update_zero ADD R1, R3, R3 - CMP $0x40, R3 - BHI sequenceDecs_decode_56_amd64_ll_update_zero - CMP $0x40, R1 - BHS sequenceDecs_decode_56_amd64_ll_update_zero - NEG R1, R1 + EOR $0x3f, R1, R1 LSR R1, R14, R14 ADD R14, R0, R0 - -sequenceDecs_decode_56_amd64_ll_update_zero: MOVD R0, (R9) // Fill bitreader for state updates - MOVD R13, 8(RSP) - MOVD R8, R0 - LSR $0x08, R0, R0 - MOVBU R0, R0 - MOVD ctx+16(FP), R1 - MOVD 96(R1), R16 - CMP $0x00, R16 - BEQ sequenceDecs_decode_56_amd64_skip_update + UBFX $8, R8, $8, R0 + CMP $0x00, R19 + BEQ sequenceDecs_decode_56_amd64_skip_update // Update Literal Length State MOVBU R6, R13 LSRW $0x10, R6, R6 - ADD R13, R3, R1 - MOVD R2, R14 - MOVD R1, R3 - NEG R1, R16 - ROR R16, R14, R14 - MOVD $0x00000001, R4 - BFI $0, R13, $8, R1 - LSLW R1, R4, R4 - SUBW $1, R4, R4 - AND R4, R14, R14 + LSL R3, R2, R14 + LSR $0x01, R14, R14 + ADD R13, R3, R3 + EOR $0x3f, R13, R13 + LSR R13, R14, R14 ADD R14, R6, R6 // Load ctx.llTable - MOVD ctx+16(FP), R1 - MOVD (R1), R1 - ADD R6<<3, R1, R15 - MOVD (R15), R6 + MOVD (R21)(R6<<3), R6 // Update Match Length State MOVBU R7, R13 LSRW $0x10, R7, R7 - ADD R13, R3, R1 - MOVD R2, R14 - MOVD R1, R3 - NEG R1, R16 - ROR R16, R14, R14 - MOVD $0x00000001, R4 - BFI $0, R13, $8, R1 - LSLW R1, R4, R4 - SUBW $1, R4, R4 - AND R4, R14, R14 + LSL R3, R2, R14 + LSR $0x01, R14, R14 + ADD R13, R3, R3 + EOR $0x3f, R13, R13 + LSR R13, R14, R14 ADD R14, R7, R7 // Load ctx.mlTable - MOVD ctx+16(FP), R1 - MOVD 24(R1), R1 - ADD R7<<3, R1, R15 - MOVD (R15), R7 + MOVD (R22)(R7<<3), R7 // Update Offset State MOVBU R8, R13 LSRW $0x10, R8, R8 - ADD R13, R3, R1 - MOVD R2, R14 - MOVD R1, R3 - NEG R1, R16 - ROR R16, R14, R14 - MOVD $0x00000001, R4 - BFI $0, R13, $8, R1 - LSLW R1, R4, R4 - SUBW $1, R4, R4 - AND R4, R14, R14 + LSL R3, R2, R14 + LSR $0x01, R14, R14 + ADD R13, R3, R3 + EOR $0x3f, R13, R13 + LSR R13, R14, R14 ADD R14, R8, R8 // Load ctx.ofTable - MOVD ctx+16(FP), R1 - MOVD 48(R1), R1 - ADD R8<<3, R1, R15 - MOVD (R15), R8 + MOVD (R23)(R8<<3), R8 sequenceDecs_decode_56_amd64_skip_update: // Adjust offset @@ -628,10 +521,7 @@ sequenceDecs_decode_56_amd64_after_adjust: sequenceDecs_decode_56_amd64_match_len_ofs_ok: ADD $0x18, R9, R9 - MOVD ctx+16(FP), R0 - MOVD 96(R0), R16 - SUBS $1, R16, R16 - MOVD R16, 96(R0) + SUBS $1, R19, R19 BPL sequenceDecs_decode_56_amd64_main_loop MOVD s+0(FP), R0 MOVD R10, 144(R0) @@ -643,35 +533,48 @@ sequenceDecs_decode_56_amd64_match_len_ofs_ok: MOVD R5, 32(R0) // Return success + MOVD ctx+16(FP), R1 + MOVD R19, 96(R1) MOVD $0x00000000, R16 MOVD R16, ret+24(FP) RET // Return with match length error sequenceDecs_decode_56_amd64_error_match_len_ofs_mismatch: + MOVD ctx+16(FP), R1 + MOVD R19, 96(R1) MOVD $0x00000001, R16 MOVD R16, ret+24(FP) RET // Return with match too long error sequenceDecs_decode_56_amd64_error_match_len_too_big: + MOVD ctx+16(FP), R1 + MOVD R19, 96(R1) MOVD $0x00000002, R16 MOVD R16, ret+24(FP) RET // Return with match offset too long error + MOVD R19, R0 + MOVD ctx+16(FP), R1 + MOVD R0, 96(R1) MOVD $0x00000003, R16 MOVD R16, ret+24(FP) RET // Return with not enough literals error error_not_enough_literals: + MOVD ctx+16(FP), R1 + MOVD R19, 96(R1) MOVD $0x00000004, R16 MOVD R16, ret+24(FP) RET // Return with overread error error_overread: + MOVD ctx+16(FP), R1 + MOVD R19, 96(R1) MOVD $0x00000006, R16 MOVD R16, ret+24(FP) RET @@ -681,13 +584,24 @@ error_overread: // skipped sequenceDecs_decode_56_bmi2 (generic twin preferred on arm64) // func sequenceDecs_executeSimple_amd64(ctx *executeAsmContext) bool -// Requires: SSE -TEXT ·sequenceDecs_executeSimple_arm64(SB), $8-9 +// Requires: MMX+, SSE +TEXT ·sequenceDecs_executeSimple_arm64(SB), $32-9 MOVD ctx+0(FP), R9 MOVD 8(R9), R1 TST R1, R1 BEQ empty_seqs MOVD (R9), R0 + + // seqsEnd = seqsBase + 24 * len(seqs) if ctx.prefetch, else seqsBase (prefetch off) + MOVD R0, R20 + MOVBU 128(R9), R10 + TST R10, R10 + BEQ prefetch_off + ADD R1<<1, R1, R20 + LSL $0x03, R20, R20 + ADD R0, R20, R20 + +prefetch_off: MOVD 24(R9), R2 MOVD 32(R9), R3 MOVD 80(R9), R5 @@ -703,32 +617,214 @@ TEXT ·sequenceDecs_executeSimple_arm64(SB), $8-9 ADD R10, R0, R0 // outBase += outPosition - ADD R6, R3, R3 + ADD R6, R3, R3 + MOVD R3, R19 + MOVD R3, R22 + SUB R6, R22, R22 + MOVD R22, R21 + NEG R22, R22 + ADD R8, R22, R22 + // Prime the prefetch window + MOVD R0, R11 + CMP R20, R11 + BHS prefetch_skip_0 + MOVD (R0), R10 + ADD R10, R19, R19 + MOVD R19, R12 + MOVD 16(R0), R10 + SUB R10, R12, R12 + CMP R21, R12 + BHS prefetch_in_out_0 + ADD R22, R12, R12 + +prefetch_in_out_0: + PRFM (R12), PLDL1KEEP + PRFM 64(R12), PLDL1KEEP + MOVD 8(R0), R10 + ADD R10, R19, R19 + +prefetch_skip_0: + ADD $24, R0, R11 + CMP R20, R11 + BHS prefetch_skip_1 + MOVD 24(R0), R10 + ADD R10, R19, R19 + MOVD R19, R12 + MOVD 40(R0), R10 + SUB R10, R12, R12 + CMP R21, R12 + BHS prefetch_in_out_1 + ADD R22, R12, R12 + +prefetch_in_out_1: + PRFM (R12), PLDL1KEEP + PRFM 64(R12), PLDL1KEEP + MOVD 32(R0), R10 + ADD R10, R19, R19 + +prefetch_skip_1: + ADD $48, R0, R11 + CMP R20, R11 + BHS prefetch_skip_2 + MOVD 48(R0), R10 + ADD R10, R19, R19 + MOVD R19, R12 + MOVD 64(R0), R10 + SUB R10, R12, R12 + CMP R21, R12 + BHS prefetch_in_out_2 + ADD R22, R12, R12 + +prefetch_in_out_2: + PRFM (R12), PLDL1KEEP + PRFM 64(R12), PLDL1KEEP + MOVD 56(R0), R10 + ADD R10, R19, R19 + +prefetch_skip_2: + ADD $72, R0, R11 + CMP R20, R11 + BHS prefetch_skip_3 + MOVD 72(R0), R10 + ADD R10, R19, R19 + MOVD R19, R12 + MOVD 88(R0), R10 + SUB R10, R12, R12 + CMP R21, R12 + BHS prefetch_in_out_3 + ADD R22, R12, R12 + +prefetch_in_out_3: + PRFM (R12), PLDL1KEEP + PRFM 64(R12), PLDL1KEEP + MOVD 80(R0), R10 + ADD R10, R19, R19 + +prefetch_skip_3: + ADD $96, R0, R11 + CMP R20, R11 + BHS prefetch_skip_4 + MOVD 96(R0), R10 + ADD R10, R19, R19 + MOVD R19, R12 + MOVD 112(R0), R10 + SUB R10, R12, R12 + CMP R21, R12 + BHS prefetch_in_out_4 + ADD R22, R12, R12 + +prefetch_in_out_4: + PRFM (R12), PLDL1KEEP + PRFM 64(R12), PLDL1KEEP + MOVD 104(R0), R10 + ADD R10, R19, R19 + +prefetch_skip_4: + ADD $120, R0, R11 + CMP R20, R11 + BHS prefetch_skip_5 + MOVD 120(R0), R10 + ADD R10, R19, R19 + MOVD R19, R12 + MOVD 136(R0), R10 + SUB R10, R12, R12 + CMP R21, R12 + BHS prefetch_in_out_5 + ADD R22, R12, R12 + +prefetch_in_out_5: + PRFM (R12), PLDL1KEEP + PRFM 64(R12), PLDL1KEEP + MOVD 128(R0), R10 + ADD R10, R19, R19 + +prefetch_skip_5: + ADD $144, R0, R11 + CMP R20, R11 + BHS prefetch_skip_6 + MOVD 144(R0), R10 + ADD R10, R19, R19 + MOVD R19, R12 + MOVD 160(R0), R10 + SUB R10, R12, R12 + CMP R21, R12 + BHS prefetch_in_out_6 + ADD R22, R12, R12 + +prefetch_in_out_6: + PRFM (R12), PLDL1KEEP + PRFM 64(R12), PLDL1KEEP + MOVD 152(R0), R10 + ADD R10, R19, R19 + +prefetch_skip_6: + ADD $168, R0, R11 + CMP R20, R11 + BHS prefetch_skip_7 + MOVD 168(R0), R10 + ADD R10, R19, R19 + MOVD R19, R12 + MOVD 184(R0), R10 + SUB R10, R12, R12 + CMP R21, R12 + BHS prefetch_in_out_7 + ADD R22, R12, R12 + +prefetch_in_out_7: + PRFM (R12), PLDL1KEEP + PRFM 64(R12), PLDL1KEEP + MOVD 176(R0), R10 + ADD R10, R19, R19 + PCALIGN $0x40 + +prefetch_skip_7: main_loop: + ADD $192, R0, R11 + CMP R20, R11 + BHS prefetch_skip_8 + MOVD 192(R0), R10 + ADD R10, R19, R19 + MOVD R19, R12 + MOVD 208(R0), R10 + SUB R10, R12, R12 + CMP R21, R12 + BHS prefetch_in_out_8 + ADD R22, R12, R12 + +prefetch_in_out_8: + PRFM (R12), PLDL1KEEP + PRFM 64(R12), PLDL1KEEP + MOVD 200(R0), R10 + ADD R10, R19, R19 + +prefetch_skip_8: MOVD (R0), R10 MOVD 16(R0), R11 MOVD 8(R0), R12 // Copy literals - TST R10, R10 - BEQ check_offset - MOVD $0, R13 + FMOVQ (R5), F0 + FMOVQ F0, (R3) + CMP $0x10, R10 + BLS copy_1_end + MOVD $0x00000010, R13 copy_1: - ADD R13, R5, R15 - VLD1 (R15), [V0.B16] - ADD R13, R3, R15 - VST1 [V0.B16], (R15) - ADD $0x10, R13, R13 - CMP R10, R13 - BLO copy_1 - ADD R10, R5, R5 - ADD R10, R3, R3 - ADD R10, R6, R6 + ADD R13, R5, R15 + FMOVQ (R15), F0 + ADD R13, R3, R15 + FMOVQ F0, (R15) + ADD $0x10, R13, R13 + CMP R10, R13 + BLO copy_1 + +copy_1_end: + ADD R10, R5, R5 + ADD R10, R3, R3 + ADD R10, R6, R6 // Malformed input if seq.mo > t+len(hist) || seq.mo > s.windowSize) -check_offset: ADD R9, R6, R10 CMP R10, R11 BGT error_match_off_too_big @@ -748,21 +844,19 @@ check_offset: BLO copy_4_small copy_4_loop: - VLD1 (R13), [V0.B16] - VST1 [V0.B16], (R3) - ADD $0x10, R13, R13 - ADD $0x10, R3, R3 - SUBS $0x10, R10, R10 - BHS copy_4_loop - ADD R10, R13, R13 - ADD $16, R13, R13 - ADD R10, R3, R3 - ADD $16, R3, R3 - ADD $-16, R13, R15 - VLD1 (R15), [V0.B16] - ADD $-16, R3, R15 - VST1 [V0.B16], (R15) - JMP copy_4_end + FMOVQ (R13), F0 + FMOVQ F0, (R3) + ADD $0x10, R13, R13 + ADD $0x10, R3, R3 + SUBS $0x10, R10, R10 + BHS copy_4_loop + ADD R10, R13, R13 + ADD $16, R13, R13 + ADD R10, R3, R3 + ADD $16, R3, R3 + FMOVQ -16(R13), F0 + FMOVQ F0, -16(R3) + JMP copy_4_end copy_4_small: CMP $0x03, R12 @@ -816,21 +910,19 @@ copy_all_from_history: BLO copy_5_small copy_5_loop: - VLD1 (R13), [V0.B16] - VST1 [V0.B16], (R3) - ADD $0x10, R13, R13 - ADD $0x10, R3, R3 - SUBS $0x10, R14, R14 - BHS copy_5_loop - ADD R14, R13, R13 - ADD $16, R13, R13 - ADD R14, R3, R3 - ADD $16, R3, R3 - ADD $-16, R13, R15 - VLD1 (R15), [V0.B16] - ADD $-16, R3, R15 - VST1 [V0.B16], (R15) - JMP copy_5_end + FMOVQ (R13), F0 + FMOVQ F0, (R3) + ADD $0x10, R13, R13 + ADD $0x10, R3, R3 + SUBS $0x10, R14, R14 + BHS copy_5_loop + ADD R14, R13, R13 + ADD $16, R13, R13 + ADD R14, R3, R3 + ADD $16, R3, R3 + FMOVQ -16(R13), F0 + FMOVQ F0, -16(R3) + JMP copy_5_end copy_5_small: CMP $0x03, R10 @@ -898,26 +990,48 @@ copy_match: BHI copy_overlapping_match // Copy non-overlapping match - ADD R12, R6, R6 - MOVD R3, R11 - ADD R12, R3, R3 + ADD R12, R6, R6 + FLDPQ (R10), (F0, F1) + FSTPQ (F0, F1), (R3) + CMP $0x20, R12 + BHI copy_2_long + ADD R12, R3, R3 + JMP handle_loop + +copy_2_long: + ADD $32, R3, R11 + ADD R12, R3, R3 + ADD $0x20, R10, R10 + SUB $0x20, R12, R12 copy_2: - VLD1 (R10), [V0.B16] - VST1 [V0.B16], (R11) - ADD $0x10, R10, R10 - ADD $0x10, R11, R11 - SUBS $0x10, R12, R12 - BHI copy_2 - JMP handle_loop + FLDPQ (R10), (F0, F1) + FSTPQ (F0, F1), (R11) + ADD $0x20, R10, R10 + ADD $0x20, R11, R11 + SUBS $0x20, R12, R12 + BHI copy_2 + JMP handle_loop // Copy overlapping match copy_overlapping_match: - ADD R12, R6, R6 + ADD R12, R6, R6 + CMP $0x10, R11 + BLO copy_slow_3 + MOVD R3, R11 + ADD R12, R3, R3 + +copy_3: + FMOVQ (R10), F0 + FMOVQ F0, (R11) + ADD $0x10, R10, R10 + ADD $0x10, R11, R11 + SUBS $0x10, R12, R12 + BHI copy_3 + JMP handle_loop copy_slow_3: - MOVBU (R10), R16 - BFI $0, R16, $8, R11 + MOVBU (R10), R11 MOVB R11, (R3) ADD $1, R10, R10 ADD $1, R3, R3 @@ -965,13 +1079,24 @@ empty_seqs: RET // func sequenceDecs_executeSimple_safe_amd64(ctx *executeAsmContext) bool -// Requires: SSE -TEXT ·sequenceDecs_executeSimple_safe_arm64(SB), $8-9 +// Requires: MMX+, SSE +TEXT ·sequenceDecs_executeSimple_safe_arm64(SB), $32-9 MOVD ctx+0(FP), R9 MOVD 8(R9), R1 TST R1, R1 BEQ empty_seqs MOVD (R9), R0 + + // seqsEnd = seqsBase + 24 * len(seqs) if ctx.prefetch, else seqsBase (prefetch off) + MOVD R0, R20 + MOVBU 128(R9), R10 + TST R10, R10 + BEQ prefetch_off + ADD R1<<1, R1, R20 + LSL $0x03, R20, R20 + ADD R0, R20, R20 + +prefetch_off: MOVD 24(R9), R2 MOVD 32(R9), R3 MOVD 80(R9), R5 @@ -987,9 +1112,188 @@ TEXT ·sequenceDecs_executeSimple_safe_arm64(SB), $8-9 ADD R10, R0, R0 // outBase += outPosition - ADD R6, R3, R3 + ADD R6, R3, R3 + MOVD R3, R19 + MOVD R3, R22 + SUB R6, R22, R22 + MOVD R22, R21 + NEG R22, R22 + ADD R8, R22, R22 + // Prime the prefetch window + MOVD R0, R11 + CMP R20, R11 + BHS prefetch_skip_0 + MOVD (R0), R10 + ADD R10, R19, R19 + MOVD R19, R12 + MOVD 16(R0), R10 + SUB R10, R12, R12 + CMP R21, R12 + BHS prefetch_in_out_0 + ADD R22, R12, R12 + +prefetch_in_out_0: + PRFM (R12), PLDL1KEEP + PRFM 64(R12), PLDL1KEEP + MOVD 8(R0), R10 + ADD R10, R19, R19 + +prefetch_skip_0: + ADD $24, R0, R11 + CMP R20, R11 + BHS prefetch_skip_1 + MOVD 24(R0), R10 + ADD R10, R19, R19 + MOVD R19, R12 + MOVD 40(R0), R10 + SUB R10, R12, R12 + CMP R21, R12 + BHS prefetch_in_out_1 + ADD R22, R12, R12 + +prefetch_in_out_1: + PRFM (R12), PLDL1KEEP + PRFM 64(R12), PLDL1KEEP + MOVD 32(R0), R10 + ADD R10, R19, R19 + +prefetch_skip_1: + ADD $48, R0, R11 + CMP R20, R11 + BHS prefetch_skip_2 + MOVD 48(R0), R10 + ADD R10, R19, R19 + MOVD R19, R12 + MOVD 64(R0), R10 + SUB R10, R12, R12 + CMP R21, R12 + BHS prefetch_in_out_2 + ADD R22, R12, R12 + +prefetch_in_out_2: + PRFM (R12), PLDL1KEEP + PRFM 64(R12), PLDL1KEEP + MOVD 56(R0), R10 + ADD R10, R19, R19 + +prefetch_skip_2: + ADD $72, R0, R11 + CMP R20, R11 + BHS prefetch_skip_3 + MOVD 72(R0), R10 + ADD R10, R19, R19 + MOVD R19, R12 + MOVD 88(R0), R10 + SUB R10, R12, R12 + CMP R21, R12 + BHS prefetch_in_out_3 + ADD R22, R12, R12 + +prefetch_in_out_3: + PRFM (R12), PLDL1KEEP + PRFM 64(R12), PLDL1KEEP + MOVD 80(R0), R10 + ADD R10, R19, R19 + +prefetch_skip_3: + ADD $96, R0, R11 + CMP R20, R11 + BHS prefetch_skip_4 + MOVD 96(R0), R10 + ADD R10, R19, R19 + MOVD R19, R12 + MOVD 112(R0), R10 + SUB R10, R12, R12 + CMP R21, R12 + BHS prefetch_in_out_4 + ADD R22, R12, R12 + +prefetch_in_out_4: + PRFM (R12), PLDL1KEEP + PRFM 64(R12), PLDL1KEEP + MOVD 104(R0), R10 + ADD R10, R19, R19 + +prefetch_skip_4: + ADD $120, R0, R11 + CMP R20, R11 + BHS prefetch_skip_5 + MOVD 120(R0), R10 + ADD R10, R19, R19 + MOVD R19, R12 + MOVD 136(R0), R10 + SUB R10, R12, R12 + CMP R21, R12 + BHS prefetch_in_out_5 + ADD R22, R12, R12 + +prefetch_in_out_5: + PRFM (R12), PLDL1KEEP + PRFM 64(R12), PLDL1KEEP + MOVD 128(R0), R10 + ADD R10, R19, R19 + +prefetch_skip_5: + ADD $144, R0, R11 + CMP R20, R11 + BHS prefetch_skip_6 + MOVD 144(R0), R10 + ADD R10, R19, R19 + MOVD R19, R12 + MOVD 160(R0), R10 + SUB R10, R12, R12 + CMP R21, R12 + BHS prefetch_in_out_6 + ADD R22, R12, R12 + +prefetch_in_out_6: + PRFM (R12), PLDL1KEEP + PRFM 64(R12), PLDL1KEEP + MOVD 152(R0), R10 + ADD R10, R19, R19 + +prefetch_skip_6: + ADD $168, R0, R11 + CMP R20, R11 + BHS prefetch_skip_7 + MOVD 168(R0), R10 + ADD R10, R19, R19 + MOVD R19, R12 + MOVD 184(R0), R10 + SUB R10, R12, R12 + CMP R21, R12 + BHS prefetch_in_out_7 + ADD R22, R12, R12 + +prefetch_in_out_7: + PRFM (R12), PLDL1KEEP + PRFM 64(R12), PLDL1KEEP + MOVD 176(R0), R10 + ADD R10, R19, R19 + PCALIGN $0x40 + +prefetch_skip_7: main_loop: + ADD $192, R0, R11 + CMP R20, R11 + BHS prefetch_skip_8 + MOVD 192(R0), R10 + ADD R10, R19, R19 + MOVD R19, R12 + MOVD 208(R0), R10 + SUB R10, R12, R12 + CMP R21, R12 + BHS prefetch_in_out_8 + ADD R22, R12, R12 + +prefetch_in_out_8: + PRFM (R12), PLDL1KEEP + PRFM 64(R12), PLDL1KEEP + MOVD 200(R0), R10 + ADD R10, R19, R19 + +prefetch_skip_8: MOVD (R0), R10 MOVD 16(R0), R11 MOVD 8(R0), R12 @@ -1002,21 +1306,19 @@ main_loop: BLO copy_1_small copy_1_loop: - VLD1 (R5), [V0.B16] - VST1 [V0.B16], (R3) - ADD $0x10, R5, R5 - ADD $0x10, R3, R3 - SUBS $0x10, R13, R13 - BHS copy_1_loop - ADD R13, R5, R5 - ADD $16, R5, R5 - ADD R13, R3, R3 - ADD $16, R3, R3 - ADD $-16, R5, R15 - VLD1 (R15), [V0.B16] - ADD $-16, R3, R15 - VST1 [V0.B16], (R15) - JMP copy_1_end + FMOVQ (R5), F0 + FMOVQ F0, (R3) + ADD $0x10, R5, R5 + ADD $0x10, R3, R3 + SUBS $0x10, R13, R13 + BHS copy_1_loop + ADD R13, R5, R5 + ADD $16, R5, R5 + ADD R13, R3, R3 + ADD $16, R3, R3 + FMOVQ -16(R5), F0 + FMOVQ F0, -16(R3) + JMP copy_1_end copy_1_small: CMP $0x03, R10 @@ -1094,21 +1396,19 @@ check_offset: BLO copy_4_small copy_4_loop: - VLD1 (R13), [V0.B16] - VST1 [V0.B16], (R3) - ADD $0x10, R13, R13 - ADD $0x10, R3, R3 - SUBS $0x10, R10, R10 - BHS copy_4_loop - ADD R10, R13, R13 - ADD $16, R13, R13 - ADD R10, R3, R3 - ADD $16, R3, R3 - ADD $-16, R13, R15 - VLD1 (R15), [V0.B16] - ADD $-16, R3, R15 - VST1 [V0.B16], (R15) - JMP copy_4_end + FMOVQ (R13), F0 + FMOVQ F0, (R3) + ADD $0x10, R13, R13 + ADD $0x10, R3, R3 + SUBS $0x10, R10, R10 + BHS copy_4_loop + ADD R10, R13, R13 + ADD $16, R13, R13 + ADD R10, R3, R3 + ADD $16, R3, R3 + FMOVQ -16(R13), F0 + FMOVQ F0, -16(R3) + JMP copy_4_end copy_4_small: CMP $0x03, R12 @@ -1162,21 +1462,19 @@ copy_all_from_history: BLO copy_5_small copy_5_loop: - VLD1 (R13), [V0.B16] - VST1 [V0.B16], (R3) - ADD $0x10, R13, R13 - ADD $0x10, R3, R3 - SUBS $0x10, R14, R14 - BHS copy_5_loop - ADD R14, R13, R13 - ADD $16, R13, R13 - ADD R14, R3, R3 - ADD $16, R3, R3 - ADD $-16, R13, R15 - VLD1 (R15), [V0.B16] - ADD $-16, R3, R15 - VST1 [V0.B16], (R15) - JMP copy_5_end + FMOVQ (R13), F0 + FMOVQ F0, (R3) + ADD $0x10, R13, R13 + ADD $0x10, R3, R3 + SUBS $0x10, R14, R14 + BHS copy_5_loop + ADD R14, R13, R13 + ADD $16, R13, R13 + ADD R14, R3, R3 + ADD $16, R3, R3 + FMOVQ -16(R13), F0 + FMOVQ F0, -16(R3) + JMP copy_5_end copy_5_small: CMP $0x03, R10 @@ -1250,21 +1548,19 @@ copy_match: BLO copy_2_small copy_2_loop: - VLD1 (R10), [V0.B16] - VST1 [V0.B16], (R3) - ADD $0x10, R10, R10 - ADD $0x10, R3, R3 - SUBS $0x10, R11, R11 - BHS copy_2_loop - ADD R11, R10, R10 - ADD $16, R10, R10 - ADD R11, R3, R3 - ADD $16, R3, R3 - ADD $-16, R10, R15 - VLD1 (R15), [V0.B16] - ADD $-16, R3, R15 - VST1 [V0.B16], (R15) - JMP copy_2_end + FMOVQ (R10), F0 + FMOVQ F0, (R3) + ADD $0x10, R10, R10 + ADD $0x10, R3, R3 + SUBS $0x10, R11, R11 + BHS copy_2_loop + ADD R11, R10, R10 + ADD $16, R10, R10 + ADD R11, R3, R3 + ADD $16, R3, R3 + FMOVQ -16(R10), F0 + FMOVQ F0, -16(R3) + JMP copy_2_end copy_2_small: CMP $0x03, R12 @@ -1324,10 +1620,22 @@ copy_2_end: // Copy overlapping match copy_overlapping_match: ADD R12, R6, R6 + CMP $0x10, R11 + BLO copy_slow_3 + +copy_3_blocks: + FMOVQ (R10), F0 + FMOVQ F0, (R3) + ADD $0x10, R10, R10 + ADD $0x10, R3, R3 + SUB $0x10, R12, R12 + CMP $0x10, R12 + BHS copy_3_blocks + TST R12, R12 + BEQ handle_loop copy_slow_3: - MOVBU (R10), R16 - BFI $0, R16, $8, R11 + MOVBU (R10), R11 MOVB R11, (R3) ADD $1, R10, R10 ADD $1, R3, R3 @@ -1376,56 +1684,50 @@ empty_seqs: // func sequenceDecs_decodeSync_amd64(s *sequenceDecs, br *bitReader, ctx *decodeSyncAsmContext) int // Requires: CMOV, SSE -TEXT ·sequenceDecs_decodeSync_arm64(SB), $64-32 +TEXT ·sequenceDecs_decodeSync_arm64(SB), $96-32 MOVD br+8(FP), R1 MOVD 24(R1), R2 MOVBU 40(R1), R3 - MOVD (R1), R0 + MOVD (R1), R22 MOVD 32(R1), R5 - ADD R5, R0, R0 - MOVD R0, 8(RSP) - MOVD ctx+16(FP), R0 - MOVD 72(R0), R6 - MOVD 80(R0), R7 - MOVD 88(R0), R8 - MOVD $0, R1 - MOVD R1, 16(RSP) + ADD R5, R22, R22 + MOVD ctx+16(FP), R25 + MOVD 72(R25), R6 + MOVD 80(R25), R7 + MOVD 88(R25), R8 + MOVD (R25), R17 + MOVD 24(R25), R1 MOVD R1, 24(RSP) + MOVD 48(R25), R1 MOVD R1, 32(RSP) - MOVD 112(R0), R9 - MOVD 128(R0), R1 - MOVD R1, 40(RSP) - MOVD 144(R0), R10 - MOVD 136(R0), R11 - MOVD 200(R0), R1 - MOVD R1, 64(RSP) - MOVD 176(R0), R1 - MOVD R1, 56(RSP) - MOVD 184(R0), R0 - MOVD R0, 48(RSP) - MOVD 48(RSP), R0 - MOVD 56(RSP), R16 - ADD R0, R16, R16 - MOVD R16, 56(RSP) + MOVD 96(R25), R23 + MOVD $0, R20 + MOVD R20, R21 + MOVD R20, R19 + MOVD 112(R25), R9 + MOVD 128(R25), R24 + MOVD 144(R25), R10 + MOVD 136(R25), R11 + MOVD 200(R25), R1 + MOVD R1, 96(RSP) + MOVD 176(R25), R26 + MOVD 184(R25), R25 + ADD R25, R26, R26 // Calculate pointer to s.out[cap(s.out)] (a past-end pointer) - MOVD 40(RSP), R16 - ADD R9, R16, R16 - MOVD R16, 40(RSP) + ADD R9, R24, R24 // outBase += outPosition - ADD R11, R9, R9 + ADD R11, R9, R9 + PCALIGN $0x40 sequenceDecs_decodeSync_amd64_main_loop: - MOVD 8(RSP), R12 - // Fill bitreader to have enough for the offset and match length. CMP $0x08, R5 BLT sequenceDecs_decodeSync_amd64_fill_byte_by_byte - MOVD R3, R0 - LSR $0x03, R0, R0 - SUB R0, R12, R12 - MOVD (R12), R2 + LSR $0x03, R3, R0 + SUB R0, R22, R22 + MOVD (R22), R2 SUB R0, R5, R5 AND $0x07, R3, R3 JMP sequenceDecs_decodeSync_amd64_fill_end @@ -1436,10 +1738,10 @@ sequenceDecs_decodeSync_amd64_fill_byte_by_byte: CMP $0x07, R3 BLE sequenceDecs_decodeSync_amd64_fill_end LSL $0x08, R2, R2 - SUB $0x01, R12, R12 + SUB $0x01, R22, R22 SUB $0x01, R5, R5 SUB $0x08, R3, R3 - MOVBU (R12), R0 + MOVBU (R22), R0 ORR R0, R2, R2 JMP sequenceDecs_decodeSync_amd64_fill_byte_by_byte @@ -1450,55 +1752,34 @@ sequenceDecs_decodeSync_amd64_fill_check_overread: sequenceDecs_decodeSync_amd64_fill_end: // Update offset MOVD R8, R0 - MOVD R3, R1 - MOVD R2, R13 - LSL R1, R13, R13 - UBFX $8, R0, $8, R16 - BFI $0, R16, $8, R1 + LSL R3, R2, R13 + LSR $0x01, R13, R13 + UBFX $8, R0, $8, R1 LSR $0x20, R0, R0 - TST R1, R1 - BEQ sequenceDecs_decodeSync_amd64_of_update_zero ADD R1, R3, R3 - CMP $0x40, R3 - BHI sequenceDecs_decodeSync_amd64_of_update_zero - CMP $0x40, R1 - BHS sequenceDecs_decodeSync_amd64_of_update_zero - NEG R1, R1 + EOR $0x3f, R1, R1 LSR R1, R13, R13 ADD R13, R0, R0 - -sequenceDecs_decodeSync_amd64_of_update_zero: - MOVD R0, 16(RSP) + MOVD R0, R20 // Update match length MOVD R7, R0 - MOVD R3, R1 - MOVD R2, R13 - LSL R1, R13, R13 - UBFX $8, R0, $8, R16 - BFI $0, R16, $8, R1 + LSL R3, R2, R13 + LSR $0x01, R13, R13 + UBFX $8, R0, $8, R1 LSR $0x20, R0, R0 - TST R1, R1 - BEQ sequenceDecs_decodeSync_amd64_ml_update_zero ADD R1, R3, R3 - CMP $0x40, R3 - BHI sequenceDecs_decodeSync_amd64_ml_update_zero - CMP $0x40, R1 - BHS sequenceDecs_decodeSync_amd64_ml_update_zero - NEG R1, R1 + EOR $0x3f, R1, R1 LSR R1, R13, R13 ADD R13, R0, R0 - -sequenceDecs_decodeSync_amd64_ml_update_zero: - MOVD R0, 24(RSP) + MOVD R0, R21 // Fill bitreader to have enough for the remaining CMP $0x08, R5 BLT sequenceDecs_decodeSync_amd64_fill_2_byte_by_byte - MOVD R3, R0 - LSR $0x03, R0, R0 - SUB R0, R12, R12 - MOVD (R12), R2 + LSR $0x03, R3, R0 + SUB R0, R22, R22 + MOVD (R22), R2 SUB R0, R5, R5 AND $0x07, R3, R3 JMP sequenceDecs_decodeSync_amd64_fill_2_end @@ -1509,10 +1790,10 @@ sequenceDecs_decodeSync_amd64_fill_2_byte_by_byte: CMP $0x07, R3 BLE sequenceDecs_decodeSync_amd64_fill_2_end LSL $0x08, R2, R2 - SUB $0x01, R12, R12 + SUB $0x01, R22, R22 SUB $0x01, R5, R5 SUB $0x08, R3, R3 - MOVBU (R12), R0 + MOVBU (R22), R0 ORR R0, R2, R2 JMP sequenceDecs_decodeSync_amd64_fill_2_byte_by_byte @@ -1523,130 +1804,89 @@ sequenceDecs_decodeSync_amd64_fill_2_check_overread: sequenceDecs_decodeSync_amd64_fill_2_end: // Update literal length MOVD R6, R0 - MOVD R3, R1 - MOVD R2, R13 - LSL R1, R13, R13 - UBFX $8, R0, $8, R16 - BFI $0, R16, $8, R1 + LSL R3, R2, R13 + LSR $0x01, R13, R13 + UBFX $8, R0, $8, R1 LSR $0x20, R0, R0 - TST R1, R1 - BEQ sequenceDecs_decodeSync_amd64_ll_update_zero ADD R1, R3, R3 - CMP $0x40, R3 - BHI sequenceDecs_decodeSync_amd64_ll_update_zero - CMP $0x40, R1 - BHS sequenceDecs_decodeSync_amd64_ll_update_zero - NEG R1, R1 + EOR $0x3f, R1, R1 LSR R1, R13, R13 ADD R13, R0, R0 - -sequenceDecs_decodeSync_amd64_ll_update_zero: - MOVD R0, 32(RSP) + MOVD R0, R19 // Fill bitreader for state updates - MOVD R12, 8(RSP) - MOVD R8, R0 - LSR $0x08, R0, R0 - MOVBU R0, R0 - MOVD ctx+16(FP), R1 - MOVD 96(R1), R16 - CMP $0x00, R16 - BEQ sequenceDecs_decodeSync_amd64_skip_update + UBFX $8, R8, $8, R0 + CMP $0x00, R23 + BEQ sequenceDecs_decodeSync_amd64_skip_update // Update Literal Length State MOVBU R6, R12 LSRW $0x10, R6, R6 - ADD R12, R3, R1 - MOVD R2, R13 - MOVD R1, R3 - NEG R1, R16 - ROR R16, R13, R13 - MOVD $0x00000001, R14 - BFI $0, R12, $8, R1 - LSLW R1, R14, R14 - SUBW $1, R14, R14 - AND R14, R13, R13 + LSL R3, R2, R13 + LSR $0x01, R13, R13 + ADD R12, R3, R3 + EOR $0x3f, R12, R12 + LSR R12, R13, R13 ADD R13, R6, R6 // Load ctx.llTable - MOVD ctx+16(FP), R1 - MOVD (R1), R1 - ADD R6<<3, R1, R15 - MOVD (R15), R6 + MOVD (R17)(R6<<3), R6 // Update Match Length State MOVBU R7, R12 LSRW $0x10, R7, R7 - ADD R12, R3, R1 - MOVD R2, R13 - MOVD R1, R3 - NEG R1, R16 - ROR R16, R13, R13 - MOVD $0x00000001, R14 - BFI $0, R12, $8, R1 - LSLW R1, R14, R14 - SUBW $1, R14, R14 - AND R14, R13, R13 + LSL R3, R2, R13 + LSR $0x01, R13, R13 + ADD R12, R3, R3 + EOR $0x3f, R12, R12 + LSR R12, R13, R13 ADD R13, R7, R7 // Load ctx.mlTable - MOVD ctx+16(FP), R1 - MOVD 24(R1), R1 - ADD R7<<3, R1, R15 - MOVD (R15), R7 + MOVD 24(RSP), R1 + MOVD (R1)(R7<<3), R7 // Update Offset State MOVBU R8, R12 LSRW $0x10, R8, R8 - ADD R12, R3, R1 - MOVD R2, R13 - MOVD R1, R3 - NEG R1, R16 - ROR R16, R13, R13 - MOVD $0x00000001, R14 - BFI $0, R12, $8, R1 - LSLW R1, R14, R14 - SUBW $1, R14, R14 - AND R14, R13, R13 + LSL R3, R2, R13 + LSR $0x01, R13, R13 + ADD R12, R3, R3 + EOR $0x3f, R12, R12 + LSR R12, R13, R13 ADD R13, R8, R8 // Load ctx.ofTable - MOVD ctx+16(FP), R1 - MOVD 48(R1), R1 - ADD R8<<3, R1, R15 - MOVD (R15), R8 + MOVD 32(RSP), R1 + MOVD (R1)(R8<<3), R8 sequenceDecs_decodeSync_amd64_skip_update: // Adjust offset - MOVD s+0(FP), R1 - MOVD 16(RSP), R12 - CMP $0x01, R0 - BLS sequenceDecs_decodeSync_amd64_adjust_offsetB_1_or_0 - ADD $144, R1, R15 - VLD1 (R15), [V0.B16] - MOVD R12, 144(R1) - ADD $152, R1, R15 - VST1 [V0.B16], (R15) - JMP sequenceDecs_decodeSync_amd64_after_adjust + MOVD s+0(FP), R1 + CMP $0x01, R0 + BLS sequenceDecs_decodeSync_amd64_adjust_offsetB_1_or_0 + FMOVQ 144(R1), F0 + MOVD R20, 144(R1) + FMOVQ F0, 152(R1) + JMP sequenceDecs_decodeSync_amd64_after_adjust sequenceDecs_decodeSync_amd64_adjust_offsetB_1_or_0: - MOVD 32(RSP), R16 - CMP $0x00000000, R16 - BNE sequenceDecs_decodeSync_amd64_adjust_offset_maybezero - ADD $1, R12, R12 - JMP sequenceDecs_decodeSync_amd64_adjust_offset_nonzero + CMP $0x00000000, R19 + BNE sequenceDecs_decodeSync_amd64_adjust_offset_maybezero + ADD $1, R20, R20 + JMP sequenceDecs_decodeSync_amd64_adjust_offset_nonzero sequenceDecs_decodeSync_amd64_adjust_offset_maybezero: - TST R12, R12 + TST R20, R20 BNE sequenceDecs_decodeSync_amd64_adjust_offset_nonzero - MOVD 144(R1), R12 + MOVD 144(R1), R20 JMP sequenceDecs_decodeSync_amd64_after_adjust sequenceDecs_decodeSync_amd64_adjust_offset_nonzero: - MOVD R12, R0 + MOVD R20, R0 MOVD $0, R13 MOVD $-1, R14 - CMP $0x03, R12 + CMP $0x03, R20 CSEL EQ, R13, R0, R0 CSEL EQ, R14, R13, R13 ADD R0<<3, R1, R15 @@ -1656,7 +1896,7 @@ sequenceDecs_decodeSync_amd64_adjust_offset_nonzero: MOVD $0x00000001, R13 sequenceDecs_decodeSync_amd64_adjust_temp_valid: - CMP $0x01, R12 + CMP $0x01, R20 BEQ sequenceDecs_decodeSync_amd64_adjust_skip MOVD 152(R1), R0 MOVD R0, 160(R1) @@ -1665,185 +1905,169 @@ sequenceDecs_decodeSync_amd64_adjust_skip: MOVD 144(R1), R0 MOVD R0, 152(R1) MOVD R13, 144(R1) - MOVD R13, R12 + MOVD R13, R20 sequenceDecs_decodeSync_amd64_after_adjust: - MOVD R12, 16(RSP) - // Check values - MOVD 24(RSP), R0 - MOVD 32(RSP), R1 - ADD R1, R0, R13 - MOVD s+0(FP), R14 - MOVD 256(R14), R16 - ADD R13, R16, R16 - MOVD R16, 256(R14) MOVD ctx+16(FP), R13 MOVD 104(R13), R16 - SUBS R1, R16, R16 + SUBS R19, R16, R16 MOVD R16, 104(R13) BMI error_not_enough_literals - CMP $0x00020002, R0 + CMP $0x00020002, R21 BHI sequenceDecs_decodeSync_amd64_error_match_len_too_big - TST R12, R12 + TST R20, R20 BNE sequenceDecs_decodeSync_amd64_match_len_ofs_ok - TST R0, R0 + TST R21, R21 BNE sequenceDecs_decodeSync_amd64_error_match_len_ofs_mismatch sequenceDecs_decodeSync_amd64_match_len_ofs_ok: - MOVD 32(RSP), R0 - MOVD 16(RSP), R1 - MOVD 24(RSP), R12 - // Check if we have enough space in s.out - ADD R12, R0, R13 - ADD $16, R13, R13 - ADD R9, R13, R13 - MOVD 40(RSP), R16 - CMP R16, R13 - BHI error_not_enough_space + ADD R21, R19, R13 + ADD $32, R13, R13 + ADD R9, R13, R13 + CMP R24, R13 + BHI error_not_enough_space // Copy literals - TST R0, R0 - BEQ check_offset - MOVD $0, R13 + FMOVQ (R10), F0 + FMOVQ F0, (R9) + CMP $0x10, R19 + BLS copy_1_end + MOVD $0x00000010, R13 copy_1: - ADD R13, R10, R15 - VLD1 (R15), [V0.B16] - ADD R13, R9, R15 - VST1 [V0.B16], (R15) - ADD $0x10, R13, R13 - CMP R0, R13 - BLO copy_1 - ADD R0, R10, R10 - ADD R0, R9, R9 - ADD R0, R11, R11 + ADD R13, R10, R15 + FMOVQ (R15), F0 + ADD R13, R9, R15 + FMOVQ F0, (R15) + ADD $0x10, R13, R13 + CMP R19, R13 + BLO copy_1 + +copy_1_end: + ADD R19, R10, R10 + ADD R19, R9, R9 + ADD R19, R11, R11 // Malformed input if seq.mo > t+len(hist) || seq.mo > s.windowSize) -check_offset: - MOVD R11, R0 - MOVD 48(RSP), R16 - ADD R16, R0, R0 - CMP R0, R1 + MOVD R11, R1 + ADD R25, R1, R1 + CMP R1, R20 BGT error_match_off_too_big - MOVD 64(RSP), R16 - CMP R16, R1 + MOVD 96(RSP), R16 + CMP R16, R20 BGT error_match_off_too_big // Copy match from history - MOVD R1, R0 - SUBS R11, R0, R0 + MOVD R20, R1 + SUBS R11, R1, R1 BLS copy_match - MOVD 56(RSP), R13 - SUB R0, R13, R13 - CMP R0, R12 + MOVD R26, R13 + SUB R1, R13, R13 + CMP R1, R21 BGT copy_all_from_history - MOVD R12, R0 - SUBS $0x10, R0, R0 + MOVD R21, R1 + SUBS $0x10, R1, R1 BLO copy_4_small copy_4_loop: - VLD1 (R13), [V0.B16] - VST1 [V0.B16], (R9) - ADD $0x10, R13, R13 - ADD $0x10, R9, R9 - SUBS $0x10, R0, R0 - BHS copy_4_loop - ADD R0, R13, R13 - ADD $16, R13, R13 - ADD R0, R9, R9 - ADD $16, R9, R9 - ADD $-16, R13, R15 - VLD1 (R15), [V0.B16] - ADD $-16, R9, R15 - VST1 [V0.B16], (R15) - JMP copy_4_end + FMOVQ (R13), F0 + FMOVQ F0, (R9) + ADD $0x10, R13, R13 + ADD $0x10, R9, R9 + SUBS $0x10, R1, R1 + BHS copy_4_loop + ADD R1, R13, R13 + ADD $16, R13, R13 + ADD R1, R9, R9 + ADD $16, R9, R9 + FMOVQ -16(R13), F0 + FMOVQ F0, -16(R9) + JMP copy_4_end copy_4_small: - CMP $0x03, R12 + CMP $0x03, R21 BEQ copy_4_move_3 - CMP $0x08, R12 + CMP $0x08, R21 BLO copy_4_move_4through7 JMP copy_4_move_8through16 copy_4_move_3: - MOVHU (R13), R0 + MOVHU (R13), R1 MOVBU 2(R13), R16 - BFI $0, R16, $8, R1 - MOVH R0, (R9) - MOVB R1, 2(R9) - ADD R12, R13, R13 - ADD R12, R9, R9 + BFI $0, R16, $8, R20 + MOVH R1, (R9) + MOVB R20, 2(R9) + ADD R21, R13, R13 + ADD R21, R9, R9 JMP copy_4_end copy_4_move_4through7: - MOVWU (R13), R0 - ADD R12, R13, R15 - MOVWU -4(R15), R1 - MOVW R0, (R9) - ADD R12, R9, R15 - MOVW R1, -4(R15) - ADD R12, R13, R13 - ADD R12, R9, R9 + MOVWU (R13), R1 + ADD R21, R13, R15 + MOVWU -4(R15), R12 + MOVW R1, (R9) + ADD R21, R9, R15 + MOVW R12, -4(R15) + ADD R21, R13, R13 + ADD R21, R9, R9 JMP copy_4_end copy_4_move_8through16: - MOVD (R13), R0 - ADD R12, R13, R15 - MOVD -8(R15), R1 - MOVD R0, (R9) - ADD R12, R9, R15 - MOVD R1, -8(R15) - ADD R12, R13, R13 - ADD R12, R9, R9 + MOVD (R13), R1 + ADD R21, R13, R15 + MOVD -8(R15), R12 + MOVD R1, (R9) + ADD R21, R9, R15 + MOVD R12, -8(R15) + ADD R21, R13, R13 + ADD R21, R9, R9 copy_4_end: - ADD R12, R11, R11 + ADD R21, R11, R11 JMP handle_loop JMP loop_finished copy_all_from_history: - MOVD R0, R14 + MOVD R1, R14 SUBS $0x10, R14, R14 BLO copy_5_small copy_5_loop: - VLD1 (R13), [V0.B16] - VST1 [V0.B16], (R9) - ADD $0x10, R13, R13 - ADD $0x10, R9, R9 - SUBS $0x10, R14, R14 - BHS copy_5_loop - ADD R14, R13, R13 - ADD $16, R13, R13 - ADD R14, R9, R9 - ADD $16, R9, R9 - ADD $-16, R13, R15 - VLD1 (R15), [V0.B16] - ADD $-16, R9, R15 - VST1 [V0.B16], (R15) - JMP copy_5_end + FMOVQ (R13), F0 + FMOVQ F0, (R9) + ADD $0x10, R13, R13 + ADD $0x10, R9, R9 + SUBS $0x10, R14, R14 + BHS copy_5_loop + ADD R14, R13, R13 + ADD $16, R13, R13 + ADD R14, R9, R9 + ADD $16, R9, R9 + FMOVQ -16(R13), F0 + FMOVQ F0, -16(R9) + JMP copy_5_end copy_5_small: - CMP $0x03, R0 + CMP $0x03, R1 BEQ copy_5_move_3 BLO copy_5_move_1or2 - CMP $0x08, R0 + CMP $0x08, R1 BLO copy_5_move_4through7 JMP copy_5_move_8through16 copy_5_move_1or2: MOVBU (R13), R16 BFI $0, R16, $8, R14 - ADD R0, R13, R15 + ADD R1, R13, R15 MOVBU -1(R15), R16 BFI $0, R16, $8, R4 MOVB R14, (R9) - ADD R0, R9, R15 + ADD R1, R9, R15 MOVB R4, -1(R15) - ADD R0, R13, R13 - ADD R0, R9, R9 + ADD R1, R13, R13 + ADD R1, R9, R9 JMP copy_5_end copy_5_move_3: @@ -1852,76 +2076,95 @@ copy_5_move_3: BFI $0, R16, $8, R4 MOVH R14, (R9) MOVB R4, 2(R9) - ADD R0, R13, R13 - ADD R0, R9, R9 + ADD R1, R13, R13 + ADD R1, R9, R9 JMP copy_5_end copy_5_move_4through7: MOVWU (R13), R14 - ADD R0, R13, R15 + ADD R1, R13, R15 MOVWU -4(R15), R4 MOVW R14, (R9) - ADD R0, R9, R15 + ADD R1, R9, R15 MOVW R4, -4(R15) - ADD R0, R13, R13 - ADD R0, R9, R9 + ADD R1, R13, R13 + ADD R1, R9, R9 JMP copy_5_end copy_5_move_8through16: MOVD (R13), R14 - ADD R0, R13, R15 + ADD R1, R13, R15 MOVD -8(R15), R4 MOVD R14, (R9) - ADD R0, R9, R15 + ADD R1, R9, R15 MOVD R4, -8(R15) - ADD R0, R13, R13 - ADD R0, R9, R9 + ADD R1, R13, R13 + ADD R1, R9, R9 copy_5_end: - ADD R0, R11, R11 - SUB R0, R12, R12 + ADD R1, R11, R11 + SUB R1, R21, R21 // Copy match from the current buffer copy_match: - MOVD R9, R0 - SUB R1, R0, R0 + MOVD R9, R1 + SUB R20, R1, R1 // ml <= mo - CMP R1, R12 + CMP R20, R21 BHI copy_overlapping_match // Copy non-overlapping match - ADD R12, R11, R11 - MOVD R9, R1 - ADD R12, R9, R9 + ADD R21, R11, R11 + FLDPQ (R1), (F0, F1) + FSTPQ (F0, F1), (R9) + CMP $0x20, R21 + BHI copy_2_long + ADD R21, R9, R9 + JMP handle_loop + +copy_2_long: + ADD $32, R9, R12 + ADD R21, R9, R9 + ADD $0x20, R1, R1 + SUB $0x20, R21, R21 copy_2: - VLD1 (R0), [V0.B16] - VST1 [V0.B16], (R1) - ADD $0x10, R0, R0 - ADD $0x10, R1, R1 - SUBS $0x10, R12, R12 - BHI copy_2 - JMP handle_loop + FLDPQ (R1), (F0, F1) + FSTPQ (F0, F1), (R12) + ADD $0x20, R1, R1 + ADD $0x20, R12, R12 + SUBS $0x20, R21, R21 + BHI copy_2 + JMP handle_loop // Copy overlapping match copy_overlapping_match: - ADD R12, R11, R11 + ADD R21, R11, R11 + CMP $0x10, R20 + BLO copy_slow_3 + MOVD R9, R12 + ADD R21, R9, R9 + +copy_3: + FMOVQ (R1), F0 + FMOVQ F0, (R12) + ADD $0x10, R1, R1 + ADD $0x10, R12, R12 + SUBS $0x10, R21, R21 + BHI copy_3 + JMP handle_loop copy_slow_3: - MOVBU (R0), R16 - BFI $0, R16, $8, R1 - MOVB R1, (R9) - ADD $1, R0, R0 + MOVBU (R1), R12 + MOVB R12, (R9) + ADD $1, R1, R1 ADD $1, R9, R9 - SUBS $1, R12, R12 + SUBS $1, R21, R21 BNE copy_slow_3 handle_loop: - MOVD ctx+16(FP), R0 - MOVD 96(R0), R16 - SUBS $1, R16, R16 - MOVD R16, 96(R0) + SUBS $1, R23, R23 BPL sequenceDecs_decodeSync_amd64_main_loop loop_finished: @@ -1930,6 +2173,16 @@ loop_finished: MOVB R3, 40(R0) MOVD R5, 32(R0) + // s.seqSize += outPosition - ctx.outPosition + MOVD ctx+16(FP), R0 + MOVD s+0(FP), R1 + MOVD R11, R2 + MOVD 136(R0), R16 + SUB R16, R2, R2 + MOVD 256(R1), R16 + ADD R2, R16, R16 + MOVD R16, 256(R1) + // Update the context MOVD ctx+16(FP), R0 MOVD R11, 136(R0) @@ -1944,9 +2197,8 @@ loop_finished: // Return with match length error sequenceDecs_decodeSync_amd64_error_match_len_ofs_mismatch: - MOVD 24(RSP), R0 MOVD ctx+16(FP), R1 - MOVD R0, 216(R1) + MOVD R21, 216(R1) MOVD $0x00000001, R16 MOVD R16, ret+24(FP) RET @@ -1954,8 +2206,7 @@ sequenceDecs_decodeSync_amd64_error_match_len_ofs_mismatch: // Return with match too long error sequenceDecs_decodeSync_amd64_error_match_len_too_big: MOVD ctx+16(FP), R0 - MOVD 24(RSP), R1 - MOVD R1, 216(R0) + MOVD R21, 216(R0) MOVD $0x00000002, R16 MOVD R16, ret+24(FP) RET @@ -1963,8 +2214,7 @@ sequenceDecs_decodeSync_amd64_error_match_len_too_big: // Return with match offset too long error error_match_off_too_big: MOVD ctx+16(FP), R0 - MOVD 16(RSP), R1 - MOVD R1, 224(R0) + MOVD R20, 224(R0) MOVD R11, 136(R0) MOVD $0x00000003, R16 MOVD R16, ret+24(FP) @@ -1973,8 +2223,7 @@ error_match_off_too_big: // Return with not enough literals error error_not_enough_literals: MOVD ctx+16(FP), R0 - MOVD 32(RSP), R1 - MOVD R1, 208(R0) + MOVD R19, 208(R0) MOVD $0x00000004, R16 MOVD R16, ret+24(FP) RET @@ -1988,10 +2237,8 @@ error_overread: // Return with not enough output space error error_not_enough_space: MOVD ctx+16(FP), R0 - MOVD 32(RSP), R1 - MOVD R1, 208(R0) - MOVD 24(RSP), R1 - MOVD R1, 216(R0) + MOVD R19, 208(R0) + MOVD R21, 216(R0) MOVD R11, 136(R0) MOVD $0x00000005, R16 MOVD R16, ret+24(FP) @@ -2001,56 +2248,50 @@ error_not_enough_space: // func sequenceDecs_decodeSync_safe_amd64(s *sequenceDecs, br *bitReader, ctx *decodeSyncAsmContext) int // Requires: CMOV, SSE -TEXT ·sequenceDecs_decodeSync_safe_arm64(SB), $64-32 +TEXT ·sequenceDecs_decodeSync_safe_arm64(SB), $96-32 MOVD br+8(FP), R1 MOVD 24(R1), R2 MOVBU 40(R1), R3 - MOVD (R1), R0 + MOVD (R1), R22 MOVD 32(R1), R5 - ADD R5, R0, R0 - MOVD R0, 8(RSP) - MOVD ctx+16(FP), R0 - MOVD 72(R0), R6 - MOVD 80(R0), R7 - MOVD 88(R0), R8 - MOVD $0, R1 - MOVD R1, 16(RSP) + ADD R5, R22, R22 + MOVD ctx+16(FP), R25 + MOVD 72(R25), R6 + MOVD 80(R25), R7 + MOVD 88(R25), R8 + MOVD (R25), R17 + MOVD 24(R25), R1 MOVD R1, 24(RSP) + MOVD 48(R25), R1 MOVD R1, 32(RSP) - MOVD 112(R0), R9 - MOVD 128(R0), R1 - MOVD R1, 40(RSP) - MOVD 144(R0), R10 - MOVD 136(R0), R11 - MOVD 200(R0), R1 - MOVD R1, 64(RSP) - MOVD 176(R0), R1 - MOVD R1, 56(RSP) - MOVD 184(R0), R0 - MOVD R0, 48(RSP) - MOVD 48(RSP), R0 - MOVD 56(RSP), R16 - ADD R0, R16, R16 - MOVD R16, 56(RSP) + MOVD 96(R25), R23 + MOVD $0, R20 + MOVD R20, R21 + MOVD R20, R19 + MOVD 112(R25), R9 + MOVD 128(R25), R24 + MOVD 144(R25), R10 + MOVD 136(R25), R11 + MOVD 200(R25), R1 + MOVD R1, 96(RSP) + MOVD 176(R25), R26 + MOVD 184(R25), R25 + ADD R25, R26, R26 // Calculate pointer to s.out[cap(s.out)] (a past-end pointer) - MOVD 40(RSP), R16 - ADD R9, R16, R16 - MOVD R16, 40(RSP) + ADD R9, R24, R24 // outBase += outPosition - ADD R11, R9, R9 + ADD R11, R9, R9 + PCALIGN $0x40 sequenceDecs_decodeSync_safe_amd64_main_loop: - MOVD 8(RSP), R12 - // Fill bitreader to have enough for the offset and match length. CMP $0x08, R5 BLT sequenceDecs_decodeSync_safe_amd64_fill_byte_by_byte - MOVD R3, R0 - LSR $0x03, R0, R0 - SUB R0, R12, R12 - MOVD (R12), R2 + LSR $0x03, R3, R0 + SUB R0, R22, R22 + MOVD (R22), R2 SUB R0, R5, R5 AND $0x07, R3, R3 JMP sequenceDecs_decodeSync_safe_amd64_fill_end @@ -2061,10 +2302,10 @@ sequenceDecs_decodeSync_safe_amd64_fill_byte_by_byte: CMP $0x07, R3 BLE sequenceDecs_decodeSync_safe_amd64_fill_end LSL $0x08, R2, R2 - SUB $0x01, R12, R12 + SUB $0x01, R22, R22 SUB $0x01, R5, R5 SUB $0x08, R3, R3 - MOVBU (R12), R0 + MOVBU (R22), R0 ORR R0, R2, R2 JMP sequenceDecs_decodeSync_safe_amd64_fill_byte_by_byte @@ -2075,55 +2316,34 @@ sequenceDecs_decodeSync_safe_amd64_fill_check_overread: sequenceDecs_decodeSync_safe_amd64_fill_end: // Update offset MOVD R8, R0 - MOVD R3, R1 - MOVD R2, R13 - LSL R1, R13, R13 - UBFX $8, R0, $8, R16 - BFI $0, R16, $8, R1 + LSL R3, R2, R13 + LSR $0x01, R13, R13 + UBFX $8, R0, $8, R1 LSR $0x20, R0, R0 - TST R1, R1 - BEQ sequenceDecs_decodeSync_safe_amd64_of_update_zero ADD R1, R3, R3 - CMP $0x40, R3 - BHI sequenceDecs_decodeSync_safe_amd64_of_update_zero - CMP $0x40, R1 - BHS sequenceDecs_decodeSync_safe_amd64_of_update_zero - NEG R1, R1 + EOR $0x3f, R1, R1 LSR R1, R13, R13 ADD R13, R0, R0 - -sequenceDecs_decodeSync_safe_amd64_of_update_zero: - MOVD R0, 16(RSP) + MOVD R0, R20 // Update match length MOVD R7, R0 - MOVD R3, R1 - MOVD R2, R13 - LSL R1, R13, R13 - UBFX $8, R0, $8, R16 - BFI $0, R16, $8, R1 + LSL R3, R2, R13 + LSR $0x01, R13, R13 + UBFX $8, R0, $8, R1 LSR $0x20, R0, R0 - TST R1, R1 - BEQ sequenceDecs_decodeSync_safe_amd64_ml_update_zero ADD R1, R3, R3 - CMP $0x40, R3 - BHI sequenceDecs_decodeSync_safe_amd64_ml_update_zero - CMP $0x40, R1 - BHS sequenceDecs_decodeSync_safe_amd64_ml_update_zero - NEG R1, R1 + EOR $0x3f, R1, R1 LSR R1, R13, R13 ADD R13, R0, R0 - -sequenceDecs_decodeSync_safe_amd64_ml_update_zero: - MOVD R0, 24(RSP) + MOVD R0, R21 // Fill bitreader to have enough for the remaining CMP $0x08, R5 BLT sequenceDecs_decodeSync_safe_amd64_fill_2_byte_by_byte - MOVD R3, R0 - LSR $0x03, R0, R0 - SUB R0, R12, R12 - MOVD (R12), R2 + LSR $0x03, R3, R0 + SUB R0, R22, R22 + MOVD (R22), R2 SUB R0, R5, R5 AND $0x07, R3, R3 JMP sequenceDecs_decodeSync_safe_amd64_fill_2_end @@ -2134,10 +2354,10 @@ sequenceDecs_decodeSync_safe_amd64_fill_2_byte_by_byte: CMP $0x07, R3 BLE sequenceDecs_decodeSync_safe_amd64_fill_2_end LSL $0x08, R2, R2 - SUB $0x01, R12, R12 + SUB $0x01, R22, R22 SUB $0x01, R5, R5 SUB $0x08, R3, R3 - MOVBU (R12), R0 + MOVBU (R22), R0 ORR R0, R2, R2 JMP sequenceDecs_decodeSync_safe_amd64_fill_2_byte_by_byte @@ -2148,130 +2368,89 @@ sequenceDecs_decodeSync_safe_amd64_fill_2_check_overread: sequenceDecs_decodeSync_safe_amd64_fill_2_end: // Update literal length MOVD R6, R0 - MOVD R3, R1 - MOVD R2, R13 - LSL R1, R13, R13 - UBFX $8, R0, $8, R16 - BFI $0, R16, $8, R1 + LSL R3, R2, R13 + LSR $0x01, R13, R13 + UBFX $8, R0, $8, R1 LSR $0x20, R0, R0 - TST R1, R1 - BEQ sequenceDecs_decodeSync_safe_amd64_ll_update_zero ADD R1, R3, R3 - CMP $0x40, R3 - BHI sequenceDecs_decodeSync_safe_amd64_ll_update_zero - CMP $0x40, R1 - BHS sequenceDecs_decodeSync_safe_amd64_ll_update_zero - NEG R1, R1 + EOR $0x3f, R1, R1 LSR R1, R13, R13 ADD R13, R0, R0 - -sequenceDecs_decodeSync_safe_amd64_ll_update_zero: - MOVD R0, 32(RSP) + MOVD R0, R19 // Fill bitreader for state updates - MOVD R12, 8(RSP) - MOVD R8, R0 - LSR $0x08, R0, R0 - MOVBU R0, R0 - MOVD ctx+16(FP), R1 - MOVD 96(R1), R16 - CMP $0x00, R16 - BEQ sequenceDecs_decodeSync_safe_amd64_skip_update + UBFX $8, R8, $8, R0 + CMP $0x00, R23 + BEQ sequenceDecs_decodeSync_safe_amd64_skip_update // Update Literal Length State MOVBU R6, R12 LSRW $0x10, R6, R6 - ADD R12, R3, R1 - MOVD R2, R13 - MOVD R1, R3 - NEG R1, R16 - ROR R16, R13, R13 - MOVD $0x00000001, R14 - BFI $0, R12, $8, R1 - LSLW R1, R14, R14 - SUBW $1, R14, R14 - AND R14, R13, R13 + LSL R3, R2, R13 + LSR $0x01, R13, R13 + ADD R12, R3, R3 + EOR $0x3f, R12, R12 + LSR R12, R13, R13 ADD R13, R6, R6 // Load ctx.llTable - MOVD ctx+16(FP), R1 - MOVD (R1), R1 - ADD R6<<3, R1, R15 - MOVD (R15), R6 + MOVD (R17)(R6<<3), R6 // Update Match Length State MOVBU R7, R12 LSRW $0x10, R7, R7 - ADD R12, R3, R1 - MOVD R2, R13 - MOVD R1, R3 - NEG R1, R16 - ROR R16, R13, R13 - MOVD $0x00000001, R14 - BFI $0, R12, $8, R1 - LSLW R1, R14, R14 - SUBW $1, R14, R14 - AND R14, R13, R13 + LSL R3, R2, R13 + LSR $0x01, R13, R13 + ADD R12, R3, R3 + EOR $0x3f, R12, R12 + LSR R12, R13, R13 ADD R13, R7, R7 // Load ctx.mlTable - MOVD ctx+16(FP), R1 - MOVD 24(R1), R1 - ADD R7<<3, R1, R15 - MOVD (R15), R7 + MOVD 24(RSP), R1 + MOVD (R1)(R7<<3), R7 // Update Offset State MOVBU R8, R12 LSRW $0x10, R8, R8 - ADD R12, R3, R1 - MOVD R2, R13 - MOVD R1, R3 - NEG R1, R16 - ROR R16, R13, R13 - MOVD $0x00000001, R14 - BFI $0, R12, $8, R1 - LSLW R1, R14, R14 - SUBW $1, R14, R14 - AND R14, R13, R13 + LSL R3, R2, R13 + LSR $0x01, R13, R13 + ADD R12, R3, R3 + EOR $0x3f, R12, R12 + LSR R12, R13, R13 ADD R13, R8, R8 // Load ctx.ofTable - MOVD ctx+16(FP), R1 - MOVD 48(R1), R1 - ADD R8<<3, R1, R15 - MOVD (R15), R8 + MOVD 32(RSP), R1 + MOVD (R1)(R8<<3), R8 sequenceDecs_decodeSync_safe_amd64_skip_update: // Adjust offset - MOVD s+0(FP), R1 - MOVD 16(RSP), R12 - CMP $0x01, R0 - BLS sequenceDecs_decodeSync_safe_amd64_adjust_offsetB_1_or_0 - ADD $144, R1, R15 - VLD1 (R15), [V0.B16] - MOVD R12, 144(R1) - ADD $152, R1, R15 - VST1 [V0.B16], (R15) - JMP sequenceDecs_decodeSync_safe_amd64_after_adjust + MOVD s+0(FP), R1 + CMP $0x01, R0 + BLS sequenceDecs_decodeSync_safe_amd64_adjust_offsetB_1_or_0 + FMOVQ 144(R1), F0 + MOVD R20, 144(R1) + FMOVQ F0, 152(R1) + JMP sequenceDecs_decodeSync_safe_amd64_after_adjust sequenceDecs_decodeSync_safe_amd64_adjust_offsetB_1_or_0: - MOVD 32(RSP), R16 - CMP $0x00000000, R16 - BNE sequenceDecs_decodeSync_safe_amd64_adjust_offset_maybezero - ADD $1, R12, R12 - JMP sequenceDecs_decodeSync_safe_amd64_adjust_offset_nonzero + CMP $0x00000000, R19 + BNE sequenceDecs_decodeSync_safe_amd64_adjust_offset_maybezero + ADD $1, R20, R20 + JMP sequenceDecs_decodeSync_safe_amd64_adjust_offset_nonzero sequenceDecs_decodeSync_safe_amd64_adjust_offset_maybezero: - TST R12, R12 + TST R20, R20 BNE sequenceDecs_decodeSync_safe_amd64_adjust_offset_nonzero - MOVD 144(R1), R12 + MOVD 144(R1), R20 JMP sequenceDecs_decodeSync_safe_amd64_after_adjust sequenceDecs_decodeSync_safe_amd64_adjust_offset_nonzero: - MOVD R12, R0 + MOVD R20, R0 MOVD $0, R13 MOVD $-1, R14 - CMP $0x03, R12 + CMP $0x03, R20 CSEL EQ, R13, R0, R0 CSEL EQ, R14, R13, R13 ADD R0<<3, R1, R15 @@ -2281,7 +2460,7 @@ sequenceDecs_decodeSync_safe_amd64_adjust_offset_nonzero: MOVD $0x00000001, R13 sequenceDecs_decodeSync_safe_amd64_adjust_temp_valid: - CMP $0x01, R12 + CMP $0x01, R20 BEQ sequenceDecs_decodeSync_safe_amd64_adjust_skip MOVD 152(R1), R0 MOVD R0, 160(R1) @@ -2290,86 +2469,70 @@ sequenceDecs_decodeSync_safe_amd64_adjust_skip: MOVD 144(R1), R0 MOVD R0, 152(R1) MOVD R13, 144(R1) - MOVD R13, R12 + MOVD R13, R20 sequenceDecs_decodeSync_safe_amd64_after_adjust: - MOVD R12, 16(RSP) - // Check values - MOVD 24(RSP), R0 - MOVD 32(RSP), R1 - ADD R1, R0, R13 - MOVD s+0(FP), R14 - MOVD 256(R14), R16 - ADD R13, R16, R16 - MOVD R16, 256(R14) MOVD ctx+16(FP), R13 MOVD 104(R13), R16 - SUBS R1, R16, R16 + SUBS R19, R16, R16 MOVD R16, 104(R13) BMI error_not_enough_literals - CMP $0x00020002, R0 + CMP $0x00020002, R21 BHI sequenceDecs_decodeSync_safe_amd64_error_match_len_too_big - TST R12, R12 + TST R20, R20 BNE sequenceDecs_decodeSync_safe_amd64_match_len_ofs_ok - TST R0, R0 + TST R21, R21 BNE sequenceDecs_decodeSync_safe_amd64_error_match_len_ofs_mismatch sequenceDecs_decodeSync_safe_amd64_match_len_ofs_ok: - MOVD 32(RSP), R0 - MOVD 16(RSP), R1 - MOVD 24(RSP), R12 - // Check if we have enough space in s.out - ADD R12, R0, R13 - ADD R9, R13, R13 - MOVD 40(RSP), R16 - CMP R16, R13 - BHI error_not_enough_space + ADD R21, R19, R13 + ADD R9, R13, R13 + CMP R24, R13 + BHI error_not_enough_space // Copy literals - TST R0, R0 + TST R19, R19 BEQ check_offset - MOVD R0, R13 + MOVD R19, R13 SUBS $0x10, R13, R13 BLO copy_1_small copy_1_loop: - VLD1 (R10), [V0.B16] - VST1 [V0.B16], (R9) - ADD $0x10, R10, R10 - ADD $0x10, R9, R9 - SUBS $0x10, R13, R13 - BHS copy_1_loop - ADD R13, R10, R10 - ADD $16, R10, R10 - ADD R13, R9, R9 - ADD $16, R9, R9 - ADD $-16, R10, R15 - VLD1 (R15), [V0.B16] - ADD $-16, R9, R15 - VST1 [V0.B16], (R15) - JMP copy_1_end + FMOVQ (R10), F0 + FMOVQ F0, (R9) + ADD $0x10, R10, R10 + ADD $0x10, R9, R9 + SUBS $0x10, R13, R13 + BHS copy_1_loop + ADD R13, R10, R10 + ADD $16, R10, R10 + ADD R13, R9, R9 + ADD $16, R9, R9 + FMOVQ -16(R10), F0 + FMOVQ F0, -16(R9) + JMP copy_1_end copy_1_small: - CMP $0x03, R0 + CMP $0x03, R19 BEQ copy_1_move_3 BLO copy_1_move_1or2 - CMP $0x08, R0 + CMP $0x08, R19 BLO copy_1_move_4through7 JMP copy_1_move_8through16 copy_1_move_1or2: MOVBU (R10), R16 BFI $0, R16, $8, R13 - ADD R0, R10, R15 + ADD R19, R10, R15 MOVBU -1(R15), R16 BFI $0, R16, $8, R14 MOVB R13, (R9) - ADD R0, R9, R15 + ADD R19, R9, R15 MOVB R14, -1(R15) - ADD R0, R10, R10 - ADD R0, R9, R9 + ADD R19, R10, R10 + ADD R19, R9, R9 JMP copy_1_end copy_1_move_3: @@ -2378,158 +2541,153 @@ copy_1_move_3: BFI $0, R16, $8, R14 MOVH R13, (R9) MOVB R14, 2(R9) - ADD R0, R10, R10 - ADD R0, R9, R9 + ADD R19, R10, R10 + ADD R19, R9, R9 JMP copy_1_end copy_1_move_4through7: MOVWU (R10), R13 - ADD R0, R10, R15 + ADD R19, R10, R15 MOVWU -4(R15), R14 MOVW R13, (R9) - ADD R0, R9, R15 + ADD R19, R9, R15 MOVW R14, -4(R15) - ADD R0, R10, R10 - ADD R0, R9, R9 + ADD R19, R10, R10 + ADD R19, R9, R9 JMP copy_1_end copy_1_move_8through16: MOVD (R10), R13 - ADD R0, R10, R15 + ADD R19, R10, R15 MOVD -8(R15), R14 MOVD R13, (R9) - ADD R0, R9, R15 + ADD R19, R9, R15 MOVD R14, -8(R15) - ADD R0, R10, R10 - ADD R0, R9, R9 + ADD R19, R10, R10 + ADD R19, R9, R9 copy_1_end: - ADD R0, R11, R11 + ADD R19, R11, R11 // Malformed input if seq.mo > t+len(hist) || seq.mo > s.windowSize) check_offset: - MOVD R11, R0 - MOVD 48(RSP), R16 - ADD R16, R0, R0 - CMP R0, R1 + MOVD R11, R1 + ADD R25, R1, R1 + CMP R1, R20 BGT error_match_off_too_big - MOVD 64(RSP), R16 - CMP R16, R1 + MOVD 96(RSP), R16 + CMP R16, R20 BGT error_match_off_too_big // Copy match from history - MOVD R1, R0 - SUBS R11, R0, R0 + MOVD R20, R1 + SUBS R11, R1, R1 BLS copy_match - MOVD 56(RSP), R13 - SUB R0, R13, R13 - CMP R0, R12 + MOVD R26, R13 + SUB R1, R13, R13 + CMP R1, R21 BGT copy_all_from_history - MOVD R12, R0 - SUBS $0x10, R0, R0 + MOVD R21, R1 + SUBS $0x10, R1, R1 BLO copy_4_small copy_4_loop: - VLD1 (R13), [V0.B16] - VST1 [V0.B16], (R9) - ADD $0x10, R13, R13 - ADD $0x10, R9, R9 - SUBS $0x10, R0, R0 - BHS copy_4_loop - ADD R0, R13, R13 - ADD $16, R13, R13 - ADD R0, R9, R9 - ADD $16, R9, R9 - ADD $-16, R13, R15 - VLD1 (R15), [V0.B16] - ADD $-16, R9, R15 - VST1 [V0.B16], (R15) - JMP copy_4_end + FMOVQ (R13), F0 + FMOVQ F0, (R9) + ADD $0x10, R13, R13 + ADD $0x10, R9, R9 + SUBS $0x10, R1, R1 + BHS copy_4_loop + ADD R1, R13, R13 + ADD $16, R13, R13 + ADD R1, R9, R9 + ADD $16, R9, R9 + FMOVQ -16(R13), F0 + FMOVQ F0, -16(R9) + JMP copy_4_end copy_4_small: - CMP $0x03, R12 + CMP $0x03, R21 BEQ copy_4_move_3 - CMP $0x08, R12 + CMP $0x08, R21 BLO copy_4_move_4through7 JMP copy_4_move_8through16 copy_4_move_3: - MOVHU (R13), R0 + MOVHU (R13), R1 MOVBU 2(R13), R16 - BFI $0, R16, $8, R1 - MOVH R0, (R9) - MOVB R1, 2(R9) - ADD R12, R13, R13 - ADD R12, R9, R9 + BFI $0, R16, $8, R20 + MOVH R1, (R9) + MOVB R20, 2(R9) + ADD R21, R13, R13 + ADD R21, R9, R9 JMP copy_4_end copy_4_move_4through7: - MOVWU (R13), R0 - ADD R12, R13, R15 - MOVWU -4(R15), R1 - MOVW R0, (R9) - ADD R12, R9, R15 - MOVW R1, -4(R15) - ADD R12, R13, R13 - ADD R12, R9, R9 + MOVWU (R13), R1 + ADD R21, R13, R15 + MOVWU -4(R15), R12 + MOVW R1, (R9) + ADD R21, R9, R15 + MOVW R12, -4(R15) + ADD R21, R13, R13 + ADD R21, R9, R9 JMP copy_4_end copy_4_move_8through16: - MOVD (R13), R0 - ADD R12, R13, R15 - MOVD -8(R15), R1 - MOVD R0, (R9) - ADD R12, R9, R15 - MOVD R1, -8(R15) - ADD R12, R13, R13 - ADD R12, R9, R9 + MOVD (R13), R1 + ADD R21, R13, R15 + MOVD -8(R15), R12 + MOVD R1, (R9) + ADD R21, R9, R15 + MOVD R12, -8(R15) + ADD R21, R13, R13 + ADD R21, R9, R9 copy_4_end: - ADD R12, R11, R11 + ADD R21, R11, R11 JMP handle_loop JMP loop_finished copy_all_from_history: - MOVD R0, R14 + MOVD R1, R14 SUBS $0x10, R14, R14 BLO copy_5_small copy_5_loop: - VLD1 (R13), [V0.B16] - VST1 [V0.B16], (R9) - ADD $0x10, R13, R13 - ADD $0x10, R9, R9 - SUBS $0x10, R14, R14 - BHS copy_5_loop - ADD R14, R13, R13 - ADD $16, R13, R13 - ADD R14, R9, R9 - ADD $16, R9, R9 - ADD $-16, R13, R15 - VLD1 (R15), [V0.B16] - ADD $-16, R9, R15 - VST1 [V0.B16], (R15) - JMP copy_5_end + FMOVQ (R13), F0 + FMOVQ F0, (R9) + ADD $0x10, R13, R13 + ADD $0x10, R9, R9 + SUBS $0x10, R14, R14 + BHS copy_5_loop + ADD R14, R13, R13 + ADD $16, R13, R13 + ADD R14, R9, R9 + ADD $16, R9, R9 + FMOVQ -16(R13), F0 + FMOVQ F0, -16(R9) + JMP copy_5_end copy_5_small: - CMP $0x03, R0 + CMP $0x03, R1 BEQ copy_5_move_3 BLO copy_5_move_1or2 - CMP $0x08, R0 + CMP $0x08, R1 BLO copy_5_move_4through7 JMP copy_5_move_8through16 copy_5_move_1or2: MOVBU (R13), R16 BFI $0, R16, $8, R14 - ADD R0, R13, R15 + ADD R1, R13, R15 MOVBU -1(R15), R16 BFI $0, R16, $8, R4 MOVB R14, (R9) - ADD R0, R9, R15 + ADD R1, R9, R15 MOVB R4, -1(R15) - ADD R0, R13, R13 - ADD R0, R9, R9 + ADD R1, R13, R13 + ADD R1, R9, R9 JMP copy_5_end copy_5_move_3: @@ -2538,140 +2696,147 @@ copy_5_move_3: BFI $0, R16, $8, R4 MOVH R14, (R9) MOVB R4, 2(R9) - ADD R0, R13, R13 - ADD R0, R9, R9 + ADD R1, R13, R13 + ADD R1, R9, R9 JMP copy_5_end copy_5_move_4through7: MOVWU (R13), R14 - ADD R0, R13, R15 + ADD R1, R13, R15 MOVWU -4(R15), R4 MOVW R14, (R9) - ADD R0, R9, R15 + ADD R1, R9, R15 MOVW R4, -4(R15) - ADD R0, R13, R13 - ADD R0, R9, R9 + ADD R1, R13, R13 + ADD R1, R9, R9 JMP copy_5_end copy_5_move_8through16: MOVD (R13), R14 - ADD R0, R13, R15 + ADD R1, R13, R15 MOVD -8(R15), R4 MOVD R14, (R9) - ADD R0, R9, R15 + ADD R1, R9, R15 MOVD R4, -8(R15) - ADD R0, R13, R13 - ADD R0, R9, R9 + ADD R1, R13, R13 + ADD R1, R9, R9 copy_5_end: - ADD R0, R11, R11 - SUB R0, R12, R12 + ADD R1, R11, R11 + SUB R1, R21, R21 // Copy match from the current buffer copy_match: - MOVD R9, R0 - SUB R1, R0, R0 + MOVD R9, R1 + SUB R20, R1, R1 // ml <= mo - CMP R1, R12 + CMP R20, R21 BHI copy_overlapping_match // Copy non-overlapping match - ADD R12, R11, R11 - MOVD R12, R1 - SUBS $0x10, R1, R1 + ADD R21, R11, R11 + MOVD R21, R12 + SUBS $0x10, R12, R12 BLO copy_2_small copy_2_loop: - VLD1 (R0), [V0.B16] - VST1 [V0.B16], (R9) - ADD $0x10, R0, R0 - ADD $0x10, R9, R9 - SUBS $0x10, R1, R1 - BHS copy_2_loop - ADD R1, R0, R0 - ADD $16, R0, R0 - ADD R1, R9, R9 - ADD $16, R9, R9 - ADD $-16, R0, R15 - VLD1 (R15), [V0.B16] - ADD $-16, R9, R15 - VST1 [V0.B16], (R15) - JMP copy_2_end + FMOVQ (R1), F0 + FMOVQ F0, (R9) + ADD $0x10, R1, R1 + ADD $0x10, R9, R9 + SUBS $0x10, R12, R12 + BHS copy_2_loop + ADD R12, R1, R1 + ADD $16, R1, R1 + ADD R12, R9, R9 + ADD $16, R9, R9 + FMOVQ -16(R1), F0 + FMOVQ F0, -16(R9) + JMP copy_2_end copy_2_small: - CMP $0x03, R12 + CMP $0x03, R21 BEQ copy_2_move_3 BLO copy_2_move_1or2 - CMP $0x08, R12 + CMP $0x08, R21 BLO copy_2_move_4through7 JMP copy_2_move_8through16 copy_2_move_1or2: - MOVBU (R0), R16 - BFI $0, R16, $8, R1 - ADD R12, R0, R15 + MOVBU (R1), R16 + BFI $0, R16, $8, R12 + ADD R21, R1, R15 MOVBU -1(R15), R16 BFI $0, R16, $8, R13 - MOVB R1, (R9) - ADD R12, R9, R15 + MOVB R12, (R9) + ADD R21, R9, R15 MOVB R13, -1(R15) - ADD R12, R0, R0 - ADD R12, R9, R9 + ADD R21, R1, R1 + ADD R21, R9, R9 JMP copy_2_end copy_2_move_3: - MOVHU (R0), R1 - MOVBU 2(R0), R16 + MOVHU (R1), R12 + MOVBU 2(R1), R16 BFI $0, R16, $8, R13 - MOVH R1, (R9) + MOVH R12, (R9) MOVB R13, 2(R9) - ADD R12, R0, R0 - ADD R12, R9, R9 + ADD R21, R1, R1 + ADD R21, R9, R9 JMP copy_2_end copy_2_move_4through7: - MOVWU (R0), R1 - ADD R12, R0, R15 + MOVWU (R1), R12 + ADD R21, R1, R15 MOVWU -4(R15), R13 - MOVW R1, (R9) - ADD R12, R9, R15 + MOVW R12, (R9) + ADD R21, R9, R15 MOVW R13, -4(R15) - ADD R12, R0, R0 - ADD R12, R9, R9 + ADD R21, R1, R1 + ADD R21, R9, R9 JMP copy_2_end copy_2_move_8through16: - MOVD (R0), R1 - ADD R12, R0, R15 + MOVD (R1), R12 + ADD R21, R1, R15 MOVD -8(R15), R13 - MOVD R1, (R9) - ADD R12, R9, R15 + MOVD R12, (R9) + ADD R21, R9, R15 MOVD R13, -8(R15) - ADD R12, R0, R0 - ADD R12, R9, R9 + ADD R21, R1, R1 + ADD R21, R9, R9 copy_2_end: JMP handle_loop // Copy overlapping match copy_overlapping_match: - ADD R12, R11, R11 + ADD R21, R11, R11 + CMP $0x10, R20 + BLO copy_slow_3 + +copy_3_blocks: + FMOVQ (R1), F0 + FMOVQ F0, (R9) + ADD $0x10, R1, R1 + ADD $0x10, R9, R9 + SUB $0x10, R21, R21 + CMP $0x10, R21 + BHS copy_3_blocks + TST R21, R21 + BEQ handle_loop copy_slow_3: - MOVBU (R0), R16 - BFI $0, R16, $8, R1 - MOVB R1, (R9) - ADD $1, R0, R0 + MOVBU (R1), R12 + MOVB R12, (R9) + ADD $1, R1, R1 ADD $1, R9, R9 - SUBS $1, R12, R12 + SUBS $1, R21, R21 BNE copy_slow_3 handle_loop: - MOVD ctx+16(FP), R0 - MOVD 96(R0), R16 - SUBS $1, R16, R16 - MOVD R16, 96(R0) + SUBS $1, R23, R23 BPL sequenceDecs_decodeSync_safe_amd64_main_loop loop_finished: @@ -2680,6 +2845,16 @@ loop_finished: MOVB R3, 40(R0) MOVD R5, 32(R0) + // s.seqSize += outPosition - ctx.outPosition + MOVD ctx+16(FP), R0 + MOVD s+0(FP), R1 + MOVD R11, R2 + MOVD 136(R0), R16 + SUB R16, R2, R2 + MOVD 256(R1), R16 + ADD R2, R16, R16 + MOVD R16, 256(R1) + // Update the context MOVD ctx+16(FP), R0 MOVD R11, 136(R0) @@ -2694,9 +2869,8 @@ loop_finished: // Return with match length error sequenceDecs_decodeSync_safe_amd64_error_match_len_ofs_mismatch: - MOVD 24(RSP), R0 MOVD ctx+16(FP), R1 - MOVD R0, 216(R1) + MOVD R21, 216(R1) MOVD $0x00000001, R16 MOVD R16, ret+24(FP) RET @@ -2704,8 +2878,7 @@ sequenceDecs_decodeSync_safe_amd64_error_match_len_ofs_mismatch: // Return with match too long error sequenceDecs_decodeSync_safe_amd64_error_match_len_too_big: MOVD ctx+16(FP), R0 - MOVD 24(RSP), R1 - MOVD R1, 216(R0) + MOVD R21, 216(R0) MOVD $0x00000002, R16 MOVD R16, ret+24(FP) RET @@ -2713,8 +2886,7 @@ sequenceDecs_decodeSync_safe_amd64_error_match_len_too_big: // Return with match offset too long error error_match_off_too_big: MOVD ctx+16(FP), R0 - MOVD 16(RSP), R1 - MOVD R1, 224(R0) + MOVD R20, 224(R0) MOVD R11, 136(R0) MOVD $0x00000003, R16 MOVD R16, ret+24(FP) @@ -2723,8 +2895,7 @@ error_match_off_too_big: // Return with not enough literals error error_not_enough_literals: MOVD ctx+16(FP), R0 - MOVD 32(RSP), R1 - MOVD R1, 208(R0) + MOVD R19, 208(R0) MOVD $0x00000004, R16 MOVD R16, ret+24(FP) RET @@ -2738,10 +2909,8 @@ error_overread: // Return with not enough output space error error_not_enough_space: MOVD ctx+16(FP), R0 - MOVD 32(RSP), R1 - MOVD R1, 208(R0) - MOVD 24(RSP), R1 - MOVD R1, 216(R0) + MOVD R19, 208(R0) + MOVD R21, 216(R0) MOVD R11, 136(R0) MOVD $0x00000005, R16 MOVD R16, ret+24(FP) diff --git a/vendor/github.com/klauspost/compress/zstd/seqdec_asm.go b/vendor/github.com/klauspost/compress/zstd/seqdec_asm.go index 42ce5de..58ac876 100644 --- a/vendor/github.com/klauspost/compress/zstd/seqdec_asm.go +++ b/vendor/github.com/klauspost/compress/zstd/seqdec_asm.go @@ -1,4 +1,4 @@ -//go:build (amd64 || arm64) && !appengine && !noasm && gc +//go:build (amd64 || arm64) && !noasm && gc package zstd @@ -55,6 +55,9 @@ type executeAsmContext struct { outPosition int litPosition int windowSize int + // prefetch enables the match-source prefetch in the execute loop; see + // sequenceDecs.useTwoPass. + prefetch bool } const noError = 0 @@ -80,12 +83,12 @@ const errorOverread = 6 // useSafeDecodeSync reports whether decodeSyncSimple must use the bounds-exact // ("safe") copy variants for the current buffer geometry. // -// When the output and literal buffers have compressedBlockOverAlloc (16) -// bytes of slack past their logical use, the assembly may use extended -// memory copies that read and write in 16-byte blocks, overrunning the end -// of a literal run or match by up to 15 bytes. Otherwise it must use the -// bounds-exact ("safe") copies. This mirrors the analogous, always-dynamic -// selection in executeSimple below. +// When the output and literal buffers have compressedBlockOverAlloc bytes of +// slack past their logical use, the assembly may use extended memory copies +// that read and write whole blocks, overrunning the end of a literal run or +// match by up to compressedBlockOverAlloc-1 bytes; an empty literal run +// still copies one 16-byte block past its position. Otherwise it must use the bounds-exact ("safe") copies. +// This mirrors the analogous, always-dynamic selection in executeSimple below. // // The unsafe copies were disabled in #644 (2022) as a mitigation for a // crash, but that crash's root cause — an unguarded bitReader overread that @@ -94,10 +97,15 @@ const errorOverread = 6 // See #1168. An asan-instrumented fuzz job (see .github/workflows/go.yml) // covers the extended-copy path, which -race and plain fuzzing cannot. func (s *sequenceDecs) useSafeDecodeSync() bool { - if s.maxSyncLen == 0 && cap(s.out)-len(s.out) < maxCompressedBlockSizeAlloc { + // A block never produces more than maxBlockSize bytes. + maxBlockSize := min(s.windowSize, maxCompressedBlockSize) + if s.maxSyncLen == 0 && cap(s.out)-len(s.out) < maxBlockSize+compressedBlockOverAlloc { return true } - if s.maxSyncLen > 0 && cap(s.out)-len(s.out)-compressedBlockOverAlloc < int(s.maxSyncLen) { + // The block, not the rest of the frame, must fit with the slack: a + // buffer sized exactly to the frame needs the safe copies only for the + // final block(s). + if s.maxSyncLen > 0 && cap(s.out)-len(s.out)-compressedBlockOverAlloc < min(int(s.maxSyncLen), maxBlockSize) { return true } if cap(s.literals) < len(s.literals)+compressedBlockOverAlloc { @@ -111,7 +119,8 @@ func (s *sequenceDecs) decodeSyncSimple(hist []byte) (bool, error) { if len(s.dict) > 0 { return false, nil } - if s.maxSyncLen == 0 && cap(s.out)-len(s.out) < maxCompressedBlockSize { + maxBlockSize := min(s.windowSize, maxCompressedBlockSize) + if s.maxSyncLen == 0 && cap(s.out)-len(s.out) < maxBlockSize { return false, nil } @@ -119,8 +128,6 @@ func (s *sequenceDecs) decodeSyncSimple(hist []byte) (bool, error) { br := s.br - maxBlockSize := min(s.windowSize, maxCompressedBlockSize) - ctx := decodeSyncAsmContext{ llTable: s.litLengths.fse.dt[:maxTablesize], mlTable: s.matchLengths.fse.dt[:maxTablesize], @@ -153,7 +160,7 @@ func (s *sequenceDecs) decodeSyncSimple(hist []byte) (bool, error) { case errorMatchOffTooBig: return true, fmt.Errorf("match offset (%d) bigger than current history (%d)", - ctx.mo, ctx.outPosition+len(hist)-startSize) + ctx.mo, ctx.outPosition-startSize) case errorNotEnoughLiterals: return true, fmt.Errorf("unexpected literal count, want %d bytes, but only %d is available", @@ -266,8 +273,10 @@ func (s *sequenceDecs) decode(seqs []seqVals) error { // executeSimple handles cases when dictionary is not used. func (s *sequenceDecs) executeSimple(seqs []seqVals, hist []byte) error { - // Ensure we have enough output size... - if len(s.out)+s.seqSize+compressedBlockOverAlloc > cap(s.out) { + // Grow only if the block does not fit. Lacking just the slack is + // handled by the safe copies below, so a buffer sized exactly to the + // frame is not reallocated and copied on its last block. + if len(s.out)+s.seqSize > cap(s.out) { addBytes := s.seqSize + len(s.out) + compressedBlockOverAlloc s.out = append(s.out, make([]byte, addBytes)...) s.out = s.out[:len(s.out)-addBytes] @@ -289,10 +298,12 @@ func (s *sequenceDecs) executeSimple(seqs []seqVals, hist []byte) error { litPosition: 0, literals: s.literals, windowSize: s.windowSize, + prefetch: s.useTwoPass(), } - // useSafe avoids overwriting the output buffer when the literals slice has - // not been allocated with the required over-allocation slack. - useSafe := cap(s.literals) < len(s.literals)+compressedBlockOverAlloc + // useSafe avoids writing past either buffer when the literals or the + // output lack the extended copies' over-allocation slack. + useSafe := cap(s.literals) < len(s.literals)+compressedBlockOverAlloc || + cap(out) < len(out)+compressedBlockOverAlloc ok := executeSimpleAsm(&ctx, useSafe) if !ok { diff --git a/vendor/github.com/klauspost/compress/zstd/seqdec_generic.go b/vendor/github.com/klauspost/compress/zstd/seqdec_generic.go index 8a3db6b..7ac4a79 100644 --- a/vendor/github.com/klauspost/compress/zstd/seqdec_generic.go +++ b/vendor/github.com/klauspost/compress/zstd/seqdec_generic.go @@ -1,10 +1,17 @@ -//go:build (!amd64 && !arm64) || appengine || !gc || noasm +//go:build (!amd64 && !arm64) || !gc || noasm package zstd import ( "fmt" "io" + "math" +) + +// See seqdec_arm64.go; the pure Go decoder has neither path. +var ( + twoPassMinFarShare = 257 // never: the share is at most 256 + decodeTwoPassMinWindow = math.MaxInt ) // decode sequences from the stream with the provided history but without dictionary. @@ -14,12 +21,17 @@ func (s *sequenceDecs) decodeSyncSimple(hist []byte) (bool, error) { // decode sequences from the stream without the provided history. func (s *sequenceDecs) decode(seqs []seqVals) error { + // The bit reader and repeat offsets are held in locals so they stay in + // registers; they are written back on success. br := s.br + in, bs := br.in, br.state() + prev0, prev1, prev2 := s.prevOffset[0], s.prevOffset[1], s.prevOffset[2] + maxBits := s.maxBits + seqSize := 0 // Grab full sizes tables, to avoid bounds checks. llTable, mlTable, ofTable := s.litLengths.fse.dt[:maxTablesize], s.matchLengths.fse.dt[:maxTablesize], s.offsets.fse.dt[:maxTablesize] llState, mlState, ofState := s.litLengths.state.state, s.matchLengths.state.state, s.offsets.state.state - s.seqSize = 0 litRemain := len(s.literals) maxBlockSize := maxCompressedBlockSize @@ -27,75 +39,74 @@ func (s *sequenceDecs) decode(seqs []seqVals) error { maxBlockSize = s.windowSize } for i := range seqs { - var ll, mo, ml int - if br.cursor > 4+((maxOffsetBits+16+16)>>3) { - // inlined function: - // ll, mo, ml = s.nextFast(br, llState, mlState, ofState) - - // Final will not read from stream. - var llB, mlB, moB uint8 - ll, llB = llState.final() - ml, mlB = mlState.final() - mo, moB = ofState.final() - - // extra bits are stored in reverse order. - br.fillFast() - mo += br.getBits(moB) - if s.maxBits > 32 { - br.fillFast() + if bs.bitsRead > 64 { + if debugDecoder { + printf("reading sequence %d, exceeded available data\n", i) } - ml += br.getBits(mlB) - ll += br.getBits(llB) - - if moB > 1 { - s.prevOffset[2] = s.prevOffset[1] - s.prevOffset[1] = s.prevOffset[0] - s.prevOffset[0] = mo - } else { - // mo = s.adjustOffset(mo, ll, moB) - // Inlined for rather big speedup - if ll == 0 { - // There is an exception though, when current sequence's literals_length = 0. - // In this case, repeated offsets are shifted by one, so an offset_value of 1 means Repeated_Offset2, - // an offset_value of 2 means Repeated_Offset3, and an offset_value of 3 means Repeated_Offset1 - 1_byte. - mo++ - } - - if mo == 0 { - mo = s.prevOffset[0] - } else { - var temp int - if mo == 3 { - temp = s.prevOffset[0] - 1 - } else { - temp = s.prevOffset[mo] - } - - if temp == 0 { - // 0 is not valid; input is corrupted; force offset to 1 - println("WARNING: temp was 0") - temp = 1 - } - - if mo != 1 { - s.prevOffset[2] = s.prevOffset[1] - } - s.prevOffset[1] = s.prevOffset[0] - s.prevOffset[0] = temp - mo = temp - } - } - br.fillFast() - } else { - if br.overread() { - if debugDecoder { - printf("reading sequence %d, exceeded available data\n", i) - } - return io.ErrUnexpectedEOF - } - ll, mo, ml = s.next(br, llState, mlState, ofState) - br.fill() + return io.ErrUnexpectedEOF } + var ll, mo, ml int + // Final will not read from stream. + var llB, mlB, moB uint8 + ll, llB = llState.final() + ml, mlB = mlState.final() + mo, moB = ofState.final() + + // extra bits are stored in reverse order. + var v int + bs = bs.fill(in) + bs, v = bs.getBits(moB) + mo += v + if maxBits > 32 { + bs = bs.fill(in) + } + bs, v = bs.getBits(mlB) + ml += v + bs, v = bs.getBits(llB) + ll += v + + if moB > 1 { + prev2 = prev1 + prev1 = prev0 + prev0 = mo + } else { + // mo = s.adjustOffset(mo, ll, moB) + // Inlined for rather big speedup + if ll == 0 { + // There is an exception though, when current sequence's literals_length = 0. + // In this case, repeated offsets are shifted by one, so an offset_value of 1 means Repeated_Offset2, + // an offset_value of 2 means Repeated_Offset3, and an offset_value of 3 means Repeated_Offset1 - 1_byte. + mo++ + } + + if mo == 0 { + mo = prev0 + } else { + var temp int + switch mo { + case 1: + temp = prev1 + case 2: + temp = prev2 + default: + temp = prev0 - 1 + } + + if temp == 0 { + // 0 is not valid; input is corrupted; force offset to 1 + println("WARNING: temp was 0") + temp = 1 + } + + if mo != 1 { + prev2 = prev1 + } + prev1 = prev0 + prev0 = temp + mo = temp + } + } + bs = bs.fill(in) if debugSequences { println("Seq", i, "Litlen:", ll, "mo:", mo, "(abs) ml:", ml) @@ -108,8 +119,8 @@ func (s *sequenceDecs) decode(seqs []seqVals) error { if ml > maxMatchLen { return fmt.Errorf("match len (%d) bigger than max allowed length", ml) } - s.seqSize += ll + ml - if s.seqSize > maxBlockSize { + seqSize += ll + ml + if seqSize > maxBlockSize { return fmt.Errorf("output bigger than max block size (%d)", maxBlockSize) } litRemain -= ll @@ -134,7 +145,8 @@ func (s *sequenceDecs) decode(seqs []seqVals) error { mlState = mlTable[mlState.newState()&maxTableMask] ofState = ofTable[ofState.newState()&maxTableMask] } else { - bits := br.get32BitsFast(nBits) + var bits uint32 + bs, bits = bs.get32BitsFast(nBits) lowBits := uint16(bits >> ((ofState.nbBits() + mlState.nbBits()) & 31)) llState = llTable[(llState.newState()+lowBits)&maxTableMask] @@ -146,10 +158,12 @@ func (s *sequenceDecs) decode(seqs []seqVals) error { ofState = ofTable[(ofState.newState()+lowBits)&maxTableMask] } } - s.seqSize += litRemain + s.seqSize = seqSize + litRemain if s.seqSize > maxBlockSize { return fmt.Errorf("output bigger than max block size (%d)", maxBlockSize) } + s.prevOffset = [3]int{prev0, prev1, prev2} + br.setState(bs) err := br.close() if err != nil { printf("Closing sequences: %v, %+v\n", err, *br) @@ -172,15 +186,29 @@ func (s *sequenceDecs) executeSimple(seqs []seqVals, hist []byte) error { var t = len(s.out) out := s.out[:t+s.seqSize] + literals := s.literals + windowSize := s.windowSize for _, seq := range seqs { + // Short sequences copy 16 bytes for each part. + if seq.ll <= 16 && seq.ml <= 16 && t+seq.ll+16 <= cap(out) && cap(literals) >= 16 { + if src := matchSource(out, hist, nil, t+seq.ll, seq.mo, 16, windowSize); src != nil { + *(*[16]byte)(out[t : t+16]) = *(*[16]byte)(literals[:16]) + t += seq.ll + *(*[16]byte)(out[t : t+16]) = *(*[16]byte)(src) + t += seq.ml + literals = literals[seq.ll:] + continue + } + } + // Add literals - copy(out[t:], s.literals[:seq.ll]) + copy(out[t:], literals[:seq.ll]) t += seq.ll - s.literals = s.literals[seq.ll:] + literals = literals[seq.ll:] // Malformed input - if seq.mo > t+len(hist) || seq.mo > s.windowSize { + if seq.mo > t+len(hist) || seq.mo > windowSize { return fmt.Errorf("match offset (%d) bigger than current history (%d)", seq.mo, t+len(hist)) } @@ -210,22 +238,16 @@ func (s *sequenceDecs) executeSimple(seqs []seqVals, hist []byte) error { t += seq.ml } else { // Overlapping copy - // Extend destination slice and copy one byte at the time. - src := out[start : start+seq.ml] - dst := out[t:] - dst = dst[:len(src)] - t += len(src) - // Destination is the space we just added. - for i := range src { - dst[i] = src[i] - } + overlapCopy(out, start, t, seq.ml) + t += seq.ml } } } // Add final literals - copy(out[t:], s.literals) + copy(out[t:], literals) + s.literals = literals if debugDecoder { - t += len(s.literals) + t += len(literals) if t != len(out) { panic(fmt.Errorf("length mismatch, want %d, got %d, ss: %d", len(out), t, s.seqSize)) } diff --git a/vendor/github.com/klauspost/compress/zstd/seqenc.go b/vendor/github.com/klauspost/compress/zstd/seqenc.go index 65045ea..6fb8885 100644 --- a/vendor/github.com/klauspost/compress/zstd/seqenc.go +++ b/vendor/github.com/klauspost/compress/zstd/seqenc.go @@ -110,3 +110,50 @@ func ofCode(offset uint32) uint8 { // A valid offset will always be > 0. return uint8(bits.Len32(offset) - 1) } + +// newDictSeqEncoder builds an encoder for a dictionary sequence table. +// Returns nil if the table is missing or unusable. +func newDictSeqEncoder(src *fseDecoder, t tableIndex) *fseEncoder { + if src == nil || src.symbolLen == 0 { + return nil + } + var e fseEncoder + e.norm = src.norm + e.symbolLen = src.symbolLen + e.actualTableLog = src.actualTableLog + if e.buildCTable() != nil { + return nil + } + e.setBits(bitTables[t]) + return &e +} + +// seedPrevFromDict loads the dictionary sequence tables as the "previous" +// encoders, so the first block can use repeat mode. +func (s *seqCoders) seedPrevFromDict(d *dict) { + seed := func(dst, src *fseEncoder) { + if src == nil { + return + } + ct := dst.ct + dst.symbolLen = src.symbolLen + dst.actualTableLog = src.actualTableLog + dst.maxBits = src.maxBits + dst.zeroBits = src.zeroBits + dst.useRLE = false + dst.preDefined = false + dst.reUsed = true + dst.norm = src.norm + // tableSymbol is only used while building, so it is not copied. + ct.stateTable = append(ct.stateTable[:0], src.ct.stateTable...) + if cap(ct.symbolTT) < len(src.ct.symbolTT) { + ct.symbolTT = make([]symbolTransform, len(src.ct.symbolTT)) + } + ct.symbolTT = ct.symbolTT[:len(src.ct.symbolTT)] + copy(ct.symbolTT, src.ct.symbolTT[:src.symbolLen]) + dst.ct = ct + } + seed(s.llPrev, d.llEnc) + seed(s.mlPrev, d.mlEnc) + seed(s.ofPrev, d.ofEnc) +} diff --git a/vendor/github.com/klauspost/compress/zstd/simple_go124.go b/vendor/github.com/klauspost/compress/zstd/simple.go similarity index 98% rename from vendor/github.com/klauspost/compress/zstd/simple_go124.go rename to vendor/github.com/klauspost/compress/zstd/simple.go index 2efc049..9b6c39a 100644 --- a/vendor/github.com/klauspost/compress/zstd/simple_go124.go +++ b/vendor/github.com/klauspost/compress/zstd/simple.go @@ -1,8 +1,6 @@ // Copyright 2025+ Klaus Post. All rights reserved. // License information can be found in the LICENSE file. -//go:build go1.24 - package zstd import ( diff --git a/vendor/github.com/klauspost/compress/zstd/snappy.go b/vendor/github.com/klauspost/compress/zstd/snappy.go index 36c56f3..06ed593 100644 --- a/vendor/github.com/klauspost/compress/zstd/snappy.go +++ b/vendor/github.com/klauspost/compress/zstd/snappy.go @@ -69,6 +69,10 @@ var ( // No CRC value is being generated and not all CRC values of the Snappy stream are checked. // However, it provides really fast recompression of Snappy streams. // The converter can be reused to avoid allocations, even after errors. +// +// Deprecated: Decode the stream with s2.NewReader, which reads Snappy streams, +// and compress the output with an Encoder. This validates the input and +// compresses much better. type SnappyConverter struct { r io.Reader err error @@ -373,6 +377,14 @@ func decodeSnappy(blk *blockEnc, src []byte) error { offset = uint32(src[s-4]) | uint32(src[s-3])<<8 | uint32(src[s-2])<<16 | uint32(src[s-1])<<24 } + // A zstd match is at least zstdMinMatch bytes. A shorter copy + // cannot be represented as a sequence and would underflow the + // matchLen computation below, producing an out-of-range match + // length code. + if length < zstdMinMatch { + return ErrSnappyCorrupt + } + if offset <= 0 || blk.size+lits < int(offset) /*|| length > len(blk)-d */ { println("offset <= 0 || blk.size+lits < int(offset)", offset, blk.size+lits, int(offset), blk.size, lits) diff --git a/vendor/github.com/mfridman/interpolate/.golangci.yaml b/vendor/github.com/mfridman/interpolate/.golangci.yaml new file mode 100644 index 0000000..b93283c --- /dev/null +++ b/vendor/github.com/mfridman/interpolate/.golangci.yaml @@ -0,0 +1,27 @@ +version: "2" +linters: + default: none + enable: + - errcheck + - govet + - ineffassign + - misspell + - modernize + - paralleltest + - staticcheck + - thelper + - tparallel + - unused + exclusions: + generated: lax + presets: + - comments + - common-false-positives + - legacy + - std-error-handling +formatters: + enable: + - gofmt + settings: + gofmt: + simplify: true diff --git a/vendor/github.com/mfridman/interpolate/CHANGELOG.md b/vendor/github.com/mfridman/interpolate/CHANGELOG.md new file mode 100644 index 0000000..9f93256 --- /dev/null +++ b/vendor/github.com/mfridman/interpolate/CHANGELOG.md @@ -0,0 +1,70 @@ +# Changelog + +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/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [Unreleased] + +## [v0.2.0] - 2026-11-10 + +This release renames the API and hides the parser types. To upgrade, replace `interpolate.Interpolate(env, s)` with `interpolate.Expand(s, env)`, and rename the `Get` method of a custom `Env` to `Lookup`, or use `interpolate.LookupFunc(os.LookupEnv)`. + +### Added + +- `LookupFunc`, an adapter that makes a function such as `os.LookupEnv` an `Env`. +- `UnsetVariableError`, the error from `${NAME?message}`, `${NAME:?message}` and `WithNoUnset`, with `Name` and `Message` fields. The error text does not change. +- `WithNoUnset`, an option that makes a reference to an unset variable an error, the same as `set -u` in bash. + +### Changed + +- `Interpolate(env, s)` is now `Expand(s, env, opts...)`. +- `Identifiers` is now `Variables`, and returns each name only once, in the order of first use. +- The `Get` method of `Env` is now `Lookup`. +- `NewSliceEnv(slice)` is now `NewListEnv(pairs...)`. Use `NewListEnv(os.Environ()...)` for a slice. + +### Removed + +- The exported parser and expression types, such as `Parser`, `NewParser`, `Expression`, `ExpressionItem`, `Expansion`, and the `*Expansion` types. Use `Expand` and `Variables`. + +### Fixed + +- On Windows, `NewMapEnv` with keys that differ only in case, such as `Path` and `PATH`, gave a random result. The last key in sorted order now wins. + +## [v0.1.0] - 2026-11-10 + +### Added + +- `${VAR:?message}`: error if `VAR` is unset or empty ([#2](https://github.com/mfridman/interpolate/issues/2)). +- `${VAR+word}` and `${VAR:+word}`: use `word` if `VAR` is set, or set and not empty. +- `${#VAR}`: the length of the value in characters. +- `\}` in the word of a brace expansion is a literal `}`, for example `${CONFIG:-{"a":1\}}`. +- New expansion types: `RequiredNonEmptyExpansion`, `AlternateExpansion`, `AlternateNonEmptyExpansion`, and `LengthExpansion`. +- Brace expansions can be nested at most 1000 levels deep. Deeper input returns an error instead of exhausting the stack. + +### Changed + +- Go 1.25 or later is required. +- A `$` that is not followed by a letter, `_`, or `{` is literal text. Before, inputs such as `$1`, `$ `, `$5`, `$@`, `'^abc$'`, and `${VAR:-$}` returned an error. +- Names follow POSIX: `[A-Za-z_][A-Za-z0-9_]*`. `$_VAR` and `${_VAR}` now expand. Non-ASCII letters are no longer part of a name, so `$é` is literal text, `$FOOé` expands `FOO`, and `${é}` is an error. +- `${VAR:+word}` is the alternate value. Before, it was parsed as a substring with offset `+word`, so `${VAR:+1}` was the value after the first character. +- Substring offsets and lengths count characters, not bytes. +- A negative substring offset before the start of the value gives an empty string, the same as bash. Before, it gave the whole value. +- A blank substring offset or length counts as 0, so `${VAR::2}`, `${VAR:2:}`, and `${VAR: }` work. Before, they returned an error. +- `Identifiers` includes the names in the word of `${VAR-word}` and `${VAR?word}`, the same as `${VAR:-word}`. +- Error messages start with a lowercase letter, and say "end of input" for unterminated expansions. An empty `${}` gives `empty expansion ${}, expected a variable name` ([#1](https://github.com/mfridman/interpolate/issues/1)). The `$VAR: message` errors from required expansions are unchanged. + +### Fixed + +- Substrings with a length near the maximum `int` value no longer panic. +- Invalid UTF-8 bytes in the input are kept unchanged. Before, they became U+FFFD. +- Calling `Parse` again on the same `Parser` parses the input again. Before, it returned an empty expression. + +## [v0.0.2] + +The last release before the changes above. See [buildkite/interpolate](https://github.com/buildkite/interpolate) for the history before the fork. + +[Unreleased]: https://github.com/mfridman/interpolate/compare/v0.2.0...HEAD +[v0.2.0]: https://github.com/mfridman/interpolate/compare/v0.1.0...v0.2.0 +[v0.1.0]: https://github.com/mfridman/interpolate/compare/v0.0.2...v0.1.0 +[v0.0.2]: https://github.com/mfridman/interpolate/releases/tag/v0.0.2 diff --git a/vendor/github.com/mfridman/interpolate/README.md b/vendor/github.com/mfridman/interpolate/README.md index 48db562..ac9f297 100644 --- a/vendor/github.com/mfridman/interpolate/README.md +++ b/vendor/github.com/mfridman/interpolate/README.md @@ -1,85 +1,127 @@ -# Interpolate +# interpolate [![Build Status](https://github.com/mfridman/interpolate/actions/workflows/ci.yaml/badge.svg)](https://github.com/mfridman/interpolate/actions/workflows/ci.yaml) [![Go Reference](https://pkg.go.dev/badge/github.com/mfridman/interpolate.svg)](https://pkg.go.dev/github.com/mfridman/interpolate) -[![Go Report Card](https://goreportcard.com/badge/github.com/mfridman/interpolate)](https://goreportcard.com/report/github.com/mfridman/interpolate) -A Go library for parameter expansion (like `${NAME}` or `$NAME`) in strings from environment -variables. An implementation of [POSIX Parameter -Expansion](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_02), -plus some other basic operations that you'd expect in a shell scripting environment [like -bash](https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html). +A Go library that expands shell-style parameters, such as `$NAME` and `${NAME:-default}`, in strings. It implements [POSIX parameter expansion](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_02) and some [bash extensions](https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html). ## Installation -``` +```sh go get github.com/mfridman/interpolate@latest ``` +Requires Go 1.25 or later. + ## Usage ```go package main import ( - "github.com/mfridman/interpolate" - "fmt" + "fmt" + "log" + + "github.com/mfridman/interpolate" ) func main() { - env := interpolate.NewSliceEnv([]string{ - "NAME=James", - }) + env := interpolate.NewListEnv("NAME=James") - output, _ := interpolate.Interpolate(env, "Hello... ${NAME} welcome to the ${ANOTHER_VAR:-🏖}") - - fmt.Println(output) - // Output: Hello... James welcome to the 🏖 + output, err := interpolate.Expand("Hello ${NAME}, welcome to the ${PLACE:-🏖}", env) + if err != nil { + log.Fatal(err) + } + fmt.Println(output) // Hello James, welcome to the 🏖 } ``` -## Supported Expansions +Values come from an `Env`: -- `${parameter}` or `$parameter` +- `interpolate.LookupFunc(os.LookupEnv)` reads the process environment. +- `interpolate.NewMapEnv(m)` reads a `map[string]string`. +- `interpolate.NewListEnv("A=1", "B=2")` reads `NAME=value` pairs, such as `os.Environ()...`. +- Any type with a `Lookup(name string) (string, bool)` method is an `Env`. - - **Use value.** If parameter is set, then it shall be substituted; otherwise, it will be blank +`interpolate.Variables` returns the names of the variables in a string, without repeats, and does not expand it. -- `${parameter:-[word]}` +### Errors and strict mode - - **Use default values.** If parameter is unset or null, the expansion of word (or an empty string - if word is omitted) shall be substituted; otherwise, the value of parameter shall be - substituted. +`${NAME?message}` and `${NAME:?message}` return an `*interpolate.UnsetVariableError` with the variable `Name` and the `Message`. Its text is `$NAME: message`. -- `${parameter-[word]}` +```go +var unsetErr *interpolate.UnsetVariableError +if errors.As(err, &unsetErr) { + fmt.Println(unsetErr.Name) // PORT +} +``` - - **Use default values when not set.** If parameter is unset, the expansion of word (or an empty - string if word is omitted) shall be substituted; otherwise, the value of parameter shall be - substituted. +By default, an unset variable expands to an empty string, the same as a shell. Use `interpolate.WithNoUnset()` to make a reference to an unset variable an error, the same as `set -u` in bash. Expansions that handle an unset variable, such as `${NAME:-word}`, do not change. -- `${parameter:[offset]}` +```go +output, err := interpolate.Expand(input, env, interpolate.WithNoUnset()) +// $TYPO -> error: $TYPO: not set +``` - - **Use the substring of parameter after offset.** A negative offset must be separated from the - colon with a space, and will select from the end of the string. If the value is out of bounds, - an empty string will be substituted. +## Supported expansions -- `${parameter:[offset]:[length]}` +| Syntax | Result | +| --- | --- | +| `$NAME` or `${NAME}` | The value of `NAME`, or an empty string if it is unset | +| `${NAME:-word}` | `word` if `NAME` is unset or empty, otherwise the value | +| `${NAME-word}` | `word` if `NAME` is unset, otherwise the value | +| `${NAME:?message}` | An error if `NAME` is unset or empty, otherwise the value | +| `${NAME?message}` | An error if `NAME` is unset, otherwise the value | +| `${NAME:+word}` | `word` if `NAME` is set and not empty, otherwise an empty string | +| `${NAME+word}` | `word` if `NAME` is set, otherwise an empty string | +| `${#NAME}` | The length of the value in characters | +| `${NAME:offset}` | The value from `offset` to the end | +| `${NAME:offset:length}` | At most `length` characters of the value from `offset` | - - **Use the substring of parameter after offset of given length.** A negative offset must be - separated from the colon with a space, and will select from the end of the string. If the offset - is out of bounds, an empty string will be substituted. If the length is greater than the length - then the entire string will be returned. +- A name starts with a letter or an underscore, followed by letters, digits, or underscores (`[A-Za-z_][A-Za-z0-9_]*`). +- A `word` or `message` can contain other expansions, such as `${NAME:-${FALLBACK:-default}}`. It is expanded only when it is used. Expansions can be nested up to 1000 levels deep. +- Without a message, the error from `?` is `$NAME: not set`, and the error from `:?` is `$NAME: empty or not set`. -- `${parameter:?[word]}` - - **Indicate Error if Null or Unset.** If parameter is unset or null, the expansion of word (or a - message indicating it is unset if word is omitted) shall be returned as an error. +### Substrings -## Prior work +- Offsets and lengths count characters, not bytes. They are decimal integers; arithmetic is not supported. +- A negative offset counts from the end. Put a space before it, as in `${NAME: -2}`, because `${NAME:-2}` is a default value. +- An offset past the end, or before the start, gives an empty string. +- A length past the end gives the rest of the value. A negative length ends that many characters before the end, so `${NAME:1:-1}` removes the first and last characters. +- A blank offset or length counts as 0, so `${NAME::2}` gives the first two characters. `${NAME:}` is an error. -This repository is a fork of [buildkite/interpolate](https://github.com/buildkite/interpolate). I'd -like to thank the authors of that library for their work. I've forked it to make some changes that I -needed for my own use cases, and to make it easier to maintain. I've also added some tests and -documentation. +## Escaping + +| Input | Output | +| --- | --- | +| `$$NAME` or `\$NAME` | `$NAME` | +| `$${NAME}` or `\${NAME}` | `${NAME}` | +| `\}` in a `word` or `message` | `}` | +| `$` not followed by a letter, `_`, or `{` | Kept as-is, so `$1`, `$(command)`, `price: $5`, and a trailing `$` do not change | +| `\\` | Kept as-is | + +A word ends at the first `}`, so write `${CONFIG:-{"a":1\}}` to get `{"a":1}`. Outside of `${...}`, `\}` is kept as-is. + +A double backslash is kept as two backslashes, and it does not escape the `$` after it: `\\$NAME` gives `\\` followed by the value of `NAME`. You cannot put one backslash directly before a literal `$`. In a regular expression, write `[$]` instead of `\$`. + +### SQL + +These rules matter when the input is SQL, for example in [goose](https://github.com/pressly/goose) migrations with `ENVSUB ON`: + +- Write `$$$$` for a `$$` dollar-quoted string, and `$$tag$$` for `$tag$`. Without escaping, `$$` becomes `$`, and `$tag` expands as a variable. +- Write `%1$$s` in `format('%1$s', name)`, because `$s` is a variable. +- Positional parameters such as `$1`, and a `$` at the end of a regular expression such as `'^abc$'`, are kept as-is. + +## Not supported + +- Pattern removal: `${NAME%word}`, `${NAME%%word}`, `${NAME#word}`, and `${NAME##word}`. +- Assignment: `${NAME:=word}` and `${NAME=word}`. +- Special and positional parameters, such as `$1`, `$@`, `$*`, `$#`, and `$?`. They are kept as literal text. + +## Acknowledgements + +This project started as a fork of [buildkite/interpolate](https://github.com/buildkite/interpolate). Thanks to its authors for their work. ## License -Licensed under MIT license, in `LICENSE`. +[MIT](LICENSE.txt) diff --git a/vendor/github.com/mfridman/interpolate/doc.go b/vendor/github.com/mfridman/interpolate/doc.go new file mode 100644 index 0000000..97b3969 --- /dev/null +++ b/vendor/github.com/mfridman/interpolate/doc.go @@ -0,0 +1,26 @@ +// Package interpolate expands shell-style parameters, such as $NAME and ${NAME:-default}, in +// strings. It implements POSIX parameter expansion and some bash extensions. [Expand] reads +// values from an [Env], and [Variables] lists the variables in a string. +// +// Supported expansions: +// +// $NAME or ${NAME} the value of NAME, or an empty string if NAME is unset +// ${NAME:-word} word if NAME is unset or empty +// ${NAME-word} word if NAME is unset +// ${NAME:?message} an error if NAME is unset or empty +// ${NAME?message} an error if NAME is unset +// ${NAME:+word} word if NAME is set and not empty, otherwise an empty string +// ${NAME+word} word if NAME is set, otherwise an empty string +// ${#NAME} the length of the value in characters +// ${NAME:offset} the value from offset +// ${NAME:offset:length} at most length characters of the value from offset +// +// Write $$ or \$ for a literal dollar sign, and \} for a literal closing brace in a word. A $ +// that is not followed by a letter, an underscore, or { is kept as-is, so $1 and $(command) do +// not change. +// +// A required expansion that fails returns an [*UnsetVariableError]. Use [WithNoUnset] to make a +// reference to an unset variable an error too, the same as set -u in bash. +// +// [Expand] and [Variables] are safe for concurrent use if the [Env] is. +package interpolate diff --git a/vendor/github.com/mfridman/interpolate/env.go b/vendor/github.com/mfridman/interpolate/env.go index d149e86..97cc488 100644 --- a/vendor/github.com/mfridman/interpolate/env.go +++ b/vendor/github.com/mfridman/interpolate/env.go @@ -1,53 +1,78 @@ package interpolate import ( + "maps" "runtime" + "slices" "strings" ) -// Env is an interface for getting environment variables by name and returning a boolean indicating -// whether the variable was found. +// Env is a source of variable values. type Env interface { - Get(key string) (string, bool) + // Lookup returns the value of the variable with the given name, and whether the variable is + // set. A variable that is set can have an empty value. + Lookup(name string) (value string, ok bool) } -// NewSliceEnv creates an Env from a slice of environment variables in the form "key=value". +// LookupFunc is a function that is an [Env]. For example, LookupFunc(os.LookupEnv) reads the +// environment of the process. +type LookupFunc func(name string) (value string, ok bool) + +// Lookup returns f(name). +func (f LookupFunc) Lookup(name string) (string, bool) { + return f(name) +} + +// NewMapEnv returns an Env with the variables in m. It copies m. // -// This can be used with [os.Environ] to create an Env. -func NewSliceEnv(env []string) Env { - envMap := mapEnv{} - for _, l := range env { - parts := strings.SplitN(l, "=", 2) - if len(parts) == 2 { - envMap[normalizeKeyName(parts[0])] = parts[1] +// On Windows, names are case insensitive. If keys in m differ only in case, the last key in +// sorted order wins. +func NewMapEnv(m map[string]string) Env { + return newMapEnv(m, runtime.GOOS == "windows") +} + +// NewListEnv returns an Env with the variables in pairs, which use the "NAME=value" form of +// [os.Environ]. Pairs without "=" are ignored. If a name occurs more than once, the last pair +// wins. +// +// On Windows, names are case insensitive. +func NewListEnv(pairs ...string) Env { + return newListEnv(pairs, runtime.GOOS == "windows") +} + +func newMapEnv(m map[string]string, foldCase bool) mapEnv { + env := mapEnv{values: make(map[string]string, len(m)), foldCase: foldCase} + // Sort the keys, so the result does not depend on map order when keys differ only in case. + for _, name := range slices.Sorted(maps.Keys(m)) { + env.values[env.key(name)] = m[name] + } + return env +} + +func newListEnv(pairs []string, foldCase bool) mapEnv { + env := mapEnv{values: make(map[string]string, len(pairs)), foldCase: foldCase} + for _, pair := range pairs { + if name, value, ok := strings.Cut(pair, "="); ok { + env.values[env.key(name)] = value } } - return envMap + return env } -// NewMapEnv creates an Env from a map of environment variables. -func NewMapEnv(env map[string]string) Env { - envMap := mapEnv{} - for k, v := range env { - envMap[normalizeKeyName(k)] = v +// mapEnv is an Env with variables in a map. With foldCase, names are case insensitive. +type mapEnv struct { + values map[string]string + foldCase bool +} + +func (e mapEnv) Lookup(name string) (string, bool) { + value, ok := e.values[e.key(name)] + return value, ok +} + +func (e mapEnv) key(name string) string { + if e.foldCase { + return strings.ToUpper(name) } - return envMap -} - -type mapEnv map[string]string - -func (m mapEnv) Get(key string) (string, bool) { - if m == nil { - return "", false - } - val, ok := m[normalizeKeyName(key)] - return val, ok -} - -// Windows isn't case sensitive for env -func normalizeKeyName(key string) string { - if runtime.GOOS == "windows" { - return strings.ToUpper(key) - } - return key + return name } diff --git a/vendor/github.com/mfridman/interpolate/expression.go b/vendor/github.com/mfridman/interpolate/expression.go new file mode 100644 index 0000000..6b1235b --- /dev/null +++ b/vendor/github.com/mfridman/interpolate/expression.go @@ -0,0 +1,288 @@ +package interpolate + +import ( + "fmt" + "strconv" + "strings" + "unicode/utf8" +) + +// expandContext holds the values and settings for one call to Expand. +type expandContext struct { + env Env + noUnset bool +} + +// value returns the value of name for a plain reference, such as $NAME or ${NAME:1}. With +// noUnset, an unset variable is an error. +func (c *expandContext) value(name string) (string, error) { + value, ok := c.env.Lookup(name) + if !ok && c.noUnset { + return "", &UnsetVariableError{Name: name, Message: "not set"} + } + return value, nil +} + +// unsetError returns the error for a required expansion. It uses the expansion of message, or +// defaultMessage if message expands to an empty string. +func (c *expandContext) unsetError(name string, message expression, defaultMessage string) error { + msg, err := message.expand(c) + if err != nil { + return err + } + if msg == "" { + msg = defaultMessage + } + return &UnsetVariableError{Name: name, Message: msg} +} + +// expression is a list of text and expansions. +type expression []expressionItem + +// expand expands all expansions in the expression, and joins the results with the text. +func (e expression) expand(c *expandContext) (string, error) { + var buf strings.Builder + for _, item := range e { + if item.Expansion == nil { + buf.WriteString(item.Text) + continue + } + result, err := item.Expansion.expand(c) + if err != nil { + return "", err + } + buf.WriteString(result) + } + return buf.String(), nil +} + +// variables returns the variable names referenced by all expansions in the expression, in order. +// A name can occur more than once. +func (e expression) variables() []string { + var names []string + for _, item := range e { + if item.Expansion != nil { + names = append(names, item.Expansion.variables()...) + } + } + return names +} + +// expressionItem is either text or an expansion, never both. +type expressionItem struct { + Text string + Expansion expansion +} + +func (i expressionItem) String() string { + if i.Expansion != nil { + return fmt.Sprintf("%#v", i.Expansion) + } + return fmt.Sprintf("%q", i.Text) +} + +// expansion is one parameter expansion, such as $NAME or ${NAME:-word}. +type expansion interface { + // expand returns the value of the expansion. + expand(c *expandContext) (string, error) + + // variables returns the variable names referenced by the expansion, including the names in + // its word or message. + variables() []string +} + +// variableExpansion is $NAME or ${NAME}. +type variableExpansion struct { + Identifier string +} + +func (e variableExpansion) variables() []string { + return []string{e.Identifier} +} + +func (e variableExpansion) expand(c *expandContext) (string, error) { + return c.value(e.Identifier) +} + +// emptyValueExpansion is ${NAME:-word}: the value, or word if the variable is unset or empty. +type emptyValueExpansion struct { + Identifier string + Content expression +} + +func (e emptyValueExpansion) variables() []string { + return append([]string{e.Identifier}, e.Content.variables()...) +} + +func (e emptyValueExpansion) expand(c *expandContext) (string, error) { + if value, _ := c.env.Lookup(e.Identifier); value != "" { + return value, nil + } + return e.Content.expand(c) +} + +// unsetValueExpansion is ${NAME-word}: the value, or word if the variable is unset. +type unsetValueExpansion struct { + Identifier string + Content expression +} + +func (e unsetValueExpansion) variables() []string { + return append([]string{e.Identifier}, e.Content.variables()...) +} + +func (e unsetValueExpansion) expand(c *expandContext) (string, error) { + if value, ok := c.env.Lookup(e.Identifier); ok { + return value, nil + } + return e.Content.expand(c) +} + +// requiredExpansion is ${NAME?message}: the value, or an error if the variable is unset. +type requiredExpansion struct { + Identifier string + Message expression +} + +func (e requiredExpansion) variables() []string { + return append([]string{e.Identifier}, e.Message.variables()...) +} + +func (e requiredExpansion) expand(c *expandContext) (string, error) { + value, ok := c.env.Lookup(e.Identifier) + if !ok { + return "", c.unsetError(e.Identifier, e.Message, "not set") + } + return value, nil +} + +// requiredNonEmptyExpansion is ${NAME:?message}: the value, or an error if the variable is unset +// or empty. +type requiredNonEmptyExpansion struct { + Identifier string + Message expression +} + +func (e requiredNonEmptyExpansion) variables() []string { + return append([]string{e.Identifier}, e.Message.variables()...) +} + +func (e requiredNonEmptyExpansion) expand(c *expandContext) (string, error) { + value, _ := c.env.Lookup(e.Identifier) + if value == "" { + return "", c.unsetError(e.Identifier, e.Message, "empty or not set") + } + return value, nil +} + +// alternateExpansion is ${NAME+word}: word if the variable is set, otherwise an empty string. +type alternateExpansion struct { + Identifier string + Content expression +} + +func (e alternateExpansion) variables() []string { + return append([]string{e.Identifier}, e.Content.variables()...) +} + +func (e alternateExpansion) expand(c *expandContext) (string, error) { + if _, ok := c.env.Lookup(e.Identifier); !ok { + return "", nil + } + return e.Content.expand(c) +} + +// alternateNonEmptyExpansion is ${NAME:+word}: word if the variable is set and not empty, +// otherwise an empty string. +type alternateNonEmptyExpansion struct { + Identifier string + Content expression +} + +func (e alternateNonEmptyExpansion) variables() []string { + return append([]string{e.Identifier}, e.Content.variables()...) +} + +func (e alternateNonEmptyExpansion) expand(c *expandContext) (string, error) { + if value, _ := c.env.Lookup(e.Identifier); value == "" { + return "", nil + } + return e.Content.expand(c) +} + +// lengthExpansion is ${#NAME}: the number of characters in the value. +type lengthExpansion struct { + Identifier string +} + +func (e lengthExpansion) variables() []string { + return []string{e.Identifier} +} + +func (e lengthExpansion) expand(c *expandContext) (string, error) { + value, err := c.value(e.Identifier) + if err != nil { + return "", err + } + return strconv.Itoa(utf8.RuneCountInString(value)), nil +} + +// substringExpansion is ${NAME:offset} or ${NAME:offset:length}. +type substringExpansion struct { + Identifier string + Offset int + Length int + HasLength bool +} + +func (e substringExpansion) variables() []string { + return []string{e.Identifier} +} + +func (e substringExpansion) expand(c *expandContext) (string, error) { + value, err := c.value(e.Identifier) + if err != nil { + return "", err + } + // Offsets and lengths count characters, not bytes, the same as bash in a UTF-8 locale. Each + // invalid UTF-8 byte counts as one character and is kept unchanged. + size := utf8.RuneCountInString(value) + + // A negative offset counts from the end. An offset before the start gives an empty string, + // the same as bash. The order of operations prevents integer overflow for extreme offsets + // and lengths. + from := e.Offset + if from < 0 { + if from < -size { + return "", nil + } + from += size + } + from = min(from, size) + + // A positive length counts from the offset. A negative length counts back from the end, and + // cannot go before the offset. + to := size + if e.HasLength { + if e.Length >= 0 { + to = from + min(e.Length, size-from) + } else { + to = max(size+e.Length, from) + } + } + + start := byteOffset(value, from) + end := start + byteOffset(value[start:], to-from) + return value[start:end], nil +} + +// byteOffset returns the byte offset of the character at index in s. Each invalid UTF-8 byte +// counts as one character, the same as [utf8.RuneCountInString]. +func byteOffset(s string, index int) int { + offset := 0 + for range index { + _, size := utf8.DecodeRuneInString(s[offset:]) + offset += size + } + return offset +} diff --git a/vendor/github.com/mfridman/interpolate/interpolate.go b/vendor/github.com/mfridman/interpolate/interpolate.go index b9478a8..e475663 100644 --- a/vendor/github.com/mfridman/interpolate/interpolate.go +++ b/vendor/github.com/mfridman/interpolate/interpolate.go @@ -1,213 +1,80 @@ package interpolate -import ( - "bytes" - "fmt" -) - -// Interpolate takes a set of environment and interpolates it into the provided string using shell -// script expansions -func Interpolate(env Env, str string) (string, error) { - if env == nil { - env = NewSliceEnv(nil) +// Expand returns s with each parameter expansion replaced by its value, and each escape such as +// $$ replaced by its text. Values come from env. A nil env has no variables. +// +// Expand returns an error if s is not valid, and an [*UnsetVariableError] if a variable that must +// have a value does not have one. +func Expand(s string, env Env, opts ...Option) (string, error) { + var cfg config + for _, opt := range opts { + opt.apply(&cfg) } - expr, err := NewParser(str).Parse() + if env == nil { + env = mapEnv{} + } + expr, err := newParser(s).Parse() if err != nil { return "", err } - return expr.Expand(env) + return expr.expand(&expandContext{env: env, noUnset: cfg.noUnset}) } -// Indentifiers parses the identifiers from any expansions in the provided string -func Identifiers(str string) ([]string, error) { - expr, err := NewParser(str).Parse() +// Variables returns the names of the variables that s refers to, in the order of their first use, +// with no repeats. It includes the variables in the words and messages of expansions, such as +// FALLBACK in ${NAME:-$FALLBACK}, and does not include escaped references such as $$NAME. +// +// Variables returns an error if s is not valid. +func Variables(s string) ([]string, error) { + expr, err := newParser(s).Parse() if err != nil { return nil, err } - return expr.Identifiers(), nil -} - -// An expansion is something that takes in ENV and returns a string or an error -type Expansion interface { - Expand(env Env) (string, error) - Identifiers() []string -} - -// VariableExpansion represents either $VAR or ${VAR}, our simplest expansion -type VariableExpansion struct { - Identifier string -} - -func (e VariableExpansion) Identifiers() []string { - return []string{e.Identifier} -} - -func (e VariableExpansion) Expand(env Env) (string, error) { - val, _ := env.Get(e.Identifier) - return val, nil -} - -// EmptyValueExpansion returns either the value of an env, or a default value if it's unset or null -type EmptyValueExpansion struct { - Identifier string - Content Expression -} - -func (e EmptyValueExpansion) Identifiers() []string { - return append([]string{e.Identifier}, e.Content.Identifiers()...) -} - -func (e EmptyValueExpansion) Expand(env Env) (string, error) { - val, _ := env.Get(e.Identifier) - if val == "" { - return e.Content.Expand(env) - } - return val, nil -} - -// UnsetValueExpansion returns either the value of an env, or a default value if it's unset -type UnsetValueExpansion struct { - Identifier string - Content Expression -} - -func (e UnsetValueExpansion) Identifiers() []string { - return []string{e.Identifier} -} - -func (e UnsetValueExpansion) Expand(env Env) (string, error) { - val, ok := env.Get(e.Identifier) - if !ok { - return e.Content.Expand(env) - } - return val, nil -} - -// SubstringExpansion returns a substring (or slice) of the env -type SubstringExpansion struct { - Identifier string - Offset int - Length int - HasLength bool -} - -func (e SubstringExpansion) Identifiers() []string { - return []string{e.Identifier} -} - -func (e SubstringExpansion) Expand(env Env) (string, error) { - val, _ := env.Get(e.Identifier) - - from := e.Offset - - // Negative offsets = from end - if from < 0 { - from += len(val) - } - - // Still negative = too far from end? Truncate to start. - if from < 0 { - from = 0 - } - - // Beyond end? Truncate to end. - if from > len(val) { - from = len(val) - } - - if !e.HasLength { - return val[from:], nil - } - - to := e.Length - - if to >= 0 { - // Positive length = from offset - to += from - } else { - // Negative length = from end - to += len(val) - - // Too far? Truncate to offset. - if to < from { - to = from + names := []string{} + seen := make(map[string]bool) + for _, name := range expr.variables() { + if !seen[name] { + seen[name] = true + names = append(names, name) } } - - // Beyond end? Truncate to end. - if to > len(val) { - to = len(val) - } - - return val[from:to], nil + return names, nil } -// RequiredExpansion returns an env value, or an error if it is unset -type RequiredExpansion struct { - Identifier string - Message Expression +// Option configures [Expand]. +type Option interface { + apply(*config) } -func (e RequiredExpansion) Identifiers() []string { - return []string{e.Identifier} +// WithNoUnset makes a reference to an unset variable an error, the same as set -u (nounset) in +// bash. It applies to $NAME, ${NAME}, ${#NAME}, ${NAME:offset} and ${NAME:offset:length}. +// Expansions that handle an unset variable, such as ${NAME:-word} and ${NAME+word}, do not +// change. The error is an [*UnsetVariableError] with the message "not set". +func WithNoUnset() Option { + return noUnsetOption{} } -func (e RequiredExpansion) Expand(env Env) (string, error) { - val, ok := env.Get(e.Identifier) - if !ok { - msg, err := e.Message.Expand(env) - if err != nil { - return "", err - } - if msg == "" { - msg = "not set" - } - return "", fmt.Errorf("$%s: %s", e.Identifier, msg) - } - return val, nil +// UnsetVariableError is the error for a variable that must have a value but does not. It comes +// from ${NAME?message}, from ${NAME:?message}, and from a reference to an unset variable with +// [WithNoUnset]. +type UnsetVariableError struct { + // Name is the name of the variable. + Name string + // Message is the expanded message from the expansion, or a default message such as "not set". + Message string } -// Expression is a collection of either Text or Expansions -type Expression []ExpressionItem - -func (e Expression) Identifiers() []string { - identifiers := []string{} - for _, item := range e { - if item.Expansion != nil { - identifiers = append(identifiers, item.Expansion.Identifiers()...) - } - } - return identifiers +// Error returns the error in the form "$NAME: message". +func (e *UnsetVariableError) Error() string { + return "$" + e.Name + ": " + e.Message } -func (e Expression) Expand(env Env) (string, error) { - buf := &bytes.Buffer{} - - for _, item := range e { - if item.Expansion != nil { - result, err := item.Expansion.Expand(env) - if err != nil { - return "", err - } - _, _ = buf.WriteString(result) - } else { - _, _ = buf.WriteString(item.Text) - } - } - - return buf.String(), nil +type config struct { + noUnset bool } -// ExpressionItem models either an Expansion or Text. Either/Or, never both. -type ExpressionItem struct { - Text string - // -- or -- - Expansion Expansion -} +type noUnsetOption struct{} -func (i ExpressionItem) String() string { - if i.Expansion != nil { - return fmt.Sprintf("%#v", i.Expansion) - } - return fmt.Sprintf("%q", i.Text) +func (noUnsetOption) apply(cfg *config) { + cfg.noUnset = true } diff --git a/vendor/github.com/mfridman/interpolate/parser.go b/vendor/github.com/mfridman/interpolate/parser.go index 936608e..c0e978d 100644 --- a/vendor/github.com/mfridman/interpolate/parser.go +++ b/vendor/github.com/mfridman/interpolate/parser.go @@ -1,10 +1,10 @@ package interpolate import ( + "errors" "fmt" "strconv" "strings" - "unicode" "unicode/utf8" ) @@ -23,39 +23,60 @@ import ( // functions and structs named the same reading the string bite by bite (peekRune and nextRune) /* -EscapedBackslash = "\\" EscapedDollar = ( "\$" | "$$") Identifier = letter { letters | -digit | "_" } Expansion = "$" ( Identifier | Brace ) Brace = "{" Identifier [ -Identifier BraceOperation ] "}" Text = { EscapedBackslash | EscapedDollar | all characters except -"$" } Expression = { Text | Expansion } EmptyValue = ":-" { Expression } UnsetValue = -"-" { Expression } Substring = ":" number [ ":" number ] Required = "?" { Expression } -Operation = EmptyValue | UnsetValue | Substring | Required +EscapedBackslash = "\\" +EscapedDollar = ( "\$" | "$$") +Identifier = ( letter | "_" ) { letter | digit | "_" } +Expansion = "$" ( Identifier | Brace ) +LiteralDollar = "$" (not followed by "{" or a letter or "_") +Brace = "{" ( Length | Identifier [ Operation ] ) "}" +EscapedBrace = "\}" (only in the word of a brace expansion) +Text = { EscapedBackslash | EscapedDollar | EscapedBrace | LiteralDollar | all characters except "$" } +Expression = { Text | Expansion } +Length = "#" Identifier +EmptyValue = ":-" { Expression } +UnsetValue = "-" { Expression } +Substring = ":" number [ ":" number ] +RequiredNonEmpty = ":?" { Expression } +Required = "?" { Expression } +AlternateNonEmpty = ":+" { Expression } +Alternate = "+" { Expression } +Operation = EmptyValue | UnsetValue | Substring | RequiredNonEmpty | Required | AlternateNonEmpty | Alternate */ const ( eof = -1 + + // maxNestingDepth is the maximum number of brace expansions that can be nested inside each + // other, as in ${A:-${B:-${C}}}. The parser is recursive, so the limit protects against stack + // exhaustion from untrusted input. + maxNestingDepth = 1000 ) -// Parser takes a string and parses out a tree of structs that represent text and Expansions -type Parser struct { +// parser takes a string and parses out a tree of structs that represent text and Expansions +type parser struct { input string // the string we are scanning pos int // the current position + depth int // the current number of nested brace expansions } -// NewParser returns a new instance of a Parser -func NewParser(str string) *Parser { - return &Parser{ +// newParser returns a new instance of a Parser +func newParser(str string) *parser { + return &parser{ input: str, pos: 0, } } -// Parse expansions out of the internal text and return them as a tree of Expressions -func (p *Parser) Parse() (Expression, error) { +// Parse expansions out of the internal text and return them as a tree of Expressions. Each call +// parses the whole input again. +func (p *parser) Parse() (expression, error) { + p.pos = 0 + p.depth = 0 return p.parseExpression() } -func (p *Parser) parseExpression(stop ...rune) (Expression, error) { - var expr Expression +func (p *parser) parseExpression(stop ...rune) (expression, error) { + var expr expression var stopStr = string(stop) for { @@ -67,48 +88,50 @@ func (p *Parser) parseExpression(stop ...rune) (Expression, error) { // check for our escaped characters first, as we assume nothing subsequently is escaped if strings.HasPrefix(p.input[p.pos:], `\\`) { p.pos += 2 - expr = append(expr, ExpressionItem{Text: `\\`}) + expr = append(expr, expressionItem{Text: `\\`}) + continue + } else if stopStr != "" && strings.HasPrefix(p.input[p.pos:], `\}`) { + // Inside a brace expansion, an escaped closing brace is text and does not end the + // expansion, the same as bash. + p.pos += 2 + expr = append(expr, expressionItem{Text: `}`}) continue } else if strings.HasPrefix(p.input[p.pos:], `\$`) || strings.HasPrefix(p.input[p.pos:], `$$`) { p.pos += 2 - expr = append(expr, ExpressionItem{Text: `$`}) + expr = append(expr, expressionItem{Text: `$`}) continue } - // Ignore bash shell expansions - if strings.HasPrefix(p.input[p.pos:], `$(`) { - p.pos += 2 - expr = append(expr, ExpressionItem{Text: `$(`}) - continue - } - - // If we run into a dollar sign and it's not the last char, it's an expansion - if c == '$' && p.pos < (len(p.input)-1) { + // A dollar sign starts an expansion only when a brace or a name follows it. Anything else, + // such as "$1", "$ ", "$(" or a trailing "$", is literal text. + if c == '$' && p.isExpansionStart() { expansion, err := p.parseExpansion() if err != nil { return nil, err } - expr = append(expr, ExpressionItem{Expansion: expansion}) + expr = append(expr, expressionItem{Expansion: expansion}) continue } - // nibble a character, otherwise if it's a \ or a $ we can loop - c = p.nextRune() + // Nibble a character, otherwise if it's a \ or a $ we can loop. Slice the input instead of + // re-encoding runes, so invalid UTF-8 bytes pass through unchanged. + start := p.pos + _ = p.nextRune() // Scan as much as we can into text - text := p.scanUntil(func(r rune) bool { + p.scanUntil(func(r rune) bool { return (r == '$' || r == '\\' || strings.ContainsRune(stopStr, r)) }) - expr = append(expr, ExpressionItem{Text: string(c) + text}) + expr = append(expr, expressionItem{Text: p.input[start:p.pos]}) } return expr, nil } -func (p *Parser) parseExpansion() (Expansion, error) { +func (p *parser) parseExpansion() (expansion, error) { if c := p.nextRune(); c != '$' { - return nil, fmt.Errorf("Expected expansion to start with $, got %c", c) + return nil, fmt.Errorf("expected expansion to start with $, got %s", describeRune(c)) } // if we have an open brace, this is a brace expansion @@ -121,12 +144,28 @@ func (p *Parser) parseExpansion() (Expansion, error) { return nil, err } - return VariableExpansion{Identifier: identifier}, nil + return variableExpansion{Identifier: identifier}, nil } -func (p *Parser) parseBraceExpansion() (Expansion, error) { +func (p *parser) parseBraceExpansion() (expansion, error) { if c := p.nextRune(); c != '{' { - return nil, fmt.Errorf("Expected brace expansion to start with {, got %c", c) + return nil, fmt.Errorf("expected brace expansion to start with {, got %s", describeRune(c)) + } + + p.depth++ + defer func() { p.depth-- }() + if p.depth > maxNestingDepth { + return nil, fmt.Errorf("brace expansions nested deeper than %d levels", maxNestingDepth) + } + + if c := p.peekRune(); c == '}' { + return nil, errors.New("empty expansion ${}, expected a variable name") + } + + // ${#parameter} is the length of the value, so it has a prefix and no operator. + if c := p.peekRune(); c == '#' { + _ = p.nextRune() + return p.parseLengthExpansion() } identifier, err := p.scanIdentifier() @@ -136,87 +175,100 @@ func (p *Parser) parseBraceExpansion() (Expansion, error) { if c := p.peekRune(); c == '}' { _ = p.nextRune() - return VariableExpansion{Identifier: identifier}, nil + return variableExpansion{Identifier: identifier}, nil } - var operator string - var exp Expansion + operator, err := p.scanOperator() + if err != nil { + return nil, err + } - // Parse an operator, some trickery is needed to handle : vs :- - if op1 := p.nextRune(); op1 == ':' { - if op2 := p.peekRune(); op2 == '-' { - _ = p.nextRune() - operator = ":-" - } else { - operator = ":" + var expansion expansion + if operator == ":" { + expansion, err = p.parseSubstringExpansion(identifier) + if err != nil { + return nil, err } - } else if op1 == '?' || op1 == '-' { - operator = string(op1) } else { - return nil, fmt.Errorf("Expected an operator, got %c", op1) - } - - switch operator { - case `:-`: - exp, err = p.parseEmptyValueExpansion(identifier) + // All other operators take a word: an expression (text and expansions) up until the end + // of the brace. + word, err := p.parseExpression('}') if err != nil { return nil, err } - case `-`: - exp, err = p.parseUnsetValueExpansion(identifier) - if err != nil { - return nil, err - } - case `:`: - exp, err = p.parseSubstringExpansion(identifier) - if err != nil { - return nil, err - } - case `?`: - exp, err = p.parseRequiredExpansion(identifier) - if err != nil { - return nil, err + switch operator { + case ":-": + expansion = emptyValueExpansion{Identifier: identifier, Content: word} + case "-": + expansion = unsetValueExpansion{Identifier: identifier, Content: word} + case ":?": + expansion = requiredNonEmptyExpansion{Identifier: identifier, Message: word} + case "?": + expansion = requiredExpansion{Identifier: identifier, Message: word} + case ":+": + expansion = alternateNonEmptyExpansion{Identifier: identifier, Content: word} + case "+": + expansion = alternateExpansion{Identifier: identifier, Content: word} } } if c := p.nextRune(); c != '}' { - return nil, fmt.Errorf("Expected brace expansion to end with }, got %c", c) + return nil, fmt.Errorf("expected brace expansion to end with }, got %s", describeRune(c)) } - return exp, nil + return expansion, nil } -func (p *Parser) parseEmptyValueExpansion(identifier string) (Expansion, error) { - // parse an expression (text and expansions) up until the end of the brace - expr, err := p.parseExpression('}') +// scanOperator scans the operator after the identifier in a brace expansion. A colon on its own +// is a substring operator. A colon followed by "-", "?" or "+" also treats an empty value as +// unset. +func (p *parser) scanOperator() (string, error) { + switch op1 := p.nextRune(); op1 { + case ':': + if op2 := p.peekRune(); op2 == '-' || op2 == '?' || op2 == '+' { + _ = p.nextRune() + return string([]rune{op1, op2}), nil + } + return ":", nil + case '-', '?', '+': + return string(op1), nil + default: + return "", fmt.Errorf("expected an operator, got %s", describeRune(op1)) + } +} + +func (p *parser) parseLengthExpansion() (expansion, error) { + identifier, err := p.scanIdentifier() if err != nil { return nil, err } - return EmptyValueExpansion{Identifier: identifier, Content: expr}, nil -} - -func (p *Parser) parseUnsetValueExpansion(identifier string) (Expansion, error) { - expr, err := p.parseExpression('}') - if err != nil { - return nil, err + if c := p.nextRune(); c != '}' { + return nil, fmt.Errorf("expected length expansion to end with }, got %s", describeRune(c)) } - return UnsetValueExpansion{Identifier: identifier, Content: expr}, nil + return lengthExpansion{Identifier: identifier}, nil } -func (p *Parser) parseSubstringExpansion(identifier string) (Expansion, error) { +func (p *parser) parseSubstringExpansion(identifier string) (expansion, error) { offset := p.scanUntil(func(r rune) bool { return r == ':' || r == '}' }) - offsetInt, err := strconv.Atoi(strings.TrimSpace(offset)) - if err != nil { - return nil, fmt.Errorf("Unable to parse offset: %v", err) + // Bash rejects ${VAR:}, but treats a blank offset as 0 when it is followed by a length, as in + // ${VAR::2}, or when it has only spaces, as in ${VAR: }. + hasLength := p.peekRune() == ':' + if offset == "" && !hasLength { + return nil, fmt.Errorf("expected substring offset, got %s", describeRune(p.peekRune())) } - if c := p.peekRune(); c == '}' { - return SubstringExpansion{Identifier: identifier, Offset: offsetInt}, nil + offsetInt, err := parseSubstringNumber(offset) + if err != nil { + return nil, fmt.Errorf("parse substring offset: %w", err) + } + + if !hasLength { + return substringExpansion{Identifier: identifier, Offset: offsetInt}, nil } _ = p.nextRune() @@ -224,28 +276,28 @@ func (p *Parser) parseSubstringExpansion(identifier string) (Expansion, error) { return r == '}' }) - lengthInt, err := strconv.Atoi(strings.TrimSpace(length)) + lengthInt, err := parseSubstringNumber(length) if err != nil { - return nil, fmt.Errorf("Unable to parse length: %v", err) + return nil, fmt.Errorf("parse substring length: %w", err) } - return SubstringExpansion{Identifier: identifier, Offset: offsetInt, Length: lengthInt, HasLength: true}, nil + return substringExpansion{Identifier: identifier, Offset: offsetInt, Length: lengthInt, HasLength: true}, nil } -func (p *Parser) parseRequiredExpansion(identifier string) (Expansion, error) { - expr, err := p.parseExpression('}') - if err != nil { - return nil, err +// parseSubstringNumber parses a substring offset or length. A blank value is 0, the same as bash. +func parseSubstringNumber(value string) (int, error) { + value = strings.TrimSpace(value) + if value == "" { + return 0, nil } - - return RequiredExpansion{Identifier: identifier, Message: expr}, nil + return strconv.Atoi(value) } -func (p *Parser) scanUntil(f func(rune) bool) string { +func (p *parser) scanUntil(f func(rune) bool) string { start := p.pos - for int(p.pos) < len(p.input) { + for p.pos < len(p.input) { c, size := utf8.DecodeRuneInString(p.input[p.pos:]) - if c == utf8.RuneError || f(c) { + if f(c) { break } p.pos += size @@ -253,18 +305,35 @@ func (p *Parser) scanUntil(f func(rune) bool) string { return p.input[start:p.pos] } -func (p *Parser) scanIdentifier() (string, error) { - if c := p.peekRune(); !unicode.IsLetter(c) { - return "", fmt.Errorf("Expected identifier to start with a letter, got %c", c) +func (p *parser) scanIdentifier() (string, error) { + if c := p.peekRune(); !isIdentifierStart(c) { + return "", fmt.Errorf("expected identifier to start with a letter or underscore, got %s", describeRune(c)) } - var notIdentifierChar = func(r rune) bool { - return (!unicode.IsLetter(r) && !unicode.IsNumber(r) && r != '_') + notIdentifierChar := func(r rune) bool { + return !isIdentifierChar(r) } return p.scanUntil(notIdentifierChar), nil } -func (p *Parser) nextRune() rune { - if int(p.pos) >= len(p.input) { +// isExpansionStart reports whether the dollar sign at the current position starts an expansion. +func (p *parser) isExpansionStart() bool { + next, _ := utf8.DecodeRuneInString(p.input[p.pos+1:]) + return next == '{' || isIdentifierStart(next) +} + +// isIdentifierStart reports whether r can start a POSIX name: an ASCII letter or an underscore. +func isIdentifierStart(r rune) bool { + return r == '_' || ('a' <= r && r <= 'z') || ('A' <= r && r <= 'Z') +} + +// isIdentifierChar reports whether r can continue a POSIX name: an ASCII letter, an ASCII digit, +// or an underscore. +func isIdentifierChar(r rune) bool { + return isIdentifierStart(r) || ('0' <= r && r <= '9') +} + +func (p *parser) nextRune() rune { + if p.pos >= len(p.input) { return eof } c, size := utf8.DecodeRuneInString(p.input[p.pos:]) @@ -272,10 +341,18 @@ func (p *Parser) nextRune() rune { return c } -func (p *Parser) peekRune() rune { - if int(p.pos) >= len(p.input) { +func (p *parser) peekRune() rune { + if p.pos >= len(p.input) { return eof } c, _ := utf8.DecodeRuneInString(p.input[p.pos:]) return c } + +// describeRune returns a description of r for use in error messages. +func describeRune(r rune) string { + if r == eof { + return "end of input" + } + return fmt.Sprintf("%q", r) +} diff --git a/vendor/github.com/pandatix/go-abnf/.gitignore b/vendor/github.com/pandatix/go-abnf/.gitignore new file mode 100644 index 0000000..4926220 --- /dev/null +++ b/vendor/github.com/pandatix/go-abnf/.gitignore @@ -0,0 +1,17 @@ +# IDE files +.vscode/* + +# Benchmark files +*.pprof +*.golden + +# Fuzzing files +testdata/fuzz/* + +# Generated files from pap +*.mmd +*.svg + +# Documents +*.pdf +*.bkp diff --git a/vendor/github.com/pandatix/go-abnf/.goreleaser.yaml b/vendor/github.com/pandatix/go-abnf/.goreleaser.yaml new file mode 100644 index 0000000..abd2c45 --- /dev/null +++ b/vendor/github.com/pandatix/go-abnf/.goreleaser.yaml @@ -0,0 +1,37 @@ +before: + hooks: + - go mod tidy + +gomod: + proxy: true + +builds: + - id: pap + main: ./cmd/pap + binary: pap + env: + - CGO_ENABLED=0 + goos: + - linux + goarch: + - amd64 + +archives: + - id: pap + builds: + - pap + +changelog: + sort: asc + filters: + exclude: + - '^docs:' + - '^test:' + +source: + enabled: true + +checksum: {} + +sboms: + - artifacts: source diff --git a/vendor/github.com/pandatix/go-abnf/CODE_OF_CONDUCT.md b/vendor/github.com/pandatix/go-abnf/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..516c72d --- /dev/null +++ b/vendor/github.com/pandatix/go-abnf/CODE_OF_CONDUCT.md @@ -0,0 +1,128 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, religion, or sexual identity +and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the + overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or + advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email + address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at +lucastesson@protonmail.com. +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series +of actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or +permanent ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within +the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.0, available at +https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct +enforcement ladder](https://github.com/mozilla/diversity). + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see the FAQ at +https://www.contributor-covenant.org/faq. Translations are available at +https://www.contributor-covenant.org/translations. diff --git a/vendor/github.com/pandatix/go-abnf/CONTRIBUTING.md b/vendor/github.com/pandatix/go-abnf/CONTRIBUTING.md new file mode 100644 index 0000000..677046c --- /dev/null +++ b/vendor/github.com/pandatix/go-abnf/CONTRIBUTING.md @@ -0,0 +1,16 @@ +# Contributing + +Open-Source means we welcome all changes and ideas any time of day and nights, through issues and pull requests. + +## How to contribute + +As the community around this project is small enough, we set the following contributing guidelines: + - if necessary, [open an issue](https://github.com/pandatix/go-abnf/issues/new) first + - fork the repository + - clone, commit, and when feeling confident enough [create a pull request](https://github.com/pandatix/go-abnf/compare) with the issue(s) it solves. + - check your notifications for comments, suggestions, and maybe an approval + +## Quality + +This implementation focuses on the IETF RFCs, security and performances. +We expect your contribution to provide a minimum quality with unitary tests when applicable. diff --git a/vendor/github.com/pandatix/go-abnf/LICENSE b/vendor/github.com/pandatix/go-abnf/LICENSE new file mode 100644 index 0000000..89527da --- /dev/null +++ b/vendor/github.com/pandatix/go-abnf/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Lucas TESSON - PandatiX + +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. diff --git a/vendor/github.com/pandatix/go-abnf/README.md b/vendor/github.com/pandatix/go-abnf/README.md new file mode 100644 index 0000000..902f081 --- /dev/null +++ b/vendor/github.com/pandatix/go-abnf/README.md @@ -0,0 +1,156 @@ +
+

Go-ABNF

+ reference + go report + Coverage Status +
+ License + CI + CodeQL +
+ OpenSSF Scoreboard + OpenSSF Best Practices Summary +
+ +A dependency-free Go module for Augmented Backus-Naur Form (ABNF). It parses an ABNF grammar into a data structure and then lets you *recognise*, *parse*, *generate*, *compile to regex*, *visualise*, and even *generate a standalone Go parser* from it. It implements [RFC 5234](https://www.rfc-editor.org/rfc/rfc5234) and [RFC 7405](https://www.rfc-editor.org/rfc/rfc7405), with Errata [2968](https://errata.rfc-editor.org/eid2968/) and [3076](https://errata.rfc-editor.org/eid3076/). + +> [!NOTE] +> **Intended use.** Go-ABNF is built first and foremost as a **testing oracle**. +> Because it can turn one grammar into several independent representations (recognizer, parse forest, regex, generator, transition graph), it is well suited to **differential testing and fuzzing**: generate inputs from a grammar, feed them to your own implementation, and cross-check the verdicts against this library - or cross-check the library's own views against each other. It favors correctness and generality (ambiguous and left-recursive grammars, Unicode) over being the fastest production parser. + +## Capabilities + +- Parse ABNF into a manipulable `*Grammar` (with cycle / DAG detection). +- Recognize input against a grammar - ambiguous and left-recursive grammars included. +- Build a full **parse forest** (SPPF) or **binary-subtree set** (BSR): count trees, detect ambiguity, extract a tree. +- Compile a grammar to a **regular expression** (precedence-aware, size-bounded). +- **Generate** inputs (random walk), a minimal covering test set, or structured ASTs - for fuzzing. +- **Visualize** a grammar as a transition graph (Mermaid). +- **Generate a standalone, specialized Go parser** from a grammar (`go generate`). +- Unicode code points and 64-bit numeric values; bounded against DoS. + +```mermaid +flowchart TD + A["ABNF text"] -->|ParseABNF| G["*Grammar"] + G -->|IsValid| R["recognise
(valid?)"] + G -->|ParseForest / ParseBSR| F["parse forest
(trees, ambiguity)"] + G -->|Regex| X["regular expression"] + G -->|Generate / ASTGenerator| S["sample inputs"] + G -->|TransitionGraph| T["graph (Mermaid)"] + G -->|GenerateGoParser| C["standalone Go parser"] + S -. feed .-> SUT["your implementation"] + R -. cross-check .- F + F -. cross-check .- X +``` + +## How it works + +ABNF is *self-describing*: its own syntax is written in ABNF. Go-ABNF bootstraps from a handwritten parse/evaluation of that meta-grammar, after which any valid grammar parsed by the library can in turn be used to parse new input - so the engine is generic, not specialized to ABNF. + +
+ +
+ +Two parse paths exist by design: +- **Recognition** (`Grammar.IsValid`) answers *does this input match?* by tracking the set of reachable input positions. It never materializes a tree, so it is cheap and is the reference verdict for the other paths. +- **Parsing** builds a derivation representation using a **GLL** engine [1], which handles arbitrary context-free grammars including ambiguity and (left/right/hidden) recursion. Two representations are available over the same engine: a **Shared Packed Parse Forest** [2] (`ParseForest`) and a **Binary Subtree Set** [3] (`ParseBSR`). Both expose `Valid`, `NumTrees`, `Ambiguous` and `Tree`. + +Repetition (`Min*Max element`) is handled *natively*: it lowers to a single self-recursive nonterminal and the bound is enforced by a counter carried in parser state, rather than unrolled - so a grammar like `0*9999999999 "x"` costs $O(1)$ to set up instead of exhausting memory. + +The generated-parser work targets BSR representation [3], in the spirit of [GoGLL](https://github.com/goccmack/gogll). + +References: +- [1] _E. Scott, A. Johnstone. "GLL Parsing," in Electronic Notes in Theoretical Computer Science, vol. 253, no. 7, pp. 177-189, 2010._ +- [2] _E. Scott, A. Johnstone. "GLL parse-tree generation," in Science of Computer Programming, vol. 78, no. 10, pp. 1828-1844, 2013._ +- [3] _E. Scott, A. Johnstone, L. van Binsbergen. "Derivation representation using binary subtree sets," in Science of Computer Programming, vol. 175, pp. 63-84, 2019._ + +## Usage + +Parse a grammar, then recognize or parse input: + +```go +g, err := goabnf.ParseABNF(grammarBytes) // []byte of ABNF, CRLF line endings +if err != nil { /* ... */ } + +ok, _ := g.IsValid("rule", input) // boolean recognizer + +f, _ := goabnf.ParseForest(input, g, "rule") +fmt.Println(f.Valid(), f.NumTrees(), f.Ambiguous()) + +bf, _ := goabnf.ParseBSR(input, g, "rule") // same answers, BSR representation +``` + +Compile to a regular expression, or render a transition graph: + +```go +re, _ := g.Regex("rule", goabnf.WithMaxRegexLen(4096)) + +tg, _ := g.TransitionGraph("rule") +fmt.Println(tg.ToMermaid()) +``` + +### As a fuzzing oracle + +Generate inputs from a grammar to drive Go's fuzzer, even when the input format is too specific for the engine to discover on its own: +```go +func FuzzMyParser(f *testing.F) { + g, err := goabnf.ParseABNF(myGrammar) + if err != nil { f.Fatal(err) } + + f.Fuzz(func(t *testing.T, seed int64) { + input, _ := g.Generate(seed, "rule", + goabnf.WithRepMax(15), // cap repetitions + goabnf.WithThreshold(1024), // cap generated size + ) + MyParser(input) // must not panic; optionally cross-check verdicts + }) +} +``` + +More fuzzing helpers are [documented here](examples/fuzzing/). + +### As a differential oracle + +The recognizer and the parse forest are independent code paths over the same grammar; agreement between them (and with your own implementation) is a strong correctness signal: +```go +ok, _ := g.IsValid("rule", input) +f, _ := goabnf.ParseForest(input, g, "rule") +if ok != f.Valid() { + t.Fatalf("oracle disagreement on %q", input) // a bug in grammar or engine +} +``` + +## Code generation + +Generate a standalone, specialized parser for a grammar - a jump-table GLL/BSR parser with inlined terminals, depending only on the standard library: +```go +src, _ := goabnf.GenerateGoParser(g, "rule", "myparser") +// or, straight from ABNF source: +src, _ = goabnf.GenerateGoParserFromABNF(grammarBytes, "rule", "myparser") +``` + +Wire it into `go generate` with the `cmd/abnf-gen` command: + +```go +//go:generate go run github.com/pandatix/go-abnf/cmd/abnf-gen -in grammar.abnf -root rule -pkg myparser -out parser_gen.go +``` + +The generated file exposes `Parse`, `Result` (`Valid`/`NumTrees`/`Ambiguous`/ `Tree`) and `ParseTree`. Its identifiers are package-scoped, so generate **one parser per package** (e.g. a dedicated `internal/myparser/`). The generated parser is faithful to the grammar you give it: feeding the *raw* RFC 5234 ABNF self-definition produces an ambiguous parser (the defect Erratum 2968 fixes), while the corrected grammar produces an unambiguous one - choose deliberately, and assert the expected tree count in a test. + +## Safety + +The engines are bounded to stay usable on untrusted grammars and inputs: `WithMaxNodes` (transition graph), `WithMaxForestNodes` / `WithMaxSlots` (forest), `WithMaxRegexLen` (regex), and the generated parser's `MaxElements`. Numeric values are accepted up to 64 bits without panicking, and matching is Unicode-aware. + +## Troubleshooting + +### My ABNF grammar does not work + +**Q**: My ABNF grammar does not work. Do you have any idea why ? + +**A**: There could be many reasons to this. First make sure your grammar ends up by a newline (LF), and especially that the input content has a CR LF. As those appear the same, it is often a source of error. + +### Difference between pap and bap + +**Q**: Is there a difference between pap and [bap](https://github.com/ietf-tools/bap) ? + +**A**: Being written in Go makes `pap` more portable and easier to embed in workflows. Beyond that, the goals differ: `bap` aims to produce meaningful end-user errors, whereas `pap` is built to *challenge* it - and goes further by building transition graphs for fuzzing Go code and by supporting Unicode code points (useful for, e.g., [TOML, which is specified in ABNF](https://github.com/toml-lang/toml/blob/main/toml.abnf)). diff --git a/vendor/github.com/pandatix/go-abnf/SECURITY.md b/vendor/github.com/pandatix/go-abnf/SECURITY.md new file mode 100644 index 0000000..cd92f4b --- /dev/null +++ b/vendor/github.com/pandatix/go-abnf/SECURITY.md @@ -0,0 +1,11 @@ +# Reporting Security Issues + +Please report any security issues you discovered in the API to lucastesson@protonmail.com. + +We will assess the risk, plus make a fix available before we create a GitHub issue. + +Thank you for your contribution. + +## Refering to this repository + +To refer to this repository using a CPE v2.3, please use `cpe:2.3:a:pandatix:go-abnf:*:*:*:*:*:*:*:*` with the `version` set to the tag you are using. diff --git a/vendor/github.com/pandatix/go-abnf/abnf.go b/vendor/github.com/pandatix/go-abnf/abnf.go new file mode 100644 index 0000000..5173714 --- /dev/null +++ b/vendor/github.com/pandatix/go-abnf/abnf.go @@ -0,0 +1,244 @@ +package goabnf + +import ( + "fmt" + "strconv" + "strings" +) + +// ElemItf defines the interface of all the element alternations: +// - ElemRulename +// - ElemGroup +// - ElemOption +// - ElemProseVal +// - ElemNumVal +// - ElemCharVal +// +// This is exposed for custom evaluation purposes, please don't use it else. +type ElemItf interface { + fmt.Stringer +} + +// Rule represents an ABNF rule, with its name and underlying alternation. +// +// This is exposed for custom evaluation purposes, please don't use it else. +type Rule struct { + // Name is the unique rule name. + // Notice it is case-insensitive according to RFC 5234 Section 2.1. + Name string + + Alternation Alternation +} + +func (rl Rule) String() string { + return fmt.Sprintf("%s = %s", rl.Name, rl.Alternation) +} + +// Alternation represents an ABNF alternation object. +// +// This is exposed for custom evaluation purposes, please don't use it else. +type Alternation struct { + // Concatenations contains the variants that validate the upper + // object (i.e. rule, group or option). + Concatenations []Concatenation +} + +func (alt Alternation) String() string { + str := "" + for _, concat := range alt.Concatenations { + str += fmt.Sprintf("%s / ", concat) + } + return strings.TrimSuffix(str, " / ") +} + +// Concatenation represents an ABNF concatenation object. +// +// This is exposed for custom evaluation purposes, please don't use it else. +type Concatenation struct { + // Repetitions contains the following repetitions, order matter. + Repetitions []Repetition +} + +func (cnt Concatenation) String() string { + str := "" + for _, rep := range cnt.Repetitions { + str += fmt.Sprintf("%s ", rep) + } + return strings.TrimSuffix(str, " ") +} + +// Repetition represents an ABNF repetition object. +// +// This is exposed for custom evaluation purposes, please don't use it else. +type Repetition struct { + Min, Max int + Element ElemItf +} + +func (rep Repetition) String() string { + if rep.Min == rep.Max { + if rep.Min == 1 { + return rep.Element.String() + } + return strconv.Itoa(rep.Min) + rep.Element.String() + } + str := "" + if rep.Min != 0 { + str += strconv.Itoa(rep.Min) + } + str += "*" + if rep.Max != inf { + str += strconv.Itoa(rep.Max) + } + return str + rep.Element.String() +} + +// ElemRulename represents an ABNF rulename object. +// +// This is exposed for custom evaluation purposes, please don't use it else. +type ElemRulename struct { + // Name is the unique rule name. + // Notice it is case-insensitive according to RFC 5234 Section 2.1. + Name string +} + +func (erln ElemRulename) String() string { + return erln.Name +} + +var _ ElemItf = (*ElemRulename)(nil) + +// ElemGroup represents an ABNF group object. +// It will be straightly passed through with its underlying alternation. +// +// This is exposed for custom evaluation purposes, please don't use it else. +type ElemGroup struct { + Alternation Alternation +} + +func (egrp ElemGroup) String() string { + return "(" + egrp.Alternation.String() + ")" +} + +var _ ElemItf = (*ElemGroup)(nil) + +// ElemOption represents an ABNF option object. +// It will be straightly converted to a 0*1 repetition. +// +// This is exposed for custom evaluation purposes, please don't use it else. +type ElemOption struct { + Alternation Alternation +} + +func (eopt ElemOption) String() string { + return "[" + eopt.Alternation.String() + "]" +} + +var _ ElemItf = (*ElemOption)(nil) + +// ElemCharVal represents an ABNF char-val object. +// +// This is exposed for custom evaluation purposes, please don't use it else. +type ElemCharVal struct { + // Sensitive is by default false, support clarrified by RFC 7405 hence + // only works on a-z and A-Z. + Sensitive bool + Values []rune +} + +func (ecvl ElemCharVal) String() string { + str := "" + for _, val := range ecvl.Values { + str += string(val) + } + return `"` + str + `"` +} + +var _ ElemItf = (*ElemCharVal)(nil) + +// ElemNumVal represents an ABNF num-val object. +// +// This is exposed for custom evaluation purposes, please don't use it else. +type ElemNumVal struct { + Base string + // Status could be: + // - `statSeries`: `elems` contains all the expected + // values in the order of the grammar defined them ; + // - `statRange`: `elems` contains the start and end + // bounds (so no more than two). + Status Status + Elems []string +} + +func (envl ElemNumVal) String() string { + str := "%" + envl.Base + spl := "." + if envl.Status == StatRange { + spl = "-" + } + for _, val := range envl.Elems { + str += val + spl + } + return strings.TrimSuffix(str, spl) +} + +var _ ElemItf = (*ElemNumVal)(nil) + +// ElemProseVal represents an ABNF prose-val object. +// +// This is exposed for custom evaluation purposes, please don't use it else. +type ElemProseVal struct { + values []string +} + +func (epvl ElemProseVal) String() string { + str := "" + for _, val := range epvl.values { + str += val + } + return "<" + str + ">" +} + +var _ ElemItf = (*ElemProseVal)(nil) + +// Status defines the type of a num-val, rather StatSeries or StatRange. +// +// This is exposed for custom evaluation purposes, please don't use it else. +type Status int + +const ( + // StatSeries represents a serie of unique byte value. + StatSeries Status = iota + // StatRange represents an interval of possible bytes. + StatRange +) + +// ABNF is the manually parsed+evaluated+validated ABNF grammar. +var ABNF = &Grammar{ + Rulemap: map[string]*Rule{ + abnfRulelist.Name: abnfRulelist, + abnfRule.Name: abnfRule, + abnfRulename.Name: abnfRulename, + abnfDefinedAs.Name: abnfDefinedAs, + abnfElements.Name: abnfElements, + abnfCWsp.Name: abnfCWsp, + abnfCNl.Name: abnfCNl, + abnfComment.Name: abnfComment, + abnfAlternation.Name: abnfAlternation, + abnfConcatenation.Name: abnfConcatenation, + abnfRepetition.Name: abnfRepetition, + abnfRepeat.Name: abnfRepeat, + abnfElement.Name: abnfElement, + abnfGroup.Name: abnfGroup, + abnfOption.Name: abnfOption, + abnfCharVal.Name: abnfCharVal, + abnfCaseInsensitiveString.Name: abnfCaseInsensitiveString, + abnfCaseSensitiveString.Name: abnfCaseSensitiveString, + abnfQuotedString.Name: abnfQuotedString, + abnfNumVal.Name: abnfNumVal, + abnfBinVal.Name: abnfBinVal, + abnfDecVal.Name: abnfDecVal, + abnfHexVal.Name: abnfHexVal, + abnfProseVal.Name: abnfProseVal, + }, +} diff --git a/vendor/github.com/pandatix/go-abnf/ast.go b/vendor/github.com/pandatix/go-abnf/ast.go new file mode 100644 index 0000000..5b5adc6 --- /dev/null +++ b/vendor/github.com/pandatix/go-abnf/ast.go @@ -0,0 +1,394 @@ +package goabnf + +import ( + "fmt" + "math/rand" + "unicode/utf8" +) + +// Generates strings by recursive descent over the grammar AST, so unlike the* +// transition-graph Generator (a finite automaton, which can only express +// *regular* rules) it handles genuinely recursive rules -- nested objects, +// balanced delimiters, expression grammars -- where a rule is reached many times +// at many depths. +// +// The hard part of recursive generation is termination: a recursive rule can +// expand forever. This generator guarantees a finite, valid production by +// precomputing each rule's minimum expansion cost and, whenever a depth or +// length budget is exceeded, steering every choice toward the cheapest-to-finish +// expansion. It never truncates mid-derivation, so the output is always a +// complete word of the grammar. (It shares the tape/rand entropy `source` with +// the transition-graph generator, so it slots into testing.F the same way.) + +const astUnbounded = 1 << 30 // "infinite" min-length sentinel (non-productive) + +// ASTGenerator generates strings admitted by a (possibly recursive) grammar +// rule, directly from the AST. +type ASTGenerator struct { + g *Grammar + start *Rule + + maxDepth int // rule-expansion depth before steering to terminate + maxLen int // output bytes before steering to terminate + maxRepeat int // cap for unbounded ("*") repetitions + + minCost map[string]int // rule name -> minimum expansion cost (productivity) +} + +// ASTGenOption configures an ASTGenerator. +type ASTGenOption interface { + apply(*ASTGenerator) +} + +type astGenOptionFunc func(*ASTGenerator) + +func (f astGenOptionFunc) apply(g *ASTGenerator) { + f(g) +} + +// WithMaxDepth bounds rule-expansion (recursion) depth; past it the generator +// steers toward terminating expansions. Defaults to 32. +func WithMaxDepth(n int) ASTGenOption { + return astGenOptionFunc(func(g *ASTGenerator) { + g.maxDepth = n + }) +} + +// WithMaxLen bounds the output length; past it the generator steers toward +// terminating expansions. Defaults to 4096. (Mandatory repetitions are always +// emitted, so the bound is soft -- a single huge fixed repetition can exceed it.) +func WithMaxLen(n int) ASTGenOption { + return astGenOptionFunc(func(g *ASTGenerator) { + g.maxLen = n + }) +} + +// WithMaxRepeat caps how far an unbounded ("*" / "1*") repetition is unrolled. +// Defaults to 16. +func WithMaxRepeat(n int) ASTGenOption { + return astGenOptionFunc(func(g *ASTGenerator) { + g.maxRepeat = n + }) +} + +// NewASTGenerator prepares a generator for rule. It errors if the rule is +// undefined, or if any rule reachable from it is undefined or non-productive +// (cannot derive any finite string), since neither can be generated. Unlike the +// transition-graph generator, recursive rules are fully supported. +func NewASTGenerator(g *Grammar, rule string, opts ...ASTGenOption) (*ASTGenerator, error) { + start := GetRule(rule, g.Rulemap) + if start == nil { + return nil, &ErrRuleNotFound{Rulename: rule} + } + ag := &ASTGenerator{ + g: g, + start: start, + maxDepth: 32, + maxLen: 4096, + maxRepeat: 16, + } + for _, o := range opts { + o.apply(ag) + } + + // Least-fixpoint of minimum expansion cost over every rule reachable in + // principle -- user rules and the built-in core rules (ALPHA, DIGIT, ...), + // which GetRule resolves as a fallback but which are absent from Rulemap. + // Keyed by canonical rule name (GetRule is case-insensitive and honors user + // overrides of core rules). A rule stuck at the sentinel is non-productive. + effective := map[string]*Rule{} + for n := range g.Rulemap { + if r := GetRule(n, g.Rulemap); r != nil { + effective[r.Name] = r + } + } + for n := range coreRules { + if r := GetRule(n, g.Rulemap); r != nil { + effective[r.Name] = r + } + } + ag.minCost = make(map[string]int, len(effective)) + for name := range effective { + ag.minCost[name] = astUnbounded + } + for changed := true; changed; { + changed = false + for name, r := range effective { + if c := ag.costAlt(r.Alternation); c < ag.minCost[name] { + ag.minCost[name] = c + changed = true + } + } + } + + // Every rule reachable from start must be defined and productive. + seen := map[string]bool{start.Name: true} + var visitAlt func(Alternation) error + visitElem := func(e ElemItf) error { + switch x := e.(type) { + case ElemRulename: + r := GetRule(x.Name, g.Rulemap) + if r == nil { + return fmt.Errorf("rule %q (reachable from %q) is undefined and cannot be generated", x.Name, rule) + } + if seen[r.Name] { + return nil + } + seen[r.Name] = true + if ag.minCost[r.Name] >= astUnbounded { + return fmt.Errorf("rule %q (reachable from %q) is non-productive (cannot derive any finite string)", r.Name, rule) + } + return visitAlt(r.Alternation) + case ElemGroup: + return visitAlt(x.Alternation) + case ElemOption: + return visitAlt(x.Alternation) + } + return nil + } + visitAlt = func(a Alternation) error { + for _, c := range a.Concatenations { + for _, rep := range c.Repetitions { + if err := visitElem(rep.Element); err != nil { + return err + } + } + } + return nil + } + if ag.minCost[start.Name] >= astUnbounded { + return nil, fmt.Errorf("rule %q is non-productive (cannot derive any finite string)", rule) + } + if err := visitAlt(start.Alternation); err != nil { + return nil, err + } + return ag, nil +} + +// Generate maps the tape to a production the grammar admits. Total and +// deterministic: any tape (including nil) yields a valid production; an +// exhausted tape biases toward the shortest one. +func (ag *ASTGenerator) Generate(tape []byte) []byte { + return ag.walk(&tapeSource{tape: tape}) +} + +// GenerateRand draws a production using r as the entropy source. +func (ag *ASTGenerator) GenerateRand(r *rand.Rand) []byte { + return ag.walk(randSource{r: r}) +} + +func (ag *ASTGenerator) walk(src source) []byte { + out := []byte{} + ag.genAlt(src, &out, ag.start.Alternation, 0) + return out +} + +// over reports whether we should stop taking expansions for their own sake and +// steer toward the nearest terminal string. +func (ag *ASTGenerator) over(out *[]byte, depth int) bool { + return depth >= ag.maxDepth || len(*out) >= ag.maxLen +} + +func (ag *ASTGenerator) genAlt(src source, out *[]byte, alt Alternation, depth int) { + cs := alt.Concatenations + if len(cs) == 0 { + return + } + idx := 0 + if ag.over(out, depth) { + idx = ag.cheapestConcat(cs) // steer: pick the cheapest-to-finish branch + } else if len(cs) > 1 { + idx = src.intn(len(cs)) + } + ag.genConcat(src, out, cs[idx], depth) +} + +func (ag *ASTGenerator) genConcat(src source, out *[]byte, concat Concatenation, depth int) { + for _, rep := range concat.Repetitions { + ag.genRep(src, out, rep, depth) + } +} + +func (ag *ASTGenerator) genRep(src source, out *[]byte, rep Repetition, depth int) { + lo := rep.Min + hi := rep.Max + if hi == inf || hi < lo { // unbounded: cap the optional unrolling + hi = lo + ag.maxRepeat + } + n := lo + if !ag.over(out, depth) && hi > lo { + n = lo + src.intn(hi-lo+1) + } + for i := 0; i < n; i++ { + ag.genElem(src, out, rep.Element, depth) + // Stop optional extras once over length, but always emit the mandatory lo. + if i+1 >= lo && len(*out) >= ag.maxLen { + break + } + } +} + +func (ag *ASTGenerator) genElem(src source, out *[]byte, elem ElemItf, depth int) { + switch e := elem.(type) { + case ElemRulename: + // Guaranteed defined+productive by NewASTGenerator. + r := GetRule(e.Name, ag.g.Rulemap) + ag.genAlt(src, out, r.Alternation, depth+1) + + case ElemGroup: + ag.genAlt(src, out, e.Alternation, depth) + + case ElemOption: + if !ag.over(out, depth) && src.intn(2) == 1 { + ag.genAlt(src, out, e.Alternation, depth) + } + + case ElemCharVal: + for _, r := range e.Values { + if !e.Sensitive && isASCIILetter(r) && src.intn(2) == 1 { + r = flipASCIICase(r) + } + *out = append(*out, []byte(string(r))...) + } + + case ElemNumVal: + switch e.Status { + case StatSeries: + for _, v := range e.Elems { + r := numvalToRune(v, e.Base) + // Emit only real characters; an out-of-range value cannot appear + // in UTF-8 input, so the series would never match anyway. + if utf8.ValidRune(r) { + *out = append(*out, []byte(string(r))...) + } + } + case StatRange: + min, max := numvalToRune(e.Elems[0], e.Base), numvalToRune(e.Elems[1], e.Base) + // Emit within the representable (Unicode) subset of the range. + if max > utf8.MaxRune { + max = utf8.MaxRune + } + if min > utf8.MaxRune || min > max { + break // nothing representable to emit + } + span := int(max-min) + 1 + if span < 1 { + span = 1 + } + *out = append(*out, []byte(string(min+rune(src.intn(span))))...) + } + + case ElemProseVal: + // prose-val is informal text; nothing mechanical to emit. + } +} + +// cheapestConcat returns the index of the concatenation with the smallest +// minimum expansion cost -- the fastest way to finish the current alternation. +func (ag *ASTGenerator) cheapestConcat(cs []Concatenation) int { + best, bestCost := 0, ag.costConcat(cs[0]) + for i := 1; i < len(cs); i++ { + if c := ag.costConcat(cs[i]); c < bestCost { + best, bestCost = i, c + } + } + return best +} + +// ---- minimum-expansion-cost cost model (for productivity + steering) ---- + +func (ag *ASTGenerator) costAlt(alt Alternation) int { + if len(alt.Concatenations) == 0 { + return 0 + } + best := astUnbounded + for _, c := range alt.Concatenations { + if v := ag.costConcat(c); v < best { + best = v + } + } + return best +} + +func (ag *ASTGenerator) costConcat(concat Concatenation) int { + total := 0 + for _, rep := range concat.Repetitions { + total = addClamp(total, mulClamp(rep.Min, ag.costElem(rep.Element))) + } + return total +} + +func (ag *ASTGenerator) costElem(elem ElemItf) int { + switch e := elem.(type) { + case ElemRulename: + r := GetRule(e.Name, ag.g.Rulemap) + if r == nil { + return astUnbounded // undefined rule + } + if c, ok := ag.minCost[r.Name]; ok { + // +1 expansion penalty: referencing a rule always costs strictly + // more than emitting a terminal, so a recursive branch can never + // tie with (and be chosen over) a terminating one -- even when a + // nullable prefix makes their emitted lengths equal. + return addClamp(1, c) + } + return astUnbounded + case ElemGroup: + return ag.costAlt(e.Alternation) + case ElemOption: + return 0 // can be skipped + case ElemCharVal: + return len(string(e.Values)) + case ElemNumVal: + switch e.Status { + case StatSeries: + n := 0 + for _, v := range e.Elems { + n += len(string(numvalToRune(v, e.Base))) + } + return n + default: // StatRange: one rune, take the lower bound's encoded length + return len(string(numvalToRune(e.Elems[0], e.Base))) + } + case ElemProseVal: + return 0 + } + return 0 +} + +func addClamp(a, b int) int { + if a >= astUnbounded || b >= astUnbounded { + return astUnbounded + } + if s := a + b; s < astUnbounded { + return s + } + return astUnbounded +} + +func mulClamp(n, c int) int { + if n == 0 { + return 0 + } + if c >= astUnbounded { + return astUnbounded + } + if p := n * c; p >= 0 && p < astUnbounded { + return p + } + return astUnbounded +} + +func isASCIILetter(r rune) bool { + return (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') +} + +func flipASCIICase(r rune) rune { + switch { + case r >= 'a' && r <= 'z': + return r - 'a' + 'A' + case r >= 'A' && r <= 'Z': + return r - 'A' + 'a' + } + return r +} diff --git a/vendor/github.com/pandatix/go-abnf/bsr.go b/vendor/github.com/pandatix/go-abnf/bsr.go new file mode 100644 index 0000000..8be32ab --- /dev/null +++ b/vendor/github.com/pandatix/go-abnf/bsr.go @@ -0,0 +1,604 @@ +package goabnf + +import ( + "math/big" + "unicode/utf8" +) + +// Binary Subtree Representation (BSR). +// +// This is an alternative derivation representation to the SPPF in sppf.go, +// following Scott, Johnstone & van Binsbergen, "Derivation representation using +// binary subtree sets" (Science of Computer Programming 175, 2019). Instead of +// interning symbol/intermediate/packed nodes, the parser records a flat set of +// elements (slot, l, k, r): a grammar slot whose consumed prefix derives the +// input span [l,r], with the most recently consumed symbol spanning [k,r] and +// the earlier prefix spanning [l,k]. The same GLL control (descriptors, GSS, +// native counted repetition) drives it; only what gets recorded differs. +// +// The GSS node's pos field already holds a production's left extent (the call +// position), so a BSR element needs no extra threading: on a dot advance the +// element is (newSlot, l=frameLeftExtent, k=pivot, r=end). +// +// The BSR engine is validated to produce identical Valid/NumTrees/Ambiguous +// results to the SPPF engine across the differential corpus; it is the intended +// foundation for grammar-directed parser generation. + +// bsrElem is one binary subtree element. The slot's dot is "just past" the most +// recently consumed symbol; that symbol spans [k,r] and the earlier prefix spans +// [l,k]. A complete production (dot == len) records the nonterminal's extent. +type bsrElem struct { + slot slot + l, k, r int +} + +// bsrGNode is a GSS node for the BSR engine. Unlike the SPPF GSS, its edges are +// unlabelled (no SPPF node is carried): the BSR pivots are recovered from node +// positions instead. +type bsrGNode struct { + ret slot // return slot in the caller's production + pos int // call position == the caller production's left extent for callees + rc int // repetition count (native counted repetition; 0 otherwise) + edges []*bsrGNode + edgeSet map[*bsrGNode]bool +} + +type bsrDesc struct { + L slot + u *bsrGNode + i int + rc int +} + +type bsrParser struct { + sg *slotGrammar + input []byte + + set map[bsrElem]bool + gss map[gssKey]*bsrGNode + u0 *bsrGNode + seen map[bsrDesc]bool + work []bsrDesc + popped map[*bsrGNode]map[int]bool + + maxElems int + aborted bool +} + +// addAlt adds the descriptor starting alternate L.alt of L.nt at i when the +// lookahead test admits it. +func (p *bsrParser) addAlt(L slot, u *bsrGNode, i, rc int) { + if p.sg.la.alt(L.nt, L.alt).admits(p.input, i) { + p.add(L, u, i, rc) + } +} + +func (p *bsrParser) add(L slot, u *bsrGNode, i, rc int) { + d := bsrDesc{L, u, i, rc} + if p.seen[d] { + return + } + p.seen[d] = true + p.work = append(p.work, d) +} + +func (p *bsrParser) gssNodeFor(ret slot, pos, rc int) *bsrGNode { + k := gssKey{ret, pos, rc} + if v, ok := p.gss[k]; ok { + return v + } + v := &bsrGNode{ret: ret, pos: pos, rc: rc, edgeSet: map[*bsrGNode]bool{}} + p.gss[k] = v + return v +} + +// record adds the BSR element for advancing into slot L over [l,r] with the last +// symbol pivoting at k. Per the binary-subtree scheme an element is kept only +// when the consumed prefix has length >= 2 (an intermediate extent) or the +// production is complete (dot == len). A length-1 prefix is degenerate (l == k) +// and is reconstructed directly from the single symbol, so it is not stored. +func (p *bsrParser) record(L slot, l, k, r int) { + prod := p.sg.nts[L.nt].alts[L.alt] + if L.dot >= 2 || L.dot == len(prod) { + if p.maxElems > 0 && len(p.set) >= p.maxElems { + p.aborted = true + return + } + p.set[bsrElem{L, l, k, r}] = true + } +} + +func (p *bsrParser) create(ret slot, u *bsrGNode, i, rc int) *bsrGNode { + v := p.gssNodeFor(ret, i, rc) + if !v.edgeSet[u] { + v.edgeSet[u] = true + v.edges = append(v.edges, u) + for j := range p.popped[v] { + p.record(ret, u.pos, i, j) + p.add(ret, u, j, rc) + } + } + return v +} + +func (p *bsrParser) pop(u *bsrGNode, j int) { + if u == p.u0 { + return + } + if p.popped[u] == nil { + p.popped[u] = map[int]bool{} + } + p.popped[u][j] = true + for _, v := range u.edges { + p.record(u.ret, v.pos, u.pos, j) + p.add(u.ret, v, j, u.rc) + } +} + +func (p *bsrParser) addRepAlts(ntID int, v *bsrGNode, i, rc int) { + nt := p.sg.nts[ntID] + if rc >= nt.repMin { + p.addAlt(slot{ntID, 0, 0}, v, i, rc) + } + if nt.repMax == inf || rc < nt.repMax { + p.addAlt(slot{ntID, 1, 0}, v, i, rc) + } +} + +func (p *bsrParser) matchTerm(s ssym, i int) int { + if s.kind == symEps { + return i + } + switch v := s.term.(type) { + case ElemCharVal: + idx := i + for k := 0; k < len(v.Values); k++ { + if idx >= len(p.input) { + return -1 + } + r, size := utf8.DecodeRune(p.input[idx:]) + if r == utf8.RuneError && size == 1 { + return -1 + } + if !sensequal(v.Values[k], r, v.Sensitive) { + return -1 + } + idx += size + } + return idx + case ElemNumVal: + switch v.Status { + case StatRange: + if i >= len(p.input) { + return -1 + } + min := numvalToRune(v.Elems[0], v.Base) + max := numvalToRune(v.Elems[1], v.Base) + r, size := utf8.DecodeRune(p.input[i:]) + if r == utf8.RuneError && size == 1 { + return -1 + } + if min <= r && r <= max { + return i + size + } + return -1 + case StatSeries: + idx := i + for k := 0; k < len(v.Elems); k++ { + ru := numvalToRune(v.Elems[k], v.Base) + if !utf8.ValidRune(ru) { + return -1 + } + str := string(ru) + sz := len(str) + if idx+sz > len(p.input) || str != string(p.input[idx:idx+sz]) { + return -1 + } + idx += sz + } + return idx + } + } + return -1 +} + +func (p *bsrParser) parse() { + startNT := p.sg.start + p.u0 = &bsrGNode{ret: slot{-1, -1, -1}, pos: 0, edgeSet: map[*bsrGNode]bool{}} + for ai := range p.sg.nts[startNT].alts { + p.addAlt(slot{startNT, ai, 0}, p.u0, 0, 0) + } + for len(p.work) > 0 { + if p.aborted { + return + } + d := p.work[len(p.work)-1] + p.work = p.work[:len(p.work)-1] + p.process(d) + } +} + +func (p *bsrParser) process(d bsrDesc) { + L, u, i, rc := d.L, d.u, d.i, d.rc + for { + prod := p.sg.nts[L.nt].alts[L.alt] + if L.dot == len(prod) { + p.pop(u, i) + return + } + s := prod[L.dot] + if s.kind == symNonterm { + if !p.sg.la.callAt(L).admits(p.input, i) { + return + } + ret := slot{L.nt, L.alt, L.dot + 1} + v := p.create(ret, u, i, rc) + if p.sg.nts[s.nt].isRep { + childRC := 0 + if s.nt == L.nt { + childRC = capRC(rc, p.sg.nts[s.nt]) + } + p.addRepAlts(s.nt, v, i, childRC) + } else { + for ai := range p.sg.nts[s.nt].alts { + p.addAlt(slot{s.nt, ai, 0}, v, i, 0) + } + } + return + } + j := p.matchTerm(s, i) + if j < 0 { + return + } + next := slot{L.nt, L.alt, L.dot + 1} + p.record(next, u.pos, i, j) + i = j + L = next + } +} + +// --------------------------------------------------------------------------- +// Queries over the BSR set +// --------------------------------------------------------------------------- + +// BSRForest is the BSR analogue of Forest: a set of binary subtree elements plus +// an index for reconstruction. Valid/NumTrees/Ambiguous/Tree mirror Forest. +type BSRForest struct { + sg *slotGrammar + input []byte + rulename string + set map[bsrElem]bool + index map[bsrKey][]int // (slot,l,r) -> pivots k + start int + n int +} + +type bsrKey struct { + slot slot + l, r int +} + +func (f *BSRForest) buildIndex() { + f.index = make(map[bsrKey][]int, len(f.set)) + for e := range f.set { + k := bsrKey{e.slot, e.l, e.r} + f.index[k] = append(f.index[k], e.k) + } +} + +// startElems returns, for each production of the start rule, the pivots of the +// complete-production elements spanning the whole input. +func (f *BSRForest) startElems() (slot, []int, bool) { + for ai, prod := range f.sg.nts[f.start].alts { + s := slot{f.start, ai, len(prod)} + if ks := f.index[bsrKey{s, 0, f.n}]; len(ks) > 0 { + return s, ks, true + } + } + return slot{}, nil, false +} + +// Valid reports whether the whole input is derivable by the root rule. +func (f *BSRForest) Valid() bool { + for ai, prod := range f.sg.nts[f.start].alts { + s := slot{f.start, ai, len(prod)} + if len(f.index[bsrKey{s, 0, f.n}]) > 0 { + return true + } + } + return false +} + +// Nodes returns the number of BSR elements (the representation's size). +func (f *BSRForest) Nodes() int { return len(f.set) } + +// symNode/interNode identities for memoisation and cycle detection. +type bsrNodeID struct { + inter bool + slot slot // for intermediate nodes + nt int // for symbol nodes + l, r int +} + +// NumTrees returns the number of distinct parse trees represented, or -1 for +// infinitely many (a cycle, i.e. an infinitely-ambiguous grammar). It mirrors +// Forest.NumTrees but counts over BSR extents instead of SPPF nodes. +func (f *BSRForest) NumTrees() *big.Int { + if !f.Valid() { + return big.NewInt(0) + } + memo := map[bsrNodeID]*big.Int{} + onStack := map[bsrNodeID]bool{} + infinite := false + + var symWays func(s ssym, a, b int) *big.Int + var countSym func(nt, l, r int) *big.Int + var countInter func(sl slot, l, r int) *big.Int + var countElem func(sl slot, l, k, r int) *big.Int + + symWays = func(s ssym, a, b int) *big.Int { + if s.kind == symNonterm { + return countSym(s.nt, a, b) + } + return big.NewInt(1) // terminal / eps leaf + } + + countElem = func(sl slot, l, k, r int) *big.Int { + prod := f.sg.nts[sl.nt].alts[sl.alt] + last := symWays(prod[sl.dot-1], k, r) + var pre *big.Int + switch sl.dot { + case 1: // empty prefix (l == k) + pre = big.NewInt(1) + case 2: // single-symbol prefix + pre = symWays(prod[0], l, k) + default: // intermediate prefix + pre = countInter(slot{sl.nt, sl.alt, sl.dot - 1}, l, k) + } + return new(big.Int).Mul(pre, last) + } + + countInter = func(sl slot, l, r int) *big.Int { + id := bsrNodeID{inter: true, slot: sl, l: l, r: r} + if v, ok := memo[id]; ok { + return v + } + if onStack[id] { + infinite = true + return big.NewInt(1) + } + onStack[id] = true + total := big.NewInt(0) + for _, k := range f.index[bsrKey{sl, l, r}] { + total.Add(total, countElem(sl, l, k, r)) + } + onStack[id] = false + memo[id] = total + return total + } + + countSym = func(nt, l, r int) *big.Int { + id := bsrNodeID{nt: nt, l: l, r: r} + if v, ok := memo[id]; ok { + return v + } + if onStack[id] { + infinite = true + return big.NewInt(1) + } + onStack[id] = true + total := big.NewInt(0) + for ai, prod := range f.sg.nts[nt].alts { + sl := slot{nt, ai, len(prod)} + for _, k := range f.index[bsrKey{sl, l, r}] { + total.Add(total, countElem(sl, l, k, r)) + } + } + onStack[id] = false + memo[id] = total + return total + } + + res := countSym(f.start, 0, f.n) + if infinite { + return big.NewInt(-1) + } + return res +} + +// Ambiguous reports whether the input has more than one distinct parse tree. +func (f *BSRForest) Ambiguous() bool { + if !f.Valid() { + return false + } + visited := map[bsrNodeID]bool{} + + var symAmb func(nt, l, r int) bool + var interAmb func(sl slot, l, r int) bool + var elemAmb func(sl slot, l, k, r int) bool + + symOf := func(s ssym, a, b int) bool { + if s.kind == symNonterm { + return symAmb(s.nt, a, b) + } + return false + } + elemAmb = func(sl slot, l, k, r int) bool { + prod := f.sg.nts[sl.nt].alts[sl.alt] + if symOf(prod[sl.dot-1], k, r) { + return true + } + switch sl.dot { + case 1: + return false + case 2: + return symOf(prod[0], l, k) + default: + return interAmb(slot{sl.nt, sl.alt, sl.dot - 1}, l, k) + } + } + interAmb = func(sl slot, l, r int) bool { + id := bsrNodeID{inter: true, slot: sl, l: l, r: r} + if visited[id] { + return false + } + visited[id] = true + ks := f.index[bsrKey{sl, l, r}] + if len(ks) > 1 { + return true + } + for _, k := range ks { + if elemAmb(sl, l, k, r) { + return true + } + } + return false + } + symAmb = func(nt, l, r int) bool { + id := bsrNodeID{nt: nt, l: l, r: r} + if visited[id] { + return false + } + visited[id] = true + packs := 0 + for ai, prod := range f.sg.nts[nt].alts { + sl := slot{nt, ai, len(prod)} + ks := f.index[bsrKey{sl, l, r}] + packs += len(ks) + } + if packs > 1 { + return true + } + for ai, prod := range f.sg.nts[nt].alts { + sl := slot{nt, ai, len(prod)} + for _, k := range f.index[bsrKey{sl, l, r}] { + if elemAmb(sl, l, k, r) { + return true + } + } + } + return false + } + return symAmb(f.start, 0, f.n) +} + +// Tree extracts a single parse tree (first element at each extent), or nil if +// the input is invalid. Synthetic nonterminals (groups, options, repetitions) +// are collapsed so only original rule names appear, matching Forest.Tree. +func (f *BSRForest) Tree() *ParseTree { + if !f.Valid() { + return nil + } + sl, ks, ok := f.startElems() + if !ok { + return nil + } + visited := map[bsrNodeID]bool{} + return f.emitSym(f.start, sl, ks[0], 0, f.n, visited) +} + +// emitSym builds a ParseTree node for nonterminal nt over [l,r], chosen via the +// complete-production slot sl with pivot k. +func (f *BSRForest) emitSym(nt int, sl slot, k, l, r int, visited map[bsrNodeID]bool) *ParseTree { + var kids []*ParseTree + f.collectElem(sl, l, k, r, &kids, visited) + info := f.sg.nts[nt] + if !info.isRule { + // synthetic (group/option/rep): splice children into the parent + return &ParseTree{Start: l, End: r, Children: kids} // caller flattens + } + return &ParseTree{Rule: info.ruleName, Start: l, End: r, Children: kids} +} + +// collectElem appends the children of element (sl,l,k,r) into out, flattening +// intermediate extents and synthetic nonterminals. +func (f *BSRForest) collectElem(sl slot, l, k, r int, out *[]*ParseTree, visited map[bsrNodeID]bool) { + prod := f.sg.nts[sl.nt].alts[sl.alt] + // prefix x_1..x_{dot-1} over [l,k] + switch sl.dot { + case 1: + // empty + case 2: + f.collectChild(prod[0], l, k, out, visited) + default: + isl := slot{sl.nt, sl.alt, sl.dot - 1} + if ks := f.index[bsrKey{isl, l, k}]; len(ks) > 0 { + f.collectElem(isl, l, ks[0], k, out, visited) + } + } + // last symbol x_{dot} over [k,r] + f.collectChild(prod[sl.dot-1], k, r, out, visited) +} + +func (f *BSRForest) collectChild(s ssym, a, b int, out *[]*ParseTree, visited map[bsrNodeID]bool) { + if s.kind != symNonterm { + if s.kind == symEps { + return // epsilon contributes no leaf + } + *out = append(*out, &ParseTree{Start: a, End: b}) + return + } + id := bsrNodeID{nt: s.nt, l: a, r: b} + if visited[id] { + return + } + visited[id] = true + // pick the first complete-production element for this nonterminal extent + for ai, prod := range f.sg.nts[s.nt].alts { + csl := slot{s.nt, ai, len(prod)} + if ks := f.index[bsrKey{csl, a, b}]; len(ks) > 0 { + info := f.sg.nts[s.nt] + if info.isRule { + var kids []*ParseTree + f.collectElem(csl, a, ks[0], b, &kids, visited) + *out = append(*out, &ParseTree{Rule: info.ruleName, Start: a, End: b, Children: kids}) + } else { + // synthetic: splice its children directly into the parent + f.collectElem(csl, a, ks[0], b, out, visited) + } + visited[id] = false + return + } + } + visited[id] = false +} + +func newBSRParser(sg *slotGrammar, input []byte, maxElems int) *bsrParser { + return &bsrParser{ + sg: sg, + input: input, + set: map[bsrElem]bool{}, + gss: map[gssKey]*bsrGNode{}, + seen: map[bsrDesc]bool{}, + popped: map[*bsrGNode]map[int]bool{}, + maxElems: maxElems, + } +} + +// ParseBSR parses input under rootRulename using the BSR engine. It accepts the +// same options as ParseForest (WithMaxForestNodes bounds the BSR set size). +func ParseBSR(input []byte, grammar *Grammar, rootRulename string, opts ...ForestOption) (*BSRForest, error) { + cfg := forestConfig{maxSlots: defaultMaxSlots} + for _, o := range opts { + o(&cfg) + } + sg, err := compileSlots(grammar, rootRulename, cfg.maxSlots) + if err != nil { + return nil, err + } + p := newBSRParser(sg, input, cfg.maxNodes) + p.parse() + if p.aborted { + return nil, &ErrForestTooLarge{Max: cfg.maxNodes} + } + f := &BSRForest{ + sg: sg, + input: input, + rulename: rootRulename, + set: p.set, + start: sg.start, + n: len(input), + } + f.buildIndex() + return f, nil +} diff --git a/vendor/github.com/pandatix/go-abnf/codegen.go b/vendor/github.com/pandatix/go-abnf/codegen.go new file mode 100644 index 0000000..7cb138f --- /dev/null +++ b/vendor/github.com/pandatix/go-abnf/codegen.go @@ -0,0 +1,903 @@ +package goabnf + +import ( + "fmt" + "go/format" + "strconv" + "strings" + "unicode/utf8" +) + +// GenerateGoParserFromABNF is a convenience wrapper that parses ABNF grammar +// source and generates a specialised parser for it in one step. root is the rule +// the generated parser starts from; pkg is the package name of the emitted file. +// It is the natural entry point for a code-generation command (e.g. driven by +// `go generate`). +func GenerateGoParserFromABNF(abnfSource []byte, root, pkg string, opts ...ABNFOption) ([]byte, error) { + g, err := ParseABNF(abnfSource, opts...) + if err != nil { + return nil, fmt.Errorf("parse ABNF source: %w", err) + } + return GenerateGoParser(g, root, pkg) +} + +// GenerateGoParser emits a standalone Go source file containing a parser +// SPECIALISED to grammar g rooted at root. Unlike a table-driven interpreter, +// the grammar is compiled into control flow: +// +// - the parse loop is a jump-table switch over slot IDs; each case is the +// straight-line code for that one slot (its symbol, its successor, its +// completion), so there is no per-step table lookup and no symbol-kind +// dispatch at runtime; +// - terminals are inlined as byte comparisons / rune decodes against baked +// literals (no ElemItf, no closure table); +// - nonterminal calls, completions, and the {min,max} repetition gating are +// baked as constants at each site; +// - only the genuinely grammar-independent machinery (GSS, descriptor +// worklist, BSR set) remains as fixed runtime, plus a compact metadata table +// used solely by the reconstruction queries (NumTrees/Ambiguous/Tree), which +// inherently need grammar structure. +// +// The output depends only on the standard library, is panic-free (input decoded +// via utf8, no manual indexing) and bounded (MaxElements aborts pathological +// inputs with ErrTooLarge). It is validated against ParseBSR via the differential +// harness. pkg is the package name for the emitted file. +func GenerateGoParser(g *Grammar, root, pkg string) ([]byte, error) { + sg, err := compileSlots(g, root, defaultMaxSlots) + if err != nil { + return nil, err + } + gen := &codegen{sg: sg, root: root, pkg: pkg} + gen.assignSlots() + src := gen.emit() + formatted, ferr := format.Source([]byte(src)) + if ferr != nil { + return []byte(src), fmt.Errorf("generated source failed to format: %w", ferr) + } + return formatted, nil +} + +type sInfo struct { + nt, alt, dot, plen int +} + +type codegen struct { + sg *slotGrammar + root string + pkg string + + slots []sInfo // slot id -> (nt,alt,dot,prodLen) + idOf [][]int // nt,alt -> base slot id (dot 0); dot d == base+d + series []string + seriesIdx map[string]int + usesUTF8 bool // whether any emitted matcher references unicode/utf8 +} + +func (c *codegen) startID(nt, alt int) int { return c.idOf[nt][alt] } +func (c *codegen) compID(nt, alt int) int { return c.idOf[nt][alt] + len(c.sg.nts[nt].alts[alt]) } + +// assignSlots numbers every slot (nt,alt,dot) with dots within a production +// consecutive, so the slot at dot d-1 is (id-1). +func (c *codegen) assignSlots() { + c.seriesIdx = map[string]int{} + c.idOf = make([][]int, len(c.sg.nts)) + for nt, info := range c.sg.nts { + c.idOf[nt] = make([]int, len(info.alts)) + for alt, prod := range info.alts { + c.idOf[nt][alt] = len(c.slots) + for dot := 0; dot <= len(prod); dot++ { + c.slots = append(c.slots, sInfo{nt, alt, dot, len(prod)}) + } + } + } +} + +func (c *codegen) emit() string { + c.scanUTF8() + var b strings.Builder + fmt.Fprintf(&b, "// Code generated by go-abnf for root %q. DO NOT EDIT.\n\n", c.root) + fmt.Fprintf(&b, "package %s\n\n", c.pkg) + c.emitImports(&b) + b.WriteString(headerBoilerplate) + c.emitProcess(&b) + c.emitSeed(&b) + c.emitMetadata(&b) + b.WriteString(queryBoilerplate) + c.emitSeriesVars(&b) + return b.String() +} + +// scanUTF8 sets usesUTF8 if any terminal compiles to code that decodes runes +// (a num-val range, or a char-val with a non-ASCII rune). +func (c *codegen) scanUTF8() { + for _, nt := range c.sg.nts { + for _, prod := range nt.alts { + for _, s := range prod { + if s.kind != symTerm { + continue + } + switch v := s.term.(type) { + case ElemNumVal: + if v.Status == StatRange { + c.usesUTF8 = true + } + case ElemCharVal: + for _, r := range v.Values { + if r > 0x7f { + c.usesUTF8 = true + } + } + } + } + } + } +} + +func (c *codegen) emitImports(b *strings.Builder) { + b.WriteString("import (\n\t\"errors\"\n\t\"math/big\"\n") + if c.usesUTF8 { + b.WriteString("\t\"unicode/utf8\"\n") + } + b.WriteString(")\n") +} + +// emitProcess generates the specialised parse loop: a jump-table switch over +// slot ids, one case per slot. +func (c *codegen) emitProcess(b *strings.Builder) { + b.WriteString("\nfunc (p *parser) process(d desc) {\n") + b.WriteString("\tL, u, i, rc := d.L, d.u, d.i, d.rc\n") + b.WriteString("\t_ = rc\n") + b.WriteString("\tfor {\n\t\tswitch L {\n") + for id, s := range c.slots { + info := c.sg.nts[s.nt] + fmt.Fprintf(b, "\t\tcase %d: // %s\n", id, c.slotComment(s)) + if s.dot == s.plen { + b.WriteString("\t\t\tp.pop(u, i)\n\t\t\treturn\n") + continue + } + sym := info.alts[s.alt][s.dot] + nextID := id + 1 + switch sym.kind { + case symNonterm: + c.emitCall(b, s, sym.nt, nextID) + default: + c.emitTerminal(b, sym, nextID) + } + } + b.WriteString("\t\tdefault:\n\t\t\treturn\n") + b.WriteString("\t\t}\n\t}\n}\n") +} + +func (c *codegen) emitCall(b *strings.Builder, s sInfo, callee, retID int) { + fmt.Fprintf(b, "\t\t\tv := p.create(%d, u, i, rc)\n", retID) + ci := c.sg.nts[callee] + if ci.isRep { + if callee == s.nt { + // self-recursion inside the rep's own loop: continue the chain. + if ci.repMax == inf { + fmt.Fprintf(b, "\t\t\tcrc := rc + 1\n\t\t\tif crc > %d {\n\t\t\t\tcrc = %d\n\t\t\t}\n", ci.repMin, ci.repMin) + } else { + b.WriteString("\t\t\tcrc := rc + 1\n") + } + fmt.Fprintf(b, "\t\t\tif crc >= %d {\n\t\t\t\tp.add(%d, v, i, crc)\n\t\t\t}\n", ci.repMin, c.startID(callee, 0)) + if ci.repMax == inf { + fmt.Fprintf(b, "\t\t\tp.add(%d, v, i, crc)\n", c.startID(callee, 1)) + } else { + fmt.Fprintf(b, "\t\t\tif crc < %d {\n\t\t\t\tp.add(%d, v, i, crc)\n\t\t\t}\n", ci.repMax, c.startID(callee, 1)) + } + } else { + // external call: fresh chain at count 0; gating decided at gen time. + if ci.repMin == 0 { + fmt.Fprintf(b, "\t\t\tp.add(%d, v, i, 0)\n", c.startID(callee, 0)) + } + if ci.repMax == inf || 0 < ci.repMax { + fmt.Fprintf(b, "\t\t\tp.add(%d, v, i, 0)\n", c.startID(callee, 1)) + } + } + } else { + for alt := range ci.alts { + fmt.Fprintf(b, "\t\t\tp.add(%d, v, i, 0)\n", c.startID(callee, alt)) + } + } + b.WriteString("\t\t\treturn\n") +} + +func (c *codegen) emitTerminal(b *strings.Builder, sym ssym, nextID int) { + if sym.kind == symEps { + fmt.Fprintf(b, "\t\t\tp.record(%d, u.pos, i, i)\n", nextID) + fmt.Fprintf(b, "\t\t\tL = %d\n\t\t\tcontinue\n", nextID) + return + } + if !c.emitMatch(b, sym) { + // The terminal can never match (a prose-val, or a series carrying a + // non-Unicode value): emitMatch has emitted `return` and defined no j, + // so the success tail below would be unreachable and reference an + // undefined j ; we should stop here. + return + } + fmt.Fprintf(b, "\t\t\tp.record(%d, u.pos, i, j)\n", nextID) + fmt.Fprintf(b, "\t\t\ti = j\n\t\t\tL = %d\n\t\t\tcontinue\n", nextID) +} + +// emitMatch emits inline code setting j to the end index on success or return on +// failure. It reports whether the terminal can match at all: a false result +// means it emitted only `return` and defined no j (prose-val, or a series with a +// non-Unicode value), so the caller must not emit the j-dependent success tail. +func (c *codegen) emitMatch(b *strings.Builder, s ssym) bool { + switch v := s.term.(type) { + case ElemCharVal: + c.emitCharVal(b, v) + return true + case ElemNumVal: + switch v.Status { + case StatRange: + lo := numvalToRune(v.Elems[0], v.Base) + hi := numvalToRune(v.Elems[1], v.Base) + b.WriteString("\t\t\tif i >= len(p.input) {\n\t\t\t\treturn\n\t\t\t}\n") + b.WriteString("\t\t\trv, rs := utf8.DecodeRune(p.input[i:])\n") + b.WriteString("\t\t\tif rv == utf8.RuneError && rs == 1 {\n\t\t\t\treturn\n\t\t\t}\n") + fmt.Fprintf(b, "\t\t\tif rv < %d || rv > %d {\n\t\t\t\treturn\n\t\t\t}\n", lo, hi) + b.WriteString("\t\t\tj := i + rs\n") + return true + case StatSeries: + return c.emitSeries(b, v) + default: + b.WriteString("\t\t\treturn\n") + return false + } + default: // prose-val: never matches + b.WriteString("\t\t\treturn\n") + return false + } +} + +func (c *codegen) emitCharVal(b *strings.Builder, v ElemCharVal) { + allASCII := true + for _, r := range v.Values { + if r > 0x7f { + allASCII = false + break + } + } + if allASCII { + fmt.Fprintf(b, "\t\t\tif i+%d > len(p.input) {\n\t\t\t\treturn\n\t\t\t}\n", len(v.Values)) + for off, r := range v.Values { + bb := byte(r) + if v.Sensitive { + fmt.Fprintf(b, "\t\t\tif p.input[i+%d] != %d {\n\t\t\t\treturn\n\t\t\t}\n", off, bb) + } else { + fmt.Fprintf(b, "\t\t\tif foldB(p.input[i+%d]) != %d {\n\t\t\t\treturn\n\t\t\t}\n", off, foldByte(bb)) + } + } + fmt.Fprintf(b, "\t\t\tj := i + %d\n", len(v.Values)) + return + } + // rare non-ASCII char-val: decode rune-by-rune. + b.WriteString("\t\t\tj := i\n") + for _, r := range v.Values { + b.WriteString("\t\t\t{\n") + b.WriteString("\t\t\t\tif j >= len(p.input) {\n\t\t\t\t\treturn\n\t\t\t\t}\n") + b.WriteString("\t\t\t\trv, rs := utf8.DecodeRune(p.input[j:])\n") + b.WriteString("\t\t\t\tif rv == utf8.RuneError && rs == 1 {\n\t\t\t\t\treturn\n\t\t\t\t}\n") + if v.Sensitive { + fmt.Fprintf(b, "\t\t\t\tif rv != %d {\n\t\t\t\t\treturn\n\t\t\t\t}\n", r) + } else { + fmt.Fprintf(b, "\t\t\t\tif foldR(rv) != %d {\n\t\t\t\t\treturn\n\t\t\t\t}\n", foldRune(r)) + } + b.WriteString("\t\t\t\tj += rs\n\t\t\t}\n") + } +} + +func (c *codegen) emitSeries(b *strings.Builder, v ElemNumVal) bool { + var sb strings.Builder + for _, e := range v.Elems { + r := numvalToRune(e, v.Base) + if !utf8.ValidRune(r) { + b.WriteString("\t\t\treturn // series contains a non-Unicode value\n") + return false + } + sb.WriteRune(r) + } + idx := c.seriesVar([]byte(sb.String())) + fmt.Fprintf(b, "\t\t\tif i+len(series%d) > len(p.input) || !bytesEqual(p.input[i:i+len(series%d)], series%d) {\n\t\t\t\treturn\n\t\t\t}\n", idx, idx, idx) + fmt.Fprintf(b, "\t\t\tj := i + len(series%d)\n", idx) + return true +} + +func (c *codegen) seriesVar(bs []byte) int { + key := string(bs) + if i, ok := c.seriesIdx[key]; ok { + return i + } + i := len(c.series) + c.seriesIdx[key] = i + parts := make([]string, len(bs)) + for k, x := range bs { + parts[k] = strconv.Itoa(int(x)) + } + c.series = append(c.series, "[]byte{"+strings.Join(parts, ", ")+"}") + return i +} + +func (c *codegen) emitSeed(b *strings.Builder) { + b.WriteString("\nfunc (p *parser) seed() {\n") + for alt := range c.sg.nts[c.sg.start].alts { + fmt.Fprintf(b, "\tp.add(%d, p.u0, 0, 0)\n", c.startID(c.sg.start, alt)) + } + b.WriteString("}\n") +} + +func (c *codegen) emitMetadata(b *strings.Builder) { + b.WriteString("\n// ---- baked metadata (reconstruction queries only) ----\n\n") + fmt.Fprintf(b, "const gRootName = %q\n", c.root) + fmt.Fprintf(b, "const gStart = %d\n\n", c.sg.start) + + b.WriteString("var slotInfo = []sInfo{\n") + for _, s := range c.slots { + fmt.Fprintf(b, "\t{%d, %d, %d, %d},\n", s.nt, s.alt, s.dot, s.plen) + } + b.WriteString("}\n\n") + + b.WriteString("var ntComplete = [][]int{\n") + for nt := range c.sg.nts { + b.WriteString("\t{") + for alt := range c.sg.nts[nt].alts { + if alt > 0 { + b.WriteString(", ") + } + fmt.Fprintf(b, "%d", c.compID(nt, alt)) + } + b.WriteString("},\n") + } + b.WriteString("}\n\n") + + b.WriteString("var qNTs = []qNT{\n") + for _, nt := range c.sg.nts { + fmt.Fprintf(b, "\t{isRule: %v, ruleName: %q, alts: ", nt.isRule, nt.ruleName) + if len(nt.alts) == 0 { + b.WriteString("nil},\n") + continue + } + b.WriteString("[][]qSym{") + for ai, prod := range nt.alts { + if ai > 0 { + b.WriteString(", ") + } + b.WriteString("{") + for si, sym := range prod { + if si > 0 { + b.WriteString(", ") + } + switch sym.kind { + case symNonterm: + fmt.Fprintf(b, "{kind: kNT, nt: %d}", sym.nt) + case symEps: + b.WriteString("{kind: kEps}") + default: + b.WriteString("{kind: kTerm}") + } + } + b.WriteString("}") + } + b.WriteString("}},\n") + } + b.WriteString("}\n") +} + +func (c *codegen) emitSeriesVars(b *strings.Builder) { + if len(c.series) == 0 { + return + } + b.WriteString("\n// ---- baked series literals ----\n") + for i, s := range c.series { + fmt.Fprintf(b, "var series%d = %s\n", i, s) + } +} + +func (c *codegen) slotComment(s sInfo) string { + nt := c.sg.nts[s.nt] + name := nt.ruleName + if name == "" { + name = nt.label + } + prod := nt.alts[s.alt] + parts := make([]string, 0, len(prod)+1) + for d, sym := range prod { + if d == s.dot { + parts = append(parts, ".") + } + parts = append(parts, symStr(c.sg, sym)) + } + if s.dot == len(prod) { + parts = append(parts, ".") + } + return strings.TrimSpace(name+" ::= "+strings.Join(parts, " ")) + + fmt.Sprintf(" (%d,%d,%d)", s.nt, s.alt, s.dot) +} + +func symStr(sg *slotGrammar, s ssym) string { + switch s.kind { + case symNonterm: + n := sg.nts[s.nt] + if n.ruleName != "" { + return n.ruleName + } + if n.label != "" { + return n.label + } + return "nt" + strconv.Itoa(s.nt) + case symEps: + return "eps" + default: + if s.term != nil { + return sanitizeComment(s.term.String()) + } + return "?" + } +} + +func sanitizeComment(s string) string { + s = strings.ReplaceAll(s, "*/", "* /") + s = strings.ReplaceAll(s, "\r", " ") + s = strings.ReplaceAll(s, "\n", " ") + return s +} + +func foldByte(b byte) byte { + if b >= 'A' && b <= 'Z' { + return b - 'A' + 'a' + } + return b +} + +func foldRune(r rune) rune { + if r >= 'A' && r <= 'Z' { + return r - 'A' + 'a' + } + return r +} + +// headerBoilerplate: runtime types, GSS/BSR engine state. Grammar-independent. +// (Imports are emitted separately so unicode/utf8 is only pulled in when a +// terminal actually decodes runes.) The generated process()/seed() and metadata +// complete the file. +const headerBoilerplate = ` +// MaxElements bounds the BSR set; parsing aborts with ErrTooLarge beyond it. +// Set to 0 to disable the bound. +var MaxElements = 1 << 22 + +// ErrTooLarge is returned when the BSR set exceeds MaxElements. +var ErrTooLarge = errors.New("parse: BSR set exceeded MaxElements") + +const inf = -1 + +const ( + kNT = 0 + kTerm = 1 + kEps = 2 +) + +// sInfo decodes a slot id into (nonterminal, alternate, dot, production length). +type sInfo struct{ nt, alt, dot, plen int } + +// qSym is a query-only symbol descriptor (kind, and nt for nonterminals). +type qSym struct{ kind, nt int } + +// qNT is query-only nonterminal metadata. +type qNT struct { + isRule bool + ruleName string + alts [][]qSym +} + +type bsrElem struct { + sl int + l, k, r int +} + +type gssKey struct { + ret int + pos int + rc int +} + +type gnode struct { + ret int + pos int + rc int + edges []*gnode + edgeSet map[*gnode]bool +} + +type desc struct { + L, i, rc int + u *gnode +} + +type parser struct { + input []byte + set map[bsrElem]bool + gss map[gssKey]*gnode + u0 *gnode + seen map[desc]bool + work []desc + popped map[*gnode]map[int]bool + aborted bool +} + +func foldB(b byte) byte { + if b >= 'A' && b <= 'Z' { + return b - 'A' + 'a' + } + return b +} + +func foldR(r rune) rune { + if r >= 'A' && r <= 'Z' { + return r - 'A' + 'a' + } + return r +} + +func bytesEqual(a, b []byte) bool { + if len(a) != len(b) { + return false + } + for i := range a { + if a[i] != b[i] { + return false + } + } + return true +} + +func (p *parser) add(L int, u *gnode, i, rc int) { + d := desc{L: L, i: i, rc: rc, u: u} + if p.seen[d] { + return + } + p.seen[d] = true + p.work = append(p.work, d) +} + +func (p *parser) gssNodeFor(ret, pos, rc int) *gnode { + k := gssKey{ret, pos, rc} + if v, ok := p.gss[k]; ok { + return v + } + v := &gnode{ret: ret, pos: pos, rc: rc, edgeSet: map[*gnode]bool{}} + p.gss[k] = v + return v +} + +// record inserts a BSR element, keeping only intermediate (prefix length >= 2) +// or complete (dot == len) extents. +func (p *parser) record(L, l, k, r int) { + si := slotInfo[L] + if si.dot >= 2 || si.dot == si.plen { + if MaxElements > 0 && len(p.set) >= MaxElements { + p.aborted = true + return + } + p.set[bsrElem{L, l, k, r}] = true + } +} + +func (p *parser) create(ret int, u *gnode, i, rc int) *gnode { + v := p.gssNodeFor(ret, i, rc) + if !v.edgeSet[u] { + v.edgeSet[u] = true + v.edges = append(v.edges, u) + for j := range p.popped[v] { + p.record(ret, u.pos, i, j) + p.add(ret, u, j, rc) + } + } + return v +} + +func (p *parser) pop(u *gnode, j int) { + if u == p.u0 { + return + } + if p.popped[u] == nil { + p.popped[u] = map[int]bool{} + } + p.popped[u][j] = true + for _, v := range u.edges { + p.record(u.ret, v.pos, u.pos, j) + p.add(u.ret, v, j, u.rc) + } +} +` + +// queryBoilerplate: Result, reconstruction queries (over slotInfo/ntComplete/ +// qNTs), and the public Parse. Grammar-independent. +const queryBoilerplate = ` +// ---- result + reconstruction queries ---- + +type ParseTree struct { + Rule string + Start, End int + Children []*ParseTree +} + +type bsrKey struct { + sl int + l, r int +} + +type nodeID struct { + sl int // slot id for intermediate nodes; -1 for symbol nodes + nt int // nonterminal id for symbol nodes + l, r int +} + +// Result holds the BSR set for a parse and answers queries over it. +type Result struct { + input []byte + set map[bsrElem]bool + index map[bsrKey][]int + n int +} + +func (r *Result) buildIndex() { + if r.index != nil { + return + } + r.index = make(map[bsrKey][]int, len(r.set)) + for e := range r.set { + bk := bsrKey{e.sl, e.l, e.r} + r.index[bk] = append(r.index[bk], e.k) + } +} + +// Valid reports whether the whole input is derivable by the root rule. +func (r *Result) Valid() bool { + r.buildIndex() + for _, sl := range ntComplete[gStart] { + if len(r.index[bsrKey{sl, 0, r.n}]) > 0 { + return true + } + } + return false +} + +// Elements returns the number of BSR elements (representation size). +func (r *Result) Elements() int { return len(r.set) } + +// NumTrees returns the number of distinct parse trees, or -1 for infinitely many. +func (r *Result) NumTrees() *big.Int { + if !r.Valid() { + return big.NewInt(0) + } + memo := map[nodeID]*big.Int{} + onStack := map[nodeID]bool{} + infinite := false + + var symWays func(s qSym, a, b int) *big.Int + var countSym func(nt, l, rr int) *big.Int + var countInter func(sl, l, rr int) *big.Int + var countElem func(sl, l, k, rr int) *big.Int + + symWays = func(s qSym, a, b int) *big.Int { + if s.kind == kNT { + return countSym(s.nt, a, b) + } + return big.NewInt(1) + } + countElem = func(sl, l, k, rr int) *big.Int { + si := slotInfo[sl] + prod := qNTs[si.nt].alts[si.alt] + last := symWays(prod[si.dot-1], k, rr) + var pre *big.Int + switch { + case si.dot == 1: + pre = big.NewInt(1) + case si.dot == 2: + pre = symWays(prod[0], l, k) + default: + pre = countInter(sl-1, l, k) + } + return new(big.Int).Mul(pre, last) + } + countInter = func(sl, l, rr int) *big.Int { + id := nodeID{sl: sl, nt: -1, l: l, r: rr} + if v, ok := memo[id]; ok { + return v + } + if onStack[id] { + infinite = true + return big.NewInt(1) + } + onStack[id] = true + total := big.NewInt(0) + for _, k := range r.index[bsrKey{sl, l, rr}] { + total.Add(total, countElem(sl, l, k, rr)) + } + onStack[id] = false + memo[id] = total + return total + } + countSym = func(nt, l, rr int) *big.Int { + id := nodeID{sl: -1, nt: nt, l: l, r: rr} + if v, ok := memo[id]; ok { + return v + } + if onStack[id] { + infinite = true + return big.NewInt(1) + } + onStack[id] = true + total := big.NewInt(0) + for _, sl := range ntComplete[nt] { + for _, k := range r.index[bsrKey{sl, l, rr}] { + total.Add(total, countElem(sl, l, k, rr)) + } + } + onStack[id] = false + memo[id] = total + return total + } + res := countSym(gStart, 0, r.n) + if infinite { + return big.NewInt(-1) + } + return res +} + +// Ambiguous reports whether the input has more than one distinct parse tree. +func (r *Result) Ambiguous() bool { + if !r.Valid() { + return false + } + visited := map[nodeID]bool{} + var symAmb func(nt, l, rr int) bool + var interAmb func(sl, l, rr int) bool + var elemAmb func(sl, l, k, rr int) bool + var symOf func(s qSym, a, b int) bool + symOf = func(s qSym, a, b int) bool { + if s.kind == kNT { + return symAmb(s.nt, a, b) + } + return false + } + elemAmb = func(sl, l, k, rr int) bool { + si := slotInfo[sl] + prod := qNTs[si.nt].alts[si.alt] + if symOf(prod[si.dot-1], k, rr) { + return true + } + switch { + case si.dot == 1: + return false + case si.dot == 2: + return symOf(prod[0], l, k) + default: + return interAmb(sl-1, l, k) + } + } + interAmb = func(sl, l, rr int) bool { + id := nodeID{sl: sl, nt: -1, l: l, r: rr} + if visited[id] { + return false + } + visited[id] = true + ks := r.index[bsrKey{sl, l, rr}] + if len(ks) > 1 { + return true + } + for _, k := range ks { + if elemAmb(sl, l, k, rr) { + return true + } + } + return false + } + symAmb = func(nt, l, rr int) bool { + id := nodeID{sl: -1, nt: nt, l: l, r: rr} + if visited[id] { + return false + } + visited[id] = true + packs := 0 + for _, sl := range ntComplete[nt] { + packs += len(r.index[bsrKey{sl, l, rr}]) + } + if packs > 1 { + return true + } + for _, sl := range ntComplete[nt] { + for _, k := range r.index[bsrKey{sl, l, rr}] { + if elemAmb(sl, l, k, rr) { + return true + } + } + } + return false + } + return symAmb(gStart, 0, r.n) +} + +// Tree extracts a single parse tree (first element at each extent), or nil if +// the input is invalid. Synthetic nonterminals are collapsed to rule names. +func (r *Result) Tree() *ParseTree { + if !r.Valid() { + return nil + } + for _, sl := range ntComplete[gStart] { + if ks := r.index[bsrKey{sl, 0, r.n}]; len(ks) > 0 { + var kids []*ParseTree + r.collectElem(sl, 0, ks[0], r.n, &kids, map[nodeID]bool{}) + return &ParseTree{Rule: qNTs[gStart].ruleName, Start: 0, End: r.n, Children: kids} + } + } + return nil +} + +func (r *Result) collectElem(sl, l, k, rr int, out *[]*ParseTree, visited map[nodeID]bool) { + si := slotInfo[sl] + prod := qNTs[si.nt].alts[si.alt] + switch { + case si.dot == 1: + case si.dot == 2: + r.collectChild(prod[0], l, k, out, visited) + default: + if ks := r.index[bsrKey{sl - 1, l, k}]; len(ks) > 0 { + r.collectElem(sl-1, l, ks[0], k, out, visited) + } + } + r.collectChild(prod[si.dot-1], k, rr, out, visited) +} + +func (r *Result) collectChild(s qSym, a, b int, out *[]*ParseTree, visited map[nodeID]bool) { + if s.kind != kNT { + if s.kind == kEps { + return + } + *out = append(*out, &ParseTree{Start: a, End: b}) + return + } + id := nodeID{sl: -1, nt: s.nt, l: a, r: b} + if visited[id] { + return + } + visited[id] = true + for _, sl := range ntComplete[s.nt] { + if ks := r.index[bsrKey{sl, a, b}]; len(ks) > 0 { + if qNTs[s.nt].isRule { + var kids []*ParseTree + r.collectElem(sl, a, ks[0], b, &kids, visited) + *out = append(*out, &ParseTree{Rule: qNTs[s.nt].ruleName, Start: a, End: b, Children: kids}) + } else { + r.collectElem(sl, a, ks[0], b, out, visited) + } + visited[id] = false + return + } + } + visited[id] = false +} + +// Parse parses input under the baked root rule using the specialised engine. +func Parse(input []byte) (*Result, error) { + p := &parser{ + input: input, + set: map[bsrElem]bool{}, + gss: map[gssKey]*gnode{}, + seen: map[desc]bool{}, + popped: map[*gnode]map[int]bool{}, + } + p.u0 = &gnode{ret: -1, edgeSet: map[*gnode]bool{}} + p.seed() + for len(p.work) > 0 { + if p.aborted { + return nil, ErrTooLarge + } + d := p.work[len(p.work)-1] + p.work = p.work[:len(p.work)-1] + p.process(d) + } + return &Result{input: input, set: p.set, n: len(input)}, nil +} +` diff --git a/vendor/github.com/pandatix/go-abnf/dag.go b/vendor/github.com/pandatix/go-abnf/dag.go new file mode 100644 index 0000000..4d004e4 --- /dev/null +++ b/vendor/github.com/pandatix/go-abnf/dag.go @@ -0,0 +1,237 @@ +package goabnf + +import ( + "fmt" + "slices" + "strings" +) + +type node struct { + Rulename string + index, lowlink int + onStack bool + Dependencies []string +} + +// Depgraph contains for each rule the rules it depends on. +// Notice it does not differentiate between a mandatory dependency +// or an avoidable one. +type Depgraph map[string]*node + +// DependencyGraph creates a dependency graph for a whole grammar. +// It includes core rules only if necessary. +func (g *Grammar) DependencyGraph() Depgraph { + graph := Depgraph{} + for _, corerule := range coreRules { + graph[strings.ToLower(corerule.Name)] = &node{ + Rulename: corerule.Name, + Dependencies: getDependencies(corerule.Alternation), + } + } + for _, rule := range g.Rulemap { + graph[strings.ToLower(rule.Name)] = &node{ + Rulename: rule.Name, + Dependencies: getDependencies(rule.Alternation), + } + } + return graph +} + +func getDependencies(alt Alternation) []string { + deps := []string{} + for _, conc := range alt.Concatenations { + for _, rep := range conc.Repetitions { + switch v := rep.Element.(type) { + case ElemGroup: + deps = appendDeps(deps, getDependencies(v.Alternation)...) + case ElemOption: + deps = appendDeps(deps, getDependencies(v.Alternation)...) + case ElemRulename: + deps = appendDeps(deps, strings.ToLower(v.Name)) + } + } + } + return deps +} + +func appendDeps(deps []string, ndeps ...string) []string { + for _, ndep := range ndeps { + if !slices.Contains(deps, ndep) { + deps = append(deps, ndep) + } + } + return deps +} + +// Mermaid returns a flowchart of the dependency graph. +func (dg Depgraph) Mermaid() string { + var out strings.Builder + out.WriteString("flowchart TD\n") + for _, node := range dg { + for _, dep := range node.Dependencies { + fmt.Fprintf(&out, "\t%s --> %s\n", node.Rulename, dep) + } + out.WriteString("\n") + } + return out.String() +} + +// IsDag find Strongly Connected Components using Tarjan's algorithm +// and returns whether it contains cycle or not. +// Could be improved by Nuutila's or Pearce's algorithms, or replaced +// by Kosaraju's algorithm. +func (g *Grammar) IsDAG() bool { + scc := &cycle{ + index: 0, + stack: []*node{}, + dg: g.DependencyGraph(), + } + scc.find() + + for _, sccs := range scc.sccs { + if len(sccs) > 1 { + return false + } + } + return true +} + +// RuleContainsCycle returns whether the rule contains a cycle or not. +// It travels through the whole rule dependency graph, such that +// it checks if the rule is cyclic AND if one of its dependency is too. +func (g *Grammar) RuleContainsCycle(rulename string) (bool, error) { + // Check the rule exists + rule := GetRule(rulename, g.Rulemap) + if rule == nil { + return false, &ErrRuleNotFound{ + Rulename: rulename, + } + } + + // Get all SCCs + scc := &cycle{ + index: 0, + stack: []*node{}, + dg: g.DependencyGraph(), + } + scc.find() + + return ruleContainsCycle(scc.sccs, rulename), nil +} + +func ruleContainsCycle(sccs [][]*node, rulename string) bool { + // Index nodes by lowercase name and flag those sitting in a non-trivial SCC + // (size > 1 == a cycle). Precomputing this removes the O(V) SCC scan that + // the previous implementation did on every recursive step. + nodeOf := make(map[string]*node, len(sccs)) + inCycle := make(map[string]bool, len(sccs)) + + for _, s := range sccs { + nontrivial := len(s) > 1 + for _, nd := range s { + key := strings.ToLower(nd.Rulename) + nodeOf[key] = nd + inCycle[key] = nontrivial + } + } + return ruleCycleVisit(strings.ToLower(rulename), nodeOf, inCycle, map[string]bool{}) +} + +// ruleCycleVisit reports whether the rule (or any transitive dependency) is +// cyclic. The visited set keeps each rule explored at most once: without it a +// diamond-shaped dependency DAG is walked along every root-to-leaf path, which +// is exponential. Marking on entry is safe because a cyclic rule returns true +// here before it can ever be marked-and-skipped, so a memoized rule is always +// genuinely acyclic. +func ruleCycleVisit(key string, nodeOf map[string]*node, inCycle, visited map[string]bool) bool { + if visited[key] { + return false + } + visited[key] = true + nd := nodeOf[key] + if nd == nil { + // Unknown rule: treat as acyclic (matches the previous behaviour). + return false + } + + // Self-loop (a size-1 SCC with a self-edge is not flagged by inCycle). + for _, dep := range nd.Dependencies { + if strings.ToLower(dep) == key { + return true + } + } + if inCycle[key] { + // If it depends on itself or is part of an SCC, then is cylic + return true + } + + for _, dep := range nd.Dependencies { + dk := strings.ToLower(dep) + if dk == key { + continue + } + if ruleCycleVisit(dk, nodeOf, inCycle, visited) { + return true + } + } + return false +} + +type cycle struct { + index int + stack []*node + sccs [][]*node + + dg Depgraph +} + +func (c *cycle) find() { + for _, v := range c.dg { + if v.index == 0 { + c.strongconnect(v) + } + } +} + +func (c *cycle) strongconnect(v *node) { + // Set the depth index for v to the smallest unused index + v.index = c.index + v.lowlink = c.index + c.index++ + c.stack = append(c.stack, v) + v.onStack = true + + // Consider successors of v + for _, dep := range v.Dependencies { + w, ok := c.dg[dep] + if !ok { + // core rules, as we know they won't have a cycle thus + // no SCC, we don't need to recurse. + continue + } + if w.index == 0 { + // Successor w has not yet been visited; recurse on it + c.strongconnect(w) + v.lowlink = min(v.lowlink, w.lowlink) + } else { + if w.onStack { + // Successor w is in stack S and hence in the current SCC + // If w is not on stack, then (v, w) is an edge pointing + // to an SCC already found and must be ignored. + v.lowlink = min(v.lowlink, w.index) + } + } + } + // If v is a root node, pop the stack and generate an SCC + if v.lowlink == v.index { + scc := []*node{} + w := (*node)(nil) + for w == nil || !strings.EqualFold(v.Rulename, w.Rulename) { + w = c.stack[len(c.stack)-1] + c.stack = c.stack[:len(c.stack)-1] + w.onStack = false + scc = append(scc, w) + } + c.sccs = append(c.sccs, scc) + } +} diff --git a/vendor/github.com/pandatix/go-abnf/errors.go b/vendor/github.com/pandatix/go-abnf/errors.go new file mode 100644 index 0000000..ea39058 --- /dev/null +++ b/vendor/github.com/pandatix/go-abnf/errors.go @@ -0,0 +1,245 @@ +package goabnf + +import ( + "errors" + "fmt" + "sort" + "strings" +) + +var ( + // ErrNoSolutionFound is an error returned when parsing an ABNF + // grammar and no solution has been found. + // + // On the ABNF parsing path it is wrapped by a [*ParseError] carrying the + // position at which parsing got stuck; errors.Is(err, ErrNoSolutionFound) + // keeps matching. + ErrNoSolutionFound = errors.New("no solution found, input ABNF grammar may be invalid") + + // ErrHandlingProseVal is an error returned when an operation tried + // to produce something on a prose-val, but it can't be handled properly. + ErrHandlingProseVal = errors.New("can't handle prose-val descriptions") + + // ErrProseValInTransitionGraph is returned when building a transition graph + // from a grammar that contains a prose-val, which has no defined expansion. + ErrProseValInTransitionGraph = errors.New("prose value is not supported in transition graphs") + + // ErrRepetitionThreshold is returned when expanding a repetition whose bound + // exceeds the threshold set with WithRepetitionThreshold. + ErrRepetitionThreshold = errors.New("repetition threshold reached") + + // ErrRepetitionMinNotOne is returned when a mandatory (max == 1) repetition + // has a minimum other than 1. + ErrRepetitionMinNotOne = errors.New("repetition minimum must be 1 when maximum is 1") + + // ErrRepetitionMinGtMax is returned when a repetition has a minimum greater + // than its maximum. + ErrRepetitionMinGtMax = errors.New("repetition minimum is greater than maximum") +) + +// ParseError reports where parsing input against a grammar got stuck. It is +// returned (wrapped around [ErrNoSolutionFound]) when an input does not parse, +// to help locate the offending construct -- in particular when writing or +// debugging an ABNF grammar. +type ParseError struct { + // Offset is the byte offset into the input of the furthest position the + // parser was able to reach before failing. + Offset int + // Line and Col are the 1-based line and column of Offset. + Line, Col int + // Expected lists the terminals the parser could have consumed at Offset, if + // that information was available. It may be empty. + Expected []string + // Found describes the input byte at Offset (e.g. `%x0A (LF)`), or "EOF" when + // Offset is at the end of input. It may be empty. + Found string + // Hint, when set, gives a plain-language diagnosis of a common mistake (e.g. + // bare LF line endings where ABNF requires CR LF). + Hint string +} + +var _ error = (*ParseError)(nil) + +func (e *ParseError) Error() string { + var b strings.Builder + fmt.Fprintf(&b, "parse error at line %d, column %d (offset %d)", e.Line, e.Col, e.Offset) + switch { + case len(e.Expected) > 0: + fmt.Fprintf(&b, ": expected %s", strings.Join(e.Expected, ", ")) + if e.Found != "" { + fmt.Fprintf(&b, ", found %s", e.Found) + } + case e.Found != "": + fmt.Fprintf(&b, ": unexpected %s", e.Found) + default: + fmt.Fprintf(&b, ": %s", ErrNoSolutionFound) + } + if e.Hint != "" { + fmt.Fprintf(&b, " (hint: %s)", e.Hint) + } + return b.String() +} + +// Unwrap reports ErrNoSolutionFound so that callers matching the historical +// sentinel with errors.Is keep working. +func (e *ParseError) Unwrap() error { return ErrNoSolutionFound } + +// describeByte renders an input byte the way ABNF terminals are written, naming +// the control characters that matter most when debugging a grammar. +func describeByte(b byte) string { + switch b { + case '\r': + return "%x0D (CR)" + case '\n': + return "%x0A (LF)" + case '\t': + return "%x09 (HTAB)" + case ' ': + return "%x20 (SP)" + } + if b >= 0x20 && b < 0x7f { + return fmt.Sprintf("%q", string(b)) + } + return fmt.Sprintf("%%x%02X", b) +} + +// newParseError builds a ParseError from a byte offset into input, computing the +// 1-based line and column, the byte found there, and a hint for the bare-LF +// line-ending mistake (the most common ABNF authoring error). +func newParseError(input []byte, offset int, expected []string) *ParseError { + if offset < 0 { + offset = 0 + } + if offset > len(input) { + offset = len(input) + } + line, col := 1, 1 + for i := 0; i < offset; i++ { + if input[i] == '\n' { + line++ + col = 1 + } else { + col++ + } + } + exp := append([]string(nil), expected...) + sort.Strings(exp) + pe := &ParseError{Offset: offset, Line: line, Col: col, Expected: exp} + if offset < len(input) { + pe.Found = describeByte(input[offset]) + // Bare LF where the previous byte is not CR: ABNF lines end with CR LF, + // so a lone LF is almost always the cause. + if input[offset] == '\n' && (offset == 0 || input[offset-1] != '\r') { + pe.Hint = `input uses bare LF line endings, but ABNF requires CR LF ("\r\n")` + } + } else { + pe.Found = "EOF" + } + return pe +} + +// ErrMultipleSolutionsFound is an error returned when a parser found +// multiple solutions when none or one were expected. +type ErrMultipleSolutionsFound struct{} + +var _ error = (*ErrMultipleSolutionsFound)(nil) + +func (err ErrMultipleSolutionsFound) Error() string { + return "multiple solutions found, this should not happen. Please open an issue. This could eventually need an Erratum from IETF tracking" +} + +// ErrRuleNotFound is an error returned when the rule was not found +// as part of the grammar. +type ErrRuleNotFound struct { + Rulename string +} + +var _ error = (*ErrRuleNotFound)(nil) + +func (err ErrRuleNotFound) Error() string { + return fmt.Sprintf("rule %s was not found in grammar", err.Rulename) +} + +// ErrCoreRuleModify is an error returned when an incremental alternative +// for a core rule. +type ErrCoreRuleModify struct { + CoreRulename string +} + +var _ error = (*ErrCoreRuleModify)(nil) + +func (err ErrCoreRuleModify) Error() string { + return fmt.Sprintf("core rule %s can't be modified", err.CoreRulename) +} + +// ErrDependencyNotFound is an error returned during ABNF grammar +// semantic vaildation, if a rule depends on an unexisting rule. +type ErrDependencyNotFound struct { + Rulename string +} + +var _ error = (*ErrDependencyNotFound)(nil) + +func (err ErrDependencyNotFound) Error() string { + return fmt.Sprintf("unsatisfied dependency (rule) %s", err.Rulename) +} + +// ErrSemanticRepetition is an error returned during ABNF grammar +// semantic validation, if a repetition has min < max. +type ErrSemanticRepetition struct { + Repetition Repetition +} + +var _ error = (*ErrSemanticRepetition)(nil) + +func (err ErrSemanticRepetition) Error() string { + return fmt.Sprintf("invalid semantic of input ABNF grammar for repetition %s", err.Repetition) +} + +// ErrTooLargeNumeral is an error returned when the numeral value +// provided to parse cannot be handled as a 7-bit US-ASCII valid value. +type ErrTooLargeNumeral struct { + Base, Value string +} + +var _ error = (*ErrTooLargeNumeral)(nil) + +func (err ErrTooLargeNumeral) Error() string { + return fmt.Sprintf("too large numeral value %s for base %s", err.Value, err.Base) +} + +// ErrDuplicatedRule is an error returned when the rule already +// exist as part of the grammar. +type ErrDuplicatedRule struct { + Rulename string +} + +var _ error = (*ErrDuplicatedRule)(nil) + +func (err ErrDuplicatedRule) Error() string { + return fmt.Sprintf("rule %s was already defined in grammar", err.Rulename) +} + +// ErrCyclicRule is an error returned when can't work due to an +// unavoidable cyclic rule. +type ErrCyclicRule struct { + Rulename string +} + +var _ error = (*ErrCyclicRule)(nil) + +func (err ErrCyclicRule) Error() string { + return fmt.Sprintf("can't generate a content as the rule %s involves an unavoidable cycle", err.Rulename) +} + +// ErrMaxNodesExceeded is returned by TransitionGraph when construction would +// allocate more nodes than the budget set with WithMaxNodes. +type ErrMaxNodesExceeded struct { + Max int +} + +var _ error = (*ErrMaxNodesExceeded)(nil) + +func (err ErrMaxNodesExceeded) Error() string { + return fmt.Sprintf("transition graph node budget of %d exceeded", err.Max) +} diff --git a/vendor/github.com/pandatix/go-abnf/fuzz.go b/vendor/github.com/pandatix/go-abnf/fuzz.go new file mode 100644 index 0000000..e8d79ff --- /dev/null +++ b/vendor/github.com/pandatix/go-abnf/fuzz.go @@ -0,0 +1,775 @@ +package goabnf + +import ( + "fmt" + "math/rand" + "unicode/utf8" +) + +// fuzz.go turns a (fully expanded) transition graph into a total +// function from arbitrary bytes to a string the grammar admits. It is the core +// primitive for structure-aware fuzzing with testing.F: because every input +// maps to a valid production, the fuzzing engine's mutations explore the +// grammar's structure instead of bouncing off the target's first syntax check. +// +// The walk is deliberately different from a TransitionGraphReader: the reader +// enumerates entrypoint->endpoint trails (each directed edge at most once) for +// finite coverage, whereas the generator takes a free walk that MAY repeat +// edges -- so it can unroll a "*" repetition into "a", "aa", "aaa", ... -- and +// is kept finite by explicit budgets (max length, per-edge repetitions, total +// steps) rather than by the no-repeat rule. When a budget is hit the walk does +// not stop dead (that could leave it on a non-accepting node); it steers along +// shortest paths to the nearest endpoint, so the output is always a complete, +// valid production. + +// source supplies the decisions that drive a walk. Two implementations exist: a +// byte tape (for testing.F, where mutations of the tape are the fuzzing signal) +// and a *rand.Rand (for property tests and corpus generation). intn(n) returns +// a value in [0, n); when a tape is exhausted it returns 0, which makes +// generation total and biases an empty/short tape toward the shortest +// production. +type source interface { + intn(n int) int +} + +type tapeSource struct { + tape []byte + pos int +} + +func (s *tapeSource) intn(n int) int { + if n <= 1 { + return 0 + } + // Read just enough bytes to address n, big-endian. One byte per decision + // when n <= 256 keeps locality high: a single-byte mutation flips at most + // one decision (until the number of decisions changes). + width := 1 + for max := n; max > 256; max = (max + 255) / 256 { + width++ + } + v := 0 + for i := 0; i < width; i++ { + b := 0 + if s.pos < len(s.tape) { + b = int(s.tape[s.pos]) + s.pos++ + } + v = v<<8 | b + if v < 0 { // overflow guard on absurd widths + v &= 0x7fffffff + } + } + return v % n +} + +type randSource struct{ r *rand.Rand } + +func (s randSource) intn(n int) int { + if n <= 1 { + return 0 + } + return s.r.Intn(n) +} + +// indexedSource addresses the tape by decision number rather than a moving +// cursor: the i-th decision always reads the fixed-width slot [i*stride, ...], +// regardless of how many bytes earlier decisions "needed". This keeps a tape +// edit local -- it can only perturb the one decision whose slot it lands in -- +// so an upstream structural change no longer reframes the bytes every later +// decision reads (the residual non-locality is purely semantic: a forked walk +// reaches different nodes, where the same slot byte means a different choice). +// stride 4 addresses any choice count up to 2^32, well above the widest +// (full-Unicode) num-val range. +type indexedSource struct { + tape []byte + i int +} + +const indexedStride = 4 + +func (s *indexedSource) intn(n int) int { + if n <= 1 { + return 0 + } + off := s.i * indexedStride + s.i++ + v := 0 + for k := range indexedStride { + b := 0 + if off+k < len(s.tape) { + b = int(s.tape[off+k]) + } + v = v<<8 | b + if v < 0 { + v &= 0x7fffffff + } + } + return v % n +} + +// Generator produces strings admitted by a transition graph. +type Generator struct { + tg *TransitionGraph + + maxLength int + maxReps int + maxSteps int + + stableAddr bool + + endSet map[string]bool // node ID -> is an endpoint ("" == emptyNode) + canReach map[string]bool // node ID -> can still reach some endpoint + distToEnd map[string]int // node ID -> fewest steps to an endpoint + entries []*Node // entrypoints that can reach an endpoint + + emitCache map[string][]emission // node ID -> octet emissions (lazy, for ExpectedNext) + emitOK map[string]bool // node ID -> emissions analyzable +} + +// GenOption configures a Generator. +type GenOption interface { + apply(*Generator) +} + +type genOptionFunc func(*Generator) + +func (f genOptionFunc) apply(g *Generator) { + f(g) +} + +// WithMaxLength bounds the number of bytes a generated production may contain. +// Once reached the walk steers to the nearest endpoint. Defaults to 4096. +func WithMaxLength(n int) GenOption { + return genOptionFunc(func(g *Generator) { + g.maxLength = n + }) +} + +// WithMaxReps bounds how many times a single edge may be traversed, which caps +// how far repetitions ("*" / "1*" / "n*m") are unrolled. Defaults to 32. +func WithMaxReps(n int) GenOption { + return genOptionFunc(func(g *Generator) { + g.maxReps = n + }) +} + +// WithMaxSteps is a hard backstop on the total number of walk steps, defending +// against pathological graphs. Defaults to 100000. +func WithMaxSteps(n int) GenOption { + return genOptionFunc(func(g *Generator) { + g.maxSteps = n + }) +} + +// WithStableAddressing makes Generate address the tape by decision number +// (fixed-width slots) instead of a moving cursor. This improves locality for a +// coverage-guided engine -- a one-byte tape edit perturbs a single decision +// rather than reframing every decision downstream of it -- at the cost of +// consuming the tape less densely. Recommended for use under testing.F. +func WithStableAddressing() GenOption { + return genOptionFunc(func(g *Generator) { + g.stableAddr = true + }) +} + +// NewGenerator prepares a Generator from a transition graph. The graph must be +// fully expanded -- build it with WithDeflateRules(true) when the target rule +// references other rules -- because an unexpanded rule node carries no bytes and +// could not be turned into a valid production. It returns an error naming the +// first such node otherwise. (Recursive rules cannot be expanded at all; in that +// case TransitionGraph itself returns ErrCyclicRule before reaching here.) +func NewGenerator(tg *TransitionGraph, opts ...GenOption) (*Generator, error) { + g := &Generator{ + tg: tg, + maxLength: 4096, + maxReps: 32, + maxSteps: 100_000, + } + for _, o := range opts { + o.apply(g) + } + + // Collect every reachable node and the reverse adjacency, and verify the + // graph is fully expanded (only producing leaves and the empty node). + revAdj := map[string][]*Node{} + nodes := map[string]*Node{} + var stack []*Node + for _, e := range tg.Entrypoints { + if e != emptyNode { + stack = append(stack, e) + } + } + for len(stack) > 0 { + n := stack[len(stack)-1] + stack = stack[:len(stack)-1] + id := tgNodeID(n) + if _, ok := nodes[id]; ok { + continue + } + nodes[id] = n + if !producing(n) { + return nil, fmt.Errorf("transition graph contains an unexpanded rule node %q; build it with WithDeflateRules(true)", n.Elem.String()) + } + for _, sc := range n.Nexts { + if sc == emptyNode { + continue + } + revAdj[tgNodeID(sc)] = append(revAdj[tgNodeID(sc)], n) + stack = append(stack, sc) + } + } + + // endSet, then backward BFS from endpoints for canReach + distToEnd. + g.endSet = map[string]bool{} + g.canReach = map[string]bool{} + g.distToEnd = map[string]int{} + var q []string + for _, e := range tg.Endpoints { + id := tgNodeID(e) + g.endSet[id] = true + if !g.canReach[id] { + g.canReach[id] = true + g.distToEnd[id] = 0 + q = append(q, id) + } + } + for len(q) > 0 { + id := q[0] + q = q[1:] + for _, p := range revAdj[id] { + pid := tgNodeID(p) + if g.canReach[pid] { + continue + } + g.canReach[pid] = true + g.distToEnd[pid] = g.distToEnd[id] + 1 + q = append(q, pid) + } + } + + for _, e := range tg.Entrypoints { + if g.canReach[tgNodeID(e)] { + g.entries = append(g.entries, e) + } + } + return g, nil +} + +// Generate maps the tape to a production the grammar admits. It is total: any +// tape (including nil) yields a valid production; an exhausted tape biases +// toward the shortest completion. +func (g *Generator) Generate(tape []byte) []byte { + if g.stableAddr { + return g.walk(&indexedSource{tape: tape}, nil) + } + return g.walk(&tapeSource{tape: tape}, nil) +} + +// GenerateRand draws a production using r as the entropy source. +func (g *Generator) GenerateRand(r *rand.Rand) []byte { + return g.walk(randSource{r: r}, nil) +} + +// traceSeg records that out[off:off+length] was emitted by a node carrying elem. +type traceSeg struct { + off, length int + elem ElemItf +} + +func (g *Generator) walk(src source, trace *[]traceSeg) []byte { + out := []byte{} + if len(g.entries) == 0 { + return out + } + node := g.entries[src.intn(len(g.entries))] + + visits := map[string]int{} + steps := 0 + for { + if node != emptyNode && producing(node) { + _, vt := nodeEmit(node, 0) + if vt < 1 { + vt = 1 + } + var idx int32 + if vt > 1 { + idx = int32(src.intn(int(vt))) + } + b, _ := nodeEmit(node, idx) + if trace != nil && len(b) > 0 { + *trace = append(*trace, traceSeg{off: len(out), length: len(b), elem: node.Elem}) + } + out = append(out, b...) + } + + // The empty node is a terminal entry/endpoint sentinel with no + // successors; reaching it as an entrypoint means the whole production is + // nullable, so stopping here yields the (valid) empty production. + if node == emptyNode { + break + } + + id := tgNodeID(node) + atEnd := g.endSet[id] + + // liveAll: successors that can still reach an endpoint (used for + // termination steering). liveCapped: those not yet at the per-edge cap + // (used for ordinary random choice). + var liveAll, liveCapped []*Node + for _, sc := range node.Nexts { + if sc == emptyNode || !g.canReach[tgNodeID(sc)] { + continue + } + liveAll = append(liveAll, sc) + if visits[id+">"+tgNodeID(sc)] < g.maxReps { + liveCapped = append(liveCapped, sc) + } + } + if len(liveAll) == 0 { + break // terminal; canReach guarantees this node is an endpoint + } + + over := len(out) >= g.maxLength || steps >= g.maxSteps + terminating := over || len(liveCapped) == 0 + + var next *Node + if atEnd { + if terminating { + break + } + // One decision: 0 == stop here, otherwise continue to a successor. + c := src.intn(len(liveCapped) + 1) + if c == 0 { + break + } + next = liveCapped[c-1] + } else if terminating { + next = g.nearestToEnd(liveAll) + } else { + next = liveCapped[src.intn(len(liveCapped))] + } + + visits[id+">"+tgNodeID(next)]++ + steps++ + node = next + } + return out +} + +// nearestToEnd returns the candidate with the fewest steps to an endpoint. +// Following it repeatedly walks a shortest path to an endpoint (distToEnd +// strictly decreases), so the termination phase never repeats an edge. +func (g *Generator) nearestToEnd(cands []*Node) *Node { + best := cands[0] + bestD := g.distToEnd[tgNodeID(best)] + for _, c := range cands[1:] { + if d := g.distToEnd[tgNodeID(c)]; d < bestD { + best, bestD = c, d + } + } + return best +} + +// From here, generate *negative* test inputs: strings that lie just outside the +// grammar, each paired with a label describing the violation. They are the +// complement of Generate's valid productions -- a correct target MUST reject them +// -- and they reach the error-handling paths (truncation, boundary overruns, +// trailing input) where many parser bugs live and which a valid-only generator +// can never exercise. +// +// A perturbation is NOT assumed invalid: grammars can be ambiguous or redundant +// (flipping "a" to "b" in `"a" / "b"` is still valid), so every candidate is +// checked against the grammar and only genuinely-rejected ones are returned. +// This makes the "target must reject" oracle sound. + +// NearMiss returns a string just outside the grammar together with a label +// describing how it violates the grammar, or ok=false if no minimal +// perturbation within the attempt budget produced a string the grammar rejects. +// It is deterministic in tape and total. +func (g *Generator) NearMiss(tape []byte) (production []byte, label string, ok bool) { + src := &tapeSource{tape: tape} + var trace []traceSeg + base := g.walk(src, &trace) + + for _, c := range g.nearMissCandidates(src, base, trace) { + if c.bytes == nil || string(c.bytes) == string(base) { + continue + } + valid, err := g.tg.grammar.IsValid(g.tg.rulename, c.bytes) + if err == nil && !valid { + return c.bytes, c.label, true + } + } + return nil, "", false +} + +// NearMissRand is the *rand.Rand-driven variant of NearMiss. +func (g *Generator) NearMissRand(r *rand.Rand) (production []byte, label string, ok bool) { + // Draw a tape and reuse the deterministic path so behaviour is identical. + tape := make([]byte, 64) + r.Read(tape) + return g.NearMiss(tape) +} + +type candidate struct { + bytes []byte + label string +} + +func cloneBytes(b []byte) []byte { + c := make([]byte, len(b)) + copy(c, b) + return c +} + +// nearMissCandidates proposes minimal perturbations of base, ordered with a +// little entropy from src so different tapes explore different operators first. +// Correctness does not depend on the order: NearMiss verifies each against the +// grammar. +func (g *Generator) nearMissCandidates(src source, base []byte, trace []traceSeg) []candidate { + var cs []candidate + + // (1) Boundary violations: take a num-val range segment one step past its + // edge. These are the high-value off-by-one cases. + for _, seg := range trace { + nv, isRange := numvalRange(seg.elem) + if !isRange { + continue + } + for _, b := range []struct { + r rune + what string + }{ + {rune(nv.min - 1), "below"}, + {rune(nv.max + 1), "above"}, + } { + if b.r < 0 || b.r > 0x10FFFF { + continue + } + cand := cloneBytes(base) + repl := []byte(string(b.r)) + out := append(append(cloneBytes(cand[:seg.off]), repl...), cand[seg.off+seg.length:]...) + cs = append(cs, candidate{out, fmt.Sprintf("byte at offset %d is one %s num-val range %s", seg.off, b.what, nv.label)}) + } + } + + // (2) Off-alphabet substitution at a chosen position: replace one byte with + // a "wild" value. Verified, so even an unlucky pick is safe. + if len(base) > 0 { + pos := src.intn(len(base)) + for _, nb := range []byte{0x00, 0xFF, base[pos] ^ 0x20, base[pos] + 1, '!'} { + if nb == base[pos] { + continue + } + cand := cloneBytes(base) + cand[pos] = nb + cs = append(cs, candidate{cand, fmt.Sprintf("byte at offset %d substituted with 0x%02x", pos, nb)}) + } + } + + // (3) Truncation: drop a suffix (incomplete input -- exercises overread / + // "premature end" handling). + for _, n := range []int{1, 2, len(base) / 2, len(base) - 1} { + if n <= 0 || n > len(base) { + continue + } + cs = append(cs, candidate{cloneBytes(base[:len(base)-n]), fmt.Sprintf("truncated by %d byte(s) (len %d)", n, len(base)-n)}) + } + + // (4) Trailing input: append a byte (exercises "ignores trailing garbage"). + for _, nb := range []byte{0x00, '!', 0xFF, 'A'} { + out := append(cloneBytes(base), nb) + cs = append(cs, candidate{out, fmt.Sprintf("trailing byte 0x%02x appended", nb)}) + } + + // (5) Deletion of a single interior byte. + if len(base) >= 2 { + pos := src.intn(len(base)) + out := append(cloneBytes(base[:pos]), base[pos+1:]...) + cs = append(cs, candidate{out, fmt.Sprintf("byte at offset %d deleted", pos)}) + } + + // Light entropy-driven rotation so the first verified hit varies by tape. + if len(cs) > 1 { + k := src.intn(len(cs)) + cs = append(cs[k:], cs[:k]...) + } + return cs +} + +type numvalInfo struct { + min, max int32 + label string +} + +// numvalRange reports whether elem is a num-val range and, if so, its bounds. +func numvalRange(elem ElemItf) (numvalInfo, bool) { + nv, ok := elem.(ElemNumVal) + if !ok || nv.Status != StatRange { + return numvalInfo{}, false + } + min, max := numvalToInt32(nv.Elems[0], nv.Base), numvalToInt32(nv.Elems[1], nv.Base) + // Clamp the upper bound to the Unicode range so the "just above" boundary + // probe (max+1) stays a meaningful rune rather than overflowing. + if max > utf8.MaxRune { + max = utf8.MaxRune + } + return numvalInfo{min: min, max: max, label: elem.String()}, true +} + +// From here answers for a given prefix "which octets may legally come next, and +// is the prefix itself a complete word?" by simulating the transition-graph +// automaton over the prefix and reading the frontier. The graph is not a plain +// byte DFA -- each node emits a multi-octet string with per-position choices +// (letter casings, num-val ranges) -- so this is an NFA-style frontier simulation, +// not a single-state walk. +// +// Its headline use is sharpening NearMiss: appending an octet that is NOT in the +// expected-next set yields a string that is provably not a prefix of any word in +// the language, i.e. guaranteed invalid, with a precise label. It also enables +// error-position testing ("the target must fail at byte N"). + +// octetSet is a 256-bit set of octets. +type octetSet [4]uint64 + +func (s *octetSet) add(b byte) { + s[b>>6] |= 1 << (b & 63) +} + +func (s octetSet) has(b byte) bool { + return s[b>>6]&(1<<(b&63)) != 0 +} + +func (s octetSet) union(o octetSet) octetSet { + return octetSet{s[0] | o[0], s[1] | o[1], s[2] | o[2], s[3] | o[3]} +} + +func (s octetSet) bytes() []byte { + var out []byte + for b := range 256 { + if s.has(byte(b)) { + out = append(out, byte(b)) + } + } + return out +} + +// emission is one fixed-length alternative of a node's output: pos[j] is the set +// of octets the node may emit at byte offset j. A node usually has exactly one +// emission; a num-val range that spans several UTF-8 lengths has one per length. +type emission struct { + pos []octetSet +} + +// expectedNextRangeCap bounds how many runes a multi-byte num-val range is +// expanded into for analysis; beyond it ExpectedNext reports ok=false rather +// than doing unbounded work. ASCII ranges are always handled (<=128 octets). +const expectedNextRangeCap = 1 << 16 + +func (g *Generator) emissions(n *Node) ([]emission, bool) { + id := tgNodeID(n) + if g.emitCache == nil { + g.emitCache = map[string][]emission{} + g.emitOK = map[string]bool{} + } + if e, seen := g.emitCache[id]; seen { + return e, g.emitOK[id] + } + e, ok := nodeEmissions(n) + g.emitCache[id] = e + g.emitOK[id] = ok + return e, ok +} + +func nodeEmissions(n *Node) ([]emission, bool) { + switch v := n.Elem.(type) { + case ElemCharVal: + e := emission{} + for _, r := range v.Values { + if !v.Sensitive && ((r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z')) { + lo, up := r, r + if lo >= 'A' && lo <= 'Z' { + lo = lo - 'A' + 'a' + } + if up >= 'a' && up <= 'z' { + up = up - 'a' + 'A' + } + var s octetSet + s.add(byte(lo)) + s.add(byte(up)) + e.pos = append(e.pos, s) + } else { + for _, b := range []byte(string(r)) { + var s octetSet + s.add(b) + e.pos = append(e.pos, s) + } + } + } + return []emission{e}, true + + case ElemNumVal: + switch v.Status { + case StatSeries: + e := emission{} + for _, el := range v.Elems { + r := numvalToRune(el, v.Base) + if !utf8.ValidRune(r) { + // An out-of-range element can never appear in UTF-8 input. + return nil, false + } + for _, b := range []byte(string(r)) { + var s octetSet + s.add(b) + e.pos = append(e.pos, s) + } + } + return []emission{e}, true + case StatRange: + min, max := numvalToInt32(v.Elems[0], v.Base), numvalToInt32(v.Elems[1], v.Base) + // Clamp to the Unicode range first: otherwise an out-of-range bound + // near MaxInt32 overflows the int32 count below, bypasses the cap + // guard, and turns the enumeration loop into a DoS. A range wholly + // above U+10FFFF emits nothing. + if max > utf8.MaxRune { + max = utf8.MaxRune + } + if min > utf8.MaxRune || min > max { + return nil, false + } + if max <= 0x7f { // ASCII: a single one-octet emission + var s octetSet + for b := min; b <= max && b <= 0x7f; b++ { // explicit ASCII bound for the conversion + s.add(byte(b)) + } + return []emission{{pos: []octetSet{s}}}, true + } + if max-min+1 > expectedNextRangeCap { + return nil, false + } + byLen := map[int]*emission{} + for r := min; r <= max; r++ { + bs := []byte(string(rune(r))) + e := byLen[len(bs)] + if e == nil { + e = &emission{pos: make([]octetSet, len(bs))} + byLen[len(bs)] = e + } + for j, b := range bs { + e.pos[j].add(b) + } + } + out := make([]emission, 0, len(byLen)) + for _, e := range byLen { + out = append(out, *e) + } + return out, true + } + } + return nil, false +} + +// ExpectedNext simulates the automaton over prefix and reports the octets that +// may legally follow it, whether prefix is itself a complete word, and whether +// the analysis succeeded (ok is false only when the graph uses a feature this +// analyzer declines to expand, e.g. an enormous multi-byte num-val range). When +// prefix is not a viable prefix of any word, next is empty and accepts is false. +func (g *Generator) ExpectedNext(prefix []byte) (next []byte, accepts bool, ok bool) { + type state struct { + n *Node + e, p int + } + ready := []state{} + seen := map[state]bool{} + push := func(s state) { + if !seen[s] { + seen[s] = true + ready = append(ready, s) + } + } + start := func(n *Node) bool { + ems, o := g.emissions(n) + if !o { + return false + } + for ei, em := range ems { + if len(em.pos) > 0 { + push(state{n, ei, 0}) + } + } + return true + } + for _, e := range g.tg.Entrypoints { + if e == emptyNode { + continue + } + if !start(e) { + return nil, false, false + } + } + + lastCompletedEndpoint := false + consumedAll := true + for idx, b := range prefix { + next2 := []state{} + seen2 := map[state]bool{} + push2 := func(s state) { + if !seen2[s] { + seen2[s] = true + next2 = append(next2, s) + } + } + lastCompletedEndpoint = false + for _, s := range ready { + ems, _ := g.emissions(s.n) + em := ems[s.e] + if !em.pos[s.p].has(b) { + continue + } + if s.p+1 == len(em.pos) { // node s.n completes on this octet + if g.endSet[tgNodeID(s.n)] { + lastCompletedEndpoint = true + } + for _, m := range s.n.Nexts { + if m == emptyNode { + continue + } + ems2, o := g.emissions(m) + if !o { + return nil, false, false + } + for ei, em2 := range ems2 { + if len(em2.pos) > 0 { + push2(state{m, ei, 0}) + } + } + } + } else { + push2(state{s.n, s.e, s.p + 1}) + } + } + ready, seen = next2, seen2 + if len(ready) == 0 { + if idx != len(prefix)-1 { + consumedAll = false // dead before the end: prefix not viable + } + break + } + } + + if !consumedAll { + return nil, false, true + } + if len(prefix) == 0 { + accepts = g.endSet[""] // empty word accepted iff emptyNode is an endpoint + } else { + accepts = lastCompletedEndpoint + } + var acc octetSet + for _, s := range ready { + ems, _ := g.emissions(s.n) + acc = acc.union(ems[s.e].pos[s.p]) + } + return acc.bytes(), accepts, true +} diff --git a/vendor/github.com/pandatix/go-abnf/generate.go b/vendor/github.com/pandatix/go-abnf/generate.go new file mode 100644 index 0000000..179db93 --- /dev/null +++ b/vendor/github.com/pandatix/go-abnf/generate.go @@ -0,0 +1,253 @@ +package goabnf + +import ( + "errors" + "maps" + "math/rand" + "strings" + "unicode/utf8" +) + +// Generate is an experimental feature that consumes a seed for +// a pseudo-random number generator, used to randomly travel through +// the grammar given a rulename to work on. +// With this, it provides reproducibility, usefull for fuzz crashers. +// +// You can leverage its capacities (maximum repetitions, length +// threshold, etc.) with the functional options. +// +// It is a good capability for testing and fuzzing parsers during +// testing, compliance, fuzzing or optimization. +func (g *Grammar) Generate(seed int64, rulename string, opts ...GenerateOption) ([]byte, error) { + if err := checkCanGenerateSafely(g, rulename); err != nil { + return nil, err + } + + // Use a pseudo-random number generator + rand := rand.NewSource(seed) + + // Define conditions from options + options := &genOpts{ + repMax: 16, + threshold: 256, + } + for _, opt := range opts { + opt.apply(options) + } + + // Generate actual content (rule exists, checked first) + rule := GetRule(rulename, g.Rulemap) + out := []byte{} + generateAlt(rand, g, &out, rule.Alternation, options) + return out, nil +} + +func generateAlt(rand rand.Source, g *Grammar, out *[]byte, alt Alternation, options *genOpts) { + // Select any possible path in the alternation + cnt := alt.Concatenations[int(rand.Int63())%len(alt.Concatenations)] + + // Travel through all the repetitions + for _, rep := range cnt.Repetitions { + repmax := rep.Max + if repmax == inf { + repmax = options.repMax + } + torep := rep.Min + int(rand.Int63())%(repmax-rep.Min+1) + for i := 0; generateKeepGoing(i, torep, rep.Min, len(*out), options.threshold); i++ { + switch elem := rep.Element.(type) { + case ElemRulename: + rule := GetRule(elem.Name, g.Rulemap) + generateAlt(rand, g, out, rule.Alternation, options) + + case ElemOption: + if (rand.Int63() % 2) == 0 { + generateAlt(rand, g, out, elem.Alternation, options) + } + + case ElemGroup: + generateAlt(rand, g, out, elem.Alternation, options) + + case ElemNumVal: + switch elem.Status { + case StatRange: + min, max := numvalToRune(elem.Elems[0], elem.Base), numvalToRune(elem.Elems[1], elem.Base) + // Generation emits UTF-8 text, so clamp to the representable + // (Unicode) subset; a range wholly above U+10FFFF (or with + // max < min) yields no character. + if max > utf8.MaxRune { + max = utf8.MaxRune + } + if min <= utf8.MaxRune && min <= max { + r := min + (rune(rand.Int63()&0x0F) % (max - min + 1)) // mask 0x0F to keep the 32-bit part (rune size) + appendPtr(out, r) + } + + case StatSeries: + for _, v := range elem.Elems { + r := numvalToRune(v, elem.Base) + // Skip values that are not real characters; they cannot be + // emitted as UTF-8 text. + if utf8.ValidRune(r) { + appendPtr(out, r) + } + } + } + + case ElemCharVal: + for _, val := range elem.Values { + if !elem.Sensitive && (int(rand.Int63())%2) == 0 { + val = runeMax(val) + } + appendPtr(out, val) + } + } + + // Prose-val is not covered, checked before to avoid generation + } + } +} + +func appendPtr(slc *[]byte, v ...rune) { + b := *slc + b = append(b, []byte(string(v))...) + *slc = b +} + +func generateKeepGoing(i, torep, minrep, lenout, threshold int) bool { + // If can do no run and reached threshold, skip + if i == 0 && minrep == 0 && lenout >= threshold { + return false + } + return i < torep +} + +// GenerateOption is an option for the *Grammar.Generate method. +type GenerateOption interface { + apply(*genOpts) +} + +type genOpts struct { + repMax int + threshold int +} + +type repMaxOption int + +// WithRepMax defines the maximum repetition to stop generating at. +func WithRepMax(repMax int) repMaxOption { + return repMaxOption(repMax) +} + +func (opt repMaxOption) apply(opts *genOpts) { + opts.repMax = int(opt) +} + +type thresholdOption int + +// WithThreshold defines the length threshold to stop generating at. +func WithThreshold(threshold int) thresholdOption { + return thresholdOption(threshold) +} + +func (opt thresholdOption) apply(opts *genOpts) { + opts.threshold = int(opt) +} + +// checkCanGenerateSafely returns no error if the rule can be generated +// safely i.e. if the rule can exist without infinite recursion, AND if it +// does not contain a prose-val as it could not generate from it. +// Factually, it checks if all involved rules have no path v such that it +// produces a cycle (v:rule-*->rule) AND that this path is mandatory +// (no option, no repetition with a minimum of zero). +func checkCanGenerateSafely(g *Grammar, rulename string) error { + rule := GetRule(rulename, g.Rulemap) + if rule == nil { + return &ErrRuleNotFound{ + Rulename: rulename, + } + } + knownRules := map[string]struct{}{ + rulename: {}, + } + if err := checkCanGenerateSafelyAlt(g, knownRules, rule.Alternation); err != nil { + if err, ok := err.(*ErrCyclicRule); ok { + return err + } + return &ErrCyclicRule{ + Rulename: rulename, + } + } + return nil +} + +func checkCanGenerateSafelyAlt(g *Grammar, knownRules map[string]struct{}, alt Alternation) error { + errs := make([]error, len(alt.Concatenations)) + for alti, concat := range alt.Concatenations { + errs[alti] = checkCanGenerateSafelyConcat(g, knownRules, concat) + } + allErrors := true + for i := 0; i < len(errs) && allErrors; i++ { + if errs[i] == nil { + allErrors = false + } + } + if allErrors { + return errors.Join(errs...) + } + return nil +} + +func checkCanGenerateSafelyConcat(g *Grammar, knownRules map[string]struct{}, concat Concatenation) error { + for _, rep := range concat.Repetitions { + // If the repetition is not mandatory, we can escape so can + // generate safely. + if rep.Min == 0 { + continue + } + + // Deal with the repetition itself then. + switch elem := rep.Element.(type) { + case ElemRulename: + // Copy rules to only focus on rules that made use come here. + // If shared with others, the dependency graph can lead to the same rule + // from another path without it being a cycle, thus must be handled. + scopeRules := duplicateMap(knownRules) + for known := range scopeRules { + if strings.EqualFold(elem.Name, known) { + return &ErrCyclicRule{ + Rulename: elem.Name, + } + } + } + rule := GetRule(elem.Name, g.Rulemap) + scopeRules[elem.Name] = struct{}{} + if err := checkCanGenerateSafelyAlt(g, scopeRules, rule.Alternation); err != nil { + if err, ok := err.(*ErrCyclicRule); ok { + return err + } + return &ErrCyclicRule{ + Rulename: elem.Name, + } + } + + case ElemGroup: + if err := checkCanGenerateSafelyAlt(g, knownRules, elem.Alternation); err != nil { + return err + } + + case ElemProseVal: + return ErrHandlingProseVal + + // Other types are not considered for the following reasons: + // - option: equivalent to rep.min==0, escapable path even if could be cyclic + // - num-val, char-val: termination paths, can't be cyclic + } + } + return nil +} + +func duplicateMap[T comparable, V any](m map[T]V) map[T]V { + n := make(map[T]V, len(m)) + maps.Copy(n, m) + return n +} diff --git a/vendor/github.com/pandatix/go-abnf/go.work b/vendor/github.com/pandatix/go-abnf/go.work new file mode 100644 index 0000000..bf64dae --- /dev/null +++ b/vendor/github.com/pandatix/go-abnf/go.work @@ -0,0 +1,6 @@ +go 1.26.0 + +use ( + . + cmd/pap +) diff --git a/vendor/github.com/pandatix/go-abnf/go.work.sum b/vendor/github.com/pandatix/go-abnf/go.work.sum new file mode 100644 index 0000000..4214faf --- /dev/null +++ b/vendor/github.com/pandatix/go-abnf/go.work.sum @@ -0,0 +1,11 @@ +github.com/BurntSushi/toml v1.2.1/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= +github.com/BurntSushi/toml v1.3.2/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= +github.com/BurntSushi/toml v1.5.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= +github.com/stretchr/objx v0.5.3/go.mod h1:rDQraq+vQZU7Fde9LOZLr8Tax6zZvy4kuNKF+QYS+U0= +golang.org/x/mod v0.30.0/go.mod h1:lAsf5O2EvJeSFMiBxXDki7sCgAxEUcZHXoXMKT4GJKc= +golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= +golang.org/x/tools v0.39.0/go.mod h1:JnefbkDPyD8UU2kI5fuf8ZX4/yUeh9W877ZeBONxUqQ= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/vendor/github.com/pandatix/go-abnf/grammar.go b/vendor/github.com/pandatix/go-abnf/grammar.go new file mode 100644 index 0000000..8b3932a --- /dev/null +++ b/vendor/github.com/pandatix/go-abnf/grammar.go @@ -0,0 +1,443 @@ +package goabnf + +import ( + "fmt" + "slices" + "strconv" + "strings" +) + +// Grammar represents an ABNF grammar as defined by RFC 5234. +// It is constituted of a set of rules with a unique name. +type Grammar struct { + Rulemap map[string]*Rule +} + +// IsValid checks there exist at least a path that completly consumes +// input, hence is valid given this grammar and especially one of its +// rule. +func (g *Grammar) IsValid(rulename string, input []byte) (bool, error) { + rule := GetRule(rulename, g.Rulemap) + if rule == nil { + return false, &ErrRuleNotFound{Rulename: rulename} + } + // Validity only needs to know whether some derivation consumes the whole + // input, never the (possibly exponentially many) derivations themselves. + // We therefore propagate the set of reachable end-positions per + // (element, index) instead of enumerating paths, which keeps this + // polynomial. Left-recursive rules are resolved by seed-growing rather than + // refused; see recognize.go and leftrec.go. + r := &recognizer{ + g: g, + input: input, + memo: map[string]map[int]bool{}, + inProgress: map[string]bool{}, + leftRec: g.leftRecursiveSCCs(), + growing: map[string]map[int]bool{}, + } + ends := r.reachElem(ElemRulename{Name: rulename}, 0) + return ends[len(input)], nil +} + +// String returns the representation of the grammar that is valid +// according to the ABNF specifications/RFCs. +// This notably imply the use of CRLF instead of LF, and does not +// preserve the initial order nor pretty print it. +func (g *Grammar) String() string { + str := "" + for _, rule := range g.Rulemap { + str += rule.String() + "\r\n" + } + return str +} + +// PrettyPrint returns a prettified string that represents the grammar. +func (g *Grammar) PrettyPrint() string { + // Determine maximum rulename length + rulenameLength := 0 + for rulename := range g.Rulemap { + if len(rulename) > rulenameLength { + rulenameLength = len(rulename) + } + } + + // Construct output + out := "" + for rulename, rl := range g.Rulemap { + spaces := "" + for i := 0; i < rulenameLength-len(rulename); i++ { + spaces += " " + } + + out += fmt.Sprintf("%s%s = %s\r\n", rulename, spaces, rl.Alternation) + } + return out +} + +// ParseABNF is a helper facilitating the call to Parse using the +// pre-computed ABNF grammar and evaluated the resulting to produce +// a ready-to-use grammar. +func ParseABNF(input []byte, opts ...ABNFOption) (*Grammar, error) { + o := process(opts...) + + // Parse the ABNF source using the ABNF meta-grammar with the GLL engine. + f, err := Parse(input, ABNF, "rulelist") + if err != nil { + return nil, err + } + if !f.Valid() { + return nil, f.ParseError() + } + if f.Ambiguous() { + return nil, &ErrMultipleSolutionsFound{} + } + + g, err := evalForest(input, f, o) + if err != nil { + return nil, err + } + + if o.validate { + if err := SemvalABNF(g); err != nil { + return nil, err + } + } + return g, nil +} + +// Parse parses input against grammar starting at rootRulename using the GLL +// engine, returning the shared packed parse forest. Unlike the previous +// backtracking parser it accepts ANY grammar -- left, right and mutual +// recursion and ambiguity included -- in worst-case cubic time, so it never +// stack-overflows on left recursion nor blows up exponentially. Inspect the +// result with the Forest methods (Valid, Ambiguous, NumTrees, Tree). +func Parse(input []byte, grammar *Grammar, rootRulename string) (*Forest, error) { + return ParseForest(input, grammar, rootRulename) +} + +// EvaluateABNF evaluates a parse forest -- produced by parsing an ABNF source +// against the ABNF meta-grammar -- into a ready-to-use *Grammar. +func EvaluateABNF(input []byte, f *Forest, opts ...ABNFOption) (*Grammar, error) { + return evalForest(input, f, process(opts...)) +} + +func evalForest(input []byte, f *Forest, o *abnfOptions) (*Grammar, error) { + tree := f.Tree() + if tree == nil { + return nil, ErrNoSolutionFound + } + ev := &feval{input: input, o: o} + return ev.rulelist(tree) +} + +// feval evaluates the rule-keyed ParseTree of an ABNF source into a *Grammar. +// It dispatches on rule names and reads byte spans, so it is decoupled from the +// exact (scaffolding-collapsed) shape of the tree. +type feval struct { + input []byte + o *abnfOptions +} + +func ptChildren(t *ParseTree, name string) []*ParseTree { + var out []*ParseTree + for _, c := range t.Children { + if c.Rule == name { + out = append(out, c) + } + } + return out +} + +func ptFirst(t *ParseTree, names ...string) *ParseTree { + for _, c := range t.Children { + if slices.Contains(names, c.Rule) { + return c + } + } + return nil +} + +func (e *feval) span(t *ParseTree) string { return string(e.input[t.Start:t.End]) } + +func (e *feval) rulelist(t *ParseTree) (*Grammar, error) { + mp := map[string]*Rule{} + for _, rc := range ptChildren(t, "rule") { + rl, definedAs, err := e.rule(rc) + if err != nil { + return nil, err + } + switch definedAs { + case "=": + isCoreRule := GetRule(rl.Name, nil) != nil + if isCoreRule { + if !e.o.redefineCore { + return nil, &ErrCoreRuleModify{CoreRulename: rl.Name} + } + } else if GetRule(rl.Name, mp) != nil { + return nil, &ErrDuplicatedRule{Rulename: rl.Name} + } + mp[rl.Name] = rl + case "=/": + isCoreRule := GetRule(rl.Name, nil) != nil + if !e.o.redefineCore && isCoreRule { + return nil, &ErrCoreRuleModify{CoreRulename: rl.Name} + } + rule := GetRule(rl.Name, mp) + if rule == nil { + return nil, &ErrRuleNotFound{Rulename: rl.Name} + } + rule.Alternation.Concatenations = append(rule.Alternation.Concatenations, rl.Alternation.Concatenations...) + mp[rule.Name] = rule + } + } + return &Grammar{Rulemap: mp}, nil +} + +func (e *feval) rule(t *ParseTree) (*Rule, string, error) { + nameNode := ptFirst(t, "rulename") + defNode := ptFirst(t, "defined-as") + elemsNode := ptFirst(t, "elements") + if nameNode == nil || defNode == nil || elemsNode == nil { + return nil, "", ErrNoSolutionFound + } + definedAs := "=" + if strings.Contains(e.span(defNode), "=/") { + definedAs = "=/" + } + altNode := ptFirst(elemsNode, "alternation") + if altNode == nil { + return nil, "", ErrNoSolutionFound + } + alt, err := e.alternation(altNode) + if err != nil { + return nil, "", err + } + return &Rule{Name: e.span(nameNode), Alternation: alt}, definedAs, nil +} + +func (e *feval) alternation(t *ParseTree) (Alternation, error) { + var cs []Concatenation + for _, cc := range ptChildren(t, "concatenation") { + c, err := e.concatenation(cc) + if err != nil { + return Alternation{}, err + } + cs = append(cs, c) + } + return Alternation{Concatenations: cs}, nil +} + +func (e *feval) concatenation(t *ParseTree) (Concatenation, error) { + var rs []Repetition + for _, rc := range ptChildren(t, "repetition") { + r, err := e.repetition(rc) + if err != nil { + return Concatenation{}, err + } + rs = append(rs, r) + } + return Concatenation{Repetitions: rs}, nil +} + +func (e *feval) repetition(t *ParseTree) (Repetition, error) { + min, max := 1, 1 + if rep := ptFirst(t, "repeat"); rep != nil { + min, max = e.parseRepeat(rep) + } + elNode := ptFirst(t, "element") + if elNode == nil { + return Repetition{}, ErrNoSolutionFound + } + elem, err := e.element(elNode) + if err != nil { + return Repetition{}, err + } + return Repetition{Min: min, Max: max, Element: elem}, nil +} + +func (e *feval) parseRepeat(t *ParseTree) (int, int) { + s := e.span(t) + before, after, ok := strings.Cut(s, "*") + if !ok { + d, _ := strconv.Atoi(s) + return d, d + } + min, max := 0, inf + if pre := before; pre != "" { + min, _ = strconv.Atoi(pre) + } + if post := after; post != "" { + max, _ = strconv.Atoi(post) + } + return min, max +} + +func (e *feval) element(t *ParseTree) (ElemItf, error) { + c := ptFirst(t, "rulename", "group", "option", "char-val", "num-val", "prose-val") + if c == nil { + return nil, ErrNoSolutionFound + } + switch c.Rule { + case "rulename": + return ElemRulename{Name: e.span(c)}, nil + case "group": + alt, err := e.alternation(ptFirst(c, "alternation")) + if err != nil { + return nil, err + } + return ElemGroup{Alternation: alt}, nil + case "option": + alt, err := e.alternation(ptFirst(c, "alternation")) + if err != nil { + return nil, err + } + return ElemOption{Alternation: alt}, nil + case "char-val": + return e.charVal(c), nil + case "num-val": + return e.numVal(c), nil + case "prose-val": + return e.proseVal(c), nil + } + return nil, ErrNoSolutionFound +} + +func (e *feval) charVal(t *ParseTree) ElemCharVal { + s := e.span(t) + sensitive := false + if len(s) >= 2 && s[0] == '%' { + if s[1] == 's' || s[1] == 'S' { + sensitive = true + } + s = s[2:] + } + first := strings.IndexByte(s, '"') + last := strings.LastIndexByte(s, '"') + value := []rune{} + if first >= 0 && last > first { + value = []rune(s[first+1 : last]) + } + return ElemCharVal{Sensitive: sensitive, Values: value} +} + +func (e *feval) numVal(t *ParseTree) ElemNumVal { + s := e.span(t) + base := "d" + rest := "" + if len(s) >= 2 && s[0] == '%' { + switch s[1] { + case 'b', 'B': + base = "b" + case 'd', 'D': + base = "d" + case 'x', 'X': + base = "x" + } + rest = s[2:] + } + status := StatSeries + var elems []string + if strings.ContainsRune(rest, '-') { + status = StatRange + elems = strings.Split(rest, "-") + } else { + elems = strings.Split(rest, ".") + } + // A num-val outside the Unicode range is still a well-formed numeric + // encoding (legitimate for non-textual / on-wire grammars), so it is kept + // as-is here. Strict semantic validation (SemvalABNF) rejects it for textual + // use; consumers that match against decoded runes treat an unrepresentable + // value as non-matching rather than panicking. + return ElemNumVal{Base: base, Status: status, Elems: elems} +} + +func (e *feval) proseVal(t *ParseTree) ElemProseVal { + values := []string{} + for i := t.Start + 1; i < t.End-1; i++ { + values = append(values, string(e.input[i])) + } + return ElemProseVal{values: values} +} + +func sensequal(target, actual rune, sensitive bool) bool { + if !sensitive { + target, actual = runeMin(target), runeMin(actual) + } + return target == actual +} + +func runeMin(r rune) rune { + if r >= 'A' && r <= 'Z' { + return r - 'A' + 'a' + } + return r +} + +func runeMax(r rune) rune { + if r >= 'a' && r <= 'z' { + return r - 'a' + 'A' + } + return r +} + +// SemvalABNF proceed to semantic validations of an ABNF grammar. +// It currently support the following checks: +// - for all rules, its dependencies (rules) exist +// - for repetition, min <= max +// - for num-val, that the value fits in 7-bits (US-ASCII encoded) +// To update this list, please open an issue. +func SemvalABNF(g *Grammar) error { + // Check all dependencies exist + for _, rule := range g.Rulemap { + deps := getDependencies(rule.Alternation) + for _, dep := range deps { + r := GetRule(dep, g.Rulemap) + if r == nil { + return &ErrDependencyNotFound{ + Rulename: dep, + } + } + } + } + + for _, rule := range g.Rulemap { + if err := semvalAlternation(rule.Alternation); err != nil { + return err + } + } + return nil +} + +func semvalAlternation(alt Alternation) error { + for _, concat := range alt.Concatenations { + for _, rep := range concat.Repetitions { + // min <= max + if rep.Max != inf && rep.Min > rep.Max { + return &ErrSemanticRepetition{ + Repetition: rep, + } + } + switch elem := rep.Element.(type) { + // num-val base + case ElemNumVal: + for _, val := range elem.Elems { + if err := checkBounds(val, elem.Base); err != nil { + return err + } + } + + // propagate recursion + case ElemGroup: + if err := semvalAlternation(elem.Alternation); err != nil { + return err + } + + case ElemOption: + if err := semvalAlternation(elem.Alternation); err != nil { + return err + } + } + } + } + return nil +} diff --git a/vendor/github.com/pandatix/go-abnf/leftrec.go b/vendor/github.com/pandatix/go-abnf/leftrec.go new file mode 100644 index 0000000..f86806d --- /dev/null +++ b/vendor/github.com/pandatix/go-abnf/leftrec.go @@ -0,0 +1,159 @@ +package goabnf + +import ( + "slices" + "strings" +) + +// Identifies left-recursive rules so the recognizer can handle them by seed-growing +// instead of refusing them. A rule is left-recursive when it can re-derive itself +// without consuming input -- i.e. it appears on a cycle of the "left-corner" +// relation: A left-corners B if B can begin a derivation of A at the same input +// position. Crucially this skips over prefixes that can vanish (zero-min repetitions, +// options, and nullable elements), so it also catches *hidden* left recursion such as +// `a = b a / "x"` where `b` is nullable -- which a purely positional check misses. + +// nullableRules computes, by least fixpoint over user and core rules, which rules can +// derive the empty string. +func (g *Grammar) nullableRules() map[string]bool { + rules := map[string]*Rule{} + for n := range g.Rulemap { + if r := GetRule(n, g.Rulemap); r != nil { + rules[strings.ToLower(r.Name)] = r + } + } + for n := range coreRules { + if r := GetRule(n, g.Rulemap); r != nil { + rules[strings.ToLower(r.Name)] = r + } + } + null := map[string]bool{} + for changed := true; changed; { + changed = false + for name, r := range rules { + if !null[name] && altNullable(g, null, r.Alternation) { + null[name] = true + changed = true + } + } + } + return null +} + +func altNullable(g *Grammar, null map[string]bool, alt Alternation) bool { + for _, c := range alt.Concatenations { + nullable := true + for _, rep := range c.Repetitions { + if !repNullable(g, null, rep) { + nullable = false + break + } + } + if nullable { + return true + } + } + return false +} + +func repNullable(g *Grammar, null map[string]bool, rep Repetition) bool { + if rep.Min == 0 { + return true + } + return elemNullable(g, null, rep.Element) +} + +func elemNullable(g *Grammar, null map[string]bool, elem ElemItf) bool { + switch v := elem.(type) { + case ElemOption: + return true + case ElemGroup: + return altNullable(g, null, v.Alternation) + case ElemRulename: + return null[strings.ToLower(v.Name)] + case ElemCharVal: + return len(v.Values) == 0 + } + // num-val always consumes; prose-val is treated as unmatchable. + return false +} + +// leftRecursiveSCCs returns, for every left-recursive rule (keyed by lowercase +// name), the set of rule names in its left-corner strongly-connected component +// (mutually left-recursive rules grown together). Non-left-recursive rules are +// absent from the map. +func (g *Grammar) leftRecursiveSCCs() map[string][]string { + null := g.nullableRules() + + // Build the left-corner dependency graph and reuse Tarjan's SCC finder. + lc := Depgraph{} + add := func(r *Rule) { + name := strings.ToLower(r.Name) + if _, ok := lc[name]; ok { + return + } + lc[name] = &node{Rulename: r.Name, Dependencies: leftCornerDeps(g, null, r.Alternation)} + } + for n := range g.Rulemap { + if r := GetRule(n, g.Rulemap); r != nil { + add(r) + } + } + for n := range coreRules { + if r := GetRule(n, g.Rulemap); r != nil { + add(r) + } + } + + finder := &cycle{index: 0, stack: []*node{}, dg: lc} + finder.find() + + out := map[string][]string{} + for _, scc := range finder.sccs { + members := make([]string, len(scc)) + for i, nd := range scc { + members[i] = strings.ToLower(nd.Rulename) + } + leftRecursive := len(scc) > 1 + if !leftRecursive { // size 1: left-recursive only with a self left-corner + leftRecursive = slices.Contains(scc[0].Dependencies, members[0]) + } + if leftRecursive { + for _, m := range members { + out[m] = members + } + } + } + return out +} + +// leftCornerDeps collects the rules reachable as a left corner of alt: walk each +// concatenation left to right, collecting rulename references, and stop at the +// first repetition that cannot vanish. +func leftCornerDeps(g *Grammar, null map[string]bool, alt Alternation) []string { + deps := []string{} + var addAlt func(Alternation) + addElem := func(e ElemItf) { + switch v := e.(type) { + case ElemRulename: + deps = appendDeps(deps, strings.ToLower(v.Name)) + case ElemGroup: + addAlt(v.Alternation) + case ElemOption: + addAlt(v.Alternation) + } + } + addAlt = func(a Alternation) { + for _, c := range a.Concatenations { + for _, rep := range c.Repetitions { + addElem(rep.Element) + if rep.Min == 0 || elemNullable(g, null, rep.Element) { + continue // this position can be empty; the next is also a left corner + } + break + } + } + } + addAlt(alt) + return deps +} diff --git a/vendor/github.com/pandatix/go-abnf/lookahead.go b/vendor/github.com/pandatix/go-abnf/lookahead.go new file mode 100644 index 0000000..a0229a6 --- /dev/null +++ b/vendor/github.com/pandatix/go-abnf/lookahead.go @@ -0,0 +1,298 @@ +package goabnf + +import ( + "fmt" + "sort" + "unicode/utf8" +) + +// One-symbol lookahead for the GLL engines. +// +// GLL as published guards parsing steps with a selection test test(x, A, γ): +// a sequence γ in a production of A is only explored at input position i when +// the next input symbol x is in FIRST(γ), or γ is nullable and x is in +// FOLLOW(A) (Scott & Johnstone, "GLL parse-tree generation", Science of +// Computer Programming 78(10), 2013, §3.3). It guards the descriptor started +// for each alternate α of A (§4.3), and the call of each nonterminal instance +// A ::= α·Xβ with γ = Xβ (§4.1), so no GSS node is created for a call that +// cannot consume the next symbol. +// +// The guard prunes sub-parses whose continuation cannot consume the next input +// symbol, such as a repetition 1*ALPHA stopping inside a run of letters. This +// keeps the forest proportional to the derivations that can still complete, +// e.g. linear in the run length for 1*ALPHA followed by a delimiter. +// +// A sequence rejected by the guard would have failed on a terminal at the same +// position, so its FIRST (and, when nullable, FOLLOW) terminals feed the +// furthest-failure diagnostics in its place. +// +// Symbols are runes (ABNF terminals are matched on decoded UTF-8), so sets are +// rune intervals plus an end-of-input marker. FIRST/FOLLOW are computed on the +// context-free reading of the slot grammar, ignoring repetition bounds: the +// bounded language is a subset of it, so the sets over-approximate and the test +// never rejects a viable sequence. + +type runeRange struct{ lo, hi rune } + +// laSet is a lookahead set: rune intervals, the end-of-input marker, and the +// terminals contributing to it (for furthest-failure diagnostics). +type laSet struct { + ranges []runeRange // sorted, non-overlapping, non-adjacent + ascii [2]uint64 // bitmap of ranges below utf8.RuneSelf + eof bool + terms []ssym + descs map[string]bool +} + +func (s *laSet) addRange(lo, hi rune) bool { + if lo > hi { + return false + } + if s.coversRange(lo, hi) { + return false + } + s.ranges = append(s.ranges, runeRange{lo, hi}) + sort.Slice(s.ranges, func(i, j int) bool { return s.ranges[i].lo < s.ranges[j].lo }) + merged := s.ranges[:1] + for _, r := range s.ranges[1:] { + last := &merged[len(merged)-1] + if r.lo <= last.hi+1 { + if r.hi > last.hi { + last.hi = r.hi + } + continue + } + merged = append(merged, r) + } + s.ranges = merged + return true +} + +func (s *laSet) coversRange(lo, hi rune) bool { + for _, r := range s.ranges { + if r.lo <= lo && hi <= r.hi { + return true + } + } + return false +} + +func (s *laSet) addTerm(t ssym) bool { + desc := "?" + if str, ok := t.term.(fmt.Stringer); ok { + desc = str.String() + } + if s.descs == nil { + s.descs = map[string]bool{} + } + if s.descs[desc] { + return false + } + s.descs[desc] = true + s.terms = append(s.terms, t) + return true +} + +// union adds o to s (optionally including o's end-of-input marker) and +// reports whether s changed. +func (s *laSet) union(o *laSet, withEOF bool) bool { + changed := false + for _, r := range o.ranges { + if s.addRange(r.lo, r.hi) { + changed = true + } + } + if withEOF && o.eof && !s.eof { + s.eof = true + changed = true + } + for _, t := range o.terms { + if s.addTerm(t) { + changed = true + } + } + return changed +} + +func (s *laSet) seal() { + for _, r := range s.ranges { + for c := r.lo; c <= r.hi && c < utf8.RuneSelf; c++ { + if c >= 0 { + s.ascii[c/64] |= 1 << (c % 64) + } + } + } +} + +func (s *laSet) contains(c rune) bool { + if c >= 0 && c < utf8.RuneSelf { + return s.ascii[c/64]&(1<<(c%64)) != 0 + } + i := sort.Search(len(s.ranges), func(i int) bool { return s.ranges[i].hi >= c }) + return i < len(s.ranges) && s.ranges[i].lo <= c +} + +// termFirst returns the FIRST set of a terminal and whether it matches the +// empty string, mirroring matchTerm. +func termFirst(t ssym) (laSet, bool) { + var s laSet + if t.kind == symEps { + return s, true + } + switch v := t.term.(type) { + case ElemCharVal: + if len(v.Values) == 0 { + return s, true + } + r := v.Values[0] + if v.Sensitive { + s.addRange(r, r) + } else { + lo := runeMin(r) + s.addRange(lo, lo) + up := runeMax(lo) + s.addRange(up, up) + } + + case ElemNumVal: + switch v.Status { + case StatRange: + s.addRange(numvalToRune(v.Elems[0], v.Base), numvalToRune(v.Elems[1], v.Base)) + + case StatSeries: + if len(v.Elems) == 0 { + return s, true + } + if r := numvalToRune(v.Elems[0], v.Base); utf8.ValidRune(r) { + s.addRange(r, r) + } + } + } + // A terminal that never matches (prose-val, out-of-range series) has an + // empty rune set but is still an attempted terminal for diagnostics. + s.addTerm(t) + return s, false +} + +// lookahead holds the selection sets FIRST(γ) ∪ (FOLLOW(A) if γ is nullable) +// of the slot grammar: sel for every alternate γ = α of A, call for every +// nonterminal instance A ::= α·Xβ with γ = Xβ. +type lookahead struct { + sel [][]laSet // [nt][alt] + call [][][]laSet // [nt][alt][dot], set only where the symbol at dot is a nonterminal +} + +func computeLookahead(sg *slotGrammar) *lookahead { + n := len(sg.nts) + nullable := make([]bool, n) + first := make([]laSet, n) + follow := make([]laSet, n) + + symNullable := func(s ssym) bool { + switch s.kind { + case symNonterm: + return nullable[s.nt] + + default: + _, null := termFirst(s) + return null + } + } + // firstSeq returns FIRST(seq) and whether seq is nullable. + firstSeq := func(seq []ssym) (laSet, bool) { + var out laSet + for _, s := range seq { + if s.kind == symNonterm { + out.union(&first[s.nt], false) + } else { + f, _ := termFirst(s) + out.union(&f, false) + } + if !symNullable(s) { + return out, false + } + } + return out, true + } + + for changed := true; changed; { + changed = false + for a, nt := range sg.nts { + for _, alt := range nt.alts { + f, null := firstSeq(alt) + if first[a].union(&f, false) { + changed = true + } + if null && !nullable[a] { + nullable[a] = true + changed = true + } + } + } + } + + follow[sg.start].eof = true + for changed := true; changed; { + changed = false + for a, nt := range sg.nts { + for _, alt := range nt.alts { + for k, s := range alt { + if s.kind != symNonterm { + continue + } + f, null := firstSeq(alt[k+1:]) + if follow[s.nt].union(&f, false) { + changed = true + } + if null && follow[s.nt].union(&follow[a], true) { + changed = true + } + } + } + } + } + + selection := func(a int, seq []ssym) laSet { + f, null := firstSeq(seq) + if null { + f.union(&follow[a], true) + } + f.seal() + return f + } + la := &lookahead{sel: make([][]laSet, n), call: make([][][]laSet, n)} + for a, nt := range sg.nts { + la.sel[a] = make([]laSet, len(nt.alts)) + la.call[a] = make([][]laSet, len(nt.alts)) + for ai, alt := range nt.alts { + la.sel[a][ai] = selection(a, alt) + la.call[a][ai] = make([]laSet, len(alt)) + for k, sym := range alt { + if sym.kind == symNonterm { + la.call[a][ai][k] = selection(a, alt[k:]) + } + } + } + } + return la +} + +// alt returns the selection set guarding alternate alt of nonterminal nt. +func (la *lookahead) alt(nt, alt int) *laSet { return &la.sel[nt][alt] } + +// callAt returns the selection set guarding the nonterminal call at slot L. +func (la *lookahead) callAt(L slot) *laSet { return &la.call[L.nt][L.alt][L.dot] } + +// admits reports whether the next input symbol at i is in s, i.e. whether the +// guarded sequence may derive a prefix of input[i:] in some context. +func (s *laSet) admits(input []byte, i int) bool { + if i >= len(input) { + return s.eof + } + r, size := utf8.DecodeRune(input[i:]) + if r == utf8.RuneError && size == 1 { + // No terminal matches an invalid UTF-8 sequence (see matchTerm). + return false + } + return s.contains(r) +} diff --git a/vendor/github.com/pandatix/go-abnf/option.go b/vendor/github.com/pandatix/go-abnf/option.go new file mode 100644 index 0000000..95664c2 --- /dev/null +++ b/vendor/github.com/pandatix/go-abnf/option.go @@ -0,0 +1,64 @@ +package goabnf + +const ( + defaultValidate = true + defaultRedefine = false +) + +func process(opts ...ABNFOption) *abnfOptions { + o := &abnfOptions{ + validate: defaultValidate, + redefineCore: defaultRedefine, + } + for _, opt := range opts { + opt.apply(o) + } + return o +} + +// ABNFOption defines the interface for parsing ABNF functional options. +type ABNFOption interface { + apply(*abnfOptions) +} + +type abnfOptions struct { + validate bool + redefineCore bool +} + +// Defines if proceed to semantic validation. +type validateOption bool + +var _ ABNFOption = (*validateOption)(nil) + +func (o validateOption) apply(opts *abnfOptions) { + opts.validate = bool(o) +} + +// WithValidation returns a functional option to proceed to +// validation or not. +// Default is true. +func WithValidation(validate bool) ABNFOption { + return validateOption(validate) +} + +// Defines if an ABNF grammar could redefine a core rule. +type redefineCoreOption bool + +var _ ABNFOption = (*redefineCoreOption)(nil) + +func (o redefineCoreOption) apply(opts *abnfOptions) { + opts.redefineCore = bool(o) +} + +// WithRedefineCoreRules returns a functional option to +// enable redefining a core rule. +// Default is false. +// +// WARNING: use with caution, as we left to the user the responsibility +// to ensure the redefinition keeps the ABNF grammar coherent (i.e. +// there is an isomorphism between the core rule and the redefinition, +// not especially the same textual representation). +func WithRedefineCoreRules(redefine bool) ABNFOption { + return redefineCoreOption(redefine) +} diff --git a/vendor/github.com/pandatix/go-abnf/recognize.go b/vendor/github.com/pandatix/go-abnf/recognize.go new file mode 100644 index 0000000..df443cf --- /dev/null +++ b/vendor/github.com/pandatix/go-abnf/recognize.go @@ -0,0 +1,320 @@ +package goabnf + +import ( + "strconv" + "strings" + "unicode/utf8" +) + +// recognize.go holds the engine behind (*Grammar).IsValid. +// +// Validity only needs the SET of input positions each element can reach, never +// the (possibly exponential) set of distinct parse trees that reach them. We +// compute, for each (element, start-index), the set of reachable end-indices, +// deduplicating positions at every step and memoizing per (element, index). +// Positions live in [0, len(input)], so the work is polynomial rather than the +// exponential path enumeration that Parse performs. +// +// IsValid enforces left-termination before calling in, so the in-progress +// guard below is defense-in-depth: it can never fire for a left-terminating +// grammar (a same-index re-entry implies the rule is not left terminating). + +type recognizer struct { + g *Grammar + input []byte + memo map[string]map[int]bool // element.String()+"@"+index -> reachable end set + inProgress map[string]bool + + // Left-recursion support. leftRec maps each left-recursive rule (lowercase + // name) to its left-corner SCC, grown jointly. growing holds the live seed + // of each rule currently being grown (key "rule@index"); a re-entrant call + // returns the seed instead of recursing. + leftRec map[string][]string + growing map[string]map[int]bool +} + +func cloneSet(s map[int]bool) map[int]bool { + out := make(map[int]bool, len(s)) + for k := range s { + out[k] = true + } + return out +} + +func (r *recognizer) reachAlt(alt Alternation, index int) map[int]bool { + out := map[int]bool{} + for _, c := range alt.Concatenations { + for e := range r.reachConcat(c, index) { + out[e] = true + } + } + return out +} + +func (r *recognizer) reachConcat(c Concatenation, index int) map[int]bool { + cur := map[int]bool{index: true} + for _, rep := range c.Repetitions { + next := map[int]bool{} + for p := range cur { + for e := range r.reachRep(rep, p) { + next[e] = true + } + } + cur = next + if len(cur) == 0 { + break + } + } + return cur +} + +func (r *recognizer) reachRep(rep Repetition, index int) map[int]bool { + ends := map[int]bool{} + if rep.Min == 0 { + ends[index] = true + } + + // level = positions reachable after exactly c occurrences. + level := map[int]bool{index: true} + // seen = every position reached at any count so far. reachElem only moves + // forward (an end position is >= its start), so once a step introduces no + // position outside seen, the reachable set has closed and no later + // repetition can add a new end position. Breaking there keeps an unbounded + // repetition over an element with large reach-sets (e.g. *(1*ALPHA)) at + // O(n^2); the previous len(next)==len(level) test never tripped because + // level shrank by one each step ({1..n}, {2..n}, ...), giving O(n^3). + seen := map[int]bool{index: true} + + // Levels are stationary after at most len(input)+1 counts: reachElem only + // moves forward, so whether position x is in a level depends on positions + // below x plus x reaching itself, and each position settles one count after + // the ones below it. The stationary check below therefore fires within cap. + cap := len(r.input) + 2 + for c := 1; c <= cap; c++ { + if rep.Max != inf && c > rep.Max { + break + } + next := map[int]bool{} + for p := range level { + for e := range r.reachElem(rep.Element, p) { + next[e] = true + } + } + if len(next) == 0 { + break + } + if c >= rep.Min { + for e := range next { + ends[e] = true + } + } + grew := false + for e := range next { + if !seen[e] { + seen[e] = true + grew = true + } + } + // Stationary level: every further count reaches the same positions, so + // a minimum not yet met is met by that same set. This happens with a + // nullable element, e.g. 3"" on an empty input, where the count must + // go past the input length to reach the minimum. + if c < rep.Min && sameSet(next, level) { + if rep.Max == inf || rep.Min <= rep.Max { + for e := range next { + ends[e] = true + } + } + break + } + level = next + // Reachable set closed and the minimum-count requirement met. + if !grew && c >= rep.Min { + break + } + } + return ends +} + +func (r *recognizer) reachElem(elem ElemItf, index int) map[int]bool { + // Left-recursive rulenames are resolved by seed-growing rather than the + // flat memoized recursion below (which would cut the recursion to empty and + // under-accept). + if rn, ok := elem.(ElemRulename); ok { + if scc, isLR := r.leftRec[strings.ToLower(rn.Name)]; isLR { + return r.reachLeftRec(strings.ToLower(rn.Name), scc, index) + } + } + + key := elem.String() + "@" + strconv.Itoa(index) + if cached, ok := r.memo[key]; ok { + return cached + } + if r.inProgress[key] { + // Re-entry at the same position == non-progressing recursion in a rule + // not flagged left-recursive. Return empty (defense-in-depth) instead of + // looping forever. + return map[int]bool{} + } + r.inProgress[key] = true + out := r.computeElem(elem, index) + delete(r.inProgress, key) + // Safe to cache: a rule reached here either is independent of any actively + // growing seed, or is itself a growing SCC member (handled by reachLeftRec + // via r.growing, not this path). A lower left-corner SCC cannot reference + // the SCC growing above it -- they would be one SCC -- so its result is + // stable. Caching nested SCCs is what keeps left recursion polynomial. + r.memo[key] = cloneSet(out) + return out +} + +// reachLeftRec computes the reachable end-set of a left-recursive rule at index +// by growing the whole left-corner SCC from the empty seed to its least +// fixpoint. Each growth step adds end-positions (bounded by len(input)), so it +// terminates; a re-entrant call to any SCC member at the same index returns the +// current seed. Pure (base-less) left recursion correctly settles at the empty +// set, i.e. "no match". +func (r *recognizer) reachLeftRec(name string, scc []string, index int) map[int]bool { + sidx := "@" + strconv.Itoa(index) + key := name + sidx + if cached, ok := r.memo[key]; ok { + return cached + } + if seed, ok := r.growing[key]; ok { + return seed // re-entrant: return the current seed + } + + keys := make([]string, len(scc)) + for i, x := range scc { + keys[i] = x + sidx + r.growing[keys[i]] = map[int]bool{} + } + for changed := true; changed; { + changed = false + for i, x := range scc { + rule := GetRule(x, r.g.Rulemap) + if rule == nil { + continue + } + ns := r.reachAlt(rule.Alternation, index) + cur := r.growing[keys[i]] + for e := range ns { + if !cur[e] { + cur[e] = true + changed = true + } + } + } + } + + // The fixpoint converged. These end-sets are final and independent of any + // outer growing seed (the SCC only re-references its own members, held in + // r.growing, and strictly lower SCCs, which cannot reference it back), so + // they can be memoized unconditionally. + var result map[int]bool + for i, x := range scc { + v := r.growing[keys[i]] + delete(r.growing, keys[i]) + r.memo[keys[i]] = cloneSet(v) + if x == name { + result = cloneSet(v) + } + } + return result +} + +func (r *recognizer) computeElem(elem ElemItf, index int) map[int]bool { + out := map[int]bool{} + switch v := elem.(type) { + case ElemRulename: + rule := GetRule(v.Name, r.g.Rulemap) + if rule == nil { + return out + } + return r.reachAlt(rule.Alternation, index) + + case ElemGroup: + return r.reachAlt(v.Alternation, index) + + case ElemOption: + out[index] = true // 0 occurrences + for e := range r.reachAlt(v.Alternation, index) { + out[e] = true + } + return out + + case ElemProseVal: + // prose-val can't be matched (same as the original parser) + return out + + case ElemNumVal: + switch v.Status { + case StatRange: + if index >= len(r.input) { + return out + } + // Bounds are numeric: a range straddling the Unicode ceiling still + // matches its representable (rune) subset, one wholly above it matches + // nothing. numvalToRune never panics (saturates out-of-int32 bounds). + min := numvalToRune(v.Elems[0], v.Base) + max := numvalToRune(v.Elems[1], v.Base) + ru, size := utf8.DecodeRune(r.input[index:]) + if ru == utf8.RuneError && size == 1 { + return out + } + if min <= ru && ru <= max { + out[index+size] = true + } + case StatSeries: + idx := index + for i := 0; i < len(v.Elems); i++ { + ru := numvalToRune(v.Elems[i], v.Base) + // A series element must denote a real character; an out-of-range + // value can never appear in UTF-8 input, so the series matches + // nothing (and we avoid a spurious U+FFFD coincidence). + if !utf8.ValidRune(ru) { + return out + } + s := string(ru) + sz := len([]byte(s)) + if idx+sz > len(r.input) || s != string(r.input[idx:idx+sz]) { + return out + } + idx += sz + } + out[idx] = true + } + return out + + case ElemCharVal: + idx := index + for i := 0; i < len(v.Values); i++ { + if idx >= len(r.input) { + return out + } + ru, size := utf8.DecodeRune(r.input[idx:]) + if ru == utf8.RuneError && size == 1 { + return out + } + if !sensequal(v.Values[i], ru, v.Sensitive) { + return out + } + idx += size + } + out[idx] = true + return out + } + return out +} + +func sameSet(a, b map[int]bool) bool { + if len(a) != len(b) { + return false + } + for k := range a { + if !b[k] { + return false + } + } + return true +} diff --git a/vendor/github.com/pandatix/go-abnf/regex.go b/vendor/github.com/pandatix/go-abnf/regex.go new file mode 100644 index 0000000..b3d49b2 --- /dev/null +++ b/vendor/github.com/pandatix/go-abnf/regex.go @@ -0,0 +1,468 @@ +package goabnf + +import ( + "fmt" + "regexp" + "sort" + "strings" + "unicode/utf8" +) + +// Regex builds a regular expression that recognises the given rulename. +// +// The rule must not contain a cycle in its dependency graph: a regular +// expression (RE2, no subroutines) cannot express recursion. +// +// Because RE2 has no subroutine/backreference, a rule referenced N times is +// inlined N times, so the output can grow exponentially with reference-nesting +// depth for diamond-shaped grammars. Pass WithMaxRegexLen to fail fast with +// *ErrRegexTooLarge instead of exhausting memory. The output is simplified +// (character classes merged, redundant groups and {1} quantifiers dropped) but +// is not guaranteed minimal. +func (g *Grammar) Regex(rulename string, opts ...RegexOption) (string, error) { + o := ®exOptions{} + for _, op := range opts { + op.applyRegex(o) + } + + isCyclic, err := g.RuleContainsCycle(rulename) + if err != nil { + return "", err + } + if isCyclic { + return "", &ErrCyclicRule{Rulename: rulename} + } + rule := GetRule(rulename, g.Rulemap) + if rule == nil { + return "", &ErrRuleNotFound{Rulename: rulename} + } + + b := &reBuilder{g: g, memo: map[string]reNode{}} + node := b.alt(rule.Alternation) + if b.err != nil { + return "", b.err + } + node = simplify(node, map[reNode]reNode{}) + + r := &reRenderer{max: o.maxLen} + var sb strings.Builder + r.render(&sb, node, precAlt) + if r.err != nil { + return "", r.err + } + return sb.String(), nil +} + +// ---- options & error ---- + +type regexOptions struct{ maxLen int } + +// RegexOption configures Regex. +type RegexOption interface{ applyRegex(*regexOptions) } + +type regexOptionFunc func(*regexOptions) + +func (f regexOptionFunc) applyRegex(o *regexOptions) { f(o) } + +// WithMaxRegexLen bounds the produced regex length in bytes. When the budget is +// exceeded, Regex returns *ErrRegexTooLarge. Zero (the default) is unbounded. +func WithMaxRegexLen(n int) RegexOption { + return regexOptionFunc(func(o *regexOptions) { o.maxLen = n }) +} + +// ErrRegexTooLarge is returned by Regex when the output would exceed the budget +// set with WithMaxRegexLen. +type ErrRegexTooLarge struct{ Max int } + +var _ error = (*ErrRegexTooLarge)(nil) + +func (e *ErrRegexTooLarge) Error() string { + return fmt.Sprintf("regex exceeds the configured %d-byte budget", e.Max) +} + +// ---- intermediate representation ---- + +const ( + precAlt = 1 // alternation binds loosest + precConcat = 2 + precRepeat = 3 + precAtom = 4 // a class or single char binds tightest +) + +type reNode interface{ prec() int } + +type reRange struct{ lo, hi rune } + +type reClass struct{ ranges []reRange } // a single [c,c] renders as a bare char +type reConcat struct{ parts []reNode } +type reAlt struct{ opts []reNode } +type reRepeat struct { + sub reNode + min, max int +} +type reEmpty struct{} + +// reNever matches nothing. It represents a num-val a RE2/Unicode pattern cannot +// express (a value entirely above U+10FFFF), keeping Regex consistent with the +// recognizer, which also matches nothing in that case. +type reNever struct{} + +func (*reClass) prec() int { return precAtom } +func (*reConcat) prec() int { return precConcat } +func (*reAlt) prec() int { return precAlt } +func (*reRepeat) prec() int { return precRepeat } +func (*reEmpty) prec() int { return precAtom } +func (*reNever) prec() int { return precAtom } + +var reEmptyV reNode = &reEmpty{} +var reNeverV reNode = &reNever{} + +func isNever(n reNode) bool { _, ok := n.(*reNever); return ok } + +// ---- build (memoised per rule => linear over the grammar DAG) ---- + +type reBuilder struct { + g *Grammar + memo map[string]reNode + err error +} + +func (b *reBuilder) rule(name string) reNode { + key := strings.ToLower(name) + if n, ok := b.memo[key]; ok { + return n + } + r := GetRule(name, b.g.Rulemap) + if r == nil { + return reEmptyV + } + n := b.alt(r.Alternation) + b.memo[key] = n + return n +} + +func (b *reBuilder) alt(a Alternation) reNode { + opts := make([]reNode, 0, len(a.Concatenations)) + for _, c := range a.Concatenations { + opts = append(opts, b.concat(c)) + } + return &reAlt{opts: opts} +} + +func (b *reBuilder) concat(c Concatenation) reNode { + parts := make([]reNode, 0, len(c.Repetitions)) + for _, rep := range c.Repetitions { + parts = append(parts, &reRepeat{sub: b.elem(rep.Element), min: rep.Min, max: rep.Max}) + } + return &reConcat{parts: parts} +} + +func (b *reBuilder) elem(e ElemItf) reNode { + switch v := e.(type) { + case ElemRulename: + return b.rule(v.Name) + case ElemGroup: + return b.alt(v.Alternation) + case ElemOption: + return &reRepeat{sub: b.alt(v.Alternation), min: 0, max: 1} + case ElemNumVal: + switch v.Status { + case StatRange: + lo := numvalToRune(v.Elems[0], v.Base) + hi := min( + // RE2 patterns are Unicode (max U+10FFFF). A range straddling that + // ceiling is clamped to its representable subset; one wholly above it + // matches nothing -- mirroring the recognizer. + numvalToRune(v.Elems[1], v.Base), utf8.MaxRune) + if lo > utf8.MaxRune || lo > hi { + return reNeverV + } + return &reClass{ranges: []reRange{{lo, hi}}} + default: // StatSeries is a CONCATENATION of values (a fixed sequence). + parts := make([]reNode, 0, len(v.Elems)) + for _, s := range v.Elems { + c := numvalToRune(s, v.Base) + // A series element must be a real character; if it is not, the + // whole sequence can never match any (Unicode) input. + if !utf8.ValidRune(c) { + return reNeverV + } + parts = append(parts, &reClass{ranges: []reRange{{c, c}}}) + } + return &reConcat{parts: parts} + } + case ElemCharVal: + // A char-val is case-insensitive unless Sensitive (RFC 7405); the + // recognizer folds ASCII A-Z only (see runeMin/sensequal), so we match + // that exactly here. + parts := make([]reNode, 0, len(v.Values)) + for _, c := range v.Values { + parts = append(parts, charClass(c, v.Sensitive)) + } + return &reConcat{parts: parts} + case ElemProseVal: + if b.err == nil { + b.err = ErrHandlingProseVal + } + return reEmptyV + } + return reEmptyV +} + +func charClass(c rune, sensitive bool) reNode { + if !sensitive { + switch { + case c >= 'A' && c <= 'Z': + lo := c - 'A' + 'a' + return &reClass{ranges: []reRange{{c, c}, {lo, lo}}} + case c >= 'a' && c <= 'z': + up := c - 'a' + 'A' + return &reClass{ranges: []reRange{{up, up}, {c, c}}} + } + } + return &reClass{ranges: []reRange{{c, c}}} +} + +// ---- simplification (pointer-memoised => linear over the DAG) ---- + +func simplify(n reNode, memo map[reNode]reNode) reNode { + if n == nil { + return reEmptyV + } + if s, ok := memo[n]; ok { + return s + } + var res reNode + switch v := n.(type) { + case *reClass: + res = &reClass{ranges: normalizeRanges(v.ranges)} + case *reEmpty: + res = reEmptyV + case *reNever: + res = reNeverV + case *reConcat: + parts := make([]reNode, 0, len(v.parts)) + never := false + for _, p := range v.parts { + sp := simplify(p, memo) + switch x := sp.(type) { + case *reEmpty: // drop: empty in a concatenation contributes nothing + case *reNever: // one un-matchable part makes the whole sequence un-matchable + never = true + case *reConcat: + parts = append(parts, x.parts...) // flatten + default: + parts = append(parts, sp) + } + } + switch { + case never: + res = reNeverV + case len(parts) == 0: + res = reEmptyV + case len(parts) == 1: + res = parts[0] + default: + res = &reConcat{parts: parts} + } + case *reAlt: + opts := make([]reNode, 0, len(v.opts)) + for _, o := range v.opts { + so := simplify(o, memo) + if isNever(so) { // a never-matching branch is dead; drop it + continue + } + if x, ok := so.(*reAlt); ok { + opts = append(opts, x.opts...) // flatten + } else { + opts = append(opts, so) + } + } + // Fold every class option into a single merged class: turns an + // alternation of single characters / ranges into one [...]. + var ranges []reRange + classes := 0 + others := make([]reNode, 0, len(opts)) + for _, o := range opts { + if c, ok := o.(*reClass); ok { + ranges = append(ranges, c.ranges...) + classes++ + } else { + others = append(others, o) + } + } + merged := make([]reNode, 0, len(others)+1) + if classes > 0 { + merged = append(merged, &reClass{ranges: normalizeRanges(ranges)}) + } + merged = append(merged, others...) + switch len(merged) { + case 0: + // Every branch was un-matchable: the alternation matches nothing. + res = reNeverV + case 1: + res = merged[0] + default: + res = &reAlt{opts: merged} + } + case *reRepeat: + sub := simplify(v.sub, memo) + switch { + case isNever(sub): + // Zero occurrences are allowed iff min == 0 (then it matches empty); + // otherwise the repetition is itself un-matchable. + if v.min == 0 { + res = reEmptyV + } else { + res = reNeverV + } + case isEmpty(sub): + res = reEmptyV + case v.min == 1 && v.max == 1: + res = sub + default: + res = &reRepeat{sub: sub, min: v.min, max: v.max} + } + default: + res = n + } + memo[n] = res + return res +} + +func isEmpty(n reNode) bool { _, ok := n.(*reEmpty); return ok } + +// normalizeRanges sorts and coalesces overlapping/adjacent ranges. +func normalizeRanges(rs []reRange) []reRange { + if len(rs) <= 1 { + return rs + } + cp := append([]reRange(nil), rs...) + sort.Slice(cp, func(i, j int) bool { + return cp[i].lo < cp[j].lo || (cp[i].lo == cp[j].lo && cp[i].hi < cp[j].hi) + }) + out := []reRange{cp[0]} + for _, r := range cp[1:] { + last := &out[len(out)-1] + if r.lo <= last.hi+1 { // overlapping or adjacent + if r.hi > last.hi { + last.hi = r.hi + } + } else { + out = append(out, r) + } + } + return out +} + +// ---- render (minimal grouping, length-budgeted) ---- + +type reRenderer struct { + max int + n int + err error +} + +func (rr *reRenderer) write(sb *strings.Builder, s string) { + if rr.err != nil { + return + } + rr.n += len(s) + if rr.max > 0 && rr.n > rr.max { + rr.err = &ErrRegexTooLarge{Max: rr.max} + return + } + sb.WriteString(s) +} + +// render emits node; it self-groups with (?:...) when its precedence is looser +// than the surrounding context requires. +func (rr *reRenderer) render(sb *strings.Builder, n reNode, ctx int) { + if rr.err != nil { + return + } + grp := n.prec() < ctx + if grp { + rr.write(sb, "(?:") + } + switch v := n.(type) { + case *reEmpty: + // (?: ) already opened if grouped; otherwise emit an explicit empty. + if !grp { + rr.write(sb, "(?:)") + } + case *reNever: + // Negated full-Unicode class: matches no character, hence nothing. + rr.write(sb, "[^\\x00-\\x{10ffff}]") + case *reClass: + rr.write(sb, renderClass(v)) + case *reConcat: + for _, p := range v.parts { + rr.render(sb, p, precConcat) + } + case *reAlt: + for i, o := range v.opts { + if i > 0 { + rr.write(sb, "|") + } + rr.render(sb, o, precAlt) + } + case *reRepeat: + rr.render(sb, v.sub, precAtom) // operand of a quantifier must be an atom + rr.write(sb, quantifier(v.min, v.max)) + } + if grp { + rr.write(sb, ")") + } +} + +func renderClass(c *reClass) string { + if len(c.ranges) == 1 && c.ranges[0].lo == c.ranges[0].hi { + return regescape(c.ranges[0].lo) // bare single character + } + var b strings.Builder + b.WriteByte('[') + for _, r := range c.ranges { + if r.lo == r.hi { + b.WriteString(classEscape(r.lo)) + } else { + b.WriteString(classEscape(r.lo)) + b.WriteByte('-') + b.WriteString(classEscape(r.hi)) + } + } + b.WriteByte(']') + return b.String() +} + +func quantifier(min, max int) string { + switch { + case min == 0 && max == 1: + return "?" + case min == 0 && max == inf: + return "*" + case min == 1 && max == inf: + return "+" + case max == inf: + return fmt.Sprintf("{%d,}", min) + case min == max: + return fmt.Sprintf("{%d}", min) + case min == 0: + return fmt.Sprintf("{0,%d}", max) + default: + return fmt.Sprintf("{%d,%d}", min, max) + } +} + +// regescape quotes a single rune for use outside a character class. +func regescape(r rune) string { return regexp.QuoteMeta(string(r)) } + +// classEscape renders a rune as a character-class member. Alphanumerics are +// never class metacharacters; everything else is emitted as \x{...} to avoid +// the class-specific escaping pitfalls of ], ^, - and \. +func classEscape(r rune) string { + if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') { + return string(r) + } + return fmt.Sprintf("\\x{%x}", r) +} diff --git a/vendor/github.com/pandatix/go-abnf/rules.go b/vendor/github.com/pandatix/go-abnf/rules.go new file mode 100644 index 0000000..a2c3987 --- /dev/null +++ b/vendor/github.com/pandatix/go-abnf/rules.go @@ -0,0 +1,1867 @@ +package goabnf + +var ( + inf int = -1 + + // coreRules are the core rules specified in RFC 5234 Section 8.1 + coreRules = map[string]*Rule{ + alpha.Name: alpha, + bit.Name: bit, + char.Name: char, + cr.Name: cr, + crlf.Name: crlf, + ctl.Name: ctl, + digit.Name: digit, + dquote.Name: dquote, + hexdig.Name: hexdig, + htab.Name: htab, + lf.Name: lf, + lwsp.Name: lwsp, + octet.Name: octet, + sp.Name: sp, + vchar.Name: vchar, + wsp.Name: wsp, + } + + // ALPHA = %x41-5A / %x61-7A + alpha = &Rule{ + Name: "ALPHA", + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemNumVal{ + Base: "x", + Status: StatRange, + Elems: []string{"41", "5A"}, + }, + }, + }, + }, { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemNumVal{ + Base: "x", + Status: StatRange, + Elems: []string{"61", "7A"}, + }, + }, + }, + }, + }, + }, + } + + // BIT = "0" / "1" + bit = &Rule{ + Name: "BIT", + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemCharVal{ + Sensitive: false, + Values: []rune{'0'}, + }, + }, + }, + }, { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemCharVal{ + Sensitive: false, + Values: []rune{'1'}, + }, + }, + }, + }, + }, + }, + } + + // CHAR = %x01-7F + char = &Rule{ + Name: "CHAR", + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemNumVal{ + Base: "x", + Status: StatRange, + Elems: []string{"01", "7F"}, + }, + }, + }, + }, + }, + }, + } + + // CR = %x0D + cr = &Rule{ + Name: "CR", + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemNumVal{ + Base: "x", + Status: StatSeries, + Elems: []string{"0D"}, + }, + }, + }, + }, + }, + }, + } + + // CRLF = CR LF + crlf = &Rule{ + Name: "CRLF", + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemRulename{ + Name: "CR", + }, + }, { + Min: 1, + Max: 1, + Element: ElemRulename{ + Name: "LF", + }, + }, + }, + }, + }, + }, + } + + // CTL = %x00-1F / %x7F + ctl = &Rule{ + Name: "CTL", + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemNumVal{ + Base: "x", + Status: StatRange, + Elems: []string{"00", "1F"}, + }, + }, + }, + }, { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemNumVal{ + Base: "x", + Status: StatSeries, + Elems: []string{"7F"}, + }, + }, + }, + }, + }, + }, + } + + // DIGIT = %x30-39 + digit = &Rule{ + Name: "DIGIT", + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemNumVal{ + Base: "x", + Status: StatRange, + Elems: []string{"30", "39"}, + }, + }, + }, + }, + }, + }, + } + + // DQUOTE = %x22 + dquote = &Rule{ + Name: "DQUOTE", + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemNumVal{ + Base: "x", + Status: StatSeries, + Elems: []string{"22"}, + }, + }, + }, + }, + }, + }, + } + + // HEXDIG = DIGIT / "A" / "B" / "C" / "D" / "E" / "F" + hexdig = &Rule{ + Name: "HEXDIG", + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemRulename{ + Name: "DIGIT", + }, + }, + }, + }, { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemCharVal{ + Sensitive: false, + Values: []rune{'A'}, + }, + }, + }, + }, { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemCharVal{ + Sensitive: false, + Values: []rune{'B'}, + }, + }, + }, + }, { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemCharVal{ + Sensitive: false, + Values: []rune{'C'}, + }, + }, + }, + }, { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemCharVal{ + Sensitive: false, + Values: []rune{'D'}, + }, + }, + }, + }, { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemCharVal{ + Sensitive: false, + Values: []rune{'E'}, + }, + }, + }, + }, { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemCharVal{ + Sensitive: false, + Values: []rune{'F'}, + }, + }, + }, + }, + }, + }, + } + + // HTAB = %x09 + htab = &Rule{ + Name: "HTAB", + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemNumVal{ + Base: "x", + Status: StatSeries, + Elems: []string{"09"}, + }, + }, + }, + }, + }, + }, + } + + // LF = %x0A + lf = &Rule{ + Name: "LF", + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemNumVal{ + Base: "x", + Status: StatSeries, + Elems: []string{"0A"}, + }, + }, + }, + }, + }, + }, + } + + // LWSP = *(WSP / CRLF WSP) + lwsp = &Rule{ + Name: "LWSP", + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 0, + Max: inf, + Element: ElemGroup{ + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemRulename{ + Name: "WSP", + }, + }, + }, + }, { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemRulename{ + Name: "CRLF", + }, + }, { + Min: 1, + Max: 1, + Element: ElemRulename{ + Name: "WSP", + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + } + + // OCTET = %x00-FF + octet = &Rule{ + Name: "OCTET", + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemNumVal{ + Base: "x", + Status: StatRange, + Elems: []string{"00", "FF"}, + }, + }, + }, + }, + }, + }, + } + + // SP = %x20 + sp = &Rule{ + Name: "SP", + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemNumVal{ + Base: "x", + Status: StatSeries, + Elems: []string{"20"}, + }, + }, + }, + }, + }, + }, + } + + // VCHAR = %x21-7E + vchar = &Rule{ + Name: "VCHAR", + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemNumVal{ + Base: "x", + Status: StatRange, + Elems: []string{"21", "7E"}, + }, + }, + }, + }, + }, + }, + } + + // WSP = SP / HTAB + wsp = &Rule{ + Name: "WSP", + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemRulename{ + Name: "SP", + }, + }, + }, + }, { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemRulename{ + Name: "HTAB", + }, + }, + }, + }, + }, + }, + } +) + +var ( + abnfRulelist = &Rule{ + Name: "rulelist", + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 1, + Max: inf, + Element: ElemGroup{ + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemRulename{ + Name: "rule", + }, + }, + }, + }, { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemGroup{ + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 0, + Max: inf, + Element: ElemRulename{ + Name: "WSP", // Fixed according to Errata 3076 + }, + }, { + Min: 1, + Max: 1, + Element: ElemRulename{ + Name: "c-nl", + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + } + + abnfRule = &Rule{ + Name: "rule", + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemRulename{ + Name: "rulename", + }, + }, { + Min: 1, + Max: 1, + Element: ElemRulename{ + Name: "defined-as", + }, + }, { + Min: 1, + Max: 1, + Element: ElemRulename{ + Name: "elements", + }, + }, { + Min: 1, + Max: 1, + Element: ElemRulename{ + Name: "c-nl", + }, + }, + }, + }, + }, + }, + } + + abnfRulename = &Rule{ + Name: "rulename", + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemRulename{ + Name: "ALPHA", + }, + }, { + Min: 0, + Max: inf, + Element: ElemGroup{ + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemRulename{ + Name: "ALPHA", + }, + }, + }, + }, { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemRulename{ + Name: "DIGIT", + }, + }, + }, + }, { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemCharVal{ + Sensitive: false, + Values: []rune{'-'}, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + } + + abnfDefinedAs = &Rule{ + Name: "defined-as", + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 0, + Max: inf, + Element: ElemRulename{ + Name: "c-wsp", + }, + }, { + Min: 1, + Max: 1, + Element: ElemGroup{ + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemCharVal{ + Sensitive: false, + Values: []rune{'='}, + }, + }, + }, + }, { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemCharVal{ + Sensitive: false, + Values: []rune{'=', '/'}, + }, + }, + }, + }, + }, + }, + }, + }, { + Min: 0, + Max: inf, + Element: ElemRulename{ + Name: "c-wsp", + }, + }, + }, + }, + }, + }, + } + + abnfElements = &Rule{ + Name: "elements", + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemRulename{ + Name: "alternation", + }, + }, { + Min: 0, + Max: inf, + Element: ElemRulename{ + Name: "WSP", // Fixed according to Errata 2968 + }, + }, + }, + }, + }, + }, + } + + abnfCWsp = &Rule{ + Name: "c-wsp", + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemRulename{ + Name: "WSP", + }, + }, + }, + }, { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemGroup{ + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemRulename{ + Name: "c-nl", + }, + }, { + Min: 1, + Max: 1, + Element: ElemRulename{ + Name: "WSP", + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + } + + abnfCNl = &Rule{ + Name: "c-nl", + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemRulename{ + Name: "comment", + }, + }, + }, + }, { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemRulename{ + Name: "CRLF", + }, + }, + }, + }, + }, + }, + } + + abnfComment = &Rule{ + Name: "comment", + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemCharVal{ + Sensitive: false, + Values: []rune{';'}, + }, + }, + { + Min: 0, + Max: inf, + Element: ElemGroup{ + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemRulename{ + Name: "WSP", + }, + }, + }, + }, + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemRulename{ + Name: "VCHAR", + }, + }, + }, + }, + }, + }, + }, + }, + { + Min: 1, + Max: 1, + Element: ElemRulename{ + Name: "CRLF", + }, + }, + }, + }, + }, + }, + } + + abnfAlternation = &Rule{ + Name: "alternation", + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemRulename{ + Name: "concatenation", + }, + }, + { + Min: 0, + Max: inf, + Element: ElemGroup{ + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 0, + Max: inf, + Element: ElemRulename{ + Name: "c-wsp", + }, + }, + { + Min: 1, + Max: 1, + Element: ElemCharVal{ + Sensitive: false, + Values: []rune{'/'}, + }, + }, + { + Min: 0, + Max: inf, + Element: ElemRulename{ + Name: "c-wsp", + }, + }, + { + Min: 1, + Max: 1, + Element: ElemRulename{ + Name: "concatenation", + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + } + + abnfConcatenation = &Rule{ + Name: "concatenation", + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemRulename{ + Name: "repetition", + }, + }, + { + Min: 0, + Max: inf, + Element: ElemGroup{ + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 1, + Max: inf, + Element: ElemRulename{ + Name: "c-wsp", + }, + }, + { + Min: 1, + Max: 1, + Element: ElemRulename{ + Name: "repetition", + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + } + + abnfRepetition = &Rule{ + Name: "repetition", + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemOption{ + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemRulename{ + Name: "repeat", + }, + }, + }, + }, + }, + }, + }, + }, + { + Min: 1, + Max: 1, + Element: ElemRulename{ + Name: "element", + }, + }, + }, + }, + }, + }, + } + + abnfRepeat = &Rule{ + Name: "repeat", + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 1, + Max: inf, + Element: ElemRulename{ + Name: "DIGIT", + }, + }, + }, + }, + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemGroup{ + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 0, + Max: inf, + Element: ElemRulename{ + Name: "DIGIT", + }, + }, + { + Min: 1, + Max: 1, + Element: ElemCharVal{ + Sensitive: false, + Values: []rune{'*'}, + }, + }, + { + Min: 0, + Max: inf, + Element: ElemRulename{ + Name: "DIGIT", + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + } + + abnfElement = &Rule{ + Name: "element", + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemRulename{ + Name: "rulename", + }, + }, + }, + }, + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemRulename{ + Name: "group", + }, + }, + }, + }, + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemRulename{ + Name: "option", + }, + }, + }, + }, + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemRulename{ + Name: "char-val", + }, + }, + }, + }, + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemRulename{ + Name: "num-val", + }, + }, + }, + }, + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemRulename{ + Name: "prose-val", + }, + }, + }, + }, + }, + }, + } + + abnfGroup = &Rule{ + Name: "group", + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemCharVal{ + Sensitive: false, + Values: []rune{'('}, + }, + }, + { + Min: 0, + Max: inf, + Element: ElemRulename{ + Name: "c-wsp", + }, + }, + { + Min: 1, + Max: 1, + Element: ElemRulename{ + Name: "alternation", + }, + }, + { + Min: 0, + Max: inf, + Element: ElemRulename{ + Name: "c-wsp", + }, + }, + { + Min: 1, + Max: 1, + Element: ElemCharVal{ + Sensitive: false, + Values: []rune{')'}, + }, + }, + }, + }, + }, + }, + } + + abnfOption = &Rule{ + Name: "option", + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemCharVal{ + Sensitive: false, + Values: []rune{'['}, + }, + }, + { + Min: 0, + Max: inf, + Element: ElemRulename{ + Name: "c-wsp", + }, + }, + { + Min: 1, + Max: 1, + Element: ElemRulename{ + Name: "alternation", + }, + }, + { + Min: 0, + Max: inf, + Element: ElemRulename{ + Name: "c-wsp", + }, + }, + { + Min: 1, + Max: 1, + Element: ElemCharVal{ + Sensitive: false, + Values: []rune{']'}, + }, + }, + }, + }, + }, + }, + } + + // Written as overrided by RFC 7405 + abnfCharVal = &Rule{ + Name: "char-val", + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemRulename{ + Name: "case-insensitive-string", + }, + }, + }, + }, { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemRulename{ + Name: "case-sensitive-string", + }, + }, + }, + }, + }, + }, + } + + abnfCaseInsensitiveString = &Rule{ + Name: "case-insensitive-string", + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemOption{ + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemCharVal{ + Sensitive: false, + Values: []rune{'%', 'i'}, + }, + }, + }, + }, + }, + }, + }, + }, { + Min: 1, + Max: 1, + Element: ElemRulename{ + Name: "quoted-string", + }, + }, + }, + }, + }, + }, + } + + abnfCaseSensitiveString = &Rule{ + Name: "case-sensitive-string", + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemCharVal{ + Sensitive: false, + Values: []rune{'%', 's'}, + }, + }, { + Min: 1, + Max: 1, + Element: ElemRulename{ + Name: "quoted-string", + }, + }, + }, + }, + }, + }, + } + + abnfQuotedString = &Rule{ + Name: "quoted-string", + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemRulename{ + Name: "DQUOTE", + }, + }, { + Min: 0, + Max: inf, + Element: ElemGroup{ + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemNumVal{ + Base: "x", + Status: StatRange, + Elems: []string{"20", "21"}, + }, + }, + }, + }, { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemNumVal{ + Base: "x", + Status: StatRange, + Elems: []string{"23", "7E"}, + }, + }, + }, + }, + }, + }, + }, + }, { + Min: 1, + Max: 1, + Element: ElemRulename{ + Name: "DQUOTE", + }, + }, + }, + }, + }, + }, + } + + abnfNumVal = &Rule{ + Name: "num-val", + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemCharVal{ + Sensitive: false, + Values: []rune{'%'}, + }, + }, + { + Min: 1, + Max: 1, + Element: ElemGroup{ + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemRulename{ + Name: "bin-val", + }, + }, + }, + }, + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemRulename{ + Name: "dec-val", + }, + }, + }, + }, + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemRulename{ + Name: "hex-val", + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + } + + abnfBinVal = &Rule{ + Name: "bin-val", + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemCharVal{ + Sensitive: false, + Values: []rune{'b'}, + }, + }, + { + Min: 1, + Max: inf, + Element: ElemRulename{ + Name: "BIT", + }, + }, + { + Min: 1, + Max: 1, + Element: ElemOption{ + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 1, + Max: inf, + Element: ElemGroup{ + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemCharVal{ + Sensitive: false, + Values: []rune{'.'}, + }, + }, + { + Min: 1, + Max: inf, + Element: ElemRulename{ + Name: "BIT", + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemGroup{ + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemCharVal{ + Sensitive: false, + Values: []rune{'-'}, + }, + }, + { + Min: 1, + Max: inf, + Element: ElemRulename{ + Name: "BIT", + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + } + + abnfDecVal = &Rule{ + Name: "dec-val", + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemCharVal{ + Sensitive: false, + Values: []rune{'d'}, + }, + }, + { + Min: 1, + Max: inf, + Element: ElemRulename{ + Name: "DIGIT", + }, + }, + { + Min: 1, + Max: 1, + Element: ElemOption{ + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 1, + Max: inf, + Element: ElemGroup{ + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemCharVal{ + Sensitive: false, + Values: []rune{'.'}, + }, + }, + { + Min: 1, + Max: inf, + Element: ElemRulename{ + Name: "DIGIT", + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemGroup{ + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemCharVal{ + Sensitive: false, + Values: []rune{'-'}, + }, + }, + { + Min: 1, + Max: inf, + Element: ElemRulename{ + Name: "DIGIT", + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + } + + abnfHexVal = &Rule{ + Name: "hex-val", + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemCharVal{ + Sensitive: false, + Values: []rune{'x'}, + }, + }, + { + Min: 1, + Max: inf, + Element: ElemRulename{ + Name: "HEXDIG", + }, + }, + { + Min: 1, + Max: 1, + Element: ElemOption{ + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 1, + Max: inf, + Element: ElemGroup{ + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemCharVal{ + Sensitive: false, + Values: []rune{'.'}, + }, + }, + { + Min: 1, + Max: inf, + Element: ElemRulename{ + Name: "HEXDIG", + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemGroup{ + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemCharVal{ + Sensitive: false, + Values: []rune{'-'}, + }, + }, + { + Min: 1, + Max: inf, + Element: ElemRulename{ + Name: "HEXDIG", + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + } + + abnfProseVal = &Rule{ + Name: "prose-val", + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemCharVal{ + Sensitive: false, + Values: []rune{'<'}, + }, + }, + { + Min: 0, + Max: inf, + Element: ElemGroup{ + Alternation: Alternation{ + Concatenations: []Concatenation{ + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemNumVal{ + Base: "x", + Status: StatRange, + Elems: []string{"20", "3D"}, + }, + }, + }, + }, + { + Repetitions: []Repetition{ + { + Min: 1, + Max: 1, + Element: ElemNumVal{ + Base: "x", + Status: StatRange, + Elems: []string{"3F", "7E"}, + }, + }, + }, + }, + }, + }, + }, + }, + { + Min: 1, + Max: 1, + Element: ElemCharVal{ + Sensitive: false, + Values: []rune{'>'}, + }, + }, + }, + }, + }, + }, + } +) diff --git a/vendor/github.com/pandatix/go-abnf/sppf.go b/vendor/github.com/pandatix/go-abnf/sppf.go new file mode 100644 index 0000000..d503e83 --- /dev/null +++ b/vendor/github.com/pandatix/go-abnf/sppf.go @@ -0,0 +1,902 @@ +package goabnf + +import ( + "fmt" + "math/big" + "strconv" + "unicode/utf8" +) + +// This file implements a GLL parser (Scott & Johnstone) producing a binarized +// Shared Packed Parse Forest (SPPF) for ABNF grammars. +// +// GLL parses ANY context-free grammar -- including left, right, hidden and +// mutual recursion, and arbitrary ambiguity -- in worst-case O(n^3) time and +// space, using a graph-structured stack (GSS) and a descriptor worklist whose +// "seen" set makes recursion terminate. The forest shares every sub-derivation +// and packs ambiguity, so it stays polynomial even when it represents +// exponentially or infinitely many trees. +// +// Pipeline: lower the ABNF AST into a flat slotted grammar (synthetic +// nonterminals for groups, options and repetitions), then run GLL over the +// slots. Recognition, ambiguity, tree counting and extraction are polynomial +// queries over the resulting forest. + +// --------------------------------------------------------------------------- +// Slotted grammar +// --------------------------------------------------------------------------- + +type symKind uint8 + +const ( + symNonterm symKind = iota + symTerm // a char-val / num-val / prose-val matcher + symEps // matches the empty string +) + +type ssym struct { + kind symKind + nt int // nonterminal id, for symNonterm + term ElemItf // terminal element, for symTerm +} + +type sgNT struct { + label string // diagnostic label + isRule bool // corresponds to an original ABNF rule (kept in the tree) + ruleName string // original rule name when isRule + alts [][]ssym // alternates; every alternate has >= 1 symbol + + // Native counted repetition. When isRep, the nonterminal stands for + // `repElem{repMin,repMax}` and its two alternates are the self-recursive + // encoding `R ::= eps | repElem R`. The [repMin,repMax] bound is enforced at + // parse time by a count carried in the GLL state (see addRepAlts), so the + // slot grammar stays O(1) in the repetition bound instead of unrolling it. + isRep bool + repMin int + repMax int // inf (== -1) means unbounded +} + +type slotGrammar struct { + nts []*sgNT + index map[string]int // dedup key -> nt id + start int + la *lookahead // selection sets guarding descriptor creation +} + +func (sg *slotGrammar) reserve(key, label string) (int, bool) { + if id, ok := sg.index[key]; ok { + return id, true + } + id := len(sg.nts) + sg.nts = append(sg.nts, &sgNT{label: label}) + sg.index[key] = id + return id, false +} + +// compileSlots lowers grammar starting at rootRulename into a slotted grammar. +const defaultMaxSlots = 1 << 16 + +func compileSlots(g *Grammar, rootRulename string, maxSlots int) (*slotGrammar, error) { + if GetRule(rootRulename, g.Rulemap) == nil { + return nil, &ErrRuleNotFound{Rulename: rootRulename} + } + sg := &slotGrammar{index: map[string]int{}} + c := &lowerer{g: g, sg: sg, max: maxSlots} + sg.start = c.rule(rootRulename) + if c.err != nil { + return nil, c.err + } + if c.over { + return nil, &ErrGrammarTooLarge{Max: maxSlots} + } + sg.la = computeLookahead(sg) + return sg, nil +} + +type lowerer struct { + g *Grammar + sg *slotGrammar + err error + max int // max nonterminals; 0 == unbounded + over bool // budget exceeded +} + +func (c *lowerer) budgetExceeded() bool { + if c.max > 0 && len(c.sg.nts) >= c.max { + c.over = true + } + return c.over +} + +func (c *lowerer) rule(name string) int { + key := "rule:" + canon(name) + id, existed := c.sg.reserve(key, name) + if existed { + return id + } + if c.budgetExceeded() { + return id + } + rule := GetRule(name, c.g.Rulemap) + if rule == nil { + // Unknown rule: a nonterminal with no alternates derives nothing. + c.sg.nts[id].label = name + return id + } + c.sg.nts[id].isRule = true + c.sg.nts[id].ruleName = rule.Name + c.sg.nts[id].alts = c.alts(rule.Alternation) + return id +} + +func (c *lowerer) alts(a Alternation) [][]ssym { + out := make([][]ssym, 0, len(a.Concatenations)) + for _, cc := range a.Concatenations { + seq := make([]ssym, 0, len(cc.Repetitions)) + for _, rep := range cc.Repetitions { + seq = append(seq, c.rep(rep)) + } + if len(seq) == 0 { + seq = []ssym{{kind: symEps}} + } + out = append(out, seq) + } + return out +} + +func (c *lowerer) rep(rep Repetition) ssym { + if rep.Min == 1 && rep.Max == 1 { + return c.elem(rep.Element) + } + key := "rep:" + rep.String() + id, existed := c.sg.reserve(key, rep.String()) + if existed { + return ssym{kind: symNonterm, nt: id} + } + if c.budgetExceeded() { + return ssym{kind: symNonterm, nt: id} + } + // A malformed bound where max < min accepts nothing: leave the rep + // nonterminal with no alternates so it derives the empty language (it is + // unsatisfiable, NOT unbounded). This matches the recognizer. + if rep.Max != inf && rep.Max < rep.Min { + return ssym{kind: symNonterm, nt: id} + } + // Lower to the self-recursive encoding R ::= eps | E R, a single nonterminal + // regardless of the bound. The [Min,Max] count is enforced at parse time + // (addRepAlts), so lowering is O(1) in the bound and there is no per-count + // nonterminal explosion (the old optTail/reqOne unrolling, which scaled with + // Max-Min and Min respectively). + esym := c.elem(rep.Element) + self := ssym{kind: symNonterm, nt: id} + c.sg.nts[id].alts = [][]ssym{ + {{kind: symEps}}, // alt 0: stop + {esym, self}, // alt 1: consume one element, then loop + } + c.sg.nts[id].label = rep.String() + c.sg.nts[id].isRep = true + c.sg.nts[id].repMin = rep.Min + c.sg.nts[id].repMax = rep.Max + return self +} + +func (c *lowerer) elem(e ElemItf) ssym { + switch v := e.(type) { + case ElemRulename: + return ssym{kind: symNonterm, nt: c.rule(v.Name)} + case ElemGroup: + return ssym{kind: symNonterm, nt: c.group(v)} + case ElemOption: + return ssym{kind: symNonterm, nt: c.option(v)} + case ElemCharVal, ElemNumVal, ElemProseVal: + return ssym{kind: symTerm, term: e} + } + return ssym{kind: symTerm, term: e} +} + +func (c *lowerer) group(v ElemGroup) int { + key := "grp:" + v.String() + id, existed := c.sg.reserve(key, v.String()) + if existed { + return id + } + if c.budgetExceeded() { + return id + } + c.sg.nts[id].alts = c.alts(v.Alternation) + return id +} + +func (c *lowerer) option(v ElemOption) int { + key := "opt:" + v.String() + id, existed := c.sg.reserve(key, v.String()) + if existed { + return id + } + if c.budgetExceeded() { + return id + } + alts := [][]ssym{{{kind: symEps}}} + alts = append(alts, c.alts(v.Alternation)...) + c.sg.nts[id].alts = alts + return id +} + +func canon(name string) string { + b := []byte(name) + for i := range b { + if b[i] >= 'A' && b[i] <= 'Z' { + b[i] += 'a' - 'A' + } + } + return string(b) +} + +// --------------------------------------------------------------------------- +// SPPF nodes +// --------------------------------------------------------------------------- + +type gnodeKind uint8 + +const ( + gSymbol gnodeKind = iota // a nonterminal node (Start..End) + gInter // a binarisation intermediate node + gTerm // a terminal / epsilon node +) + +type gnode struct { + kind gnodeKind + nt int // symbol nonterminal id, for gSymbol + Start, End int + packs []pack // >1 pack == ambiguity +} + +// pack is a packed node. It is labelled by the grammar slot it completes and +// its pivot (Scott & Johnstone, "GLL parse-tree generation", Science of +// Computer Programming 78(10), 2013, §3.1); the pivot is the left extent of the +// last child. Two alternates deriving the same span through the same children +// are distinct derivations, hence distinct packed nodes. +type pack struct { + L slot + kids []*gnode // 1 or 2 children +} + +func (n *gnode) addPack(L slot, children []*gnode) { + for _, p := range n.packs { + if p.L != L || len(p.kids) != len(children) { + continue + } + same := true + for i := range p.kids { + if p.kids[i] != children[i] { + same = false + break + } + } + if same { + return + } + } + n.packs = append(n.packs, pack{L: L, kids: children}) +} + +// --------------------------------------------------------------------------- +// GLL machinery +// --------------------------------------------------------------------------- + +type slot struct{ nt, alt, dot int } + +type gssNode struct { + ret slot // return slot + pos int + rc int // repetition count carried for native counted repetition (0 otherwise) + edges []gssEdge + edgeSet map[gssEdge]bool +} + +type gssEdge struct { + w *gnode + to *gssNode +} + +type descriptor struct { + L slot + u *gssNode + i int + w *gnode + rc int // repetition count (0 outside a counted repetition) +} + +type gllParser struct { + sg *slotGrammar + input []byte + + nodes map[nodeKey]*gnode + gss map[gssKey]*gssNode + u0 *gssNode + seen map[descriptor]bool + work []descriptor + popped map[*gssNode]map[*gnode]bool + + maxNodes int + aborted bool + + // Furthest-failure diagnostics: maxPos is the deepest input offset at which + // a terminal match was attempted and failed; expected collects the terminals + // that could have been consumed there (deduplicated via expectedSeen). They + // drive ParseError when the parse has no solution. + maxPos int + expected []string + expectedSeen map[string]bool +} + +// nodeKey interns SPPF nodes without allocating strings. Distinct kinds never +// collide: symbol nodes key on (kind,nt,start,end); intermediate nodes on +// (kind,L,start,end); terminal nodes on (kind,start,end). +type nodeKey struct { + kind gnodeKind + nt int + L slot + start, end int +} + +type gssKey struct { + ret slot + pos int + rc int +} + +// addAlt adds the descriptor starting alternate L.alt of L.nt at i when the +// lookahead test admits it. A rejected alternate would fail on its first +// terminal at i (or, when nullable, its continuation would), so its terminals +// are reported to the furthest-failure diagnostics in its place. +func (p *gllParser) addAlt(L slot, u *gssNode, i int, rc int) { + if p.admits(p.sg.la.alt(L.nt, L.alt), i) { + p.add(L, u, i, nil, rc) + } +} + +// admits applies a lookahead test at i. A rejected sequence would have failed +// on one of the set's terminals at i, so those feed the furthest-failure +// diagnostics in its place. +func (p *gllParser) admits(s *laSet, i int) bool { + if s.admits(p.input, i) { + return true + } + if i >= p.maxPos { + for _, t := range s.terms { + p.noteFail(i, t) + } + } + return false +} + +func (p *gllParser) add(L slot, u *gssNode, i int, w *gnode, rc int) { + d := descriptor{L, u, i, w, rc} + if p.seen[d] { + return + } + p.seen[d] = true + p.work = append(p.work, d) +} + +func (p *gllParser) gssNodeFor(ret slot, pos, rc int) *gssNode { + k := gssKey{ret, pos, rc} + if v, ok := p.gss[k]; ok { + return v + } + v := &gssNode{ret: ret, pos: pos, rc: rc, edgeSet: map[gssEdge]bool{}} + p.gss[k] = v + return v +} + +func (p *gllParser) create(L slot, u *gssNode, i int, w *gnode, rc int) *gssNode { + v := p.gssNodeFor(L, i, rc) + e := gssEdge{w: w, to: u} + if !v.edgeSet[e] { + v.edgeSet[e] = true + v.edges = append(v.edges, e) + for z := range p.popped[v] { + y := p.getNodeP(L, w, z) + p.add(L, u, z.End, y, rc) + } + } + return v +} + +func (p *gllParser) pop(u *gssNode, i int, z *gnode) { + if u == p.u0 { + return + } + if p.popped[u] == nil { + p.popped[u] = map[*gnode]bool{} + } + p.popped[u][z] = true + for _, e := range u.edges { + y := p.getNodeP(u.ret, e.w, z) + p.add(u.ret, e.to, i, y, u.rc) + } +} + +func (p *gllParser) findNode(k nodeKey) *gnode { + if v, ok := p.nodes[k]; ok { + return v + } + if p.maxNodes > 0 && len(p.nodes) >= p.maxNodes { + p.aborted = true + } + v := &gnode{kind: k.kind, nt: k.nt, Start: k.start, End: k.end} + p.nodes[k] = v + return v +} + +func (p *gllParser) getNodeT(start, end int) *gnode { + return p.findNode(nodeKey{kind: gTerm, nt: -1, start: start, end: end}) +} + +// getNodeP combines left node w (may be nil == $) and right node z under slot L. +func (p *gllParser) getNodeP(L slot, w, z *gnode) *gnode { + prod := p.sg.nts[L.nt].alts[L.alt] + betaEmpty := L.dot == len(prod) + if L.dot == 1 && !betaEmpty { + return z // single symbol consumed, more to come: pass straight up + } + start := z.Start + if w != nil { + start = w.Start + } + var k nodeKey + if betaEmpty { + k = nodeKey{kind: gSymbol, nt: L.nt, start: start, end: z.End} + } else { + k = nodeKey{kind: gInter, nt: -1, L: L, start: start, end: z.End} + } + y := p.findNode(k) + if w != nil { + y.addPack(L, []*gnode{w, z}) + } else { + y.addPack(L, []*gnode{z}) + } + return y +} + +// matchTerm returns the end index after matching the terminal at i, or -1. +func (p *gllParser) matchTerm(s ssym, i int) int { + if s.kind == symEps { + return i + } + switch v := s.term.(type) { + case ElemCharVal: + idx := i + for k := 0; k < len(v.Values); k++ { + if idx >= len(p.input) { + return -1 + } + r, size := utf8.DecodeRune(p.input[idx:]) + if r == utf8.RuneError && size == 1 { + return -1 + } + if !sensequal(v.Values[k], r, v.Sensitive) { + return -1 + } + idx += size + } + return idx + case ElemNumVal: + switch v.Status { + case StatRange: + if i >= len(p.input) { + return -1 + } + // Numeric comparison: a range straddling U+10FFFF matches its rune + // subset; numvalToRune never panics (saturates out-of-int32 bounds). + min := numvalToRune(v.Elems[0], v.Base) + max := numvalToRune(v.Elems[1], v.Base) + r, size := utf8.DecodeRune(p.input[i:]) + if r == utf8.RuneError && size == 1 { + return -1 + } + if min <= r && r <= max { + return i + size + } + return -1 + case StatSeries: + idx := i + for k := 0; k < len(v.Elems); k++ { + ru := numvalToRune(v.Elems[k], v.Base) + // Series elements must be real characters: an out-of-range value + // matches no UTF-8 input (and avoids a spurious U+FFFD match). + if !utf8.ValidRune(ru) { + return -1 + } + str := string(ru) + sz := len(str) + if idx+sz > len(p.input) || str != string(p.input[idx:idx+sz]) { + return -1 + } + idx += sz + } + return idx + } + } + return -1 // prose-val and anything else never matches +} + +// parse runs the GLL loop and returns the symbol node (start, 0, n) or nil. +func (p *gllParser) parse() *gnode { + startNT := p.sg.start + p.u0 = &gssNode{ret: slot{-1, -1, -1}, pos: 0} + for ai := range p.sg.nts[startNT].alts { + p.addAlt(slot{startNT, ai, 0}, p.u0, 0, 0) + } + for len(p.work) > 0 { + if p.aborted { + return nil + } + d := p.work[len(p.work)-1] + p.work = p.work[:len(p.work)-1] + p.process(d) + } + key := nodeKey{kind: gSymbol, nt: startNT, start: 0, end: len(p.input)} + return p.nodes[key] +} + +func (p *gllParser) process(d descriptor) { + L, u, i, w, rc := d.L, d.u, d.i, d.w, d.rc + for { + prod := p.sg.nts[L.nt].alts[L.alt] + if L.dot == len(prod) { + z := w + if z == nil { + z = p.getNodeT(i, i) + } + p.pop(u, i, z) + return + } + s := prod[L.dot] + if s.kind == symNonterm { + if !p.admits(p.sg.la.callAt(L), i) { + return + } + ret := slot{L.nt, L.alt, L.dot + 1} + // Preserve the current repetition frame count across the sub-parse so + // that when it returns we resume the loop with the right count. + v := p.create(ret, u, i, w, rc) + if p.sg.nts[s.nt].isRep { + // Native counted repetition: a self-reference inside the rep's own + // loop alternate continues the chain (count+1); any other reference + // starts a fresh chain at count 0. + childRC := 0 + if s.nt == L.nt { + childRC = capRC(rc, p.sg.nts[s.nt]) + } + p.addRepAlts(s.nt, v, i, childRC) + } else { + for ai := range p.sg.nts[s.nt].alts { + p.addAlt(slot{s.nt, ai, 0}, v, i, 0) + } + } + return + } + j := p.matchTerm(s, i) + if j < 0 { + p.noteFail(i, s) + return + } + cR := p.getNodeT(i, j) + next := slot{L.nt, L.alt, L.dot + 1} + w = p.getNodeP(next, w, cR) + i = j + L = next + } +} + +// noteFail records that a terminal match failed at input offset i. It maintains +// the furthest such offset and, for that offset only, the set of terminals that +// could have been consumed -- the classic "furthest-failure" position used to +// report where parsing got stuck. +func (p *gllParser) noteFail(i int, s ssym) { + if i > p.maxPos { + p.maxPos = i + p.expected = p.expected[:0] + p.expectedSeen = nil + } + if i != p.maxPos { + return + } + desc := "?" + if str, ok := s.term.(fmt.Stringer); ok { + desc = str.String() + } + if p.expectedSeen == nil { + p.expectedSeen = map[string]bool{} + } + if !p.expectedSeen[desc] { + p.expectedSeen[desc] = true + p.expected = append(p.expected, desc) + } +} + +// capRC returns the count after consuming one more element of a repetition R +// currently at count rc. For an unbounded repetition it saturates at repMin +// (once the minimum is met the exact count no longer matters), which keeps the +// reachable counts -- and hence the GLL state -- finite even when the element is +// nullable. +func capRC(rc int, nt *sgNT) int { + next := rc + 1 + if nt.repMax == inf && next > nt.repMin { + next = nt.repMin + } + return next +} + +// addRepAlts seeds the two alternates of a repetition nonterminal, gated by the +// current count rc: it may stop (alt 0) only once the minimum is met, and may +// consume another element (alt 1) only while under the maximum. This enforces +// the {repMin,repMax} bound in parser state instead of unrolling it into the +// grammar, mirroring the recognizer's c>=min / c= nt.repMin { + p.addAlt(slot{ntID, 0, 0}, v, i, rc) // stop: alt 0 == [eps] + } + if nt.repMax == inf || rc < nt.repMax { + p.addAlt(slot{ntID, 1, 0}, v, i, rc) // loop: alt 1 == [element, self] + } +} + +// --------------------------------------------------------------------------- +// Public API +// --------------------------------------------------------------------------- + +// Forest is a shared packed parse forest produced by ParseForest. +type Forest struct { + sg *slotGrammar + input []byte + rulename string + root *gnode + built int + + // maxPos / expected carry the furthest-failure diagnostics from the parse, + // surfaced through ParseError when the forest is invalid. + maxPos int + expected []string +} + +// ForestOption configures ParseForest. +type ForestOption func(*forestConfig) + +type forestConfig struct { + maxNodes int + maxSlots int +} + +// WithMaxForestNodes bounds the number of SPPF nodes the forest may allocate. +// Because a complete SPPF is worst-case cubic in the input length, this caps the +// time and memory ParseForest can spend on adversarial input. 0 means unbounded. +func WithMaxForestNodes(n int) ForestOption { return func(c *forestConfig) { c.maxNodes = n } } + +// WithMaxSlots bounds the number of nonterminals produced while lowering the +// grammar. A finite repetition m*n lowers to ~n nonterminals, so this caps the +// cost of an adversarial grammar such as a = 9999999999"x". 0 means unbounded; +// the default is 65536. +func WithMaxSlots(n int) ForestOption { return func(c *forestConfig) { c.maxSlots = n } } + +// ErrForestTooLarge is returned by ParseForest when the SPPF exceeds the +// configured WithMaxForestNodes budget. +type ErrForestTooLarge struct{ Max int } + +func (e *ErrForestTooLarge) Error() string { + return "abnf: parse forest exceeded " + strconv.Itoa(e.Max) + " nodes" +} + +// ErrGrammarTooLarge is returned by ParseForest when lowering the grammar would +// exceed the WithMaxSlots budget, typically because of an absurd repetition +// bound (e.g. a = 9999999999"x"). +type ErrGrammarTooLarge struct{ Max int } + +func (e *ErrGrammarTooLarge) Error() string { + return "abnf: grammar lowering exceeded " + strconv.Itoa(e.Max) + " nonterminals" +} + +func newGLLParser(sg *slotGrammar, input []byte, maxNodes int) *gllParser { + return &gllParser{ + sg: sg, + input: input, + nodes: map[nodeKey]*gnode{}, + gss: map[gssKey]*gssNode{}, + seen: map[descriptor]bool{}, + popped: map[*gssNode]map[*gnode]bool{}, + maxNodes: maxNodes, + } +} + +// ParseForest parses input with grammar starting at rootRulename using GLL, +// returning the shared packed parse forest. It runs in worst-case O(n^3) time +// and space for ANY grammar -- left/right/mutual recursion and ambiguity +// included -- so it is safe on untrusted or malformed grammars. +func ParseForest(input []byte, grammar *Grammar, rootRulename string, opts ...ForestOption) (*Forest, error) { + cfg := forestConfig{maxSlots: defaultMaxSlots} + for _, o := range opts { + o(&cfg) + } + sg, err := compileSlots(grammar, rootRulename, cfg.maxSlots) + if err != nil { + return nil, err + } + p := newGLLParser(sg, input, cfg.maxNodes) + root := p.parse() + if p.aborted { + return nil, &ErrForestTooLarge{Max: cfg.maxNodes} + } + return &Forest{sg: sg, input: input, rulename: rootRulename, root: root, built: len(p.nodes), maxPos: p.maxPos, expected: p.expected}, nil +} + +// Valid reports whether the whole input is derivable by the root rule. +func (f *Forest) Valid() bool { return f.root != nil } + +// ParseError returns the furthest-failure diagnostic for an invalid forest: +// where parsing got stuck and which terminals were expected there. It returns +// nil when the forest is valid. The returned error unwraps to +// [ErrNoSolutionFound]. +func (f *Forest) ParseError() *ParseError { + if f.Valid() { + return nil + } + return newParseError(f.input, f.maxPos, f.expected) +} + +// Nodes returns the number of forest nodes reachable from the root. +func (f *Forest) Nodes() int { + if f.root == nil { + return 0 + } + seen := map[*gnode]bool{} + var walk func(n *gnode) + walk = func(n *gnode) { + if seen[n] { + return + } + seen[n] = true + for _, pk := range n.packs { + for _, c := range pk.kids { + walk(c) + } + } + } + walk(f.root) + return len(seen) +} + +// Ambiguous reports whether the input has more than one distinct parse tree. +func (f *Forest) Ambiguous() bool { + if f.root == nil { + return false + } + seen := map[*gnode]bool{} + var walk func(n *gnode) bool + walk = func(n *gnode) bool { + if seen[n] { + return false + } + seen[n] = true + if len(n.packs) > 1 { + return true + } + for _, pk := range n.packs { + for _, c := range pk.kids { + if walk(c) { + return true + } + } + } + return false + } + return walk(f.root) +} + +// NumTrees returns the number of distinct parse trees the forest represents. +// A result of -1 means infinitely many (a cycle in the forest, i.e. an +// infinitely-ambiguous grammar such as A = A / "x"). +func (f *Forest) NumTrees() *big.Int { + if f.root == nil { + return big.NewInt(0) + } + memo := map[*gnode]*big.Int{} + onStack := map[*gnode]bool{} + infinite := false + var count func(n *gnode) *big.Int + count = func(n *gnode) *big.Int { + if v, ok := memo[n]; ok { + return v + } + if onStack[n] { + infinite = true + return big.NewInt(1) + } + onStack[n] = true + total := big.NewInt(0) + if len(n.packs) == 0 { + total = big.NewInt(1) + } + for _, pk := range n.packs { + prod := big.NewInt(1) + for _, c := range pk.kids { + prod.Mul(prod, count(c)) + } + total.Add(total, prod) + } + onStack[n] = false + memo[n] = total + return total + } + res := count(f.root) + if infinite { + return big.NewInt(-1) + } + return res +} + +// ParseTree is a concrete syntax tree keyed by grammar rules: rule nodes carry +// the rule name, terminals are leaves with empty Rule. +type ParseTree struct { + Rule string + Start, End int + Children []*ParseTree +} + +// Tree extracts a single parse tree (first packing at each node), or nil if the +// input is invalid. A visited guard keeps extraction finite on cyclic forests. +func (f *Forest) Tree() *ParseTree { + if f.root == nil { + return nil + } + return f.emitSymbol(f.root, map[*gnode]bool{}) +} + +func (f *Forest) emitSymbol(n *gnode, onStack map[*gnode]bool) *ParseTree { + t := &ParseTree{Start: n.Start, End: n.End} + if n.kind == gSymbol && n.nt >= 0 && f.sg.nts[n.nt].isRule { + t.Rule = f.sg.nts[n.nt].ruleName + } + onStack[n] = true + f.collect(n, &t.Children, onStack) + delete(onStack, n) + return t +} + +func (f *Forest) collect(n *gnode, into *[]*ParseTree, onStack map[*gnode]bool) { + if len(n.packs) == 0 { + if n.kind == gTerm && n.End > n.Start { + *into = append(*into, &ParseTree{Start: n.Start, End: n.End}) + } + return + } + for _, c := range n.packs[0].kids { + f.collectChild(c, into, onStack) + } +} + +func (f *Forest) collectChild(c *gnode, into *[]*ParseTree, onStack map[*gnode]bool) { + switch { + case c.kind == gTerm: + if c.End > c.Start { + *into = append(*into, &ParseTree{Start: c.Start, End: c.End}) + } + case c.kind == gSymbol && c.nt >= 0 && f.sg.nts[c.nt].isRule: + if onStack[c] { + *into = append(*into, &ParseTree{Rule: f.sg.nts[c.nt].ruleName, Start: c.Start, End: c.End}) + return + } + *into = append(*into, f.emitSymbol(c, onStack)) + default: + if onStack[c] { + return + } + onStack[c] = true + f.collect(c, into, onStack) + delete(onStack, c) + } +} diff --git a/vendor/github.com/pandatix/go-abnf/transition_graph.go b/vendor/github.com/pandatix/go-abnf/transition_graph.go new file mode 100644 index 0000000..336318e --- /dev/null +++ b/vendor/github.com/pandatix/go-abnf/transition_graph.go @@ -0,0 +1,1546 @@ +package goabnf + +import ( + "crypto/rand" + "encoding/hex" + "fmt" + "slices" + "sort" + "strings" + "unicode/utf8" +) + +// TransitionGraph represent a grammar transition graph. +// It contains the list of entrypoints and endpoints. +// You could travel through the graph starting from the entrypoints. +type TransitionGraph struct { + grammar *Grammar + rulename string + options *tgoptions + + Entrypoints []*Node + Endpoints []*Node +} + +// Node of a TransitionGraph. +// Unically identifiate the node of the transition graph along +// with its underlying element and its next nodes. +type Node struct { + ID string + Elem ElemItf + + Nexts []*Node +} + +// TransitionGraph builds a transition graph out of a grammar +// and the given rulename. +// TODO it is possible to build transition graph out of cylic rules iff it is not concatenated to another repetition (can't pipe O->I as there is no O). For instance, `a = "a" a` can exist. +func (g *Grammar) TransitionGraph(rulename string, opts ...TGOption) (*TransitionGraph, error) { + // Build transition graph machine + options := &tgoptions{ + deflateRules: false, + deflateNumVals: false, + deflateCharVals: false, + repetitionThreshold: 256, + maxNodes: 0, // 0 == unbounded (backward compatible) + } + for _, opt := range opts { + opt.apply(options) + } + m := &tgmachine{ + options: options, + grammar: g, + buf: map[string][2][]*Node{}, + } + + // Find the rule + rule := GetRule(rulename, g.Rulemap) + if rule == nil { + return nil, &ErrRuleNotFound{ + Rulename: rulename, + } + } + + // Ensure the rule is semantically valid and does not contain cycle. + // Semantic validity is required to ensure rule dependencies actually + // exist, while no cycle is required because the algorithm is recursive + // and may not stop else. + if options.deflateRules { + if err := SemvalABNF(g); err != nil { + return nil, err + } + } + cycle, err := g.RuleContainsCycle(rulename) + if err != nil { + return nil, err + } + if cycle { + return nil, &ErrCyclicRule{ + Rulename: rulename, + } + } + + // Build transition graph + entrypoints, endpoints, err := m.altGraph(rule.Alternation) + if err != nil { + return nil, err + } + return &TransitionGraph{ + grammar: g, + rulename: rulename, + options: options, + Entrypoints: entrypoints, + Endpoints: endpoints, + }, nil +} + +var ( + // The empty node enable to bridge the no-entrypoint case of a repetition. + // This occurs when the minimum is 0. + // It disappear as soon as the repetition is piped as an input from lower + // inputs to upper outputs. + emptyNode = (*Node)(nil) +) + +type tgoptions struct { + deflateRules bool + deflateNumVals bool + deflateCharVals bool + repetitionThreshold int + maxNodes int +} + +type TGOption interface { + apply(opts *tgoptions) +} + +type deflateRulesOption bool + +func (opt deflateRulesOption) apply(opts *tgoptions) { + opts.deflateRules = bool(opt) +} + +// WithDeflateRules when passed to true, will recursively build the transition +// graphs of the rules it uses (reuse them if possible) and concatenate the +// sub transition graphs. +// It generates a more complex but exhaustive transition graph. +func WithDeflateRules(deflate bool) TGOption { + return deflateRulesOption(deflate) +} + +var _ TGOption = deflateRulesOption(false) + +type deflateNumValsOption bool + +func (opt deflateNumValsOption) apply(opts *tgoptions) { + opts.deflateNumVals = bool(opt) +} + +// WithDeflateNumVals when passed to true, will replace a single node representing +// the ranges or series of multiple numeric values to individual nodes. +// It generates a more complex but exhaustive transition graph. +func WithDeflateNumVals(deflate bool) TGOption { + return deflateNumValsOption(deflate) +} + +var _ TGOption = deflateNumValsOption(false) + +type deflateCharVals bool + +func (opt deflateCharVals) apply(opts *tgoptions) { + opts.deflateCharVals = bool(opt) +} + +// WithDeflateCharVals when passed to true, will replace a single node representing +// the char value to an exhaustive concatenation of all characters (lower and upper +// case) and the transitions between them. +func WithDeflateCharVals(deflate bool) TGOption { + return deflateCharVals(deflate) +} + +var _ TGOption = deflateCharVals(false) + +type repetitionThreshold int + +func (opt repetitionThreshold) apply(opts *tgoptions) { + opts.repetitionThreshold = int(opt) +} + +// WithRepetitionThreshold defines the threshold to block a large repetition +// to occur, elseway it may consum all memory to build the transition graph. +// For instance, a rule defined as follows may self-DoS go-abnf. +// +// a = 9555("a") +// +// WARNING it does not avoid such memory consumption on chained repetitions. +// For instance, the two following cases could produce large transition graphs +// without control with this functional option. +// +// a = 10( 10( 10("a") ) ) +// +// a = 10 ( 10*"a" ( 10"a" 9"a" 8"a" ) / ( *10"a" *10"a" *10"a" ) ) 10"a" +// +// Defaults to 256. +func WithRepetitionThreshold(threshold int) TGOption { + return repetitionThreshold(threshold) +} + +type maxNodesOption int + +func (opt maxNodesOption) apply(opts *tgoptions) { + opts.maxNodes = int(opt) +} + +// WithMaxNodes bounds the total number of nodes the transition graph may +// allocate during construction. Unlike WithRepetitionThreshold, which only caps +// a single repetition, this bounds the *whole* graph and so also defends against +// the combinatorial blow-up of nested repetitions (e.g. 10( 10( 10("a") ) )) and +// of wide num-val ranges deflated with WithDeflateNumVals. When the bound would +// be exceeded, construction stops with *ErrMaxNodesExceeded before the nodes are +// allocated. +// +// A value <= 0 (the default) means unbounded, preserving the previous behaviour. +// Set a positive bound when building transition graphs from untrusted grammars +// to keep the work within a controlled domain. +func WithMaxNodes(max int) TGOption { + return maxNodesOption(max) +} + +// reserve accounts for n nodes about to be created, failing fast (before any +// allocation) when the WithMaxNodes budget would be exceeded. It is a no-op when +// the budget is unbounded. +func (m *tgmachine) reserve(n int) error { + if m.options.maxNodes <= 0 { + return nil // unbounded + } + if n < 0 || m.nodeCount+n < 0 || m.nodeCount+n > m.options.maxNodes { + return &ErrMaxNodesExceeded{Max: m.options.maxNodes} + } + m.nodeCount += n + return nil +} + +// reserveClones accounts for cloning the subgraph reachable from entries reps +// times. When the budget is unbounded it does no work at all (in particular it +// skips the reachability count), so the default path keeps its previous cost. +func (m *tgmachine) reserveClones(reps int, entries []*Node) error { + if m.options.maxNodes <= 0 { + return nil + } + return m.reserve(reps * countReachable(entries)) +} + +// countReachable counts the distinct non-empty nodes reachable from entries, +// i.e. how many nodes cloneTransitionGraph would clone. +func countReachable(entries []*Node) int { + seen := map[string]bool{} + stack := make([]*Node, 0, len(entries)) + for _, e := range entries { + if e != emptyNode { + stack = append(stack, e) + } + } + for len(stack) > 0 { + n := stack[len(stack)-1] + stack = stack[:len(stack)-1] + if n == emptyNode || seen[n.ID] { + continue + } + seen[n.ID] = true + for _, sc := range n.Nexts { + if sc != emptyNode && !seen[sc.ID] { + stack = append(stack, sc) + } + } + } + return len(seen) +} + +// CoverageMode selects what set of strings a TransitionGraphReader produces. +type CoverageMode int + +const ( + // CoverageAllTrails (mode A, the default) emits every entrypoint->endpoint + // trail (a walk using each directed edge at most once) and, for each trail, + // every combination of its nodes' terminal variations. It is finite and + // terminating for any graph, but on dense graphs or wide range/charval nodes + // the number of trail x variation combinations can be very large. + CoverageAllTrails CoverageMode = iota + + // CoverageCompact (mode B) emits a small set of strings that still covers + // every reachable vertex, every edge, and every terminal value (each charval + // casing, each numval range value) at least once, then stops. Its size is + // bounded by roughly (#edges + #vertices + sum of per-node variations), so it + // stays small even for grammars where CoverageAllTrails explodes. + CoverageCompact +) + +// ReaderOption configures a TransitionGraphReader. +type ReaderOption interface { + apply(*readerOptions) +} + +type readerOptions struct { + mode CoverageMode +} + +type coverageModeOption CoverageMode + +func (o coverageModeOption) apply(opts *readerOptions) { + opts.mode = CoverageMode(o) +} + +// WithCoverageMode selects the coverage strategy of the reader (CoverageAllTrails +// by default, or CoverageCompact for a bounded covering set). +func WithCoverageMode(mode CoverageMode) ReaderOption { + return coverageModeOption(mode) +} + +func (tg *TransitionGraph) Reader(opts ...ReaderOption) *TransitionGraphReader { + ro := readerOptions{mode: CoverageAllTrails} + for _, o := range opts { + o.apply(&ro) + } + return &TransitionGraphReader{tg: tg, mode: ro.mode} +} + +// TransitionGraphReader produces a finite set of strings that COVERS the +// transition graph: every reachable vertex and edge that lies on some +// entrypoint->endpoint walk appears in at least one produced string. It does so +// by enumerating every entrypoint->endpoint *trail* (a walk that uses each +// directed edge at most once) in order of increasing length, and for each trail +// every combination of its nodes' terminal variations (char-val casing, +// num-val ranges). Trails are bounded by the number of edges, so the set is +// finite and enumeration always terminates -- for any graph, cyclic or not. +type TransitionGraphReader struct { + tg *TransitionGraph + + mode CoverageMode + all map[string]*Node // every node reachable from the entrypoints + + // CoverageCompact precomputed output. + prods [][]byte + prodIdx int + builtCompact bool + + prepared bool + entries []*Node // entrypoints that can reach an endpoint via producing nodes + endSet map[string]bool // endpoint node IDs + canReach map[string]bool // node can reach an endpoint via producing nodes + + // Trail enumeration state. + length int // current trail length (number of nodes) + stack []pathFrame // current trail being walked + usedEdges map[string]int // edges currently on the trail (>0 == used) + levelHadAnyPath bool // any length-`length` trail seen this level + exhausted bool // no more trails (coverage complete) + + // Variation odometer for the current trail. + havePath bool + varIdx []int32 + varTot []int32 + + // Staged production. + staged []byte + hasStaged bool +} + +type pathFrame struct { + node *Node + cursor int + allowed []*Node // children selectable at this depth given the trail prefix +} + +func tgNodeID(n *Node) string { + if n == nil { + return "" + } + return n.ID +} + +// producing reports whether a node can emit terminal bytes. Rulename nodes +// (present only when rules are not deflated) cannot, so no trail may pass +// through them. +func producing(n *Node) bool { + if n == emptyNode { + return true + } + switch n.Elem.(type) { + case ElemCharVal, ElemNumVal: + return true + default: + return false + } +} + +func (tgr *TransitionGraphReader) prepare() { + if tgr.prepared { + return + } + tgr.prepared = true + tgr.endSet = map[string]bool{} + for _, e := range tgr.tg.Endpoints { + tgr.endSet[tgNodeID(e)] = true + } + tgr.usedEdges = map[string]int{} + + // Collect every node reachable from the entrypoints. + all := map[string]*Node{} + var collect func(n *Node) + collect = func(n *Node) { + id := tgNodeID(n) + if _, ok := all[id]; ok { + return + } + all[id] = n + if n == emptyNode { + return // the empty sentinel ((*Node)(nil)) has no successors + } + for _, s := range n.Nexts { + collect(s) + } + } + for _, e := range tgr.tg.Entrypoints { + collect(e) + } + tgr.all = all + + // canReach[n] = n can produce AND (n is an endpoint OR some producing + // successor of n can reach an endpoint). Monotonic fixpoint. + tgr.canReach = map[string]bool{} + for changed := true; changed; { + changed = false + for id, n := range all { + if tgr.canReach[id] || !producing(n) { + continue + } + ok := tgr.endSet[id] + if !ok && n != emptyNode { + for _, sc := range n.Nexts { + if producing(sc) && tgr.canReach[tgNodeID(sc)] { + ok = true + break + } + } + } + if ok { + tgr.canReach[id] = true + changed = true + } + } + } + + for _, e := range tgr.tg.Entrypoints { + if producing(e) && tgr.canReach[tgNodeID(e)] { + tgr.entries = append(tgr.entries, e) + } + } +} + +func edgeStr(from, to *Node) string { + return tgNodeID(from) + ">" + tgNodeID(to) +} + +// allowedAt returns the children selectable at depth d given the current trail +// prefix: successors that can still reach an endpoint and whose edge is not yet +// used on this trail. At depth 0 the "children" are the entrypoints. +func (tgr *TransitionGraphReader) allowedAt(d int) []*Node { + if d == 0 { + return tgr.entries + } + parent := tgr.stack[d-1].node + if parent == emptyNode { + return nil // empty sentinel has no successors + } + var out []*Node + for _, sc := range parent.Nexts { + if !tgr.canReach[tgNodeID(sc)] { + continue + } + if tgr.usedEdges[edgeStr(parent, sc)] > 0 { + continue + } + out = append(out, sc) + } + return out +} + +func (tgr *TransitionGraphReader) pushFirst(d int) bool { + allowed := tgr.allowedAt(d) + if len(allowed) == 0 { + return false + } + node := allowed[0] + if d >= 1 { + tgr.usedEdges[edgeStr(tgr.stack[d-1].node, node)]++ + } + tgr.stack = append(tgr.stack, pathFrame{node: node, cursor: 0, allowed: allowed}) + return true +} + +func (tgr *TransitionGraphReader) bump() bool { + for len(tgr.stack) > 0 { + d := len(tgr.stack) - 1 + f := &tgr.stack[d] + if d >= 1 { + tgr.usedEdges[edgeStr(tgr.stack[d-1].node, f.node)]-- + } + if f.cursor+1 < len(f.allowed) { + f.cursor++ + f.node = f.allowed[f.cursor] + if d >= 1 { + tgr.usedEdges[edgeStr(tgr.stack[d-1].node, f.node)]++ + } + return true + } + tgr.stack = tgr.stack[:d] + } + return false +} + +// nextLeaf advances the trail to the next walk of exactly tgr.length nodes. +func (tgr *TransitionGraphReader) nextLeaf() bool { + L := tgr.length + for { + switch { + case len(tgr.stack) == L: + if !tgr.bump() { + return false + } + case len(tgr.stack) < L: + if !tgr.pushFirst(len(tgr.stack)) { + if !tgr.bump() { + return false + } + } + } + if len(tgr.stack) == L { + tgr.levelHadAnyPath = true + return true + } + } +} + +func (tgr *TransitionGraphReader) resetLevel() { + tgr.stack = tgr.stack[:0] + for k := range tgr.usedEdges { + delete(tgr.usedEdges, k) + } + tgr.levelHadAnyPath = false +} + +// advancePath sets tgr.stack to the next entrypoint->endpoint trail, returning +// false once every trail has been produced (coverage complete). +func (tgr *TransitionGraphReader) advancePath() bool { + for { + if tgr.length == 0 { + tgr.length = 1 + tgr.resetLevel() + } + for tgr.nextLeaf() { + if tgr.endSet[tgNodeID(tgr.stack[len(tgr.stack)-1].node)] { + return true + } + } + if !tgr.levelHadAnyPath { + return false // no trail this long exists => done + } + tgr.length++ + tgr.resetLevel() + } +} + +func (tgr *TransitionGraphReader) ensureStaged() { + if tgr.hasStaged || tgr.exhausted { + return + } + if !tgr.havePath { + if !tgr.advancePath() { + tgr.exhausted = true + return + } + tgr.havePath = true + tgr.varTot = tgr.varTot[:0] + tgr.varIdx = tgr.varIdx[:0] + for i := range tgr.stack { + _, vt := nodeEmit(tgr.stack[i].node, 0) + if vt < 1 { + vt = 1 + } + tgr.varTot = append(tgr.varTot, vt) + tgr.varIdx = append(tgr.varIdx, 0) + } + } + tgr.staged = tgr.staged[:0] + for i := range tgr.stack { + b, _ := nodeEmit(tgr.stack[i].node, tgr.varIdx[i]) + tgr.staged = append(tgr.staged, b...) + } + tgr.hasStaged = true +} + +func (tgr *TransitionGraphReader) consumeStaged() { + tgr.hasStaged = false + i := len(tgr.varIdx) - 1 + for i >= 0 { + tgr.varIdx[i]++ + if tgr.varIdx[i] < tgr.varTot[i] { + break + } + tgr.varIdx[i] = 0 + i-- + } + if i < 0 { + tgr.havePath = false // variations exhausted -> move to next trail + } +} + +// Next reports whether another covering string is available. +func (tgr *TransitionGraphReader) Next() bool { + tgr.prepare() + if tgr.mode == CoverageCompact { + tgr.buildCompact() + return tgr.prodIdx < len(tgr.prods) + } + tgr.ensureStaged() + return tgr.hasStaged +} + +// Scan returns the next covering string, or nil once coverage is complete. +func (tgr *TransitionGraphReader) Scan() []byte { + tgr.prepare() + if tgr.mode == CoverageCompact { + tgr.buildCompact() + if tgr.prodIdx >= len(tgr.prods) { + return nil + } + out := tgr.prods[tgr.prodIdx] + tgr.prodIdx++ + return out + } + tgr.ensureStaged() + if !tgr.hasStaged { + return nil + } + out := make([]byte, len(tgr.staged)) + copy(out, tgr.staged) + tgr.consumeStaged() + return out +} + +// buildCompact precomputes the CoverageCompact output: a bounded set of strings +// that together visit every reachable vertex, traverse every edge, and emit every +// terminal value (each charval casing, each numval range value) at least once. +// It is greedy, not minimal, but its size is bounded by roughly +// (#edges + #vertices + sum of per-node variation counts). +func (tgr *TransitionGraphReader) buildCompact() { + if tgr.builtCompact { + return + } + tgr.builtCompact = true + + viable := func(n *Node) []*Node { + if n == emptyNode { + return nil + } + var out []*Node + for _, sc := range n.Nexts { + if producing(sc) && tgr.canReach[tgNodeID(sc)] { + out = append(out, sc) + } + } + return out + } + + // Forward BFS from entrypoints: coverable vertices, edges, and entry->node + // shortest-path predecessors. + predEntry := map[string]*Node{} + nodeByID := map[string]*Node{} + discOrder := map[string]int{} // stable BFS discovery index per node + var disc []*Node // nodes in discovery order + type edge struct{ u, w *Node } + var allEdges []edge + seenEdge := map[string]bool{} + var queue []*Node + see := func(n *Node) { + id := tgNodeID(n) + if _, ok := predEntry[id]; ok { + return + } + predEntry[id] = n + nodeByID[id] = n + discOrder[id] = len(disc) + disc = append(disc, n) + queue = append(queue, n) + } + for _, e := range tgr.entries { + see(e) + } + for len(queue) > 0 { + n := queue[0] + queue = queue[1:] + for _, sc := range viable(n) { + sid := tgNodeID(sc) + ek := tgNodeID(n) + ">" + sid + if !seenEdge[ek] { + seenEdge[ek] = true + allEdges = append(allEdges, edge{n, sc}) + } + if _, ok := predEntry[sid]; !ok { + predEntry[sid] = n + nodeByID[sid] = sc + discOrder[sid] = len(disc) + disc = append(disc, sc) + queue = append(queue, sc) + } + } + } + + // Backward BFS from endpoints: node->endpoint shortest-path successors. + // Node IDs are random UUIDs, so we order everything by stable BFS discovery + // index instead -- otherwise the chosen shortest paths (and thus the covering + // set) would vary between builds. + revAdj := map[string][]*Node{} + for _, n := range disc { + for _, sc := range viable(n) { + sid := tgNodeID(sc) + revAdj[sid] = append(revAdj[sid], n) + } + } + succEnd := map[string]*Node{} + var q2 []*Node + for _, n := range disc { + if tgr.endSet[tgNodeID(n)] { + succEnd[tgNodeID(n)] = n + q2 = append(q2, n) + } + } + for len(q2) > 0 { + n := q2[0] + q2 = q2[1:] + for _, p := range revAdj[tgNodeID(n)] { + pid := tgNodeID(p) + if _, ok := succEnd[pid]; !ok { + succEnd[pid] = n + q2 = append(q2, p) + } + } + } + + entryPath := func(u *Node) []*Node { + var rev []*Node + cur := u + for { + rev = append(rev, cur) + id := tgNodeID(cur) + p := predEntry[id] + if tgNodeID(p) == id { + break + } + cur = p + } + for i, j := 0, len(rev)-1; i < j; i, j = i+1, j-1 { + rev[i], rev[j] = rev[j], rev[i] + } + return rev + } + endPath := func(w *Node) []*Node { + var out []*Node + cur := w + for { + out = append(out, cur) + id := tgNodeID(cur) + sc := succEnd[id] + if tgNodeID(sc) == id { + break + } + cur = sc + } + return out + } + + coveredV := map[string]bool{} + coveredE := map[string]bool{} + // nextVal[id] is the smallest variation index of a node not yet emitted. + // Values are always taken in increasing order, so a forward cursor per node + // makes value coverage O(total values) instead of O(sum of width^2). + nextVal := map[string]int32{} + + markWalk := func(w []*Node) { + for i, n := range w { + coveredV[tgNodeID(n)] = true + if i+1 < len(w) { + coveredE[tgNodeID(n)+">"+tgNodeID(w[i+1])] = true + } + } + } + emit := func(w []*Node, force bool) bool { + va := make([]int32, len(w)) + claimed := map[string]int32{} // fresh values taken for each node in THIS emit + newCount := 0 + for p, n := range w { + id := tgNodeID(n) + _, vt := nodeEmit(n, 0) + if vt < 1 { + vt = 1 + } + claim := nextVal[id] + claimed[id] + if claim < vt { + va[p] = claim + claimed[id]++ + newCount++ + } else { + va[p] = 0 // all of this node's values already covered; reuse 0 + } + } + if !force && newCount == 0 { + return false + } + for id, c := range claimed { + nextVal[id] += c + } + var bs []byte + for p, n := range w { + b, _ := nodeEmit(n, va[p]) + bs = append(bs, b...) + } + tgr.prods = append(tgr.prods, bs) + return true + } + + var walks [][]*Node + + sort.SliceStable(allEdges, func(i, j int) bool { + ui, uj := discOrder[tgNodeID(allEdges[i].u)], discOrder[tgNodeID(allEdges[j].u)] + if ui != uj { + return ui < uj + } + return discOrder[tgNodeID(allEdges[i].w)] < discOrder[tgNodeID(allEdges[j].w)] + }) + for _, e := range allEdges { + ek := tgNodeID(e.u) + ">" + tgNodeID(e.w) + if coveredE[ek] { + continue + } + if _, ok := succEnd[tgNodeID(e.w)]; !ok { + continue + } + w := append(entryPath(e.u), endPath(e.w)...) + walks = append(walks, w) + emit(w, true) + markWalk(w) + } + + for _, v := range disc { + id := tgNodeID(v) + if coveredV[id] { + continue + } + if _, ok := succEnd[id]; !ok { + continue + } + var w []*Node + if tgr.endSet[id] { + w = entryPath(v) + } else { + ep := endPath(v) + w = append(entryPath(v), ep[1:]...) + } + walks = append(walks, w) + emit(w, true) + markWalk(w) + } + + for _, w := range walks { + for emit(w, false) { + } + } +} + +// nodeEmit returns the bytes a node emits for variation index tpos, and the +// node's total number of variations. For a non-sensitive char-val the variations +// are the 2^k casings of its k cased letters; for a num-val range, one byte per +// value in the range. +func nodeEmit(node *Node, tpos int32) (prod []byte, vtotal int32) { + if node == emptyNode { + return nil, 1 + } + switch v := node.Elem.(type) { + case ElemCharVal: + if v.Sensitive { + for _, val := range v.Values { + prod = append(prod, string(val)...) + } + return prod, 1 + } + var numVar int + for _, r := range v.Values { + if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') { + numVar++ + } + } + // 2^numVar casings; cap to avoid int32 overflow on pathologically long + // case-insensitive literals (2^31 casings is unenumerable anyway). Letters + // beyond the cap are emitted lower-case only. + // XXX This is an arbitrary bound + if numVar > 30 { + numVar = 30 + } + vtotal = int32(1) << uint(numVar) + bit := uint(0) + for _, r := range v.Values { + isLower := r >= 'a' && r <= 'z' + isUpper := r >= 'A' && r <= 'Z' + if !isLower && !isUpper { + prod = append(prod, string(r)...) + continue + } + lower := r + if isUpper { + lower = lower - 'A' + 'a' + } + upper := r + if isLower { + upper = upper - 'a' + 'A' + } + if (tpos>>bit)&1 == 1 { + prod = append(prod, string(upper)...) + } else { + prod = append(prod, string(lower)...) + } + bit++ + } + return prod, vtotal + + case ElemNumVal: + switch v.Status { + case StatSeries: + for _, elem := range v.Elems { + r := numvalToRune(elem, v.Base) + prod = append(prod, []byte(string(r))...) + } + return prod, 1 + case StatRange: + min, max := numvalToInt32(v.Elems[0], v.Base), numvalToInt32(v.Elems[1], v.Base) + // The graph operates over runes; clamp to the Unicode range so an + // out-of-range bound cannot overflow the int32 count below. + if max > utf8.MaxRune { + max = utf8.MaxRune + } + if min > utf8.MaxRune || min > max { + return nil, 1 // no representable character in this range + } + r := rune(min + tpos) + return []byte(string(r)), max - min + 1 + } + } + return nil, 1 +} + +type tgmachine struct { + options *tgoptions + grammar *Grammar + buf map[string][2][]*Node + + nodeCount int // nodes reserved so far, checked against options.maxNodes +} + +func (m *tgmachine) altGraph(alt Alternation) (entrypoints []*Node, endpoints []*Node, err error) { + for _, concat := range alt.Concatenations { + ci, co, err := m.concatGraph(concat) + if err != nil { + return nil, nil, err + } + + // Group concatenation inputs, but avoid duplicating the emptyNode + entryHasEmpty := slices.Contains(entrypoints, emptyNode) + for _, vci := range ci { + if vci == emptyNode && entryHasEmpty { + continue + } + entrypoints = append(entrypoints, vci) + } + + // Group concatenation outputs, but avoid duplicating the emptyNode + endHasEmpty := slices.Contains(endpoints, emptyNode) + for _, vco := range co { + if vco == emptyNode && endHasEmpty { + continue + } + endpoints = append(endpoints, vco) + } + } + return +} + +func (m *tgmachine) concatGraph(concat Concatenation) (entrypoints []*Node, endpoints []*Node, err error) { + ci, co, err := m.repGraph(concat.Repetitions[0]) + if err != nil { + return nil, nil, err + } + for i := 1; i < len(concat.Repetitions); i++ { + repi, repo, err := m.repGraph(concat.Repetitions[i]) + if err != nil { + return nil, nil, err + } + ci, co = concatTransitionGraphs(ci, co, repi, repo) + } + return ci, co, nil +} + +func concatTransitionGraphs(prevI, prevO, currI, currO []*Node) (entrypoints []*Node, endpoints []*Node) { + // If prevI contains the emptyNode it means currI (possibly with + // the emptyNode) is also part of the entrypoints (without prevI's + // emptyNode). + if slices.Contains(prevI, emptyNode) { + for _, vprevI := range prevI { + if vprevI == emptyNode { + continue + } + entrypoints = append(entrypoints, vprevI) + } + entrypoints = append(entrypoints, currI...) + } else { + entrypoints = prevI + } + + // plug previous outputs (prevO) to current inputs (currI). + for _, vprevO := range prevO { + if vprevO == emptyNode { + continue + } + for _, vrepi := range currI { + if vrepi == emptyNode { + continue + } + vprevO.Nexts = append(vprevO.Nexts, vrepi) + } + } + + // new concatenation output is the previous ones if current + // inputs contains the emptyNode (repetition is skippable), + // and the current outputs ones. + if slices.Contains(currI, emptyNode) { + endpoints = append(endpoints, prevO...) + } + for _, vrepo := range currO { + if vrepo == emptyNode { + continue + } + endpoints = append(endpoints, vrepo) + } + + return +} + +func (m *tgmachine) repGraph(rep Repetition) (entrypoints []*Node, endpoints []*Node, err error) { + // element entry-/end-points (resp. I/O) + elemi, elemo, err := m.elemGraph(rep.Element) + if err != nil { + return nil, nil, err + } + + if rep.Min == 0 { + entrypoints = appendNodes(entrypoints, emptyNode) + endpoints = appendNodes(endpoints, emptyNode) + + switch rep.Max { + case 1: + // min = 0 & max = 1: optional v + entrypoints = appendNodes(entrypoints, elemi...) + endpoints = appendNodes(endpoints, elemo...) + case inf: + // min = 0 & max = inf: optional infinity + elemiNoEmpty := []*Node{} + for _, velemi := range elemi { + if velemi == emptyNode { + continue + } + elemiNoEmpty = appendNodes(elemiNoEmpty, velemi) + } + for _, velemo := range elemo { + if velemo == emptyNode { + continue + } + velemo.Nexts = appendNodes(velemo.Nexts, elemiNoEmpty...) + } + entrypoints = appendNodes(entrypoints, elemi...) + endpoints = appendNodes(endpoints, elemo...) + + default: + // min = 0 & 1 < max < inf: optional to n + if rep.Max > m.options.repetitionThreshold { + return nil, nil, ErrRepetitionThreshold + } + if err := m.reserveClones(rep.Max, elemi); err != nil { + return nil, nil, err + } + tgs, chi, _ := chainTransitionGraph(elemi, elemo, rep.Max) + entrypoints = appendNodes(entrypoints, chi...) + for _, tg := range tgs { + endpoints = appendNodes(endpoints, tg.Endpoints...) + } + } + } else { + switch rep.Max { + case 1: + // min == 1 & max == 1: mandatory + if rep.Min != 1 { + return nil, nil, ErrRepetitionMinNotOne + } + entrypoints = appendNodes(entrypoints, elemi...) + endpoints = appendNodes(endpoints, elemo...) + + case inf: + // min >= 1 && max = inf: n to infinity + if rep.Min > m.options.repetitionThreshold { + return nil, nil, ErrRepetitionThreshold + } + if err := m.reserveClones(rep.Min, elemi); err != nil { + return nil, nil, err + } + tgs, chi, cho := chainTransitionGraph(elemi, elemo, rep.Min) + entrypoints = appendNodes(entrypoints, chi...) + endpoints = appendNodes(endpoints, cho...) + + last := tgs[len(tgs)-1] + for _, vo := range last.Endpoints { + if vo == emptyNode { + continue + } + for _, etp := range last.Entrypoints { + // Make sure to not append the empty node as a next node, this is not possible + if etp == emptyNode { + continue + } + vo.Nexts = appendNodes(vo.Nexts, etp) + } + } + + default: + // min >= 1 && max < inf: n to m + if rep.Min > rep.Max { + return nil, nil, ErrRepetitionMinGtMax + } + if rep.Max > m.options.repetitionThreshold { + return nil, nil, ErrRepetitionThreshold + } + + // Build the flat chain (not endpoints, except last) + firstI, lastO := elemi, elemo + if rep.Min > 1 { + if err := m.reserveClones(rep.Min, elemi); err != nil { + return nil, nil, err + } + _, firstI, lastO = chainTransitionGraph(elemi, elemo, rep.Min) + } + entrypoints = appendNodes(entrypoints, firstI...) + endpoints = appendNodes(endpoints, lastO...) + + // Build remaining endpoints + remaining := rep.Max - rep.Min + if remaining > 0 { + if err := m.reserveClones(rep.Max-rep.Min, elemi); err != nil { + return nil, nil, err + } + tgs, chi, _ := chainTransitionGraph(elemi, elemo, rep.Max-rep.Min) + for _, tg := range tgs { + endpoints = appendNodes(endpoints, tg.Endpoints...) + } + for _, vlasto := range lastO { + if vlasto == emptyNode { + continue + } + for _, nchi := range chi { + if nchi == emptyNode { + continue + } + vlasto.Nexts = appendNodes(vlasto.Nexts, nchi) + } + } + } + } + } + + return +} + +func chainTransitionGraph(i, o []*Node, n int) (tgs []TransitionGraph, entrypoints []*Node, endpoints []*Node) { + // Make sure to not chain... nothing ¯\_(ツ)_/¯ + if n == 0 { + return + } + tgs = make([]TransitionGraph, n) + + // Init chaining + entrypoints, endpoints = cloneTransitionGraph(i, o) + tgs[0] = TransitionGraph{ + Entrypoints: entrypoints, + Endpoints: endpoints, + } + + // Gotta chain them all + for j := 1; j < n; j++ { + nextI, nextO := cloneTransitionGraph(i, o) + tgs[j] = TransitionGraph{ + Entrypoints: nextI, + Endpoints: nextO, + } + entrypoints, endpoints = concatTransitionGraphs(entrypoints, endpoints, nextI, nextO) + } + return +} + +func cloneTransitionGraph(i, o []*Node) (entrypoints []*Node, endpoints []*Node) { + // Traverse graph to map all cloned originToNewNodes by their origin IDs + originToNewNodes := map[string]cnode{} + for _, vi := range i { + if vi == emptyNode { + continue + } + cloneTG(originToNewNodes, vi) + } + + // Rebuild links + for _, cnode := range originToNewNodes { + nnxts := make([]*Node, 0, len(cnode.origin.Nexts)) + for _, onext := range cnode.origin.Nexts { + nnxts = append(nnxts, originToNewNodes[onext.ID].cloned) + } + cnode.cloned.Nexts = nnxts + } + + // Get cloned I/O + entrypoints = make([]*Node, 0, len(i)) + for _, vi := range i { + if vi == emptyNode { + entrypoints = append(entrypoints, emptyNode) + continue + } + entrypoints = append(entrypoints, originToNewNodes[vi.ID].cloned) + } + endpoints = make([]*Node, 0, len(o)) + for _, vo := range o { + if vo == emptyNode { + endpoints = append(endpoints, emptyNode) + continue + } + endpoints = append(endpoints, originToNewNodes[vo.ID].cloned) + } + return +} + +type cnode struct { + origin, cloned *Node +} + +func cloneTG(originToNewNodes map[string]cnode, origin *Node) { + id := newID() + + originToNewNodes[origin.ID] = cnode{ + origin: origin, + cloned: &Node{ + ID: id, + Elem: origin.Elem, + Nexts: nil, // will map it later, requires all origins to be cloned first + }, + } + + // recurse iff not known yet + for _, n := range origin.Nexts { + if _, ok := originToNewNodes[n.ID]; ok { + continue + } + cloneTG(originToNewNodes, n) + } +} + +func appendNodes(existing []*Node, news ...*Node) []*Node { + for _, n := range news { + if slices.Contains(existing, n) { + continue + } + existing = append(existing, n) + } + return existing +} + +func (m *tgmachine) elemGraph(elem ElemItf) (entrypoints []*Node, endpoints []*Node, err error) { + switch v := elem.(type) { + // Final elements => create the node, no need to pipe I/O + case ElemCharVal: + if len(v.Values) == 0 { + entrypoints = append(entrypoints, emptyNode) + endpoints = append(endpoints, emptyNode) + return + } + + if !m.options.deflateCharVals { + if err := m.reserve(1); err != nil { + return nil, nil, err + } + n := newNode(v) + entrypoints = append(entrypoints, n) + endpoints = append(endpoints, n) + return + } + + if err := m.reserve(2 * len(v.Values)); err != nil { + return nil, nil, err + } + + var prevs []*Node = nil + var curr []*Node = nil + for _, r := range v.Values { + isLower := r >= 'a' && r <= 'z' + isUpper := r >= 'A' && r <= 'Z' + requireBoth := (isLower || isUpper) && !v.Sensitive + + if !requireBoth { + n := newNode(ElemCharVal{ + Sensitive: true, + Values: []rune{r}, + }) + curr = []*Node{n} + + if prevs == nil { + entrypoints = append(entrypoints, n) + } + for _, v := range prevs { + v.Nexts = append(v.Nexts, curr...) + } + prevs = []*Node{n} + } else { + nlv := r + if isUpper { + nlv = runeMin(nlv) + } + nuv := r + if isLower { + nuv = runeMax(nuv) + } + + nl := newNode(ElemCharVal{ + Sensitive: true, + Values: []rune{nlv}, + }) + nu := newNode(ElemCharVal{ + Sensitive: true, + Values: []rune{nuv}, + }) + curr = []*Node{nl, nu} + + if prevs == nil { + entrypoints = append(entrypoints, nl, nu) + } + for _, v := range prevs { + v.Nexts = append(v.Nexts, curr...) + } + prevs = []*Node{nl, nu} + } + } + endpoints = append(endpoints, curr...) + return + + case ElemNumVal: + if !m.options.deflateNumVals { + if err := m.reserve(1); err != nil { + return nil, nil, err + } + n := newNode(v) + entrypoints = append(entrypoints, n) + endpoints = append(endpoints, n) + return + } + switch v.Status { + case StatRange: + min, max := numvalToInt32(v.Elems[0], v.Base), numvalToInt32(v.Elems[1], v.Base) + // One node is enumerated per rune; clamp to the Unicode range so an + // out-of-range bound cannot overflow the count (int32) and bypass the + // node budget, which would turn this loop into a DoS. A range wholly + // above U+10FFFF contributes no node (it matches nothing). + if max > utf8.MaxRune { + max = utf8.MaxRune + } + if min > utf8.MaxRune || min > max { + return + } + if err := m.reserve(int(max - min + 1)); err != nil { + return nil, nil, err + } + for i := min; i <= max; i++ { + n := newNode(ElemNumVal{ + Base: v.Base, + Status: StatSeries, + Elems: []string{int32ToNumval(i, v.Base)}, + }) + entrypoints = append(entrypoints, n) + endpoints = append(endpoints, n) + } + + case StatSeries: + if err := m.reserve(len(v.Elems)); err != nil { + return nil, nil, err + } + for _, s := range v.Elems { + n := newNode(ElemNumVal{ + Base: v.Base, + Status: StatSeries, + Elems: []string{s}, + }) + entrypoints = append(entrypoints, n) + endpoints = append(endpoints, n) + } + } + return + + // Recursive elements => pipe I/O + case ElemRulename: + if m.options.deflateRules { + name := strings.ToLower(v.Name) + if n, ok := m.buf[name]; ok { + if err := m.reserveClones(1, n[0]); err != nil { + return nil, nil, err + } + entrypoints, endpoints := cloneTransitionGraph(n[0], n[1]) + return entrypoints, endpoints, nil + } + rule := GetRule(v.Name, m.grammar.Rulemap) + if rule == nil { + return nil, nil, &ErrRuleNotFound{ + Rulename: v.Name, + } + } + i, o, err := m.altGraph(rule.Alternation) + if err != nil { + return nil, nil, err + } + if err := m.reserveClones(1, i); err != nil { + return nil, nil, err + } + ni, no := cloneTransitionGraph(i, o) + m.buf[name] = [2][]*Node{ni, no} + return i, o, nil + } + if err := m.reserve(1); err != nil { + return nil, nil, err + } + n := newNode(v) + entrypoints = append(entrypoints, n) + endpoints = append(endpoints, n) + return + + case ElemOption: + elemi, elemo, err := m.altGraph(v.Alternation) + if err != nil { + return nil, nil, err + } + elemi = appendNodes(elemi, emptyNode) + elemo = appendNodes(elemo, emptyNode) + return elemi, elemo, nil + + case ElemGroup: + return m.altGraph(v.Alternation) + case ElemProseVal: + return nil, nil, ErrProseValInTransitionGraph + } + + panic("unsupported element") +} + +// newID returns a random identifier for a graph node, the way containerd and +// containers/storage build container IDs: random bytes from crypto/rand, hex +// encoded. Node IDs only have to be unique within one graph, so 16 bytes are +// plenty. crypto/rand.Read never returns an error since Go 1.24. +func newID() string { + b := make([]byte, 16) + rand.Read(b) + return hex.EncodeToString(b) +} + +func newNode(elem ElemItf) *Node { + id := newID() + return &Node{ + ID: id, + Elem: elem, + // Final node, no need to pipe I/O + } +} + +// ToMermaid produces a mermaid-encoded representation of the transition graph. +func (tg *TransitionGraph) ToMermaid() string { + // Map all nodes + mp := map[string]*Node{} + for _, node := range tg.Entrypoints { + if node == emptyNode { + continue + } + mapNodes(mp, node) + } + + // Write them all + str := "flowchart LR\n classDef entrypoint fill:#479abf\n\n" + for _, node := range mp { + // Write down the node + nodeStr := " " + node.ID + elemStr := elemToString(node.Elem) + if slices.Contains(tg.Endpoints, node) { + nodeStr += "(((\"" + elemStr + "\")))" + } else { + nodeStr += "[\"" + elemStr + "\"]" + } + str += nodeStr + if slices.Contains(tg.Entrypoints, node) { + str += ":::entrypoint" + } + str += "\n" + + // Write down its links + for _, next := range node.Nexts { + str += fmt.Sprintf(" %s --> %s\n", node.ID, next.ID) + } + str += "\n" + } + + // Don't forget the empty node + if slices.Contains(tg.Entrypoints, emptyNode) { + str += " emptyNode(((\u2205))):::entrypoint\n" + } + + return str +} + +func mapNodes(mp map[string]*Node, node *Node) { + if _, ok := mp[node.ID]; ok { + return + } + mp[node.ID] = node + for _, next := range node.Nexts { + mapNodes(mp, next) + } +} + +func elemToString(elem ElemItf) string { + switch v := elem.(type) { + case ElemRulename: + return v.Name + case ElemCharVal: + str := "" + for _, b := range v.Values { + if b == '`' { + str += "backquote" + } else if b == '"' { + str += "dquote" + } else if 33 <= b && b <= 127 { + str += string(b) + } + } + return str + case ElemNumVal: + if v.Status == StatRange { + return fmt.Sprintf("0%s%s-%s", v.Base, v.Elems[0], v.Elems[1]) + } + return fmt.Sprintf("0%s%s", v.Base, strings.Join(v.Elems, ".")) + } + panic("not implemented yet") +} diff --git a/vendor/github.com/pandatix/go-abnf/utils.go b/vendor/github.com/pandatix/go-abnf/utils.go new file mode 100644 index 0000000..dcc9e6d --- /dev/null +++ b/vendor/github.com/pandatix/go-abnf/utils.go @@ -0,0 +1,152 @@ +package goabnf + +import ( + "math" + "strconv" + "strings" +) + +// int32ToNumval converts an integer value into its numeric-string representation +// in the given base. It is the inverse of numvalToInt32 and produces the form +// stored in an ElemNumVal's Elems (e.g. 97 in base "x" -> "61"). +func int32ToNumval(v int32, base string) string { + switch base { + case "B", "b": + return strconv.FormatInt(int64(v), 2) + case "D", "d": + return strconv.FormatInt(int64(v), 10) + case "X", "x": + return strings.ToUpper(strconv.FormatInt(int64(v), 16)) + } + return strconv.FormatInt(int64(v), 10) +} + +// baseRadix maps an ABNF num-val base marker (bin/dec/hex) to its integer radix. +func baseRadix(base string) int { + switch base { + case "B", "b": + return 2 + case "D", "d": + return 10 + case "X", "x": + return 16 + } + return 10 +} + +// numvalToUint64 parses a num-val literal in the given base into its numeric +// value. ok is false only when the literal does not fit in 64 bits (or is +// malformed), which lets callers degrade gracefully instead of overflowing +// silently. This is the single overflow-safe entry point every other conversion +// builds on. +// +// A num-val is a plain non-negative integer, not intrinsically a Unicode scalar: +// values beyond U+10FFFF are legitimate (e.g. for non-textual / on-wire +// grammars). Unicode is handled as the common case at match time; this layer is +// no longer Unicode-bounded. +func numvalToUint64(str, base string) (uint64, bool) { + v, err := strconv.ParseUint(str, baseRadix(base), 64) + if err != nil { + return 0, false + } + return v, true +} + +// numvalToInt32 converts a num-val into an int32 codepoint. It never panics: a +// value that does not fit a positive int32 is saturated to math.MaxInt32, which +// is above the maximum Unicode scalar (U+10FFFF) and therefore matches no decoded +// rune. A range bound that merely straddles the Unicode ceiling still covers its +// representable (Unicode) subset, because the saturated upper bound stays above +// every rune. +func numvalToInt32(str, base string) int32 { + v, ok := numvalToUint64(str, base) + if !ok || v > math.MaxInt32 { + return math.MaxInt32 + } + return int32(v) +} + +// numvalToRune converts a num-val into the corresponding rune. It never panics; +// a value beyond the Unicode range yields a rune that no UTF-8 input can produce, +// so callers matching against decoded runes simply find no match. Callers that +// require text validity (e.g. a num-val series, which must denote real +// characters) should additionally check utf8.ValidRune. +func numvalToRune(str, base string) rune { + return rune(numvalToInt32(str, base)) +} + +// checkBounds enforces the Unicode-range invariant (value <= U+10FFFF). It is +// the strict-validation path used by SemvalABNF: with validation enabled (the +// default, and the common textual case) a num-val outside the Unicode range is +// rejected. The conversion helpers above are deliberately broader -- a num-val is +// a plain integer and larger values are legitimate for non-textual grammars -- so +// without validation such values are accepted and handled (matched as no rune). +func checkBounds(str, base string) error { + str = strings.TrimLeft(str, "0") + switch base { + // Whatever the base, the higher value we arbitrary decide to support is + // the maximal Unicode character i.e. U+10FFFF. + // + // Every value (represented as integer) is then in interval [0;1_114_111]. + // For each base, we can compute the number of characters of an acceptable + // num-val as ceil(log(base,1_114_111)). + // + // We also have to ensure that it does not go over the boundaries even if + // of an acceptable length, e.g., 0xFFFFFF is not. + + case "B", "b": + // 21 = ceil(log(2, max_unicode)) + // U+10FFFF = Ob100001111111111111111 + if len(str) > 21 || + (len(str) == 21 && (str[1] != '0' || str[2] != '0' || str[3] != '0' || str[4] != '0')) { + return &ErrTooLargeNumeral{ + Base: base, + Value: str, + } + } + + case "D", "d": + // 7 = ceil(log(10, max_unicode)) + // U+10FFFF = 0d1114111 + if len(str) > 7 || + (len(str) == 7 && (str[0] > '1' || (str[0] == '1' && (str[1] > '1' || (str[1] == '1' && (str[2] > '1' || (str[2] == '1' && (str[3] > '4' || (str[3] == '4' && (str[4] > '1' || (str[4] == '1' && (str[5] > '1' || (str[5] == '1' && str[6] > '1'))))))))))))) { + return &ErrTooLargeNumeral{ + Base: base, + Value: str, + } + } + + case "X", "x": + // 6 = ceil(log(16, max_unicode)) + // U+10FFFF = 0x10FFFF + if len(str) > 6 || + (len(str) == 6 && (str[0] > '1' || (str[0] == '1' && (str[1] > '0')))) { + return &ErrTooLargeNumeral{ + Base: base, + Value: str, + } + } + } + + return nil +} + +// GetRule returns the rule by the given rulename, whether +// it is a core rule or present in the grammar, or nil if not found. +// It validates the RFC 5234 Section 2.1 "rule names are case insensitive". +func GetRule(rulename string, rulemap map[string]*Rule) *Rule { + // First look in the newly defined rules, as we could override definitions + if rule := getRuleIn(rulename, rulemap); rule != nil { + return rule + } + return getRuleIn(rulename, coreRules) +} + +func getRuleIn(rulename string, rulemap map[string]*Rule) *Rule { + for _, rule := range rulemap { + if strings.EqualFold(rulename, rule.Name) { + return rule + } + } + return nil +} diff --git a/vendor/github.com/pressly/goose/v3/.goreleaser.yaml b/vendor/github.com/pressly/goose/v3/.goreleaser.yaml index db8a84b..7da813e 100644 --- a/vendor/github.com/pressly/goose/v3/.goreleaser.yaml +++ b/vendor/github.com/pressly/goose/v3/.goreleaser.yaml @@ -35,3 +35,30 @@ snapshot: version_template: "{{ incpatch .Version }}-next" changelog: use: github-native +dockers_v2: + - images: + - ghcr.io/pressly/goose + dockerfile: goreleaser.Dockerfile + platforms: + - linux/amd64 + - linux/arm64 + # Prereleases only get the exact tag, for example v3.30.0-rc1. + tags: + - "{{ .Tag }}" + - "{{ if not .Prerelease }}v{{ .Major }}.{{ .Minor }}{{ end }}" + - "{{ if not .Prerelease }}v{{ .Major }}{{ end }}" + - "{{ if not .Prerelease }}latest{{ end }}" + labels: + org.opencontainers.image.title: goose + org.opencontainers.image.description: "Database migration tool" + org.opencontainers.image.source: https://github.com/pressly/goose + org.opencontainers.image.url: https://pressly.github.io/goose + org.opencontainers.image.licenses: MIT + org.opencontainers.image.version: "{{ .Tag }}" + org.opencontainers.image.revision: "{{ .FullCommit }}" + org.opencontainers.image.created: "{{ .Date }}" + # GHCR reads these from the image index of a multi-platform image. + annotations: + org.opencontainers.image.description: "Database migration tool" + org.opencontainers.image.source: https://github.com/pressly/goose + org.opencontainers.image.licenses: MIT diff --git a/vendor/github.com/pressly/goose/v3/CHANGELOG.md b/vendor/github.com/pressly/goose/v3/CHANGELOG.md index 315fe5a..2d4a868 100644 --- a/vendor/github.com/pressly/goose/v3/CHANGELOG.md +++ b/vendor/github.com/pressly/goose/v3/CHANGELOG.md @@ -7,6 +7,83 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] +## [v3.30.1] - 2026-11-12 + +### Changed + +- `+goose ENVSUB ON`: support more shell expansions, such as `${VAR:?message}`, `${VAR:+word}`, + and `${#VAR}`. A `$` that does not start a variable name, such as `$1`, is now kept as-is + instead of an error (#1174) + +### Fixed + +- Build failure when `github.com/mfridman/interpolate` is upgraded to v0.2.0, for example with + `go get -u` (#1176) +- Lock: fix an edge case where a long-lived locker could stop waiting for a held lock and fail + immediately. Programs that migrate once at startup were not affected (#1173) + +## [v3.30.0] - 2026-11-10 + +### Added + +- Container image at `ghcr.io/pressly/goose` for `linux/amd64` and `linux/arm64`, published on + each release. The image is based on distroless static, runs as a nonroot user, and supports + `.sql` migrations only (#1093) + +### Changed + +- Various dependency upgrades +- SQL parser: reduce memory use when parsing migration files, and make parsing much faster when + the race detector is on (#1155, #1156) + +### Fixed + +- CLI: `goose validate` failed on Go migrations that register an inlined function (#1110) +- Provider: SQL-only migrations with unpadded versions (`1_`, `2_`, `10_`) were sorted by + filename instead of version. This affected `ListSources` and `GetVersions`, as well as `Up` + when versioning was disabled (#1124) + +## [v3.29.0] - 2026-10-11 + +### Added + +- Support [environ credentials](https://github.com/ydb-platform/ydb-go-sdk-auth-environ#auth-environment-variables) + for YDB using connection string parameter `use_env_credentials`. + +### Changed + +- Various dependency upgrades + +## [v3.28.0] - 2026-09-02 + +### Added + +- CLI: `azuresql` driver for Azure SQL with Microsoft Entra ID (Azure AD) authentication via + `fedauth` connection string parameters, e.g. + `goose azuresql "sqlserver://host?database=mydb&fedauth=ActiveDirectoryDefault" status`. + Excluded when building with the `no_mssql` or `no_azuresql` tags (#1109) +- MySQL/MariaDB table-based `Locker` via `lock.NewMySQLTableLocker`, the MySQL counterpart to the + Postgres table locker from #993, accepting the same `TableLockerOption` set (#1075) + +### Changed + +- **Minimum Go version is now 1.26** +- ClickHouse: new `goose_db_version` tables are created with `ORDER BY (version_id)` instead of + `ORDER BY (date)`. Existing tables are unchanged (#1085) +- MySQL/TiDB: the `tstamp` column is now `DATETIME` instead of `TIMESTAMP`, which is capped at + 2038-01-19 (#1053). Only newly created tables are affected; existing tables can be updated with: + + ```sql + ALTER TABLE goose_db_version MODIFY tstamp datetime NULL DEFAULT CURRENT_TIMESTAMP; + ``` + +- Various dependency upgrades + +### Fixed + +- `goose create` returns a clear "file exists" error, including the path, instead of `%!w()` + when the migration file already exists (#1104) + ## [v3.27.3] - 2026-07-22 ### Changed @@ -325,7 +402,11 @@ Here's a quick summary: - Add new `context.Context`-aware functions and methods, for both sql and go migrations. - Return error when no migration files found or dir is not a directory. -[Unreleased]: https://github.com/pressly/goose/compare/v3.27.3...HEAD +[Unreleased]: https://github.com/pressly/goose/compare/v3.30.1...HEAD +[v3.30.1]: https://github.com/pressly/goose/compare/v3.30.0...v3.30.1 +[v3.30.0]: https://github.com/pressly/goose/compare/v3.29.0...v3.30.0 +[v3.29.0]: https://github.com/pressly/goose/compare/v3.28.0...v3.29.0 +[v3.28.0]: https://github.com/pressly/goose/compare/v3.27.3...v3.28.0 [v3.27.3]: https://github.com/pressly/goose/compare/v3.27.2...v3.27.3 [v3.27.2]: https://github.com/pressly/goose/compare/v3.27.1...v3.27.2 [v3.27.1]: https://github.com/pressly/goose/compare/v3.27.0...v3.27.1 diff --git a/vendor/github.com/pressly/goose/v3/Makefile b/vendor/github.com/pressly/goose/v3/Makefile index 99c429f..0f0e631 100644 --- a/vendor/github.com/pressly/goose/v3/Makefile +++ b/vendor/github.com/pressly/goose/v3/Makefile @@ -89,6 +89,10 @@ test-clickhouse: add-gowork go test $(GO_TEST_FLAGS) ./internal/testing/integration -run='(TestClickhouse|TestClickhouseRemote)' |\ tparse --follow -sort=elapsed +test-mysql-long: add-gowork test-mysql + go test $(GO_TEST_FLAGS) ./internal/testing/integration/locking -run='TestMySQL' |\ + tparse --follow -sort=elapsed + test-mysql: add-gowork go test $(GO_TEST_FLAGS) ./internal/testing/integration -run='TestMySQL' | tparse --follow -sort=elapsed diff --git a/vendor/github.com/pressly/goose/v3/README.md b/vendor/github.com/pressly/goose/v3/README.md index a022d8c..9ef845a 100644 --- a/vendor/github.com/pressly/goose/v3/README.md +++ b/vendor/github.com/pressly/goose/v3/README.md @@ -6,8 +6,6 @@ CI](https://github.com/pressly/goose/actions/workflows/ci.yaml/badge.svg)](https://github.com/pressly/goose/actions/workflows/ci.yaml) [![Go Reference](https://pkg.go.dev/badge/github.com/pressly/goose/v3.svg)](https://pkg.go.dev/github.com/pressly/goose/v3) -[![Go Report -Card](https://goreportcard.com/badge/github.com/pressly/goose/v3)](https://goreportcard.com/report/github.com/pressly/goose/v3) Goose is a database migration tool. Both a CLI and a library. @@ -39,8 +37,11 @@ Binary too big? Build a lite version by excluding the drivers you don't need: go build -tags='no_postgres no_mysql no_sqlite3 no_ydb' -o goose ./cmd/goose # Available build tags: -# no_clickhouse no_libsql no_mssql no_mysql -# no_postgres no_sqlite3 no_vertica no_ydb +# no_azuresql no_clickhouse no_libsql no_mssql +# no_mysql no_postgres no_sqlite3 no_vertica +# no_ydb +# +# Note: no_mssql also excludes the azuresql driver. ``` For macOS users `goose` is available as a [Homebrew @@ -50,6 +51,22 @@ Formulae](https://formulae.brew.sh/formula/goose#default): brew install goose ``` +A container image is available for `linux/amd64` and `linux/arm64`. It has no shell and supports `.sql` migrations only. The working directory is `/migrations`. + +```shell +docker run --rm \ + -v "$PWD/migrations:/migrations" \ + -e GOOSE_DRIVER=postgres \ + -e GOOSE_DBSTRING="postgres://user:password@host:5432/dbname" \ + ghcr.io/pressly/goose:latest up +``` + +Tags: `vX.Y.Z`, `vX.Y`, `vX`, and `latest`. To copy the binary into your own image: + +```dockerfile +COPY --from=ghcr.io/pressly/goose:v3.30.1 /usr/local/bin/goose /usr/local/bin/goose +``` + See [installation documentation](https://pressly.github.io/goose/installation/) for more details. # Usage @@ -75,6 +92,7 @@ Drivers: sqlite3 spanner mssql + azuresql redshift tidb clickhouse @@ -95,6 +113,7 @@ Examples: goose redshift "postgres://user:password@qwerty.us-east-1.redshift.amazonaws.com:5439/db" status goose tidb "user:password@/dbname?parseTime=true" status goose mssql "sqlserver://user:password@hostname:1433?database=master" status + goose azuresql "sqlserver://myserver.database.windows.net?database=mydb&fedauth=ActiveDirectoryDefault" status goose clickhouse "tcp://127.0.0.1:9000" status goose ydb "grpcs://localhost:2135/local?go_query_mode=scripting&go_fake_tx=scripting&go_query_bind=declare,numeric" status goose starrocks "user:password@/dbname?parseTime=true&interpolateParams=true" status @@ -114,6 +133,8 @@ Options: file path to root CA's certificates in pem format (only support on mysql) -dir string directory with migration files (default ".", can be set via the GOOSE_MIGRATION_DIR env variable). + -env string + load environment variables from file (default .env) -h print help -no-color disable color output (NO_COLOR env variable supported) @@ -143,12 +164,15 @@ Commands: status Dump the migration status for the current DB version Print the current version of the database create NAME [sql|go] Creates new migration file with the current timestamp + env Print the current Goose environment configuration fix Apply sequential ordering to migrations validate Check migration files without running them ```
+See [drivers](#drivers) for driver-specific details. + Commonly used commands: [create](#create) •  [up](#up) •  [up-to](#up-to) •  [down](#down) •  [down-to](#down-to) •  [status](#status) •  [version](#version) @@ -361,15 +385,18 @@ $$ LANGUAGE plpgsql;
Supported expansions (click here to expand): -- `${VAR}` or $VAR - expands to the value of the environment variable `VAR` -- `${VAR:-default}` - expands to the value of the environment variable `VAR`, or `default` if `VAR` - is unset or null -- `${VAR-default}` - expands to the value of the environment variable `VAR`, or `default` if `VAR` - is unset -- `${VAR?err_msg}` - expands to the value of the environment variable `VAR`, or prints `err_msg` and - error if `VAR` unset -- ~~`${VAR:?err_msg}` - expands to the value of the environment variable `VAR`, or prints `err_msg` - and error if `VAR` unset or null.~~ **THIS IS NOT SUPPORTED** +- `${VAR}` or `$VAR` - the value of `VAR`, or an empty string if `VAR` is unset +- `${VAR:-default}` - `default` if `VAR` is unset or empty +- `${VAR-default}` - `default` if `VAR` is unset +- `${VAR:?err_msg}` - an error with `err_msg` if `VAR` is unset or empty +- `${VAR?err_msg}` - an error with `err_msg` if `VAR` is unset +- `${VAR:+word}` - `word` if `VAR` is set and not empty, otherwise an empty string +- `${VAR+word}` - `word` if `VAR` is set, otherwise an empty string +- `${#VAR}` - the length of the value in characters +- `${VAR:offset}` or `${VAR:offset:length}` - a substring of the value + +Write `$$` or `\$` for a literal `$`. A `$` that does not start a variable name, such as `$1`, is +kept as-is. See [mfridman/interpolate](https://github.com/mfridman/interpolate?tab=readme-ov-file#supported-expansions) @@ -489,6 +516,15 @@ When you're ready to deploy your migrations in a production environment, we also ordering. We recommend running `fix` in the CI pipeline, and only when the migrations are ready for production. +# Drivers + +Some drivers have specific requirements or special behaviour. Make sure to read the documentation +for your database's driver before adopting and deploying Goose. + +* [ClickHouse](doc/dialect-clickhouse.md) only fully supports some clickhouse + deployment modes and requires careful configuration or work-arounds for + others. + ## Credit The gopher mascot was designed by [Renée French](https://reneefrench.blogspot.com/) / [CC diff --git a/vendor/github.com/pressly/goose/v3/create.go b/vendor/github.com/pressly/goose/v3/create.go index a26eae5..538632f 100644 --- a/vendor/github.com/pressly/goose/v3/create.go +++ b/vendor/github.com/pressly/goose/v3/create.go @@ -58,11 +58,7 @@ func CreateWithTemplate(db *sql.DB, dir string, tmpl *template.Template, name, m } path := filepath.Join(dir, filename) - if _, err := os.Stat(path); !os.IsNotExist(err) { - return fmt.Errorf("failed to create migration file: %w", err) - } - - f, err := os.Create(path) + f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o666) if err != nil { return fmt.Errorf("failed to create migration file: %w", err) } diff --git a/vendor/github.com/pressly/goose/v3/down.go b/vendor/github.com/pressly/goose/v3/down.go index 29e7daa..4b59fb0 100644 --- a/vendor/github.com/pressly/goose/v3/down.go +++ b/vendor/github.com/pressly/goose/v3/down.go @@ -4,6 +4,7 @@ import ( "context" "database/sql" "fmt" + "slices" ) // Down rolls back a single migration from the current version. @@ -92,13 +93,13 @@ func DownToContext(ctx context.Context, db *sql.DB, dir string, version int64, o // target version. func downToNoVersioning(ctx context.Context, db *sql.DB, migrations Migrations, version int64) error { var finalVersion int64 - for i := len(migrations) - 1; i >= 0; i-- { - if version >= migrations[i].Version { - finalVersion = migrations[i].Version + for _, migration := range slices.Backward(migrations) { + if version >= migration.Version { + finalVersion = migration.Version break } - migrations[i].noVersioning = true - if err := migrations[i].DownContext(ctx, db); err != nil { + migration.noVersioning = true + if err := migration.DownContext(ctx, db); err != nil { return err } } diff --git a/vendor/github.com/pressly/goose/v3/goreleaser.Dockerfile b/vendor/github.com/pressly/goose/v3/goreleaser.Dockerfile new file mode 100644 index 0000000..a2f8b7f --- /dev/null +++ b/vendor/github.com/pressly/goose/v3/goreleaser.Dockerfile @@ -0,0 +1,11 @@ +# This Dockerfile is used by GoReleaser (see dockers_v2 in .goreleaser.yaml). +# It copies the prebuilt goose binary, so it does not work with a plain +# `docker build .` from the repository root. +# +# The distroless static image has CA certificates, tzdata, and a nonroot user, +# but no shell. +FROM gcr.io/distroless/static-debian13:nonroot +ARG TARGETPLATFORM +COPY $TARGETPLATFORM/goose /usr/local/bin/goose +WORKDIR /migrations +ENTRYPOINT ["/usr/local/bin/goose"] diff --git a/vendor/github.com/pressly/goose/v3/internal/dialects/clickhouse.go b/vendor/github.com/pressly/goose/v3/internal/dialects/clickhouse.go index 7b676b9..7b62d68 100644 --- a/vendor/github.com/pressly/goose/v3/internal/dialects/clickhouse.go +++ b/vendor/github.com/pressly/goose/v3/internal/dialects/clickhouse.go @@ -23,7 +23,7 @@ func (c *clickhouse) CreateTable(tableName string) string { tstamp DateTime default now() ) ENGINE = MergeTree() - ORDER BY (date)` + ORDER BY (version_id)` return fmt.Sprintf(q, tableName) } diff --git a/vendor/github.com/pressly/goose/v3/internal/dialects/mysql.go b/vendor/github.com/pressly/goose/v3/internal/dialects/mysql.go index 9341589..4d1a2be 100644 --- a/vendor/github.com/pressly/goose/v3/internal/dialects/mysql.go +++ b/vendor/github.com/pressly/goose/v3/internal/dialects/mysql.go @@ -20,7 +20,7 @@ func (m *mysql) CreateTable(tableName string) string { id bigint(20) unsigned NOT NULL AUTO_INCREMENT, version_id bigint NOT NULL, is_applied boolean NOT NULL, - tstamp timestamp NULL default now(), + tstamp datetime NULL default CURRENT_TIMESTAMP, PRIMARY KEY(id) )` return fmt.Sprintf(q, tableName) diff --git a/vendor/github.com/pressly/goose/v3/internal/dialects/tidb.go b/vendor/github.com/pressly/goose/v3/internal/dialects/tidb.go index f5b58f2..9978424 100644 --- a/vendor/github.com/pressly/goose/v3/internal/dialects/tidb.go +++ b/vendor/github.com/pressly/goose/v3/internal/dialects/tidb.go @@ -20,7 +20,7 @@ func (t *Tidb) CreateTable(tableName string) string { id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT UNIQUE, version_id bigint NOT NULL, is_applied boolean NOT NULL, - tstamp timestamp NULL default now(), + tstamp datetime NULL default CURRENT_TIMESTAMP, PRIMARY KEY(id) )` return fmt.Sprintf(q, tableName) diff --git a/vendor/github.com/pressly/goose/v3/internal/sqlparser/parser.go b/vendor/github.com/pressly/goose/v3/internal/sqlparser/parser.go index 5afc07f..c24bae2 100644 --- a/vendor/github.com/pressly/goose/v3/internal/sqlparser/parser.go +++ b/vendor/github.com/pressly/goose/v3/internal/sqlparser/parser.go @@ -9,7 +9,6 @@ import ( "log" "os" "strings" - "sync" "github.com/mfridman/interpolate" ) @@ -81,14 +80,8 @@ func (s *stateMachine) print(msg string, args ...any) { } } -const scanBufSize = 4 * 1024 * 1024 - -var bufferPool = sync.Pool{ - New: func() any { - buf := make([]byte, scanBufSize) - return &buf - }, -} +// scanBufSize is the maximum length of a single line in a migration file. +const scanBufSize = 4 * 1024 * 1024 // 4 MiB // Split given SQL script into individual statements and return // SQL statements for given direction (up=true, down=false). @@ -101,12 +94,11 @@ var bufferPool = sync.Pool{ // 'StatementBegin' and 'StatementEnd' to allow the script to // tell us to ignore semicolons. func ParseSQLMigration(r io.Reader, direction Direction, debug bool) (stmts []string, useTx bool, err error) { - scanBufPtr := bufferPool.Get().(*[]byte) - scanBuf := *scanBufPtr - defer bufferPool.Put(scanBufPtr) - scanner := bufio.NewScanner(r) - scanner.Buffer(scanBuf, scanBufSize) + // A nil buffer makes the scanner allocate its default 4 KiB buffer and grow + // it, up to scanBufSize, only when a line needs it. Most migration files are + // a few KiB, so a large fixed buffer per call would be mostly wasted. + scanner.Buffer(nil, scanBufSize) stateMachine := newStateMachine(start, debug) useTx = true @@ -209,16 +201,15 @@ func ParseSQLMigration(r io.Reader, direction Direction, debug bool) (stmts []st // Do not include the "+goose StatementEnd" annotation in the final statement. default: if useEnvsub { - expanded, err := interpolate.Interpolate(&envWrapper{}, line) + expanded, err := interpolate.Expand(line, interpolate.LookupFunc(os.LookupEnv)) if err != nil { return nil, false, fmt.Errorf("variable substitution failed: %w:\n%s", err, line) } line = expanded } // Write SQL line to a buffer. - if _, err := buf.WriteString(line + "\n"); err != nil { - return nil, false, fmt.Errorf("failed to write to buf: %w", err) - } + buf.WriteString(line) + buf.WriteByte('\n') } // Read SQL body one by line, if we're in the right direction. // @@ -358,37 +349,22 @@ func missingSemicolonError(state parserState, direction Direction, s string) err ) } -type envWrapper struct{} - -var _ interpolate.Env = (*envWrapper)(nil) - -func (e *envWrapper) Get(key string) (string, bool) { - return os.LookupEnv(key) -} - func cleanupStatement(input string) string { return strings.TrimSpace(input) } // Checks the line to see if the line has a statement-ending semicolon // or if the line contains a double-dash comment. +// +// The line is split into words on Unicode whitespace, the same way +// bufio.ScanWords does, and the words before the first "--" are inspected. func endsWithSemicolon(line string) bool { - scanBufPtr := bufferPool.Get().(*[]byte) - scanBuf := *scanBufPtr - defer bufferPool.Put(scanBufPtr) - prev := "" - scanner := bufio.NewScanner(strings.NewReader(line)) - scanner.Buffer(scanBuf, scanBufSize) - scanner.Split(bufio.ScanWords) - - for scanner.Scan() { - word := scanner.Text() + for word := range strings.FieldsSeq(line) { if strings.HasPrefix(word, "--") { break } prev = word } - return strings.HasSuffix(prev, ";") } diff --git a/vendor/github.com/pressly/goose/v3/lock/internal/store/mysql.go b/vendor/github.com/pressly/goose/v3/lock/internal/store/mysql.go new file mode 100644 index 0000000..ad213e8 --- /dev/null +++ b/vendor/github.com/pressly/goose/v3/lock/internal/store/mysql.go @@ -0,0 +1,346 @@ +package store + +import ( + "context" + "database/sql" + "errors" + "fmt" + "strings" + "time" + + "go.uber.org/multierr" +) + +// NewMySQL creates a new MySQL-based [LockStore]. +func NewMySQL(tableName string) (LockStore, error) { + if tableName == "" { + return nil, errors.New("table name must not be empty") + } + return &mysqlStore{ + tableName: tableName, + }, nil +} + +var _ LockStore = (*mysqlStore)(nil) + +type mysqlStore struct { + tableName string +} + +func (s *mysqlStore) TableExists( + ctx context.Context, + db *sql.DB, +) (bool, error) { + schemaName, tableName := parseTableIdentifier(s.tableName) + + var query string + var args []any + if schemaName != "" { + query = `SELECT EXISTS ( SELECT 1 FROM information_schema.tables WHERE table_schema = ? AND table_name = ? )` + args = []any{schemaName, tableName} + } else { + query = `SELECT EXISTS ( SELECT 1 FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = ? )` + args = []any{tableName} + } + + var exists bool + if err := db.QueryRowContext(ctx, query, args...).Scan( + &exists, + ); err != nil { + return false, fmt.Errorf("table exists: %w", err) + } + return exists, nil +} + +func (s *mysqlStore) CreateLockTable( + ctx context.Context, + db *sql.DB, +) error { + exists, err := s.TableExists(ctx, db) + if err != nil { + return fmt.Errorf("check lock table existence: %w", err) + } + if exists { + return nil + } + + query := fmt.Sprintf(`CREATE TABLE %s ( + lock_id BIGINT NOT NULL PRIMARY KEY, + locked BOOLEAN NOT NULL DEFAULT 0, + locked_at DATETIME(6) NULL, + locked_by TEXT NULL, + lease_expires_at DATETIME(6) NULL, + updated_at DATETIME(6) NULL + )`, s.tableName) + if _, err := db.ExecContext(ctx, query); err != nil { + // Double-check if another process created it concurrently + if exists, checkErr := s.TableExists(ctx, db); checkErr == nil && exists { + // Another process created it, that's fine! + return nil + } + return fmt.Errorf("create lock table %q: %w", s.tableName, err) + } + return nil +} + +func (s *mysqlStore) AcquireLock( + ctx context.Context, + db *sql.DB, + lockID int64, + lockedBy string, + leaseDuration time.Duration, +) (_ *AcquireLockResult, retErr error) { + leaseSeconds := int(leaseDuration.Seconds()) + + tx, err := db.BeginTx(ctx, nil) + if err != nil { + return nil, fmt.Errorf("acquire lock %d: begin tx: %w", lockID, err) + } + defer func() { + if retErr != nil { + retErr = multierr.Append(retErr, tx.Rollback()) + } + }() + + // First, try to insert a brand-new row. If a row already exists for this lock_id, + // INSERT IGNORE silently no-ops (RowsAffected == 0) and we fall through to the UPDATE. + insertQ := fmt.Sprintf(`INSERT IGNORE INTO %s (lock_id, locked, locked_at, locked_by, lease_expires_at, updated_at) + VALUES (?, true, now(6), ?, now(6) + INTERVAL ? SECOND, now(6))`, s.tableName) + insertRes, err := tx.ExecContext(ctx, insertQ, lockID, lockedBy, leaseSeconds) + if err != nil { + return nil, fmt.Errorf("acquire lock %d: %w", lockID, err) + } + inserted, err := insertRes.RowsAffected() + if err != nil { + return nil, fmt.Errorf("acquire lock %d: rows affected: %w", lockID, err) + } + + if inserted == 0 { + // Row exists: only steal if currently unlocked or lease has expired. + updateQ := fmt.Sprintf(`UPDATE %s SET + locked = true, + locked_at = now(6), + locked_by = ?, + lease_expires_at = now(6) + INTERVAL ? SECOND, + updated_at = now(6) + WHERE lock_id = ? AND (locked = false OR lease_expires_at < now(6))`, s.tableName) + updateRes, err := tx.ExecContext(ctx, updateQ, lockedBy, leaseSeconds, lockID) + if err != nil { + return nil, fmt.Errorf("acquire lock %d: %w", lockID, err) + } + affected, err := updateRes.RowsAffected() + if err != nil { + return nil, fmt.Errorf("acquire lock %d: rows affected: %w", lockID, err) + } + if affected == 0 { + // TODO(mf): should we return a special error type here? + return nil, fmt.Errorf("acquire lock %d: already held by another instance", lockID) + } + } + + // MySQL has no RETURNING clause; read the row back to learn the resulting lease. + selectQ := fmt.Sprintf(`SELECT locked_by, lease_expires_at FROM %s WHERE lock_id = ?`, s.tableName) + var returnedLockedBy string + var leaseExpiresAt time.Time + if err := tx.QueryRowContext(ctx, selectQ, lockID).Scan( + &returnedLockedBy, + &leaseExpiresAt, + ); err != nil { + return nil, fmt.Errorf("acquire lock %d: %w", lockID, err) + } + + if err := tx.Commit(); err != nil { + return nil, fmt.Errorf("acquire lock %d: commit: %w", lockID, err) + } + + // Verify we got the lock by checking the returned locked_by matches our instance ID + if returnedLockedBy != lockedBy { + return nil, fmt.Errorf("acquire lock %d: acquired by %s instead of %s", lockID, returnedLockedBy, lockedBy) + } + + return &AcquireLockResult{ + LockedBy: returnedLockedBy, + LeaseExpiresAt: leaseExpiresAt, + }, nil +} + +func (s *mysqlStore) ReleaseLock( + ctx context.Context, + db *sql.DB, + lockID int64, + lockedBy string, +) (_ *ReleaseLockResult, retErr error) { + tx, err := db.BeginTx(ctx, nil) + if err != nil { + return nil, fmt.Errorf("release lock %d: begin tx: %w", lockID, err) + } + defer func() { + if retErr != nil { + retErr = multierr.Append(retErr, tx.Rollback()) + } + }() + + // Release lock only if it's held by the current instance + updateQ := fmt.Sprintf(`UPDATE %s SET + locked = false, + locked_at = NULL, + locked_by = NULL, + lease_expires_at = NULL, + updated_at = now(6) + WHERE lock_id = ? AND locked_by = ?`, s.tableName) + res, err := tx.ExecContext(ctx, updateQ, lockID, lockedBy) + if err != nil { + return nil, fmt.Errorf("release lock %d: %w", lockID, err) + } + affected, err := res.RowsAffected() + if err != nil { + return nil, fmt.Errorf("release lock %d: rows affected: %w", lockID, err) + } + if affected == 0 { + // TODO(mf): should we return a special error type here? + return nil, fmt.Errorf("release lock %d: not held by this instance", lockID) + } + + if err := tx.Commit(); err != nil { + return nil, fmt.Errorf("release lock %d: commit: %w", lockID, err) + } + + return &ReleaseLockResult{ + LockID: lockID, + }, nil +} + +func (s *mysqlStore) UpdateLease( + ctx context.Context, + db *sql.DB, + lockID int64, + lockedBy string, + leaseDuration time.Duration, +) (_ *UpdateLeaseResult, retErr error) { + leaseSeconds := int(leaseDuration.Seconds()) + + tx, err := db.BeginTx(ctx, nil) + if err != nil { + return nil, fmt.Errorf("failed to update lease for lock %d: begin tx: %w", lockID, err) + } + defer func() { + if retErr != nil { + retErr = multierr.Append(retErr, tx.Rollback()) + } + }() + + // Update lease expiration time for heartbeat, only if we own the lock + updateQ := fmt.Sprintf(`UPDATE %s SET + lease_expires_at = now(6) + INTERVAL ? SECOND, + updated_at = now(6) + WHERE lock_id = ? AND locked_by = ? AND locked = true`, s.tableName) + res, err := tx.ExecContext(ctx, updateQ, leaseSeconds, lockID, lockedBy) + if err != nil { + return nil, fmt.Errorf("failed to update lease for lock %d: %w", lockID, err) + } + affected, err := res.RowsAffected() + if err != nil { + return nil, fmt.Errorf("failed to update lease for lock %d: rows affected: %w", lockID, err) + } + if affected == 0 { + return nil, fmt.Errorf("failed to update lease for lock %d: not held by this instance", lockID) + } + + selectQ := fmt.Sprintf(`SELECT lease_expires_at FROM %s WHERE lock_id = ?`, s.tableName) + var leaseExpiresAt time.Time + if err := tx.QueryRowContext(ctx, selectQ, lockID).Scan(&leaseExpiresAt); err != nil { + return nil, fmt.Errorf("failed to update lease for lock %d: %w", lockID, err) + } + + if err := tx.Commit(); err != nil { + return nil, fmt.Errorf("failed to update lease for lock %d: commit: %w", lockID, err) + } + + return &UpdateLeaseResult{ + LeaseExpiresAt: leaseExpiresAt, + }, nil +} + +func (s *mysqlStore) CheckLockStatus( + ctx context.Context, + db *sql.DB, + lockID int64, +) (*LockStatus, error) { + query := fmt.Sprintf(`SELECT locked, locked_by, lease_expires_at, updated_at FROM %s WHERE lock_id = ?`, s.tableName) + var status LockStatus + + err := db.QueryRowContext(ctx, query, + lockID, + ).Scan( + &status.Locked, + &status.LockedBy, + &status.LeaseExpiresAt, + &status.UpdatedAt, + ) + if err != nil { + if errors.Is(err, sql.ErrNoRows) { + return nil, fmt.Errorf("lock %d not found", lockID) + } + return nil, fmt.Errorf("check lock status for %d: %w", lockID, err) + } + + return &status, nil +} + +func (s *mysqlStore) CleanupStaleLocks(ctx context.Context, db *sql.DB) (_ []int64, retErr error) { + tx, err := db.BeginTx(ctx, nil) + if err != nil { + return nil, fmt.Errorf("cleanup stale locks: begin tx: %w", err) + } + defer func() { + if retErr != nil { + retErr = multierr.Append(retErr, tx.Rollback()) + } + }() + + // MySQL has no RETURNING on UPDATE; lock rows for update, collect their IDs, then clear them. + selectQ := fmt.Sprintf(`SELECT lock_id FROM %s WHERE locked = true AND lease_expires_at < now(6) FOR UPDATE`, s.tableName) + rows, err := tx.QueryContext(ctx, selectQ) + if err != nil { + return nil, fmt.Errorf("cleanup stale locks: %w", err) + } + var cleanedLocks []int64 + for rows.Next() { + var lockID int64 + if err := rows.Scan(&lockID); err != nil { + return nil, multierr.Append(fmt.Errorf("scan cleaned lock ID: %w", err), rows.Close()) + } + cleanedLocks = append(cleanedLocks, lockID) + } + if err := rows.Err(); err != nil { + retErr = multierr.Append(retErr, rows.Close()) + return nil, fmt.Errorf("iterate over cleaned locks: %w", err) + } + if err := rows.Close(); err != nil { + return nil, fmt.Errorf("close cleaned locks rows: %w", err) + } + + if len(cleanedLocks) > 0 { + placeholders := strings.TrimSuffix(strings.Repeat("?,", len(cleanedLocks)), ",") + updateQ := fmt.Sprintf(`UPDATE %s SET + locked = false, + locked_at = NULL, + locked_by = NULL, + lease_expires_at = NULL, + updated_at = now(6) + WHERE lock_id IN (%s)`, s.tableName, placeholders) + args := make([]any, len(cleanedLocks)) + for i, id := range cleanedLocks { + args[i] = id + } + if _, err := tx.ExecContext(ctx, updateQ, args...); err != nil { + return nil, fmt.Errorf("cleanup stale locks: %w", err) + } + } + + if err := tx.Commit(); err != nil { + return nil, fmt.Errorf("cleanup stale locks: commit: %w", err) + } + + return cleanedLocks, nil +} diff --git a/vendor/github.com/pressly/goose/v3/lock/internal/table/config.go b/vendor/github.com/pressly/goose/v3/lock/internal/table/config.go index bde5b51..254b523 100644 --- a/vendor/github.com/pressly/goose/v3/lock/internal/table/config.go +++ b/vendor/github.com/pressly/goose/v3/lock/internal/table/config.go @@ -3,6 +3,8 @@ package table import ( "log/slog" "time" + + "github.com/sethvargo/go-retry" ) // Config holds configuration for table locker. @@ -26,3 +28,17 @@ type ProbeConfig struct { IntervalDuration time.Duration FailureThreshold uint64 } + +// backoff returns a new backoff for one Lock or Unlock call. The backoff counts the retries it has +// used and never resets, so each call must get its own. +func (p ProbeConfig) backoff() retry.Backoff { + // retry.NewConstant is not used here, because it panics on an interval that is not positive. + constant := retry.BackoffFunc(func() (time.Duration, bool) { + return p.IntervalDuration, false + }) + return retry.WithMaxRetries( + p.FailureThreshold, + // Add +/- 25% jitter to reduce thundering herd + retry.WithJitterPercent(25, constant), + ) +} diff --git a/vendor/github.com/pressly/goose/v3/lock/internal/table/locker.go b/vendor/github.com/pressly/goose/v3/lock/internal/table/locker.go index 2f16256..f897c81 100644 --- a/vendor/github.com/pressly/goose/v3/lock/internal/table/locker.go +++ b/vendor/github.com/pressly/goose/v3/lock/internal/table/locker.go @@ -29,8 +29,8 @@ type Locker struct { instanceID string leaseDuration time.Duration heartbeatInterval time.Duration - retryLock retry.Backoff - retryUnlock retry.Backoff + lockTimeout ProbeConfig + unlockTimeout ProbeConfig logger *slog.Logger retryPolicy RetryPolicyFunc @@ -63,16 +63,8 @@ func New(lockStore store.LockStore, cfg Config) *Locker { heartbeatInterval: cfg.HeartbeatInterval, logger: logger, retryPolicy: cfg.RetryPolicy, - retryLock: retry.WithMaxRetries( - cfg.LockTimeout.FailureThreshold, - // Add +/- 25% jitter to reduce thundering herd - retry.WithJitterPercent(25, retry.NewConstant(cfg.LockTimeout.IntervalDuration)), - ), - retryUnlock: retry.WithMaxRetries( - cfg.UnlockTimeout.FailureThreshold, - // Add +/- 25% jitter to reduce thundering herd - retry.WithJitterPercent(25, retry.NewConstant(cfg.UnlockTimeout.IntervalDuration)), - ), + lockTimeout: cfg.LockTimeout, + unlockTimeout: cfg.UnlockTimeout, } } @@ -89,7 +81,7 @@ func (l *Locker) Lock(ctx context.Context, db *sql.DB) error { return fmt.Errorf("ensure lock table exists: %w", err) } - err := retry.Do(ctx, l.retryLock, func(ctx context.Context) error { + err := retry.Do(ctx, l.lockTimeout.backoff(), func(ctx context.Context) error { _, err := l.store.AcquireLock(ctx, db, l.lockID, l.instanceID, l.leaseDuration) if err != nil { // Clean up any stale locks before retrying @@ -143,7 +135,7 @@ func (l *Locker) Unlock(ctx context.Context, db *sql.DB) error { // Stop heartbeat first l.stopHeartbeat() - err := retry.Do(ctx, l.retryUnlock, func(ctx context.Context) error { + err := retry.Do(ctx, l.unlockTimeout.backoff(), func(ctx context.Context) error { _, err := l.store.ReleaseLock(ctx, db, l.lockID, l.instanceID) if err != nil { if l.shouldRetry(err) { diff --git a/vendor/github.com/pressly/goose/v3/lock/mysql.go b/vendor/github.com/pressly/goose/v3/lock/mysql.go new file mode 100644 index 0000000..731e1e9 --- /dev/null +++ b/vendor/github.com/pressly/goose/v3/lock/mysql.go @@ -0,0 +1,54 @@ +package lock + +import ( + "fmt" + "time" + + "github.com/pressly/goose/v3/lock/internal/store" + "github.com/pressly/goose/v3/lock/internal/table" +) + +// NewMySQLTableLocker returns a Locker that uses MySQL table-based locking. It manages a single +// lock row and keeps the lock alive automatically. +// +// Default behavior: +// +// - Lease (30s): How long the lock is valid if heartbeat stops +// - Heartbeat (5s): How often the lock gets refreshed to keep it alive +// - If the process dies, others can take the lock after lease expires +// +// Defaults: +// +// Table: "goose_lock" +// Lock ID: 4097083626 (crc32 of "goose") +// Lock retry: 5s intervals, 5min timeout +// Unlock retry: 2s intervals, 1min timeout +// +// Lock and Unlock both retry on failure. Lock stays alive automatically until released. All +// defaults can be overridden with options. +func NewMySQLTableLocker(options ...TableLockerOption) (Locker, error) { + config := table.Config{ + TableName: DefaultLockTableName, + LockID: DefaultLockID, + LeaseDuration: 30 * time.Second, + HeartbeatInterval: 5 * time.Second, + LockTimeout: table.ProbeConfig{ + IntervalDuration: 5 * time.Second, + FailureThreshold: 60, // 5 minutes total + }, + UnlockTimeout: table.ProbeConfig{ + IntervalDuration: 2 * time.Second, + FailureThreshold: 30, // 1 minute total + }, + } + for _, opt := range options { + if err := opt.apply(&config); err != nil { + return nil, err + } + } + lockStore, err := store.NewMySQL(config.TableName) + if err != nil { + return nil, fmt.Errorf("create lock store: %w", err) + } + return table.New(lockStore, config), nil +} diff --git a/vendor/github.com/pressly/goose/v3/lock/postgres.go b/vendor/github.com/pressly/goose/v3/lock/postgres.go index 830d598..68adec1 100644 --- a/vendor/github.com/pressly/goose/v3/lock/postgres.go +++ b/vendor/github.com/pressly/goose/v3/lock/postgres.go @@ -86,28 +86,22 @@ func NewPostgresSessionLocker(opts ...SessionLockerOption) (SessionLocker, error } } return &postgresSessionLocker{ - lockID: cfg.lockID, - retryLock: retry.WithMaxRetries( - cfg.lockProbe.failureThreshold, - retry.NewConstant(cfg.lockProbe.intervalDuration), - ), - retryUnlock: retry.WithMaxRetries( - cfg.unlockProbe.failureThreshold, - retry.NewConstant(cfg.unlockProbe.intervalDuration), - ), + lockID: cfg.lockID, + lockProbe: cfg.lockProbe, + unlockProbe: cfg.unlockProbe, }, nil } type postgresSessionLocker struct { lockID int64 - retryLock retry.Backoff - retryUnlock retry.Backoff + lockProbe probe + unlockProbe probe } var _ SessionLocker = (*postgresSessionLocker)(nil) func (l *postgresSessionLocker) SessionLock(ctx context.Context, conn *sql.Conn) error { - return retry.Do(ctx, l.retryLock, func(ctx context.Context) error { + return retry.Do(ctx, l.lockProbe.backoff(), func(ctx context.Context) error { row := conn.QueryRowContext(ctx, "SELECT pg_try_advisory_lock($1)", l.lockID) var locked bool if err := row.Scan(&locked); err != nil { @@ -125,7 +119,7 @@ func (l *postgresSessionLocker) SessionLock(ctx context.Context, conn *sql.Conn) } func (l *postgresSessionLocker) SessionUnlock(ctx context.Context, conn *sql.Conn) error { - return retry.Do(ctx, l.retryUnlock, func(ctx context.Context) error { + return retry.Do(ctx, l.unlockProbe.backoff(), func(ctx context.Context) error { var unlocked bool row := conn.QueryRowContext(ctx, "SELECT pg_advisory_unlock($1)", l.lockID) if err := row.Scan(&unlocked); err != nil { diff --git a/vendor/github.com/pressly/goose/v3/lock/session_locker_options.go b/vendor/github.com/pressly/goose/v3/lock/session_locker_options.go index 083e404..c9abbd5 100644 --- a/vendor/github.com/pressly/goose/v3/lock/session_locker_options.go +++ b/vendor/github.com/pressly/goose/v3/lock/session_locker_options.go @@ -3,6 +3,8 @@ package lock import ( "errors" "time" + + "github.com/sethvargo/go-retry" ) const ( @@ -89,6 +91,16 @@ type probe struct { failureThreshold uint64 } +// backoff returns a new backoff for one lock or unlock call. The backoff counts the retries it +// has used and never resets, so each call must get its own. +func (p probe) backoff() retry.Backoff { + // retry.NewConstant is not used here, because it panics on an interval that is not positive. + constant := retry.BackoffFunc(func() (time.Duration, bool) { + return p.intervalDuration, false + }) + return retry.WithMaxRetries(p.failureThreshold, constant) +} + var _ SessionLockerOption = (sessionLockerConfigFunc)(nil) type sessionLockerConfigFunc func(*sessionLockerConfig) error diff --git a/vendor/github.com/pressly/goose/v3/migrate.go b/vendor/github.com/pressly/goose/v3/migrate.go index b60c61a..fbf4098 100644 --- a/vendor/github.com/pressly/goose/v3/migrate.go +++ b/vendor/github.com/pressly/goose/v3/migrate.go @@ -8,6 +8,7 @@ import ( "io/fs" "math" "path" + "slices" "sort" "strings" "time" @@ -63,9 +64,9 @@ func (ms Migrations) Next(current int64) (*Migration, error) { // Previous : Get the previous migration. func (ms Migrations) Previous(current int64) (*Migration, error) { - for i := len(ms) - 1; i >= 0; i-- { - if ms[i].Version < current { - return ms[i], nil + for _, m := range slices.Backward(ms) { + if m.Version < current { + return m, nil } } diff --git a/vendor/github.com/pressly/goose/v3/provider_collect.go b/vendor/github.com/pressly/goose/v3/provider_collect.go index 12ecb7f..96e6310 100644 --- a/vendor/github.com/pressly/goose/v3/provider_collect.go +++ b/vendor/github.com/pressly/goose/v3/provider_collect.go @@ -122,10 +122,6 @@ func merge(sources *fileSources, registered map[int64]*Migration) ([]*Migration, migrations = append(migrations, m) migrationLookup[source.Version] = m } - // If there are no Go files in the filesystem and no registered Go migrations, return early. - if len(sources.goSources) == 0 && len(registered) == 0 { - return migrations, nil - } // Return an error if the given sources contain a versioned Go migration that has not been // registered. This is a sanity check to ensure users didn't accidentally create a valid looking // Go migration file on disk and forget to register it. diff --git a/vendor/github.com/prometheus/client_golang/internal/github.com/golang/gddo/httputil/header/header.go b/vendor/github.com/prometheus/client_golang/internal/github.com/golang/gddo/httputil/header/header.go index 820bf43..2cd16f1 100644 --- a/vendor/github.com/prometheus/client_golang/internal/github.com/golang/gddo/httputil/header/header.go +++ b/vendor/github.com/prometheus/client_golang/internal/github.com/golang/gddo/httputil/header/header.go @@ -39,7 +39,7 @@ func init() { // token = 1* // qdtext = > - for c := 0; c < 256; c++ { + for c := range 256 { var t octetType isCtl := c <= 31 || c == 127 isChar := 0 <= c && c <= 127 diff --git a/vendor/github.com/prometheus/client_golang/prometheus/build_info_collector.go b/vendor/github.com/prometheus/client_golang/prometheus/build_info_collector.go index 450189f..b80b964 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/build_info_collector.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/build_info_collector.go @@ -32,7 +32,8 @@ func NewBuildInfoCollector() Collector { "Build information about the main Go module.", nil, Labels{"path": path, "version": version, "checksum": sum}, ), - GaugeValue, 1)} + GaugeValue, 1, + )} c.init(c.self) return c } diff --git a/vendor/github.com/prometheus/client_golang/prometheus/collectors/go_collector_latest.go b/vendor/github.com/prometheus/client_golang/prometheus/collectors/go_collector_latest.go index d29ade6..c5a5d50 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/collectors/go_collector_latest.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/collectors/go_collector_latest.go @@ -11,9 +11,6 @@ // See the License for the specific language governing permissions and // limitations under the License. -//go:build go1.17 -// +build go1.17 - package collectors import ( diff --git a/vendor/github.com/prometheus/client_golang/prometheus/desc.go b/vendor/github.com/prometheus/client_golang/prometheus/desc.go index a3c92e7..881d91d 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/desc.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/desc.go @@ -21,7 +21,6 @@ import ( "github.com/cespare/xxhash/v2" dto "github.com/prometheus/client_model/go" "github.com/prometheus/common/model" - "google.golang.org/protobuf/proto" "github.com/prometheus/client_golang/prometheus/internal" ) @@ -181,8 +180,8 @@ func (v2) NewDesc(fqName, help string, variableLabels ConstrainableLabels, const d.constLabelPairs = make([]*dto.LabelPair, 0, len(constLabels)) for n, v := range constLabels { d.constLabelPairs = append(d.constLabelPairs, &dto.LabelPair{ - Name: proto.String(n), - Value: proto.String(v), + Name: new(n), + Value: new(v), }) } sort.Sort(internal.LabelPairSorter(d.constLabelPairs)) diff --git a/vendor/github.com/prometheus/client_golang/prometheus/get_pid.go b/vendor/github.com/prometheus/client_golang/prometheus/get_pid.go index 614fd61..c7be2a0 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/get_pid.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/get_pid.go @@ -12,7 +12,6 @@ // limitations under the License. //go:build !js || wasm -// +build !js wasm package prometheus diff --git a/vendor/github.com/prometheus/client_golang/prometheus/get_pid_gopherjs.go b/vendor/github.com/prometheus/client_golang/prometheus/get_pid_gopherjs.go index eaf8059..0ddc8c6 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/get_pid_gopherjs.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/get_pid_gopherjs.go @@ -12,7 +12,6 @@ // limitations under the License. //go:build js && !wasm -// +build js,!wasm package prometheus diff --git a/vendor/github.com/prometheus/client_golang/prometheus/go_collector.go b/vendor/github.com/prometheus/client_golang/prometheus/go_collector.go index 520cbd7..a472584 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/go_collector.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/go_collector.go @@ -211,23 +211,28 @@ func newBaseGoCollector() baseGoCollector { goroutinesDesc: NewDesc( "go_goroutines", "Number of goroutines that currently exist.", - nil, nil), + nil, nil, + ), threadsDesc: NewDesc( "go_threads", "Number of OS threads created.", - nil, nil), + nil, nil, + ), gcDesc: NewDesc( "go_gc_duration_seconds", "A summary of the wall-time pause (stop-the-world) duration in garbage collection cycles.", - nil, nil), + nil, nil, + ), gcLastTimeDesc: NewDesc( "go_memstats_last_gc_time_seconds", "Number of seconds since 1970 of last garbage collection.", - nil, nil), + nil, nil, + ), goInfoDesc: NewDesc( "go_info", "Information about the Go environment.", - nil, Labels{"version": runtime.Version()}), + nil, Labels{"version": runtime.Version()}, + ), } } diff --git a/vendor/github.com/prometheus/client_golang/prometheus/go_collector_latest.go b/vendor/github.com/prometheus/client_golang/prometheus/go_collector_latest.go index 1db1c4b..23091e1 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/go_collector_latest.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/go_collector_latest.go @@ -11,9 +11,6 @@ // See the License for the specific language governing permissions and // limitations under the License. -//go:build go1.17 -// +build go1.17 - package prometheus import ( @@ -27,7 +24,6 @@ import ( "github.com/prometheus/client_golang/prometheus/internal" dto "github.com/prometheus/client_model/go" - "google.golang.org/protobuf/proto" ) const ( @@ -573,14 +569,14 @@ func (h *batchHistogram) Write(out *dto.Metric) error { // by obtaining the next float64 value down, in order. upperBound := math.Nextafter(h.buckets[i+1], h.buckets[i]) dtoBuckets = append(dtoBuckets, &dto.Bucket{ - CumulativeCount: proto.Uint64(totalCount), - UpperBound: proto.Float64(upperBound), + CumulativeCount: new(totalCount), + UpperBound: new(upperBound), }) } out.Histogram = &dto.Histogram{ Bucket: dtoBuckets, - SampleCount: proto.Uint64(totalCount), - SampleSum: proto.Float64(sum), + SampleCount: new(totalCount), + SampleSum: new(sum), } return nil } diff --git a/vendor/github.com/prometheus/client_golang/prometheus/histogram.go b/vendor/github.com/prometheus/client_golang/prometheus/histogram.go index 88bae3b..1d6ca16 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/histogram.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/histogram.go @@ -803,8 +803,8 @@ func (h *histogram) Write(out *dto.Metric) error { his := &dto.Histogram{ Bucket: make([]*dto.Bucket, len(h.upperBounds)), - SampleCount: proto.Uint64(count), - SampleSum: proto.Float64(math.Float64frombits(atomic.LoadUint64(&coldCounts.sumBits))), + SampleCount: new(count), + SampleSum: new(math.Float64frombits(atomic.LoadUint64(&coldCounts.sumBits))), CreatedTimestamp: timestamppb.New(h.lastResetTime), } out.Histogram = his @@ -814,8 +814,8 @@ func (h *histogram) Write(out *dto.Metric) error { for i, upperBound := range h.upperBounds { cumCount += atomic.LoadUint64(&coldCounts.buckets[i]) his.Bucket[i] = &dto.Bucket{ - CumulativeCount: proto.Uint64(cumCount), - UpperBound: proto.Float64(upperBound), + CumulativeCount: new(cumCount), + UpperBound: new(upperBound), } if e := h.exemplars[i].Load(); e != nil { his.Bucket[i].Exemplar = e.(*dto.Exemplar) @@ -824,15 +824,15 @@ func (h *histogram) Write(out *dto.Metric) error { // If there is an exemplar for the +Inf bucket, we have to add that bucket explicitly. if e := h.exemplars[len(h.upperBounds)].Load(); e != nil { b := &dto.Bucket{ - CumulativeCount: proto.Uint64(count), - UpperBound: proto.Float64(math.Inf(1)), + CumulativeCount: new(count), + UpperBound: new(math.Inf(1)), Exemplar: e.(*dto.Exemplar), } his.Bucket = append(his.Bucket, b) } if h.nativeHistogramSchema > math.MinInt32 { - his.ZeroThreshold = proto.Float64(math.Float64frombits(atomic.LoadUint64(&coldCounts.nativeHistogramZeroThresholdBits))) - his.Schema = proto.Int32(atomic.LoadInt32(&coldCounts.nativeHistogramSchema)) + his.ZeroThreshold = new(math.Float64frombits(atomic.LoadUint64(&coldCounts.nativeHistogramZeroThresholdBits))) + his.Schema = new(atomic.LoadInt32(&coldCounts.nativeHistogramSchema)) zeroBucket := atomic.LoadUint64(&coldCounts.nativeHistogramZeroBucket) defer func() { @@ -840,7 +840,7 @@ func (h *histogram) Write(out *dto.Metric) error { coldCounts.nativeHistogramBucketsNegative.Range(addAndReset(&hotCounts.nativeHistogramBucketsNegative, &hotCounts.nativeHistogramBucketsNumber)) }() - his.ZeroCount = proto.Uint64(zeroBucket) + his.ZeroCount = new(zeroBucket) his.NegativeSpan, his.NegativeDelta = makeBuckets(&coldCounts.nativeHistogramBucketsNegative) his.PositiveSpan, his.PositiveDelta = makeBuckets(&coldCounts.nativeHistogramBucketsPositive) @@ -1331,12 +1331,12 @@ func (h *constHistogram) Write(out *dto.Metric) error { buckets := make([]*dto.Bucket, 0, len(h.buckets)) - his.SampleCount = proto.Uint64(h.count) - his.SampleSum = proto.Float64(h.sum) + his.SampleCount = new(h.count) + his.SampleSum = new(h.sum) for upperBound, count := range h.buckets { buckets = append(buckets, &dto.Bucket{ - CumulativeCount: proto.Uint64(count), - UpperBound: proto.Float64(upperBound), + CumulativeCount: new(count), + UpperBound: new(upperBound), }) } @@ -1481,7 +1481,7 @@ func pickSchema(bucketFactor float64) int32 { func makeBuckets(buckets *sync.Map) ([]*dto.BucketSpan, []int64) { var ii []int - buckets.Range(func(k, v any) bool { + buckets.Range(func(k, _ any) bool { ii = append(ii, k.(int)) return true }) @@ -1518,13 +1518,13 @@ func makeBuckets(buckets *sync.Map) ([]*dto.BucketSpan, []int64) { // at the very beginning, or because we have found a gap // of more than two buckets. spans = append(spans, &dto.BucketSpan{ - Offset: proto.Int32(iDelta), + Offset: new(iDelta), Length: proto.Uint32(0), }) } else { // We have found a small gap (or no gap at all). // Insert empty buckets as needed. - for j := int32(0); j < iDelta; j++ { + for range iDelta { appendDelta(0) } } @@ -1570,7 +1570,7 @@ func addAndReset(hotBuckets *sync.Map, bucketNumber *uint32) func(k, v any) bool } func deleteSyncMap(m *sync.Map) { - m.Range(func(k, v any) bool { + m.Range(func(k, _ any) bool { m.Delete(k) return true }) @@ -1578,7 +1578,7 @@ func deleteSyncMap(m *sync.Map) { func findSmallestKey(m *sync.Map) int { result := math.MaxInt32 - m.Range(func(k, v any) bool { + m.Range(func(k, _ any) bool { key := k.(int) if key < result { result = key @@ -1956,7 +1956,7 @@ func NewConstNativeHistogram( PositiveSpan: PositiveSpan, PositiveDelta: PositiveDelta, - ZeroCount: proto.Uint64(zeroBucket), + ZeroCount: new(zeroBucket), }, labelPairs: MakeLabelPairs(desc, labelValues), } @@ -2044,13 +2044,13 @@ func makeBucketsFromMap(buckets map[int]int64) ([]*dto.BucketSpan, []int64) { // at the very beginning, or because we have found a gap // of more than two buckets. spans = append(spans, &dto.BucketSpan{ - Offset: proto.Int32(iDelta), + Offset: new(iDelta), Length: proto.Uint32(0), }) } else { // We have found a small gap (or no gap at all). // Insert empty buckets as needed. - for j := int32(0); j < iDelta; j++ { + for range iDelta { appendDelta(0) } } diff --git a/vendor/github.com/prometheus/client_golang/prometheus/internal/go_runtime_metrics.go b/vendor/github.com/prometheus/client_golang/prometheus/internal/go_runtime_metrics.go index d273b66..e38dfe0 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/internal/go_runtime_metrics.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/internal/go_runtime_metrics.go @@ -11,9 +11,6 @@ // See the License for the specific language governing permissions and // limitations under the License. -//go:build go1.17 -// +build go1.17 - package internal import ( diff --git a/vendor/github.com/prometheus/client_golang/prometheus/metric.go b/vendor/github.com/prometheus/client_golang/prometheus/metric.go index c5cb90a..e4bbf3b 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/metric.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/metric.go @@ -22,7 +22,6 @@ import ( dto "github.com/prometheus/client_model/go" "github.com/prometheus/common/model" - "google.golang.org/protobuf/proto" ) var separatorByteSlice = []byte{model.SeparatorByte} // For convenient use with xxhash. @@ -153,7 +152,7 @@ type timestampedMetric struct { func (m timestampedMetric) Write(pb *dto.Metric) error { e := m.Metric.Write(pb) - pb.TimestampMs = proto.Int64(m.t.Unix()*1000 + int64(m.t.Nanosecond()/1000000)) + pb.TimestampMs = new(m.t.Unix()*1000 + int64(m.t.Nanosecond()/1000000)) return e } @@ -209,8 +208,8 @@ func (m *withExemplarsMetric) Write(pb *dto.Metric) error { } else { // The +Inf bucket should be explicitly added if there is an exemplar for it, similar to non-const histogram logic in https://github.com/prometheus/client_golang/blob/main/prometheus/histogram.go#L357-L365. b := &dto.Bucket{ - CumulativeCount: proto.Uint64(h.GetSampleCount()), - UpperBound: proto.Float64(math.Inf(1)), + CumulativeCount: new(h.GetSampleCount()), + UpperBound: new(math.Inf(1)), Exemplar: e, } h.Bucket = append(h.Bucket, b) diff --git a/vendor/github.com/prometheus/client_golang/prometheus/num_threads.go b/vendor/github.com/prometheus/client_golang/prometheus/num_threads.go index 7c12b21..7ffac21 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/num_threads.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/num_threads.go @@ -12,7 +12,6 @@ // limitations under the License. //go:build !js || wasm -// +build !js wasm package prometheus diff --git a/vendor/github.com/prometheus/client_golang/prometheus/num_threads_gopherjs.go b/vendor/github.com/prometheus/client_golang/prometheus/num_threads_gopherjs.go index 7348df0..65f4263 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/num_threads_gopherjs.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/num_threads_gopherjs.go @@ -12,7 +12,6 @@ // limitations under the License. //go:build js && !wasm -// +build js,!wasm package prometheus diff --git a/vendor/github.com/prometheus/client_golang/prometheus/process_collector_darwin.go b/vendor/github.com/prometheus/client_golang/prometheus/process_collector_darwin.go index 2b16298..46e7e45 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/process_collector_darwin.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/process_collector_darwin.go @@ -54,21 +54,22 @@ func getOpenFileCount() (float64, error) { // benefits, however, include fewer system calls and not failing when at the // open file soft limit. - if dir, err := os.Open("/dev/fd"); err != nil { + dir, err := os.Open("/dev/fd") + if err != nil { return 0.0, err - } else { - defer dir.Close() - - // Avoid ReadDir(), as it calls stat(2) on each descriptor. Not only is - // that info not used, but KQUEUE descriptors fail stat(2), which causes - // the whole method to fail. - if names, err := dir.Readdirnames(0); err != nil { - return 0.0, err - } else { - // Subtract 1 to ignore the open /dev/fd descriptor above. - return float64(len(names) - 1), nil - } } + defer dir.Close() + + // Avoid ReadDir(), as it calls stat(2) on each descriptor. Not only is + // that info not used, but KQUEUE descriptors fail stat(2), which causes + // the whole method to fail. + names, err := dir.Readdirnames(0) + if err != nil { + return 0.0, err + } + + // Subtract 1 to ignore the open /dev/fd descriptor above. + return float64(len(names) - 1), nil } func (c *processCollector) processCollect(ch chan<- Metric) { diff --git a/vendor/github.com/prometheus/client_golang/prometheus/process_collector_not_supported.go b/vendor/github.com/prometheus/client_golang/prometheus/process_collector_not_supported.go index 7732b7f..8650b6f 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/process_collector_not_supported.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/process_collector_not_supported.go @@ -12,7 +12,6 @@ // limitations under the License. //go:build wasip1 || js || ios -// +build wasip1 js ios package prometheus diff --git a/vendor/github.com/prometheus/client_golang/prometheus/process_collector_procfsenabled.go b/vendor/github.com/prometheus/client_golang/prometheus/process_collector_procfsenabled.go index 8074f70..56c97d6 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/process_collector_procfsenabled.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/process_collector_procfsenabled.go @@ -12,7 +12,6 @@ // limitations under the License. //go:build !windows && !js && !wasip1 && !darwin -// +build !windows,!js,!wasip1,!darwin package prometheus diff --git a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/http.go b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/http.go index c28af5c..0af3dee 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/http.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/http.go @@ -51,10 +51,12 @@ import ( ) const ( + acceptHeader = "Accept" contentTypeHeader = "Content-Type" contentEncodingHeader = "Content-Encoding" acceptEncodingHeader = "Accept-Encoding" processStartTimeHeader = "Process-Start-Time-Unix" + varyHeader = "Vary" ) // Compression represents the content encodings handlers support for the HTTP @@ -70,9 +72,8 @@ const ( func defaultCompressionFormats() []Compression { if internal.NewZstdWriter != nil { return []Compression{Identity, Gzip, Zstd} - } else { - return []Compression{Identity, Gzip} } + return []Compression{Identity, Gzip} } var gzipPool = sync.Pool{ @@ -315,11 +316,20 @@ func HandlerForTransactional(reg prometheus.TransactionalGatherer, opts HandlerO } } - var contentType expfmt.Format - if opts.EnableOpenMetrics { - contentType = expfmt.NegotiateIncludingOpenMetrics(req.Header) - } else { - contentType = expfmt.Negotiate(req.Header) + var ( + contentType expfmt.Format + acceptedFormats = opts.AcceptedFormats + ) + if len(acceptedFormats) == 0 { + acceptedFormats = expfmt.DefaultAcceptedFormats() + if opts.EnableOpenMetrics { + acceptedFormats = expfmt.DefaultOpenMetricsAcceptedFormats() + } + } + contentType = expfmt.NegotiateAccept(req.Header, acceptedFormats...) + rsp.Header().Add(varyHeader, acceptHeader) + if len(compressions) > 0 { + rsp.Header().Add(varyHeader, acceptEncodingHeader) } rsp.Header().Set(contentTypeHeader, string(contentType)) @@ -598,6 +608,8 @@ type HandlerOpts struct { // a trailing ".0" if they would otherwise look like integer numbers // (which changes the identity of the resulting series on the Prometheus // server). + // + // Note that setting AcceptedFormats overrides this option. EnableOpenMetrics bool // EnableOpenMetricsTextCreatedSamples specifies if this handler should add, extra, synthetic // Created Timestamps for counters, histograms and summaries, which for the current @@ -622,6 +634,18 @@ type HandlerOpts struct { // NOTE: This feature is experimental and not covered by OpenMetrics or Prometheus // exposition format. ProcessStartTime time.Time + // AcceptedFormats allows customizing the formats the handler will negotiate + // with the client based on the request's Accept header. + // The client's Accept header and q-values take precedence, but the order of + // formats in AcceptedFormats specifies the server's preference order used as a + // tie-breaker (e.g. for wildcard "*/*" requests or equal q-values) and fallback. + // If empty, the default set is used (expfmt.DefaultAcceptedFormats()). + // If empty and EnableOpenMetrics is true, stable OpenMetrics formats are negotiated + // (expfmt.DefaultOpenMetricsAcceptedFormats()). + // This is useful for testing experimental formats (e.g. OpenMetrics 2.0) + // or restricting the formats you want to allow. + // Using EnableOpenMetrics with an empty AcceptedFormats is still the recommended option for the majority of cases. + AcceptedFormats []expfmt.Format } // httpError removes any content-encoding header and then calls http.Error with diff --git a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/option.go b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/option.go index d4c0954..258a2a5 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/option.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/option.go @@ -41,7 +41,7 @@ type options struct { func defaultOptions() *options { return &options{ - getExemplarFn: func(req *http.Request) prometheus.Labels { return nil }, + getExemplarFn: func(_ *http.Request) prometheus.Labels { return nil }, extraLabelsFromRequest: map[string]LabelValueFromRequest{}, } } diff --git a/vendor/github.com/prometheus/client_golang/prometheus/registry.go b/vendor/github.com/prometheus/client_golang/prometheus/registry.go index ed0681c..4151b59 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/registry.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/registry.go @@ -17,6 +17,7 @@ import ( "bytes" "errors" "fmt" + "maps" "os" "path/filepath" "runtime" @@ -31,7 +32,6 @@ import ( "github.com/cespare/xxhash/v2" dto "github.com/prometheus/client_model/go" "github.com/prometheus/common/expfmt" - "google.golang.org/protobuf/proto" ) const ( @@ -296,6 +296,7 @@ func (r *Registry) Register(c Collector) error { defer func() { // Drain channel in case of premature return to not leak a goroutine. for range descChan { + continue } r.mtx.Unlock() }() @@ -369,9 +370,7 @@ func (r *Registry) Register(c Collector) error { for hash := range newDescIDs { r.descIDs[hash] = struct{}{} } - for name, dimHash := range newDimHashesByName { - r.dimHashesByName[name] = dimHash - } + maps.Copy(r.dimHashesByName, newDimHashesByName) return nil } @@ -476,7 +475,7 @@ func (r *Registry) Gather() ([]*dto.MetricFamily, error) { for { select { case collector := <-checkedCollectors: - safeErrs.Append((safeCollect(collector, checkedMetricChan))) + safeErrs.Append(safeCollect(collector, checkedMetricChan)) case collector := <-uncheckedCollectors: safeErrs.Append(safeCollect(collector, uncheckedMetricChan)) default: @@ -502,10 +501,12 @@ func (r *Registry) Gather() ([]*dto.MetricFamily, error) { defer func() { if checkedMetricChan != nil { for range checkedMetricChan { + continue } } if uncheckedMetricChan != nil { for range uncheckedMetricChan { + continue } } }() @@ -727,10 +728,10 @@ func processMetric( } } else { // New name. metricFamily = &dto.MetricFamily{} - metricFamily.Name = proto.String(desc.fqName) - metricFamily.Help = proto.String(desc.help) + metricFamily.Name = new(desc.fqName) + metricFamily.Help = new(desc.help) if desc.unit != "" { - metricFamily.Unit = proto.String(desc.unit) + metricFamily.Unit = new(desc.unit) } // TODO(beorn7): Simplify switch once Desc has type. switch { @@ -956,7 +957,8 @@ func checkMetricConsistency( if !utf8.ValidString(labelPair.GetValue()) { return fmt.Errorf( "collected metric %q { %s} has a label named %q whose value is not utf8: %#v", - name, dtoMetric, labelName, labelPair.GetValue()) + name, dtoMetric, labelName, labelPair.GetValue(), + ) } previousLabelName = labelName } @@ -981,7 +983,7 @@ func checkMetricConsistency( h.Write(separatorByteSlice) } if dtoMetric.TimestampMs != nil { - h.WriteString(strconv.FormatInt(*(dtoMetric.TimestampMs), 10)) + h.WriteString(strconv.FormatInt(*dtoMetric.TimestampMs, 10)) h.Write(separatorByteSlice) } hSum := h.Sum64() @@ -1013,7 +1015,7 @@ func checkDescConsistency( copy(lpsFromDesc, desc.constLabelPairs) for _, l := range desc.variableLabels.names { lpsFromDesc = append(lpsFromDesc, &dto.LabelPair{ - Name: proto.String(l), + Name: new(l), }) } if len(lpsFromDesc) != len(dtoMetric.Label) { diff --git a/vendor/github.com/prometheus/client_golang/prometheus/summary.go b/vendor/github.com/prometheus/client_golang/prometheus/summary.go index c12b8d1..d92850c 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/summary.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/summary.go @@ -25,7 +25,6 @@ import ( dto "github.com/prometheus/client_model/go" "github.com/beorn7/perks/quantile" - "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/timestamppb" ) @@ -337,8 +336,8 @@ func (s *summary) Write(out *dto.Metric) error { s.bufMtx.Unlock() s.flushColdBuf() - sum.SampleCount = proto.Uint64(s.cnt) - sum.SampleSum = proto.Float64(s.sum) + sum.SampleCount = new(s.cnt) + sum.SampleSum = new(s.sum) for _, rank := range s.sortedObjectives { var q float64 @@ -348,8 +347,8 @@ func (s *summary) Write(out *dto.Metric) error { q = s.headStream.Query(rank) } qs = append(qs, &dto.Quantile{ - Quantile: proto.Float64(rank), - Value: proto.Float64(q), + Quantile: new(rank), + Value: new(q), }) } @@ -512,8 +511,8 @@ func (s *noObjectivesSummary) Write(out *dto.Metric) error { } sum := &dto.Summary{ - SampleCount: proto.Uint64(count), - SampleSum: proto.Float64(math.Float64frombits(atomic.LoadUint64(&coldCounts.sumBits))), + SampleCount: new(count), + SampleSum: new(math.Float64frombits(atomic.LoadUint64(&coldCounts.sumBits))), CreatedTimestamp: s.createdTs, } @@ -718,13 +717,13 @@ func (s *constSummary) Write(out *dto.Metric) error { } qs := make([]*dto.Quantile, 0, len(s.quantiles)) - sum.SampleCount = proto.Uint64(s.count) - sum.SampleSum = proto.Float64(s.sum) + sum.SampleCount = new(s.count) + sum.SampleSum = new(s.sum) for rank, q := range s.quantiles { qs = append(qs, &dto.Quantile{ - Quantile: proto.Float64(rank), - Value: proto.Float64(q), + Quantile: new(rank), + Value: new(q), }) } diff --git a/vendor/github.com/prometheus/client_golang/prometheus/value.go b/vendor/github.com/prometheus/client_golang/prometheus/value.go index cc23011..c856e4f 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/value.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/value.go @@ -23,7 +23,6 @@ import ( "github.com/prometheus/client_golang/prometheus/internal" dto "github.com/prometheus/client_model/go" - "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/timestamppb" ) @@ -196,11 +195,11 @@ func populateMetric( m.Label = labelPairs switch t { case CounterValue: - m.Counter = &dto.Counter{Value: proto.Float64(v), Exemplar: e, CreatedTimestamp: ct} + m.Counter = &dto.Counter{Value: new(v), Exemplar: e, CreatedTimestamp: ct} case GaugeValue: - m.Gauge = &dto.Gauge{Value: proto.Float64(v)} + m.Gauge = &dto.Gauge{Value: new(v)} case UntypedValue: - m.Untyped = &dto.Untyped{Value: proto.Float64(v)} + m.Untyped = &dto.Untyped{Value: new(v)} default: return fmt.Errorf("encountered unknown type %v", t) } @@ -227,8 +226,8 @@ func MakeLabelPairs(desc *Desc, labelValues []string) []*dto.LabelPair { labelPairs := make([]*dto.LabelPair, 0, totalLen) for i, l := range desc.variableLabels.names { labelPairs = append(labelPairs, &dto.LabelPair{ - Name: proto.String(l), - Value: proto.String(labelValues[i]), + Name: new(l), + Value: new(labelValues[i]), }) } labelPairs = append(labelPairs, desc.constLabelPairs...) @@ -244,7 +243,7 @@ const ExemplarMaxRunes = 128 // number of runes in the label names and values exceeds ExemplarMaxRunes. func newExemplar(value float64, ts time.Time, l Labels) (*dto.Exemplar, error) { e := &dto.Exemplar{} - e.Value = proto.Float64(value) + e.Value = new(value) tsProto := timestamppb.New(ts) if err := tsProto.CheckValid(); err != nil { return nil, err @@ -262,8 +261,8 @@ func newExemplar(value float64, ts time.Time, l Labels) (*dto.Exemplar, error) { } runes += utf8.RuneCountInString(value) labelPairs = append(labelPairs, &dto.LabelPair{ - Name: proto.String(name), - Value: proto.String(value), + Name: new(name), + Value: new(value), }) } if runes > ExemplarMaxRunes { diff --git a/vendor/github.com/prometheus/client_golang/prometheus/wrap.go b/vendor/github.com/prometheus/client_golang/prometheus/wrap.go index 697f555..cc9ae8f 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/wrap.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/wrap.go @@ -20,7 +20,6 @@ import ( "github.com/prometheus/client_golang/prometheus/internal" dto "github.com/prometheus/client_model/go" - "google.golang.org/protobuf/proto" ) // WrapRegistererWith returns a Registerer wrapping the provided @@ -212,8 +211,8 @@ func (m *wrappingMetric) Write(out *dto.Metric) error { } for ln, lv := range m.labels { out.Label = append(out.Label, &dto.LabelPair{ - Name: proto.String(ln), - Value: proto.String(lv), + Name: new(ln), + Value: new(lv), }) } sort.Sort(internal.LabelPairSorter(out.Label)) diff --git a/vendor/github.com/prometheus/common/expfmt/decode.go b/vendor/github.com/prometheus/common/expfmt/decode.go index 8f8dc65..7cfe43f 100644 --- a/vendor/github.com/prometheus/common/expfmt/decode.go +++ b/vendor/github.com/prometheus/common/expfmt/decode.go @@ -61,10 +61,30 @@ func ResponseFormat(h http.Header) Format { return FmtProtoDelim case textType: + if params["version"] == TextVersion_1_0_0 { + if _, ok := params[model.EscapingKey]; ok { + return FmtText_1_0_0.WithEscapingScheme(Format(ct).ToEscapingScheme()) + } + return FmtText_1_0_0 + } if v, ok := params["version"]; ok && v != TextVersion { return FmtUnknown } return FmtText + + case OpenMetricsType: + switch params["version"] { + case "", OpenMetricsVersion_0_0_1: + return FmtOpenMetrics_0_0_1 + case OpenMetricsVersion_1_0_0: + return FmtOpenMetrics_1_0_0 + case OpenMetricsVersion_2_0_0_rc: + return FmtOpenMetrics_2_0_0_rc + case OpenMetricsVersion_2_0_0: + return FmtOpenMetrics_2_0_0 + default: + return FmtUnknown + } } return FmtUnknown @@ -72,13 +92,13 @@ func ResponseFormat(h http.Header) Format { // NewDecoder returns a new decoder based on the given input format. Metric // names are validated based on the provided Format -- if the format requires -// escaping, raditional Prometheues validity checking is used. Otherwise, names -// are checked for UTF-8 validity. Supported formats include delimited protobuf -// and Prometheus text format. For historical reasons, this decoder fallbacks -// to classic text decoding for any other format. This decoder does not fully -// support OpenMetrics although it may often succeed due to the similarities -// between the formats. This decoder may not support the latest features of -// Prometheus text format and is not intended for high-performance applications. +// escaping, traditional Prometheus validity checking is used. Otherwise, names +// are checked for UTF-8 validity. Supported formats include delimited protobuf, +// Prometheus text format, and OpenMetrics 0.0.1 / 1.0.0 / 2.0.0-rc / 2.0.0. For historical +// reasons, this decoder falls back to classic text decoding for other legacy +// formats, and returns an error for unsupported formats such as text protobuf. +// This decoder may not support the latest features of Prometheus text format +// and is not intended for high-performance applications. // See: https://github.com/prometheus/common/issues/812 func NewDecoder(r io.Reader, format Format) Decoder { scheme := model.LegacyValidation @@ -90,6 +110,26 @@ func NewDecoder(r io.Reader, format Format) Decoder { return &protoDecoder{r: bufio.NewReader(r), s: scheme} case TypeProtoText, TypeProtoCompact: return &errDecoder{err: fmt.Errorf("format %s not supported for decoding", format)} + case TypeOpenMetrics: + _, params, err := mime.ParseMediaType(string(format)) + if err != nil { + return &errDecoder{err: fmt.Errorf("format %s not supported for decoding", format)} + } + switch params["version"] { + case "", OpenMetricsVersion_0_0_1, OpenMetricsVersion_1_0_0: + return &openMetricsDecoder{p: newOpenMetricsParser(r, scheme)} + case OpenMetricsVersion_2_0_0_rc, OpenMetricsVersion_2_0_0: + // format.ToEscapingScheme() defaults to UnderscoreEscaping when no escaping + // parameter is set, whereas OpenMetrics 2.0 supports UTF-8 names by default + // unless a non-UTF-8 escaping scheme is explicitly requested. + om2Scheme := model.UTF8Validation + if _, hasEscaping := params[model.EscapingKey]; hasEscaping && format.ToEscapingScheme() != model.NoEscaping { + om2Scheme = model.LegacyValidation + } + return &openMetrics20Decoder{p: newOpenMetrics20Parser(r, om2Scheme)} + default: + return &errDecoder{err: fmt.Errorf("format %s not supported for decoding", format)} + } } return &textDecoder{r: r, s: scheme} } @@ -139,6 +179,45 @@ func (d *errDecoder) Decode(*dto.MetricFamily) error { return d.err } +// openMetricsDecoder implements the Decoder interface for the OpenMetrics 1.0 protocol. +type openMetricsDecoder struct { + p *openMetricsParser + err error +} + +// Decode implements the Decoder interface. +func (d *openMetricsDecoder) Decode(v *dto.MetricFamily) error { + if d.err != nil { + return d.err + } + if err := d.p.next(v); err != nil { + d.err = err + return err + } + return nil +} + +// openMetrics20Decoder implements the Decoder interface for the OpenMetrics 2.0 protocol. +// Like openMetricsDecoder, it uses goabnf.ParseForest per line without a line-length +// cap (which has superlinear parse time in line length) and is intended for +// reference/conformance decoding rather than high-performance or untrusted inputs. +type openMetrics20Decoder struct { + p *openMetrics20Parser + err error +} + +// Decode implements the Decoder interface. +func (d *openMetrics20Decoder) Decode(v *dto.MetricFamily) error { + if d.err != nil { + return d.err + } + if err := d.p.next(v); err != nil { + d.err = err + return err + } + return nil +} + // textDecoder implements the Decoder interface for the text protocol. type textDecoder struct { r io.Reader diff --git a/vendor/github.com/prometheus/common/expfmt/encode.go b/vendor/github.com/prometheus/common/expfmt/encode.go index 73c24df..20b75c4 100644 --- a/vendor/github.com/prometheus/common/expfmt/encode.go +++ b/vendor/github.com/prometheus/common/expfmt/encode.go @@ -16,7 +16,9 @@ package expfmt import ( "fmt" "io" + "mime" "net/http" + "slices" "github.com/munnerz/goautoneg" dto "github.com/prometheus/client_model/go" @@ -26,6 +28,60 @@ import ( "github.com/prometheus/common/model" ) +var formatToAccept = map[Format]goautoneg.Accept{} + +func init() { + for _, f := range []Format{ + FmtText, + FmtText_1_0_0, + FmtProtoDelim, + FmtProtoText, + FmtProtoCompact, + FmtOpenMetrics_1_0_0, + FmtOpenMetrics_2_0_0_rc, + FmtOpenMetrics_2_0_0, + FmtOpenMetrics_0_0_1, + } { + if parsed := goautoneg.ParseAccept(string(f)); len(parsed) > 0 { + formatToAccept[f] = parsed[0] + } + } +} + +var ( + defaultAcceptedFormats = []Format{ + FmtProtoDelim, + FmtProtoText, + FmtProtoCompact, + FmtText, + FmtText_1_0_0, + } + + defaultOpenMetricsAcceptedFormats = []Format{ + FmtOpenMetrics_1_0_0, + FmtOpenMetrics_0_0_1, + FmtProtoDelim, + FmtProtoText, + FmtProtoCompact, + FmtText, + FmtText_1_0_0, + } +) + +// DefaultAcceptedFormats returns a copy of standard accepted formats for Negotiate, +// ordered by preference (delimited protobuf, protobuf text, compact protobuf text, +// and Prometheus text formats). Version 0.0.4 remains the fallback when no +// supported version is requested. +func DefaultAcceptedFormats() []Format { + return slices.Clone(defaultAcceptedFormats) +} + +// DefaultOpenMetricsAcceptedFormats returns a copy of standard accepted formats including +// stable OpenMetrics formats, ordered by preference. +func DefaultOpenMetricsAcceptedFormats() []Format { + return slices.Clone(defaultOpenMetricsAcceptedFormats) +} + // Encoder types encode metric families into an underlying wire protocol. type Encoder interface { Encode(*dto.MetricFamily) error @@ -57,77 +113,106 @@ func (ec encoderCloser) Close() error { // Negotiate returns the Content-Type based on the given Accept header. If no // appropriate accepted type is found, FmtText is returned (which is the -// Prometheus text format). This function will never negotiate FmtOpenMetrics, -// as the support is still experimental. To include the option to negotiate -// FmtOpenMetrics, use NegotiateIncludingOpenMetrics. +// Prometheus text format). +// +// Deprecated: Use NegotiateAccept(h, DefaultAcceptedFormats()...) +// or specify only the formats supported by your server. func Negotiate(h http.Header) Format { - escapingScheme := Format(fmt.Sprintf("; escaping=%s", Format(model.NameEscapingScheme.String()))) + return NegotiateAccept(h, defaultAcceptedFormats...) +} + +// NegotiateIncludingOpenMetrics works like Negotiate but includes all stable +// FmtOpenMetrics formats as an option for the result. +// +// Deprecated: Use NegotiateAccept(h, DefaultOpenMetricsAcceptedFormats()...) +// or specify only the formats supported by your server. +func NegotiateIncludingOpenMetrics(h http.Header) Format { + return NegotiateAccept(h, defaultOpenMetricsAcceptedFormats...) +} + +// NegotiateAccept returns the Content-Type based on the given Accept header +// and the list of accepted Formats provided by the caller, in order of preference. +// If no accepted format matches the Accept header, it falls back to the text +// format if present in the accepted list, or the first accepted format (or FmtText +// if accepted is empty). +// The escaping scheme is taken from the matching Accept clause. Without one, +// OpenMetrics 2.0 gets allow-utf-8 and all other formats model.NameEscapingScheme. +func NegotiateAccept(h http.Header, accepted ...Format) Format { + escapingScheme := Format("; escaping=" + model.NameEscapingScheme.String()) for _, ac := range goautoneg.ParseAccept(h.Get(hdrAccept)) { - if escapeParam := ac.Params[model.EscapingKey]; escapeParam != "" { - switch Format(escapeParam) { - case model.AllowUTF8, model.EscapeUnderscores, model.EscapeDots, model.EscapeValues: - escapingScheme = Format("; escaping=" + escapeParam) - default: - // If the escaping parameter is unknown, ignore it. + for _, f := range accepted { + if matchFormat(ac, f) { + return f + escapingFor(ac, f) } } - ver := ac.Params["version"] - if ac.Type+"/"+ac.SubType == ProtoType && ac.Params["proto"] == ProtoProtocol { - switch ac.Params["encoding"] { - case "delimited": - return FmtProtoDelim + escapingScheme - case "text": - return FmtProtoText + escapingScheme - case "compact-text": - return FmtProtoCompact + escapingScheme - } - } - if ac.Type == "text" && ac.SubType == "plain" && (ver == TextVersion || ver == "") { - return FmtText + escapingScheme + } + for _, f := range accepted { + if f.FormatType() == TypeTextPlain { + return f + escapingScheme } } + if len(accepted) > 0 { + return accepted[0] + escapingScheme + } return FmtText + escapingScheme } -// NegotiateIncludingOpenMetrics works like Negotiate but includes -// FmtOpenMetrics as an option for the result. Note that this function is -// temporary and will disappear once FmtOpenMetrics is fully supported and as -// such may be negotiated by the normal Negotiate function. -func NegotiateIncludingOpenMetrics(h http.Header) Format { - escapingScheme := Format(fmt.Sprintf("; escaping=%s", Format(model.NameEscapingScheme.String()))) - for _, ac := range goautoneg.ParseAccept(h.Get(hdrAccept)) { - if escapeParam := ac.Params[model.EscapingKey]; escapeParam != "" { - switch Format(escapeParam) { - case model.AllowUTF8, model.EscapeUnderscores, model.EscapeDots, model.EscapeValues: - escapingScheme = Format("; escaping=" + escapeParam) - default: - // If the escaping parameter is unknown, ignore it. - } +// escapingFor returns the escaping term for the Accept clause that matched f. +func escapingFor(ac goautoneg.Accept, f Format) Format { + switch p := ac.Params[model.EscapingKey]; p { + case model.AllowUTF8, model.EscapeUnderscores, model.EscapeDots, model.EscapeValues: + // An explicit request always wins, also for OpenMetrics 2.0. + return Format("; escaping=" + p) + } + if f.FormatType() == TypeOpenMetrics && isOpenMetrics20Version(f.Version()) { + // OpenMetrics 2.0 is UTF-8 native, so asking for it implies UTF-8 name support. + return Format("; escaping=" + model.AllowUTF8) + } + return Format("; escaping=" + model.NameEscapingScheme.String()) +} + +// matchFormat checks if a parsed accept clause matches a given Format. +func matchFormat(ac goautoneg.Accept, f Format) bool { + target, ok := formatToAccept[f] + if !ok { + parsed := goautoneg.ParseAccept(string(f)) + if len(parsed) == 0 { + return false } - ver := ac.Params["version"] - if ac.Type+"/"+ac.SubType == ProtoType && ac.Params["proto"] == ProtoProtocol { - switch ac.Params["encoding"] { - case "delimited": - return FmtProtoDelim + escapingScheme - case "text": - return FmtProtoText + escapingScheme - case "compact-text": - return FmtProtoCompact + escapingScheme - } + target = parsed[0] + } + + if ac.Type != "*" && ac.Type != target.Type { + return false + } + if ac.SubType != "*" && ac.SubType != target.SubType { + return false + } + + // Default OpenMetrics version to OpenMetricsVersion_0_0_1. + acVersion := ac.Params["version"] + if acVersion == "" && ac.Type+"/"+ac.SubType == OpenMetricsType { + acVersion = OpenMetricsVersion_0_0_1 + } + if acVersion == "" && ac.Type == "text" && ac.SubType == "plain" { + acVersion = TextVersion + } + + // General param matching. + for k, v := range target.Params { + if k == "charset" { + continue } - if ac.Type == "text" && ac.SubType == "plain" && (ver == TextVersion || ver == "") { - return FmtText + escapingScheme + acVal := ac.Params[k] + if k == "version" { + acVal = acVersion } - if ac.Type+"/"+ac.SubType == OpenMetricsType && (ver == OpenMetricsVersion_0_0_1 || ver == OpenMetricsVersion_1_0_0 || ver == "") { - switch ver { - case OpenMetricsVersion_1_0_0: - return FmtOpenMetrics_1_0_0 + escapingScheme - default: - return FmtOpenMetrics_0_0_1 + escapingScheme - } + if acVal != v { + return false } } - return FmtText + escapingScheme + + return true } // NewEncoder returns a new encoder based on content type negotiation. All @@ -181,6 +266,19 @@ func NewEncoder(w io.Writer, format Format, options ...EncoderOption) Encoder { close: func() error { return nil }, } case TypeOpenMetrics: + _, params, err := mime.ParseMediaType(string(format)) + if err == nil && isOpenMetrics20Version(params["version"]) { + return encoderCloser{ + encode: func(v *dto.MetricFamily) error { + _, err := MetricFamilyToOpenMetrics20(w, model.EscapeMetricFamily(v, escapingScheme), options...) + return err + }, + close: func() error { + _, err := FinalizeOpenMetrics(w) + return err + }, + } + } return encoderCloser{ encode: func(v *dto.MetricFamily) error { _, err := MetricFamilyToOpenMetrics(w, model.EscapeMetricFamily(v, escapingScheme), options...) diff --git a/vendor/github.com/prometheus/common/expfmt/expfmt.go b/vendor/github.com/prometheus/common/expfmt/expfmt.go index 10bf357..fd994b2 100644 --- a/vendor/github.com/prometheus/common/expfmt/expfmt.go +++ b/vendor/github.com/prometheus/common/expfmt/expfmt.go @@ -16,50 +16,56 @@ package expfmt import ( "errors" + "mime" "strings" "github.com/prometheus/common/model" ) -// Format specifies the HTTP content type of the different wire protocols. -type Format string - // Constants to assemble the Content-Type values for the different wire -// protocols. The Content-Type strings here are all for the legacy exposition -// formats, where valid characters for metric names and label names are limited. -// Support for arbitrary UTF-8 characters in those names is already partially -// implemented in this module (see model.ValidationScheme), but to actually use -// it on the wire, new content-type strings will have to be agreed upon and -// added here. +// protocols. const ( - TextVersion = "0.0.4" - ProtoType = `application/vnd.google.protobuf` - ProtoProtocol = `io.prometheus.client.MetricFamily` - // Deprecated: Use expfmt.NewFormat(expfmt.TypeProtoCompact) instead. - ProtoFmt = ProtoType + "; proto=" + ProtoProtocol + ";" + TextVersion = "0.0.4" + //nolint:revive // Allow for underscores. + TextVersion_1_0_0 = "1.0.0" + ProtoType = `application/vnd.google.protobuf` + ProtoProtocol = `io.prometheus.client.MetricFamily` + ProtoFmt = ProtoType + "; proto=" + ProtoProtocol + ";" + OpenMetricsType = `application/openmetrics-text` //nolint:revive // Allow for underscores. OpenMetricsVersion_0_0_1 = "0.0.1" //nolint:revive // Allow for underscores. OpenMetricsVersion_1_0_0 = "1.0.0" + //nolint:revive // Allow for underscores. + OpenMetricsVersion_2_0_0_rc = "2.0.0-rc" + //nolint:revive // Allow for underscores. + OpenMetricsVersion_2_0_0 = "2.0.0" +) - // The Content-Type values for the different wire protocols. Do not do direct - // comparisons to these constants, instead use the comparison functions. - // - // Deprecated: Use expfmt.NewFormat(expfmt.TypeUnknown) instead. +// Format specifies the HTTP content type of the different wire protocols. +// The Content-Type values for the different wire protocols represent +// baseline Content-Types used for HTTP headers and content negotiation. +// +// Because Content-Types on the wire may include dynamic parameters +// (such as "; escaping=...") or whitespace variations, avoid comparing Format +// values using direct equality (==). +type Format string + +const ( FmtUnknown Format = `` - // Deprecated: Use expfmt.NewFormat(expfmt.TypeTextPlain) instead. - FmtText Format = `text/plain; version=` + TextVersion + `; charset=utf-8` - // Deprecated: Use expfmt.NewFormat(expfmt.TypeProtoDelim) instead. - FmtProtoDelim Format = ProtoFmt + ` encoding=delimited` - // Deprecated: Use expfmt.NewFormat(expfmt.TypeProtoText) instead. - FmtProtoText Format = ProtoFmt + ` encoding=text` - // Deprecated: Use expfmt.NewFormat(expfmt.TypeProtoCompact) instead. + FmtText Format = `text/plain; version=` + TextVersion + `; charset=utf-8` + //nolint:revive // Allow for underscores. + FmtText_1_0_0 Format = `text/plain; version=` + TextVersion_1_0_0 + `; charset=utf-8` + FmtProtoDelim Format = ProtoFmt + ` encoding=delimited` + FmtProtoText Format = ProtoFmt + ` encoding=text` FmtProtoCompact Format = ProtoFmt + ` encoding=compact-text` - // Deprecated: Use expfmt.NewFormat(expfmt.TypeOpenMetrics) instead. + //nolint:revive // Allow for underscores. + FmtOpenMetrics_2_0_0 Format = OpenMetricsType + `; version=` + OpenMetricsVersion_2_0_0 + `; charset=utf-8` + //nolint:revive // Allow for underscores. + FmtOpenMetrics_2_0_0_rc Format = OpenMetricsType + `; version=` + OpenMetricsVersion_2_0_0_rc + `; charset=utf-8` //nolint:revive // Allow for underscores. FmtOpenMetrics_1_0_0 Format = OpenMetricsType + `; version=` + OpenMetricsVersion_1_0_0 + `; charset=utf-8` - // Deprecated: Use expfmt.NewFormat(expfmt.TypeOpenMetrics) instead. //nolint:revive // Allow for underscores. FmtOpenMetrics_0_0_1 Format = OpenMetricsType + `; version=` + OpenMetricsVersion_0_0_1 + `; charset=utf-8` ) @@ -86,8 +92,8 @@ const ( // NewFormat generates a new Format from the type provided. Mostly used for // tests, most Formats should be generated as part of content negotiation in -// encode.go. If a type has more than one version, the latest version will be -// returned. +// encode.go. If a type has more than one version, the latest stable version will be +// returned, except that TypeTextPlain retains version 0.0.4 for compatibility. func NewFormat(t FormatType) Format { switch t { case TypeProtoCompact: @@ -107,37 +113,39 @@ func NewFormat(t FormatType) Format { // NewOpenMetricsFormat generates a new OpenMetrics format matching the // specified version number. +// +// Note: OpenMetrics versions 2.0.0-rc and 2.0.0 are experimental (supporting +// counter, gauge, summary, untyped, histogram, and gaugehistogram metric types). func NewOpenMetricsFormat(version string) (Format, error) { - if version == OpenMetricsVersion_0_0_1 { + switch version { + case OpenMetricsVersion_0_0_1: return FmtOpenMetrics_0_0_1, nil - } - if version == OpenMetricsVersion_1_0_0 { + case OpenMetricsVersion_1_0_0: return FmtOpenMetrics_1_0_0, nil + case OpenMetricsVersion_2_0_0_rc: + // OpenMetrics 2.0.0-rc is experimental. + return FmtOpenMetrics_2_0_0_rc, nil + case OpenMetricsVersion_2_0_0: + // OpenMetrics 2.0.0 is experimental. + return FmtOpenMetrics_2_0_0, nil + default: + return FmtUnknown, errors.New("unknown open metrics version string") } - return FmtUnknown, errors.New("unknown open metrics version string") } -// WithEscapingScheme returns a copy of Format with the specified escaping -// scheme appended to the end. If an escaping scheme already exists it is -// removed. -func (f Format) WithEscapingScheme(s model.EscapingScheme) Format { - var terms []string - for p := range strings.SplitSeq(string(f), ";") { - toks := strings.Split(p, "=") - if len(toks) != 2 { - trimmed := strings.TrimSpace(p) - if len(trimmed) > 0 { - terms = append(terms, trimmed) - } - continue - } - key := strings.TrimSpace(toks[0]) - if key != model.EscapingKey { - terms = append(terms, strings.TrimSpace(p)) - } +func isOpenMetrics20Version(v string) bool { + return v == OpenMetricsVersion_2_0_0 || v == OpenMetricsVersion_2_0_0_rc +} + +// Version returns the version parameter without validating whether it is supported. +// It returns an empty string if the parameter is absent or the Content-Type +// cannot be parsed. +func (f Format) Version() string { + _, params, err := mime.ParseMediaType(string(f)) + if err != nil { + return "" } - terms = append(terms, model.EscapingKey+"="+s.String()) - return Format(strings.Join(terms, "; ")) + return params["version"] } // FormatType deduces an overall FormatType for the given format. @@ -180,7 +188,7 @@ func (f Format) FormatType() FormatType { if !ok { return TypeTextPlain } - if v == TextVersion { + if v == TextVersion || v == TextVersion_1_0_0 { return TypeTextPlain } return TypeUnknown @@ -189,8 +197,31 @@ func (f Format) FormatType() FormatType { } } -// ToEscapingScheme returns an EscapingScheme depending on the Format. Iff the -// Format contains a escaping=allow-utf-8 term, it will select NoEscaping. If a valid +// WithEscapingScheme returns a copy of Format with the specified escaping +// scheme appended to the end. If an escaping scheme already exists it is +// removed. +func (f Format) WithEscapingScheme(s model.EscapingScheme) Format { + var terms []string + for p := range strings.SplitSeq(string(f), ";") { + toks := strings.Split(p, "=") + if len(toks) != 2 { + trimmed := strings.TrimSpace(p) + if len(trimmed) > 0 { + terms = append(terms, trimmed) + } + continue + } + key := strings.TrimSpace(toks[0]) + if key != model.EscapingKey { + terms = append(terms, strings.TrimSpace(p)) + } + } + terms = append(terms, model.EscapingKey+"="+s.String()) + return Format(strings.Join(terms, "; ")) +} + +// ToEscapingScheme returns an EscapingScheme depending on the Format. IFF the +// Format contains an escaping=allow-utf-8 term, it will select NoEscaping. If a valid // "escaping" term exists, that will be used. Otherwise, the global default will // be returned. func (f Format) ToEscapingScheme() model.EscapingScheme { diff --git a/vendor/github.com/prometheus/common/expfmt/openmetrics_2_0_create.go b/vendor/github.com/prometheus/common/expfmt/openmetrics_2_0_create.go new file mode 100644 index 0000000..47a88f7 --- /dev/null +++ b/vendor/github.com/prometheus/common/expfmt/openmetrics_2_0_create.go @@ -0,0 +1,1220 @@ +// Copyright The Prometheus Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package expfmt + +import ( + "bufio" + "errors" + "fmt" + "io" + "math" + "strconv" + "strings" + "unicode/utf8" + + dto "github.com/prometheus/client_model/go" + "google.golang.org/protobuf/types/known/timestamppb" + + "github.com/prometheus/common/model" +) + +// MetricFamilyToOpenMetrics20 converts a MetricFamily proto message into the +// OpenMetrics text format version 2.0.0 and writes the resulting lines to 'out'. +// It returns the number of bytes written and any error encountered. +// +// NOTE: This method targets OpenMetrics 2.0.0 (currently aligned with 2.0-rc.0) which is experimental. +// All metric types defined in client_model (counter, gauge, summary, untyped, histogram, +// and gaugehistogram) are supported; info and stateset are not supported as they are not present in +// client_model. Breaking changes might happen in the future. +// EncoderOptions are accepted for signature compatibility with +// MetricFamilyToOpenMetrics and are currently ignored. +// +// OpenMetrics 2.0 enforces stricter validation rules defined in the specification +// than Prometheus text or OpenMetrics 1.0 formats (such as requiring non-negative +// count and sum, and non-negative quantile values for summaries). Consequently, +// MetricFamilyToOpenMetrics20 may reject metric families that the other encoders accept. +func MetricFamilyToOpenMetrics20(out io.Writer, in *dto.MetricFamily, options ...EncoderOption) (written int, err error) { + // Options are accepted for signature compatibility and ignored. + _ = options + name := in.GetName() + if name == "" { + return 0, fmt.Errorf("MetricFamily has no name: %s", in) + } + if containsRawNewline(name) { + return 0, fmt.Errorf("MetricFamily name %q contains raw newlines", name) + } + if !utf8.ValidString(name) { + return 0, fmt.Errorf("MetricFamily name %q is not valid UTF-8", name) + } + if in.Help != nil { + if !utf8.ValidString(*in.Help) { + return 0, fmt.Errorf("MetricFamily help %q is not valid UTF-8", *in.Help) + } + // A carriage return may appear in HELP, but not at the end, where it + // would make the line end in "\r\n". + if strings.HasSuffix(*in.Help, "\r") { + return 0, fmt.Errorf("MetricFamily help %q ends with a carriage return", *in.Help) + } + } + if in.Unit != nil { + if containsRawNewline(*in.Unit) { + return 0, fmt.Errorf("MetricFamily unit %q contains raw newlines", *in.Unit) + } + if !utf8.ValidString(*in.Unit) { + return 0, fmt.Errorf("MetricFamily unit %q is not valid UTF-8", *in.Unit) + } + } + + // Try the interface upgrade. If it doesn't work, we'll use a + // bufio.Writer from the sync.Pool. + w, ok := out.(enhancedWriter) + if !ok { + b := bufPool.Get().(*bufio.Writer) + b.Reset(out) + w = b + defer func() { + bErr := b.Flush() + if err == nil { + err = bErr + } + bufPool.Put(b) + }() + } + + var ( + n int + metricType = in.GetType() + ) + + // Comments, first HELP, then TYPE. + if in.Help != nil { + n, err = w.WriteString("# HELP ") + written += n + if err != nil { + return written, err + } + n, err = writeName(w, name) + written += n + if err != nil { + return written, err + } + err = w.WriteByte(' ') + written++ + if err != nil { + return written, err + } + n, err = writeEscapedString(w, *in.Help, true) + written += n + if err != nil { + return written, err + } + err = w.WriteByte('\n') + written++ + if err != nil { + return written, err + } + } + n, err = w.WriteString("# TYPE ") + written += n + if err != nil { + return written, err + } + n, err = writeName(w, name) + written += n + if err != nil { + return written, err + } + switch metricType { + case dto.MetricType_COUNTER: + n, err = w.WriteString(" counter\n") + case dto.MetricType_GAUGE: + n, err = w.WriteString(" gauge\n") + case dto.MetricType_SUMMARY: + n, err = w.WriteString(" summary\n") + case dto.MetricType_UNTYPED: + n, err = w.WriteString(" unknown\n") + case dto.MetricType_HISTOGRAM: + n, err = w.WriteString(" histogram\n") + case dto.MetricType_GAUGE_HISTOGRAM: + n, err = w.WriteString(" gaugehistogram\n") + default: + // TODO: Support Info and StateSet once they are supported in the + // Prometheus protobuf format. + return written, fmt.Errorf("unknown metric type %s", metricType.String()) + } + written += n + if err != nil { + return written, err + } + if in.Unit != nil { + n, err = w.WriteString("# UNIT ") + written += n + if err != nil { + return written, err + } + n, err = writeName(w, name) + written += n + if err != nil { + return written, err + } + + err = w.WriteByte(' ') + written++ + if err != nil { + return written, err + } + n, err = writeEscapedString(w, *in.Unit, true) + written += n + if err != nil { + return written, err + } + err = w.WriteByte('\n') + written++ + if err != nil { + return written, err + } + } + + // Finally the samples, one line for each. + for _, metric := range in.Metric { + if metric == nil { + return written, fmt.Errorf("expected non-nil metric in MetricFamily %s", name) + } + switch metricType { + case dto.MetricType_COUNTER: + if metric.Counter == nil { + return written, fmt.Errorf("expected counter in metric %s %s", name, metric) + } + val := metric.Counter.GetValue() + if math.IsNaN(val) { + return written, fmt.Errorf("counter value cannot be NaN in metric %s", name) + } + if val < 0 { + return written, fmt.Errorf("counter value cannot be negative (%g) in metric %s", val, name) + } + n, err = writeOpenMetrics20Sample(w, name, metric, val, 0, false, metric.Counter.CreatedTimestamp, metric.Counter.Exemplar) + case dto.MetricType_GAUGE: + if metric.Gauge == nil { + return written, fmt.Errorf("expected gauge in metric %s %s", name, metric) + } + n, err = writeOpenMetrics20Sample(w, name, metric, metric.Gauge.GetValue(), 0, false, nil, nil) + case dto.MetricType_UNTYPED: + if metric.Untyped == nil { + return written, fmt.Errorf("expected untyped in metric %s %s", name, metric) + } + n, err = writeOpenMetrics20Sample(w, name, metric, metric.Untyped.GetValue(), 0, false, nil, nil) + case dto.MetricType_SUMMARY: + if metric.Summary == nil { + return written, fmt.Errorf("expected summary in metric %s %s", name, metric) + } + n, err = writeCompositeSummary(w, name, metric) + case dto.MetricType_HISTOGRAM, dto.MetricType_GAUGE_HISTOGRAM: + if metric.Histogram == nil { + return written, fmt.Errorf("expected histogram in metric %s %s", name, metric) + } + n, err = writeCompositeHistogram(w, name, metric, metricType == dto.MetricType_GAUGE_HISTOGRAM) + default: + return written, fmt.Errorf("unexpected type in metric %s %s", name, metric) + } + written += n + if err != nil { + return written, err + } + } + return written, nil +} + +// writeOpenMetrics20Sample writes a single sample for simple types (Counter, Gauge, Untyped). +func writeOpenMetrics20Sample(w enhancedWriter, name string, metric *dto.Metric, floatValue float64, intValue uint64, useIntValue bool, startTimestamp *timestamppb.Timestamp, exemplar *dto.Exemplar) (int, error) { + if err := validateLabels20(metric.Label); err != nil { + return 0, err + } + written := 0 + n, err := writeOpenMetricsNameAndLabelPairs(w, name, metric.Label, "", 0) + written += n + if err != nil { + return written, err + } + err = w.WriteByte(' ') + written++ + if err != nil { + return written, err + } + + if useIntValue { + n, err = writeUint(w, intValue) + } else { + n, err = writeOpenMetricsFloat(w, floatValue) + } + written += n + if err != nil { + return written, err + } + + if metric.TimestampMs != nil { + err = w.WriteByte(' ') + written++ + if err != nil { + return written, err + } + n, err = writeOpenMetrics20Timestamp(w, float64(*metric.TimestampMs)/1000) + written += n + if err != nil { + return written, err + } + } + + // Start Timestamp + if startTimestamp != nil { + if err := startTimestamp.CheckValid(); err != nil { + return written, fmt.Errorf("invalid created timestamp in metric %s: %w", name, err) + } + n, err = w.WriteString(" st@") + written += n + if err != nil { + return written, err + } + n, err = writeProtoTimestamp(w, startTimestamp) + written += n + if err != nil { + return written, err + } + } + + if exemplar != nil { + n, err = writeExemplar20(w, exemplar) + written += n + if err != nil { + return written, err + } + } + + err = w.WriteByte('\n') + written++ + if err != nil { + return written, err + } + return written, nil +} + +// writeExemplar20 writes the provided exemplar in OpenMetrics 2.0 format to w. +// In OpenMetrics 2.0, invalid exemplars or exemplars without a timestamp are dropped. +func writeExemplar20(w enhancedWriter, e *dto.Exemplar) (int, error) { + if e == nil { + return 0, nil + } + // In OpenMetrics 2.0, invalid exemplars are dropped rather than failing the entire exposition. + if err := validateExemplar20(e); err != nil { + return 0, nil + } + written := 0 + n, err := w.WriteString(" # ") + written += n + if err != nil { + return written, err + } + if len(e.Label) == 0 { + n, err = w.WriteString("{}") + } else { + n, err = writeOpenMetricsNameAndLabelPairs(w, "", e.Label, "", 0) + } + written += n + if err != nil { + return written, err + } + err = w.WriteByte(' ') + written++ + if err != nil { + return written, err + } + n, err = writeOpenMetricsFloat(w, e.GetValue()) + written += n + if err != nil { + return written, err + } + err = w.WriteByte(' ') + written++ + if err != nil { + return written, err + } + ts := e.Timestamp + n, err = writeProtoTimestamp(w, ts) + written += n + if err != nil { + return written, err + } + return written, nil +} + +// writeOpenMetrics20Timestamp writes a float64 as a timestamp without scientific notation. +func writeOpenMetrics20Timestamp(w enhancedWriter, f float64) (int, error) { + bp := numBufPool.Get().(*[]byte) + *bp = strconv.AppendFloat((*bp)[:0], f, 'f', -1, 64) + written, err := w.Write(*bp) + numBufPool.Put(bp) + return written, err +} + +func writeCompositeSummary(w enhancedWriter, name string, metric *dto.Metric) (int, error) { + s := metric.Summary + if s == nil { + return 0, fmt.Errorf("expected summary in metric %s", name) + } + + if err := validateLabels20(metric.Label); err != nil { + return 0, err + } + for _, lp := range metric.Label { + if lp.GetName() == "quantile" { + return 0, fmt.Errorf("metric %s is a summary but label set contains %q label", name, "quantile") + } + } + + sum := s.GetSampleSum() + if math.IsNaN(sum) { + return 0, fmt.Errorf("summary sum cannot be NaN in metric %s", name) + } + + var prevQuantile float64 + for i, q := range s.Quantile { + if q == nil { + return 0, fmt.Errorf("expected non-nil quantile in metric %s", name) + } + qv := q.GetQuantile() + if math.IsNaN(qv) { + return 0, fmt.Errorf("summary quantile cannot be NaN in metric %s", name) + } + if qv < 0 || qv > 1 { + return 0, fmt.Errorf("summary quantile %g must be between 0 and 1 in metric %s", qv, name) + } + if i > 0 && qv <= prevQuantile { + return 0, fmt.Errorf("summary quantiles must be strictly increasing: %g <= %g in metric %s", qv, prevQuantile, name) + } + prevQuantile = qv + } + + if s.CreatedTimestamp != nil { + if err := s.CreatedTimestamp.CheckValid(); err != nil { + return 0, fmt.Errorf("invalid created timestamp in metric %s: %w", name, err) + } + } + + written := 0 + n, err := writeOpenMetricsNameAndLabelPairs(w, name, metric.Label, "", 0) + written += n + if err != nil { + return written, err + } + + n, err = w.WriteString(" {count:") + written += n + if err != nil { + return written, err + } + + n, err = writeUint(w, s.GetSampleCount()) + written += n + if err != nil { + return written, err + } + + n, err = w.WriteString(",sum:") + written += n + if err != nil { + return written, err + } + + n, err = writeFloat(w, sum) + written += n + if err != nil { + return written, err + } + + n, err = w.WriteString(",quantile:[") + written += n + if err != nil { + return written, err + } + + for i, q := range s.Quantile { + if i > 0 { + err = w.WriteByte(',') + written++ + if err != nil { + return written, err + } + } + n, err = writeFloat(w, q.GetQuantile()) + written += n + if err != nil { + return written, err + } + err = w.WriteByte(':') + written++ + if err != nil { + return written, err + } + n, err = writeFloat(w, q.GetValue()) + written += n + if err != nil { + return written, err + } + } + + n, err = w.WriteString("]}") + written += n + if err != nil { + return written, err + } + + if metric.TimestampMs != nil { + err = w.WriteByte(' ') + written++ + if err != nil { + return written, err + } + n, err = writeOpenMetrics20Timestamp(w, float64(*metric.TimestampMs)/1000) + written += n + if err != nil { + return written, err + } + } + + if s.CreatedTimestamp != nil { + n, err = w.WriteString(" st@") + written += n + if err != nil { + return written, err + } + n, err = writeProtoTimestamp(w, s.CreatedTimestamp) + written += n + if err != nil { + return written, err + } + } + + err = w.WriteByte('\n') + written++ + if err != nil { + return written, err + } + + return written, nil +} + +func writeCompositeHistogram(w enhancedWriter, name string, metric *dto.Metric, isGauge bool) (int, error) { + h := metric.Histogram + if h == nil { + return 0, fmt.Errorf("expected histogram in metric %s", name) + } + + isNative := h.Schema != nil + hasClassicBuckets := len(h.Bucket) > 0 || !isNative + + if err := validateLabels20(metric.Label); err != nil { + return 0, err + } + if hasClassicBuckets { + for _, lp := range metric.Label { + if lp.GetName() == "le" { + return 0, fmt.Errorf("metric %s has classic buckets but label set contains %q label", name, "le") + } + } + } + + if h.SampleCountFloat != nil { + c := *h.SampleCountFloat + if math.IsNaN(c) { + if isGauge { + return 0, fmt.Errorf("gaugehistogram count cannot be NaN in metric %s", name) + } + return 0, fmt.Errorf("histogram count cannot be NaN in metric %s", name) + } + if c < 0 { + if isGauge { + return 0, fmt.Errorf("gaugehistogram count cannot be negative (%g) in metric %s", c, name) + } + return 0, fmt.Errorf("histogram count cannot be negative (%g) in metric %s", c, name) + } + } + + var isFloatCount bool + var sampleCountFloat float64 + var sampleCountUint uint64 + switch { + case h.SampleCountFloat != nil && (*h.SampleCountFloat > 0 || h.SampleCount == nil || isGauge): + isFloatCount = true + sampleCountFloat = *h.SampleCountFloat + case h.SampleCount != nil: + sampleCountUint = *h.SampleCount + sampleCountFloat = float64(sampleCountUint) + } + + if isNative { + if err := validateNativeHistogram(name, h); err != nil { + return 0, err + } + } + + if hasClassicBuckets { + if err := validateClassicBuckets(name, h, sampleCountFloat, sampleCountUint, isFloatCount, isGauge); err != nil { + return 0, err + } + } + + if !isGauge && h.CreatedTimestamp != nil { + if err := h.CreatedTimestamp.CheckValid(); err != nil { + return 0, fmt.Errorf("invalid created timestamp in metric %s: %w", name, err) + } + } + + written := 0 + n, err := writeOpenMetricsNameAndLabelPairs(w, name, metric.Label, "", 0) + written += n + if err != nil { + return written, err + } + + n, err = w.WriteString(" {") + written += n + if err != nil { + return written, err + } + + if isGauge { + n, err = w.WriteString("gcount:") + } else { + n, err = w.WriteString("count:") + } + written += n + if err != nil { + return written, err + } + + if isFloatCount { + n, err = writeFloat(w, sampleCountFloat) + } else { + n, err = writeUint(w, sampleCountUint) + } + written += n + if err != nil { + return written, err + } + + if isGauge { + n, err = w.WriteString(",gsum:") + } else { + n, err = w.WriteString(",sum:") + } + written += n + if err != nil { + return written, err + } + n, err = writeFloat(w, h.GetSampleSum()) + written += n + if err != nil { + return written, err + } + + if isNative { + n, err = writeNativeBuckets(w, h, isGauge) + written += n + if err != nil { + return written, err + } + } + + var classicExemplars []*dto.Exemplar + if hasClassicBuckets { + n, err = writeClassicBuckets(w, h, sampleCountFloat, sampleCountUint, isFloatCount, isGauge, &classicExemplars) + written += n + if err != nil { + return written, err + } + } + + err = w.WriteByte('}') + written++ + if err != nil { + return written, err + } + + if metric.TimestampMs != nil { + err = w.WriteByte(' ') + written++ + if err != nil { + return written, err + } + n, err = writeOpenMetrics20Timestamp(w, float64(*metric.TimestampMs)/1000) + written += n + if err != nil { + return written, err + } + } + + if !isGauge && h.CreatedTimestamp != nil { + ts := h.CreatedTimestamp + n, err = w.WriteString(" st@") + written += n + if err != nil { + return written, err + } + n, err = writeProtoTimestamp(w, ts) + written += n + if err != nil { + return written, err + } + } + + var exemplarsToEmit []*dto.Exemplar + if len(classicExemplars) > 0 { + // We follow the spec suggestion and prefer classic histogram + // exemplars in dual mode. + exemplarsToEmit = classicExemplars + } else if len(h.Exemplars) > 0 { + exemplarsToEmit = h.Exemplars + } + + for _, e := range exemplarsToEmit { + if e == nil || e.Timestamp == nil { + continue + } + n, err = writeExemplar20(w, e) + written += n + if err != nil { + return written, err + } + } + + err = w.WriteByte('\n') + written++ + if err != nil { + return written, err + } + + return written, nil +} + +func validateNativeHistogram(name string, h *dto.Histogram) error { + schema := *h.Schema + if schema < -4 || schema > 8 { + return fmt.Errorf("native histogram schema %d is out of range [-4, 8] in metric %s", schema, name) + } + + zeroThreshold := h.GetZeroThreshold() + if math.IsNaN(zeroThreshold) || math.IsInf(zeroThreshold, 0) || zeroThreshold < 0 { + return fmt.Errorf("native histogram zero_threshold %g must be a non-negative, finite number in metric %s", zeroThreshold, name) + } + + if h.ZeroCountFloat != nil { + c := *h.ZeroCountFloat + if math.IsNaN(c) { + return fmt.Errorf("native histogram zero_count cannot be NaN in metric %s", name) + } + if c < 0 { + return fmt.Errorf("native histogram zero_count cannot be negative (%g) in metric %s", c, name) + } + } + + if err := validateSpansAndBuckets(name, "negative", h.NegativeSpan, h.NegativeDelta, h.NegativeCount); err != nil { + return err + } + return validateSpansAndBuckets(name, "positive", h.PositiveSpan, h.PositiveDelta, h.PositiveCount) +} + +func validateSpansAndBuckets( + name string, + spanName string, + spans []*dto.BucketSpan, + deltas []int64, + floatCounts []float64, +) error { + isFloatBuckets := len(floatCounts) > 0 + var numBuckets int + if isFloatBuckets { + numBuckets = len(floatCounts) + } else { + numBuckets = len(deltas) + } + + var totalLength uint64 + for i, span := range spans { + if span == nil { + return errors.New("expected non-nil bucket span") + } + if i > 0 && span.GetOffset() < 0 { + return fmt.Errorf("subsequent %s span offset cannot be negative: %d in metric %s", spanName, span.GetOffset(), name) + } + totalLength += uint64(span.GetLength()) + } + + if numBuckets == 0 { + if totalLength == 0 { + return nil + } + return fmt.Errorf("sum of %s span lengths (%d) does not match bucket count (0) in metric %s", spanName, totalLength, name) + } + + if totalLength != uint64(numBuckets) { + return fmt.Errorf("sum of %s span lengths (%d) does not match bucket count (%d) in metric %s", spanName, totalLength, numBuckets, name) + } + + if isFloatBuckets { + for _, v := range floatCounts { + if math.IsNaN(v) { + return fmt.Errorf("%s bucket count cannot be NaN in metric %s", spanName, name) + } + if v < 0 { + return fmt.Errorf("%s bucket count cannot be negative (%g) in metric %s", spanName, v, name) + } + } + } else { + var current int64 + for _, d := range deltas { + current += d + if current < 0 { + return fmt.Errorf("%s bucket count cannot be negative (%d) in metric %s", spanName, current, name) + } + } + } + return nil +} + +func writeNativeBuckets(w enhancedWriter, h *dto.Histogram, isGauge bool) (int, error) { + schema := *h.Schema + zeroThreshold := h.GetZeroThreshold() + + var isFloatZeroCount bool + var zeroCountFloat float64 + var zeroCountUint uint64 + switch { + case h.ZeroCountFloat != nil && (*h.ZeroCountFloat > 0 || h.ZeroCount == nil || isGauge): + isFloatZeroCount = true + zeroCountFloat = *h.ZeroCountFloat + case h.ZeroCount != nil: + zeroCountUint = *h.ZeroCount + zeroCountFloat = float64(zeroCountUint) + } + + written := 0 + n, err := w.WriteString(",schema:") + written += n + if err != nil { + return written, err + } + n, err = writeInt(w, int64(schema)) + written += n + if err != nil { + return written, err + } + + n, err = w.WriteString(",zero_threshold:") + written += n + if err != nil { + return written, err + } + n, err = writeFloat(w, zeroThreshold) + written += n + if err != nil { + return written, err + } + + n, err = w.WriteString(",zero_count:") + written += n + if err != nil { + return written, err + } + if isFloatZeroCount { + n, err = writeFloat(w, zeroCountFloat) + } else { + n, err = writeUint(w, zeroCountUint) + } + written += n + if err != nil { + return written, err + } + + n, err = writeSpansAndBuckets(w, ",negative_spans:[", ",negative_buckets:[", h.NegativeSpan, h.NegativeDelta, h.NegativeCount) + written += n + if err != nil { + return written, err + } + + n, err = writeSpansAndBuckets(w, ",positive_spans:[", ",positive_buckets:[", h.PositiveSpan, h.PositiveDelta, h.PositiveCount) + written += n + if err != nil { + return written, err + } + + return written, nil +} + +func writeSpansAndBuckets( + w enhancedWriter, + spansPrefix string, + bucketsPrefix string, + spans []*dto.BucketSpan, + deltas []int64, + floatCounts []float64, +) (int, error) { + isFloatBuckets := len(floatCounts) > 0 + var numBuckets int + if isFloatBuckets { + numBuckets = len(floatCounts) + } else { + numBuckets = len(deltas) + } + + if numBuckets == 0 { + return 0, nil + } + + written := 0 + n, err := w.WriteString(spansPrefix) + written += n + if err != nil { + return written, err + } + for i, span := range spans { + if i > 0 { + err = w.WriteByte(',') + written++ + if err != nil { + return written, err + } + } + n, err = writeInt(w, int64(span.GetOffset())) + written += n + if err != nil { + return written, err + } + err = w.WriteByte(':') + written++ + if err != nil { + return written, err + } + n, err = writeUint(w, uint64(span.GetLength())) + written += n + if err != nil { + return written, err + } + } + err = w.WriteByte(']') + written++ + if err != nil { + return written, err + } + + n, err = w.WriteString(bucketsPrefix) + written += n + if err != nil { + return written, err + } + if isFloatBuckets { + for i, v := range floatCounts { + if i > 0 { + err = w.WriteByte(',') + written++ + if err != nil { + return written, err + } + } + n, err = writeFloat(w, v) + written += n + if err != nil { + return written, err + } + } + } else { + var current int64 + for i, d := range deltas { + if i > 0 { + err = w.WriteByte(',') + written++ + if err != nil { + return written, err + } + } + current += d + n, err = writeInt(w, current) + written += n + if err != nil { + return written, err + } + } + } + err = w.WriteByte(']') + written++ + if err != nil { + return written, err + } + + return written, nil +} + +func validateClassicBuckets( + name string, + h *dto.Histogram, + sampleCount float64, + sampleCountUint uint64, + isFloatCount bool, + isGauge bool, +) error { + var infSeen bool + var prevBound float64 + var prevCount float64 + for i, b := range h.Bucket { + if b == nil { + return errors.New("expected non-nil bucket") + } + ub := b.GetUpperBound() + if math.IsNaN(ub) { + return fmt.Errorf("classic bucket upper bound cannot be NaN in metric %s", name) + } + if i > 0 && ub <= prevBound { + return fmt.Errorf("classic bucket upper bounds must be strictly increasing: %g <= %g in metric %s", ub, prevBound, name) + } + prevBound = ub + + if b.CumulativeCountFloat != nil { + c := *b.CumulativeCountFloat + if math.IsNaN(c) { + return fmt.Errorf("classic bucket count cannot be NaN in metric %s", name) + } + if c < 0 { + return fmt.Errorf("classic bucket count cannot be negative (%g) in metric %s", c, name) + } + } + + var bCount float64 + switch { + case b.CumulativeCountFloat != nil && (*b.CumulativeCountFloat > 0 || b.CumulativeCount == nil || isGauge): + bCount = *b.CumulativeCountFloat + case b.CumulativeCount != nil: + bCount = float64(*b.CumulativeCount) + } + + if i > 0 && bCount < prevCount { + return fmt.Errorf("classic bucket counts must be monotonically increasing: %g < %g in metric %s", bCount, prevCount, name) + } + prevCount = bCount + + if math.IsInf(ub, +1) { + if i != len(h.Bucket)-1 { + return fmt.Errorf("+Inf bucket must be the last bucket in metric %s", name) + } + infSeen = true + if isFloatCount { + if bCount != sampleCount { + return fmt.Errorf("classic bucket +Inf count (%g) does not match sample count (%g) in metric %s", bCount, sampleCount, name) + } + } else { + if b.CumulativeCount != nil { + if *b.CumulativeCount != sampleCountUint { + return fmt.Errorf("classic bucket +Inf count (%d) does not match sample count (%d) in metric %s", *b.CumulativeCount, sampleCountUint, name) + } + } else { + if bCount < 0 || bCount > math.MaxUint64 || uint64(bCount) != sampleCountUint || float64(uint64(bCount)) != bCount { + return fmt.Errorf("classic bucket +Inf count (%g) does not match sample count (%d) in metric %s", bCount, sampleCountUint, name) + } + } + } + } + } + + if !infSeen && len(h.Bucket) > 0 { + if sampleCount < prevCount { + return fmt.Errorf("sample count (%g) is less than highest bucket count (%g) in metric %s", sampleCount, prevCount, name) + } + } + return nil +} + +func writeClassicBuckets( + w enhancedWriter, + h *dto.Histogram, + sampleCount float64, + sampleCountUint uint64, + isFloatCount bool, + isGauge bool, + collectedExemplars *[]*dto.Exemplar, +) (int, error) { + var infSeen bool + written := 0 + n, err := w.WriteString(",bucket:[") + written += n + if err != nil { + return written, err + } + + for i, b := range h.Bucket { + if i > 0 { + err = w.WriteByte(',') + written++ + if err != nil { + return written, err + } + } + n, err = writeFloat(w, b.GetUpperBound()) + written += n + if err != nil { + return written, err + } + err = w.WriteByte(':') + written++ + if err != nil { + return written, err + } + switch { + case b.CumulativeCountFloat != nil && (*b.CumulativeCountFloat > 0 || b.CumulativeCount == nil || isGauge): + n, err = writeFloat(w, *b.CumulativeCountFloat) + case b.CumulativeCount != nil: + n, err = writeUint(w, *b.CumulativeCount) + default: + n, err = writeUint(w, 0) + } + written += n + if err != nil { + return written, err + } + if math.IsInf(b.GetUpperBound(), +1) { + infSeen = true + } + if b.Exemplar != nil && b.Exemplar.Timestamp != nil { + *collectedExemplars = append(*collectedExemplars, b.Exemplar) + } + } + + if !infSeen { + if len(h.Bucket) > 0 { + err = w.WriteByte(',') + written++ + if err != nil { + return written, err + } + } + n, err = w.WriteString("+Inf:") + written += n + if err != nil { + return written, err + } + if isFloatCount { + n, err = writeFloat(w, sampleCount) + } else { + n, err = writeUint(w, sampleCountUint) + } + written += n + if err != nil { + return written, err + } + } + + err = w.WriteByte(']') + written++ + if err != nil { + return written, err + } + + return written, nil +} + +func validateLabels20(labels []*dto.LabelPair) error { + for _, lp := range labels { + if lp == nil { + return errors.New("expected non-nil label pair") + } + lname := lp.GetName() + if lname == "" { + return errors.New("label name cannot be empty") + } + if lname == string(model.MetricNameLabel) { + return fmt.Errorf("label name %q is reserved", model.MetricNameLabel) + } + if containsRawNewline(lname) { + return fmt.Errorf("label name %q contains raw newlines", lname) + } + } + return nil +} + +func containsRawNewline(s string) bool { + return strings.IndexByte(s, '\n') >= 0 || strings.IndexByte(s, '\r') >= 0 +} + +func validateExemplar20(e *dto.Exemplar) error { + if e.Timestamp == nil { + return errors.New("exemplar timestamp is required") + } + if err := e.Timestamp.CheckValid(); err != nil { + return err + } + return validateLabels20(e.Label) +} + +func writeProtoTimestamp(w enhancedWriter, ts *timestamppb.Timestamp) (int, error) { + if err := ts.CheckValid(); err != nil { + return 0, err + } + if ts.Nanos == 0 { + return writeInt(w, ts.Seconds) + } + sec := ts.Seconds + nanos := int64(ts.Nanos) + if sec < 0 { + sec++ + nanos = 1_000_000_000 - nanos + if sec == 0 { + n, err := w.WriteString("-0") + if err != nil { + return n, err + } + n2, err := writeNanos(w, nanos) + return n + n2, err + } + } + + n, err := writeInt(w, sec) + if err != nil { + return n, err + } + n2, err := writeNanos(w, nanos) + return n + n2, err +} + +func writeNanos(w enhancedWriter, nanos int64) (int, error) { + err := w.WriteByte('.') + if err != nil { + return 0, err + } + written := 1 + bp := numBufPool.Get().(*[]byte) + *bp = strconv.AppendInt((*bp)[:0], nanos, 10) + pad := 9 - len(*bp) + for range pad { + err = w.WriteByte('0') + written++ + if err != nil { + numBufPool.Put(bp) + return written, err + } + } + val := *bp + for len(val) > 0 && val[len(val)-1] == '0' { + val = val[:len(val)-1] + } + n2, err := w.Write(val) + written += n2 + numBufPool.Put(bp) + return written, err +} diff --git a/vendor/github.com/prometheus/common/expfmt/openmetrics_2_0_parse.go b/vendor/github.com/prometheus/common/expfmt/openmetrics_2_0_parse.go new file mode 100644 index 0000000..52ec10d --- /dev/null +++ b/vendor/github.com/prometheus/common/expfmt/openmetrics_2_0_parse.go @@ -0,0 +1,1341 @@ +// Copyright The Prometheus Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package expfmt + +import ( + "bufio" + "errors" + "fmt" + "io" + "math" + "math/bits" + "strconv" + "strings" + "sync" + + goabnf "github.com/pandatix/go-abnf" + dto "github.com/prometheus/client_model/go" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/types/known/timestamppb" + + "github.com/prometheus/common/model" +) + +// openMetrics20ABNF is the OpenMetrics 2.0 ABNF grammar (RFC 5234 / RFC 7405). +// +// NOTE: Every OpenMetrics 2.0 metric-descriptor, sample, and eof construct is +// strictly single-line (normal-char excludes LF %x0A). Adding the `line` rule +// allows streaming line-by-line from an io.Reader via goabnf.ParseForest per +// line while keeping the full exposition grammar intact. +const openMetrics20ABNF = `exposition = metricset eof-line + +metricset = *(metric-descriptor / sample) + +line = metric-descriptor / sample / eof-line +eof-line = HASH SP %s"EOF" [ LF ] + +metric-descriptor = HASH SP descriptor-type SP metric-descriptor-name SP metric-type LF +metric-descriptor =/ HASH SP descriptor-help SP metric-descriptor-name SP help-value LF +metric-descriptor =/ HASH SP descriptor-unit SP metric-descriptor-name SP unit-value LF + +descriptor-type = %s"TYPE" +descriptor-help = %s"HELP" +descriptor-unit = %s"UNIT" + +metric-descriptor-name = metricname / metricname-utf8 +help-value = escaped-string +unit-value = *metricname-char + +metric-type = %s"counter" / %s"gauge" / %s"histogram" / %s"gaugehistogram" / %s"stateset" +metric-type =/ %s"info" / %s"summary" / %s"unknown" + +sample = metricname-and-labels SP value [SP sample-timestamp] [SP start-timestamp] *exemplar LF + +value = sample-number / "{" composite-value "}" +sample-number = number + +sample-timestamp = timestamp +timestamp = realnumber + +; Lowercase st @ timestamp +start-timestamp = %s"st" "@" timestamp + +exemplar = SP HASH SP labels-in-braces SP exemplar-value SP exemplar-timestamp +exemplar-value = number +exemplar-timestamp = timestamp + +metricname-and-labels = metricname [labels-in-braces] / name-and-labels-in-braces +labels-in-braces = "{" [label *(COMMA label)] "}" +name-and-labels-in-braces = "{" metricname-utf8 *(COMMA label) "}" + +label = label-key "=" DQUOTE label-value DQUOTE +label-key = label-name / label-name-utf8 +label-name-utf8 = DQUOTE escaped-string-non-empty DQUOTE +label-value = escaped-string + +; Number value +number = realnumber +; Case insensitive +number =/ [SIGN] (%i"inf" / %i"infinity") +number =/ %i"nan" + +; Real floats +; Leading 0s explicitly okay +realnumber = [SIGN] 1*DIGIT ["." *DIGIT] [ "e" [SIGN] 1*DIGIT ] +realnumber =/ [SIGN] *DIGIT "." 1*DIGIT [ "e" [SIGN] 1*DIGIT ] + +; Integers +; Leading 0s explicitly okay +integer = [SIGN] 1*DIGIT +non-negative-integer = ["+"] 1*DIGIT + +BS = "\" +COMMA = "," +HASH = "#" +SIGN = "-" / "+" + +metricname = metricname-initial-char 0*metricname-char + +metricname-char = metricname-initial-char / DIGIT +metricname-initial-char = ALPHA / "_" / ":" +metricname-utf8 = DQUOTE escaped-string-non-empty DQUOTE + +label-name = label-name-initial-char *label-name-char + +label-name-char = label-name-initial-char / DIGIT +label-name-initial-char = ALPHA / "_" + +escaped-string = *escaped-char +escaped-string-non-empty = 1*escaped-char + +escaped-char = normal-char +escaped-char =/ BS (DQUOTE / BS / normal-char) + +; Any unicode character, except newline, double quote, and backslash +normal-char = %x00-09 / %x0B-21 / %x23-5B / %x5D-D7FF / %xE000-10FFFF + +; Composite values +composite-value = histogram-value / gauge-histogram-value / summary-value + +; Histograms +histogram-value = h-count "," h-sum "," histogram-buckets +gauge-histogram-value = %s"g" h-count "," %s"g" h-sum "," histogram-buckets + +; count:x +h-count = %s"count" ":" number +; sum:f allows real numbers and +-Inf and NaN +h-sum = %s"sum" ":" number + +histogram-buckets = classic-buckets / native-buckets [ "," classic-buckets ] + +; bucket:[...,+Inf:v] The +Inf bucket is required. +classic-buckets = %s"bucket" ":" "[" [ ch-le-counts "," ] ch-pos-inf-bucket "]" +ch-le-counts = (ch-neg-inf-bucket / ch-le-bucket) *("," ch-le-bucket) +ch-pos-inf-bucket = "+" %s"Inf" ":" number +ch-neg-inf-bucket = "-" %s"Inf" ":" number +ch-le-bucket = realnumber ":" number + +; schema:3,zero_threshold:1e-128,zero_count:2,negative_spans:[1:1],negative_buckets:[2],positive_spans:[-3:1,2:2],positive_buckets:[3,1,0] +native-buckets = nh-schema "," nh-zero-threshold "," nh-zero-count [ "," nh-negative-spans "," nh-negative-buckets ] [ "," nh-positive-spans "," nh-positive-buckets ] + +; schema:i +nh-schema = %s"schema" ":" integer +; zero_threshold:f +nh-zero-threshold = %s"zero_threshold" ":" realnumber +; zero_count:x +nh-zero-count = %s"zero_count" ":" number +; negative_spans:[1:2,3:4] and positive_spans:[-3:1,2:2] +nh-negative-spans = %s"negative_spans" ":" "[" [nh-spans] "]" +nh-positive-spans = %s"positive_spans" ":" "[" [nh-spans] "]" +; Spans hold offset and length. The offset can start from any index, even +; negative, however subsequent spans can only advance the index, not decrease it. +nh-spans = nh-start-span *("," nh-span) +nh-start-span = integer ":" non-negative-integer +nh-span = non-negative-integer ":" non-negative-integer + +; negative_buckets:[1,2,3] and positive_buckets:[1,2,3] +nh-negative-buckets = %s"negative_buckets" ":" "[" [nh-buckets] "]" +nh-positive-buckets = %s"positive_buckets" ":" "[" [nh-buckets] "]" + +nh-buckets = number *("," number) + +; Summary + +; count:12.0,sum:100.0,quantile:[0.9:2.0,0.95:3.0,0.99:20.0] +summary-value = cs-count "," cs-sum "," cs-quantile + +; count:x where x is a number +cs-count = %s"count" ":" number +; sum:x where x is a real number or +-Inf or NaN +cs-sum = %s"sum" ":" number +; quantile:[...] +cs-quantile = %s"quantile" ":" "[" [ cs-q-counts ] "]" +cs-q-counts = cs-q-count *("," cs-q-count) +cs-q-count = realnumber ":" number +` + +var ( + om20GrammarOnce sync.Once + om20Grammar *goabnf.Grammar + om20GrammarErr error +) + +func getOpenMetrics20Grammar() (*goabnf.Grammar, error) { + om20GrammarOnce.Do(func() { + raw := strings.ReplaceAll(openMetrics20ABNF, "\r\n", "\n") + raw = strings.ReplaceAll(raw, "\n", "\r\n") + om20Grammar, om20GrammarErr = goabnf.ParseABNF([]byte(raw)) + }) + return om20Grammar, om20GrammarErr +} + +// openMetrics20Parser streams OpenMetrics 2.0 text exposition format line-by-line +// using the OpenMetrics 2.0 ABNF grammar. +// +// NOTE: Like openMetricsParser, this parser invokes goabnf.ParseForest on each +// full line without a line-length cap, which has superlinear (roughly quadratic) +// parse time in line length. As documented on NewDecoder, it is intended for +// reference and conformance decoding rather than high-performance or untrusted inputs. +type openMetrics20Parser struct { + br *bufio.Reader + g *goabnf.Grammar + initErr error + scheme model.ValidationScheme + families map[string]*openMetricsFamilyState + curFamily *openMetricsFamilyState + lineNum int + pendingLine []byte + pendingNode *goabnf.ParseTree + done bool +} + +func newOpenMetrics20Parser(r io.Reader, scheme model.ValidationScheme) *openMetrics20Parser { + br, ok := r.(*bufio.Reader) + if !ok { + br = bufio.NewReader(r) + } + g, err := getOpenMetrics20Grammar() + if err != nil { + err = fmt.Errorf("failed to initialize OpenMetrics 2.0 ABNF grammar: %w", err) + } + return &openMetrics20Parser{ + br: br, + g: g, + initErr: err, + scheme: scheme, + families: make(map[string]*openMetricsFamilyState), + } +} + +func (p *openMetrics20Parser) validationScheme() model.ValidationScheme { + if p.scheme == model.UnsetValidation { + return model.UTF8Validation + } + return p.scheme +} + +func emitOpenMetrics20Family(st *openMetricsFamilyState, v *dto.MetricFamily) { + if st.mf.Type == nil { + st.mf.Type = dto.MetricType_UNTYPED.Enum() + } + v.Name = st.mf.Name + v.Help = st.mf.Help + v.Type = st.mf.Type + v.Metric = st.mf.Metric + v.Unit = st.mf.Unit + st.emitted = true + st.mf.Metric = nil +} + +// next reads from the input stream until the next MetricFamily is complete and +// populates v, or returns io.EOF when # EOF is reached. +func (p *openMetrics20Parser) next(v *dto.MetricFamily) error { + if p.initErr != nil { + return p.initErr + } + for { + if p.done { + return io.EOF + } + + var ( + line []byte + node *goabnf.ParseTree + ) + if p.pendingNode != nil { + line = p.pendingLine + node = p.pendingNode + p.pendingLine = nil + p.pendingNode = nil + } else { + rawLine, readErr := p.br.ReadBytes('\n') + if len(rawLine) == 0 { + if errors.Is(readErr, io.EOF) { + return ParseError{ + Line: max(1, p.lineNum+1), + Msg: "data does not end with # EOF", + } + } + return readErr + } + if readErr != nil && !errors.Is(readErr, io.EOF) { + return readErr + } + p.lineNum++ + line = rawLine + + forest, err := goabnf.ParseForest(line, p.g, "line") + if err != nil { + return err + } + if !forest.Valid() { + return formatABNFLineParseError(p.lineNum, forest.ParseError()) + } + tree := forest.Tree() + if tree == nil || len(tree.Children) == 0 { + return ParseError{Line: p.lineNum, Msg: "failed to extract parse tree"} + } + node = tree.Children[0] + } + + switch node.Rule { + case "eof-line": + if _, peekErr := p.br.Peek(1); !errors.Is(peekErr, io.EOF) { + if peekErr != nil { + return peekErr + } + return ParseError{ + Line: p.lineNum + 1, + Msg: "unexpected data after # EOF", + } + } + p.done = true + if p.curFamily != nil && p.curFamily.hasSamples && !p.curFamily.emitted { + st := p.curFamily + p.curFamily = nil + emitOpenMetrics20Family(st, v) + return nil + } + return io.EOF + + case "metric-descriptor": + if p.curFamily != nil && !p.curFamily.emitted { + mfName := extractDescriptorMetricName(line, node) + if mfName != p.curFamily.mf.GetName() { + if p.curFamily.hasSamples { + p.pendingLine = line + p.pendingNode = node + st := p.curFamily + p.curFamily = nil + emitOpenMetrics20Family(st, v) + return nil + } + p.curFamily.emitted = true + p.curFamily = nil + } + } + if err := p.handleDescriptor(line, node); err != nil { + return err + } + + case "sample": + if p.curFamily != nil && !p.curFamily.emitted { + sampleName := extractSampleMetricName(line, node) + if sampleName != p.curFamily.mf.GetName() { + if p.curFamily.hasSamples { + p.pendingLine = line + p.pendingNode = node + st := p.curFamily + p.curFamily = nil + emitOpenMetrics20Family(st, v) + return nil + } + p.curFamily.emitted = true + p.curFamily = nil + } + } + if err := p.handleSample(line, node); err != nil { + return err + } + } + } +} + +func extractDescriptorMetricName(input []byte, node *goabnf.ParseTree) string { + for _, c := range node.Children { + if c.Rule == "metric-descriptor-name" { + return extractMetricNameNode(input, c) + } + } + return "" +} + +func (p *openMetrics20Parser) getOrCreateDescriptorFamily(name string) (*openMetricsFamilyState, error) { + if !p.validationScheme().IsValidMetricName(name) { + return nil, ParseError{Line: p.lineNum, Msg: fmt.Sprintf("invalid metric name %q", name)} + } + if p.curFamily != nil && !p.curFamily.emitted && p.curFamily.mf.GetName() == name { + if p.curFamily.hasSamples { + return nil, ParseError{Line: p.lineNum, Msg: fmt.Sprintf("metadata for metric %q after samples", name)} + } + return p.curFamily, nil + } + if prev, exists := p.families[name]; exists { + if prev.hasSamples { + return nil, ParseError{Line: p.lineNum, Msg: fmt.Sprintf("metadata for metric %q after samples", name)} + } + if prev.emitted { + return nil, ParseError{Line: p.lineNum, Msg: fmt.Sprintf("interleaved metric family %q", name)} + } + return prev, nil + } + st := &openMetricsFamilyState{ + mf: &dto.MetricFamily{ + Name: proto.String(name), + }, + } + p.families[name] = st + if p.curFamily == nil || !p.curFamily.hasSamples { + p.curFamily = st + } + return st, nil +} + +func (p *openMetrics20Parser) handleDescriptor(input []byte, node *goabnf.ParseTree) error { + var ( + descKind string + mfName string + valNode *goabnf.ParseTree + ) + for _, c := range node.Children { + switch c.Rule { + case "descriptor-type", "descriptor-help", "descriptor-unit": + descKind = c.Rule + case "metric-descriptor-name": + mfName = extractMetricNameNode(input, c) + case "metric-type", "help-value", "unit-value": + valNode = c + } + } + + st, err := p.getOrCreateDescriptorFamily(mfName) + if err != nil { + return err + } + + switch descKind { + case "descriptor-type": + if st.hasType { + return ParseError{Line: p.lineNum, Msg: fmt.Sprintf("second TYPE line for metric name %q", mfName)} + } + st.hasType = true + rawType := string(input[valNode.Start:valNode.End]) + switch rawType { + case "counter": + st.mf.Type = dto.MetricType_COUNTER.Enum() + case "gauge": + st.mf.Type = dto.MetricType_GAUGE.Enum() + case "histogram": + st.mf.Type = dto.MetricType_HISTOGRAM.Enum() + case "gaugehistogram": + st.mf.Type = dto.MetricType_GAUGE_HISTOGRAM.Enum() + case "summary": + st.mf.Type = dto.MetricType_SUMMARY.Enum() + case "unknown": + st.mf.Type = dto.MetricType_UNTYPED.Enum() + case "info", "stateset": + // TODO(bwplotka): Expand client_model (dto.MetricType) to support INFO and STATESET metric types. + return ParseError{Line: p.lineNum, Msg: fmt.Sprintf("unsupported metric type %q", rawType)} + default: + return ParseError{Line: p.lineNum, Msg: fmt.Sprintf("unknown metric type %q", rawType)} + } + case "descriptor-help": + if st.hasHelp { + return ParseError{Line: p.lineNum, Msg: fmt.Sprintf("second HELP line for metric name %q", mfName)} + } + st.hasHelp = true + rawHelp := string(input[valNode.Start:valNode.End]) + if strings.HasSuffix(rawHelp, "\r") { + return ParseError{Line: p.lineNum, Msg: fmt.Sprintf("unexpected carriage return in HELP for metric %q", mfName)} + } + st.mf.Help = proto.String(unescapeOpenMetricsString(rawHelp)) + case "descriptor-unit": + if st.hasUnit { + return ParseError{Line: p.lineNum, Msg: fmt.Sprintf("second UNIT line for metric name %q", mfName)} + } + st.hasUnit = true + unit := string(input[valNode.Start:valNode.End]) + if unit != "" { + st.mf.Unit = proto.String(unit) + } + } + return nil +} + +func (p *openMetrics20Parser) resolveSampleFamily(sampleName string) (*openMetricsFamilyState, error) { + if !p.validationScheme().IsValidMetricName(sampleName) { + return nil, ParseError{Line: p.lineNum, Msg: fmt.Sprintf("invalid metric name %q", sampleName)} + } + + if p.curFamily != nil && !p.curFamily.emitted && p.curFamily.mf.GetName() == sampleName { + if p.curFamily.mf.Type == nil { + p.curFamily.mf.Type = dto.MetricType_UNTYPED.Enum() + } + p.curFamily.hasSamples = true + return p.curFamily, nil + } + + if st, exists := p.families[sampleName]; exists { + if st.emitted { + return nil, ParseError{Line: p.lineNum, Msg: fmt.Sprintf("interleaved metric family %q", st.mf.GetName())} + } + if st.mf.Type == nil { + st.mf.Type = dto.MetricType_UNTYPED.Enum() + } + st.hasSamples = true + p.curFamily = st + return st, nil + } + + st := &openMetricsFamilyState{ + mf: &dto.MetricFamily{ + Name: proto.String(sampleName), + Type: dto.MetricType_UNTYPED.Enum(), + }, + hasSamples: true, + } + p.families[sampleName] = st + p.curFamily = st + return st, nil +} + +func (p *openMetrics20Parser) handleSample(input []byte, node *goabnf.ParseTree) error { + var ( + nameAndLabelsNode *goabnf.ParseTree + valueNode *goabnf.ParseTree + hasTS bool + tsStr string + hasST bool + stStr string + exemplarNodes []*goabnf.ParseTree + ) + for _, c := range node.Children { + switch c.Rule { + case "metricname-and-labels": + nameAndLabelsNode = c + case "value": + valueNode = c + case "sample-timestamp": + hasTS = true + tsStr = string(input[c.Start:c.End]) + case "start-timestamp": + for _, sc := range c.Children { + if sc.Rule == "timestamp" { + hasST = true + stStr = string(input[sc.Start:sc.End]) + } + } + case "exemplar": + exemplarNodes = append(exemplarNodes, c) + } + } + + sampleName, rawLabels := extractNameAndLabels(input, nameAndLabelsNode) + st, err := p.resolveSampleFamily(sampleName) + if err != nil { + return err + } + + labelPairs, err := p.validateAndBuildLabels(st.mf.GetName(), rawLabels) + if err != nil { + return err + } + + var tsMs *int64 + if hasTS { + parsedTS, err := parseSampleTimestampMs(tsStr) + if err != nil { + return ParseError{Line: p.lineNum, Msg: fmt.Sprintf("invalid timestamp %q: %v", tsStr, err)} + } + tsMs = proto.Int64(parsedTS) + } + + var startTS *timestamppb.Timestamp + if hasST { + startTS, err = parseTimestampToProto(stStr) + if err != nil { + return ParseError{Line: p.lineNum, Msg: fmt.Sprintf("invalid start timestamp %q: %v", stStr, err)} + } + } + + var exemplars []*dto.Exemplar + if len(exemplarNodes) > 0 { + exemplars = make([]*dto.Exemplar, 0, len(exemplarNodes)) + for _, en := range exemplarNodes { + ex, err := p.parseExemplar(input, en) + if err != nil { + return err + } + exemplars = append(exemplars, ex) + } + } + + var ( + scalarNode *goabnf.ParseTree + compositeNode *goabnf.ParseTree + ) + for _, vc := range valueNode.Children { + switch vc.Rule { + case "sample-number": + scalarNode = vc + case "composite-value": + compositeNode = vc + } + } + + mtype := st.mf.GetType() + switch mtype { + case dto.MetricType_COUNTER: + if scalarNode == nil { + return ParseError{Line: p.lineNum, Msg: fmt.Sprintf("composite value not supported for counter %q", sampleName)} + } + valStr := string(input[scalarNode.Start:scalarNode.End]) + val, err := parseOpenMetricsFloat(valStr) + if err != nil { + return ParseError{Line: p.lineNum, Msg: fmt.Sprintf("invalid counter value %q: %v", valStr, err)} + } + if math.IsNaN(val) { + return ParseError{Line: p.lineNum, Msg: fmt.Sprintf("counter sample value must not be NaN for %q", sampleName)} + } + if val < 0 { + return ParseError{Line: p.lineNum, Msg: fmt.Sprintf("counter sample value must not be negative for %q", sampleName)} + } + // NOTE: dto.Counter only supports a single Exemplar field in client_model; + // if multiple exemplars are present on the wire, keep the first one. + var ex *dto.Exemplar + if len(exemplars) > 0 { + ex = exemplars[0] + } + st.mf.Metric = append(st.mf.Metric, &dto.Metric{ + Label: labelPairs, + Counter: &dto.Counter{ + Value: proto.Float64(val), + CreatedTimestamp: startTS, + Exemplar: ex, + }, + TimestampMs: tsMs, + }) + + case dto.MetricType_GAUGE: + if scalarNode == nil { + return ParseError{Line: p.lineNum, Msg: fmt.Sprintf("composite value not supported for gauge %q", sampleName)} + } + if startTS != nil { + return ParseError{Line: p.lineNum, Msg: fmt.Sprintf("start timestamp not allowed on gauge metric %q", sampleName)} + } + if len(exemplars) > 0 { + return ParseError{Line: p.lineNum, Msg: fmt.Sprintf("exemplar not allowed on gauge metric %q", sampleName)} + } + valStr := string(input[scalarNode.Start:scalarNode.End]) + val, err := parseOpenMetricsFloat(valStr) + if err != nil { + return ParseError{Line: p.lineNum, Msg: fmt.Sprintf("invalid gauge value %q: %v", valStr, err)} + } + st.mf.Metric = append(st.mf.Metric, &dto.Metric{ + Label: labelPairs, + Gauge: &dto.Gauge{Value: proto.Float64(val)}, + TimestampMs: tsMs, + }) + + case dto.MetricType_UNTYPED: + if scalarNode == nil { + return ParseError{Line: p.lineNum, Msg: fmt.Sprintf("composite value not supported for untyped %q", sampleName)} + } + if startTS != nil { + return ParseError{Line: p.lineNum, Msg: fmt.Sprintf("start timestamp not allowed on untyped metric %q", sampleName)} + } + if len(exemplars) > 0 { + return ParseError{Line: p.lineNum, Msg: fmt.Sprintf("exemplar not allowed on untyped metric %q", sampleName)} + } + valStr := string(input[scalarNode.Start:scalarNode.End]) + val, err := parseOpenMetricsFloat(valStr) + if err != nil { + return ParseError{Line: p.lineNum, Msg: fmt.Sprintf("invalid untyped value %q: %v", valStr, err)} + } + st.mf.Metric = append(st.mf.Metric, &dto.Metric{ + Label: labelPairs, + Untyped: &dto.Untyped{Value: proto.Float64(val)}, + TimestampMs: tsMs, + }) + + case dto.MetricType_SUMMARY: + if compositeNode == nil { + return ParseError{Line: p.lineNum, Msg: fmt.Sprintf("composite value required for metric type summary %q", sampleName)} + } + if len(exemplars) > 0 { + return ParseError{Line: p.lineNum, Msg: fmt.Sprintf("exemplar not allowed on summary metric %q", sampleName)} + } + summaryProto, err := parseCompositeSummary(p.lineNum, input, compositeNode, sampleName, labelPairs, startTS) + if err != nil { + return err + } + st.mf.Metric = append(st.mf.Metric, &dto.Metric{ + Label: labelPairs, + Summary: summaryProto, + TimestampMs: tsMs, + }) + + case dto.MetricType_HISTOGRAM, dto.MetricType_GAUGE_HISTOGRAM: + if compositeNode == nil { + return ParseError{Line: p.lineNum, Msg: fmt.Sprintf("composite value required for metric type %s %q", mtype, sampleName)} + } + isGauge := mtype == dto.MetricType_GAUGE_HISTOGRAM + if isGauge && startTS != nil { + return ParseError{Line: p.lineNum, Msg: fmt.Sprintf("start timestamp not allowed on gaugehistogram metric %q", sampleName)} + } + histProto, err := parseCompositeHistogram(p.lineNum, input, compositeNode, sampleName, labelPairs, isGauge, startTS, exemplars) + if err != nil { + return err + } + st.mf.Metric = append(st.mf.Metric, &dto.Metric{ + Label: labelPairs, + Histogram: histProto, + TimestampMs: tsMs, + }) + } + + return nil +} + +func (p *openMetrics20Parser) validateAndBuildLabels(mfName string, rawLabels []parsedLabel) ([]*dto.LabelPair, error) { + if len(rawLabels) == 0 { + return nil, nil + } + pairs := make([]*dto.LabelPair, 0, len(rawLabels)) + seen := make(map[string]struct{}, len(rawLabels)) + for _, rl := range rawLabels { + if rl.name == "" { + return nil, ParseError{Line: p.lineNum, Msg: "label name must not be empty"} + } + if rl.name == string(model.MetricNameLabel) { + return nil, ParseError{Line: p.lineNum, Msg: fmt.Sprintf("label name %q is reserved", model.MetricNameLabel)} + } + if !p.validationScheme().IsValidLabelName(rl.name) { + return nil, ParseError{Line: p.lineNum, Msg: fmt.Sprintf("invalid label name %q", rl.name)} + } + if !model.LabelValue(rl.value).IsValid() { + return nil, ParseError{Line: p.lineNum, Msg: fmt.Sprintf("invalid label value %q", rl.value)} + } + if _, dup := seen[rl.name]; dup { + return nil, ParseError{Line: p.lineNum, Msg: fmt.Sprintf("duplicate label %q for metric %q", rl.name, mfName)} + } + seen[rl.name] = struct{}{} + pairs = append(pairs, &dto.LabelPair{ + Name: proto.String(rl.name), + Value: proto.String(rl.value), + }) + } + return pairs, nil +} + +func (p *openMetrics20Parser) parseExemplar(input []byte, node *goabnf.ParseTree) (*dto.Exemplar, error) { + om1 := openMetricsParser{scheme: p.validationScheme(), lineNum: p.lineNum} + return om1.parseExemplar(input, node, false) +} + +func parseCompositeSummary( + lineNum int, + input []byte, + compNode *goabnf.ParseTree, + mfName string, + labels []*dto.LabelPair, + startTS *timestamppb.Timestamp, +) (*dto.Summary, error) { + for _, lp := range labels { + if lp.GetName() == model.QuantileLabel { + return nil, ParseError{Line: lineNum, Msg: fmt.Sprintf("summary %q label set must not contain %q label", mfName, model.QuantileLabel)} + } + } + + var sumNode *goabnf.ParseTree + for _, c := range compNode.Children { + if c.Rule == "summary-value" { + sumNode = c + break + } + } + if sumNode == nil { + return nil, ParseError{Line: lineNum, Msg: fmt.Sprintf("expected summary composite value for %q", mfName)} + } + + var ( + countStr string + sumStr string + quantiles []*dto.Quantile + ) + for _, c := range sumNode.Children { + switch c.Rule { + case "cs-count": + countStr = extractFirstRuleText(input, c, "number") + case "cs-sum": + sumStr = extractFirstRuleText(input, c, "number") + case "cs-quantile": + var prevQ float64 + for _, qc := range c.Children { + if qc.Rule != "cs-q-counts" { + continue + } + for i, qpair := range qc.Children { + if qpair.Rule != "cs-q-count" { + continue + } + qStr := extractFirstRuleText(input, qpair, "realnumber") + vStr := extractFirstRuleText(input, qpair, "number") + q, err := parseOpenMetricsFloat(qStr) + if err != nil || math.IsNaN(q) { + return nil, ParseError{Line: lineNum, Msg: fmt.Sprintf("invalid quantile %q", qStr)} + } + if q < 0 || q > 1 { + return nil, ParseError{Line: lineNum, Msg: fmt.Sprintf("quantile must be between 0.0 and 1.0, got %g", q)} + } + if i > 0 && q <= prevQ { + return nil, ParseError{Line: lineNum, Msg: fmt.Sprintf("quantiles must be sorted in increasing order: %g <= %g", q, prevQ)} + } + prevQ = q + + v, err := parseOpenMetricsFloat(vStr) + if err != nil { + return nil, ParseError{Line: lineNum, Msg: fmt.Sprintf("invalid quantile value %q: %v", vStr, err)} + } + quantiles = append(quantiles, &dto.Quantile{ + Quantile: proto.Float64(q), + Value: proto.Float64(v), + }) + } + } + } + } + + countUint, ok := parsePlainUint64(countStr) + if !ok { + f, err := parseOpenMetricsFloat(countStr) + if err != nil || math.IsNaN(f) || math.IsInf(f, 0) || f < 0 || f >= math.Exp2(64) || float64(uint64(f)) != f { + return nil, ParseError{Line: lineNum, Msg: fmt.Sprintf("invalid summary count %q", countStr)} + } + countUint = uint64(f) + } + + // Per the OpenMetrics 2.0 spec, summary sum must not be NaN (unlike + // histogram sum, which can be NaN). + sumVal, err := parseOpenMetricsFloat(sumStr) + if err != nil || math.IsNaN(sumVal) { + return nil, ParseError{Line: lineNum, Msg: fmt.Sprintf("invalid summary sum %q", sumStr)} + } + + return &dto.Summary{ + SampleCount: proto.Uint64(countUint), + SampleSum: proto.Float64(sumVal), + Quantile: quantiles, + CreatedTimestamp: startTS, + }, nil +} + +func parseCompositeHistogram( + lineNum int, + input []byte, + compNode *goabnf.ParseTree, + mfName string, + labels []*dto.LabelPair, + isGauge bool, + startTS *timestamppb.Timestamp, + exemplars []*dto.Exemplar, +) (*dto.Histogram, error) { + expectedRule := "histogram-value" + if isGauge { + expectedRule = "gauge-histogram-value" + } + + var hNode *goabnf.ParseTree + for _, c := range compNode.Children { + if c.Rule == expectedRule { + hNode = c + break + } + } + if hNode == nil { + return nil, ParseError{Line: lineNum, Msg: fmt.Sprintf("expected %s for %q", expectedRule, mfName)} + } + + var ( + countStr string + sumStr string + bucketsNode *goabnf.ParseTree + ) + for _, c := range hNode.Children { + switch c.Rule { + case "h-count": + countStr = extractFirstRuleText(input, c, "number") + case "h-sum": + sumStr = extractFirstRuleText(input, c, "number") + case "histogram-buckets": + bucketsNode = c + } + } + + countFloat, err := parseOpenMetricsFloat(countStr) + if err != nil || math.IsNaN(countFloat) { + return nil, ParseError{Line: lineNum, Msg: fmt.Sprintf("invalid histogram count %q", countStr)} + } + if countFloat < 0 { + if isGauge { + return nil, ParseError{Line: lineNum, Msg: "gcount must not be negative"} + } + return nil, ParseError{Line: lineNum, Msg: "count must not be negative"} + } + countUint, countIsInt := parsePlainUint64(countStr) + + sumFloat, err := parseOpenMetricsFloat(sumStr) + if err != nil { + return nil, ParseError{Line: lineNum, Msg: fmt.Sprintf("invalid histogram sum %q: %v", sumStr, err)} + } + + var ( + classicNode *goabnf.ParseTree + nativeNode *goabnf.ParseTree + ) + for _, c := range bucketsNode.Children { + switch c.Rule { + case "classic-buckets": + classicNode = c + case "native-buckets": + nativeNode = c + } + } + + // NOTE: OpenMetrics 2.0 has no distinct wire tag for integer vs float histograms, + // and writeFloat encodes whole-number floats without a trailing ".0". We classify + // a histogram as a FloatHistogram iff any count, zero_count, or bucket count token + // is not a plain integer (e.g. contains a decimal point, exponent, or "+Inf"). + // Consequently, a FloatHistogram whose counts and buckets are all whole integers + // on the wire decodes as an integer Histogram. + isFloatHistogram := !countIsInt + h := &dto.Histogram{ + SampleSum: proto.Float64(sumFloat), + CreatedTimestamp: startTS, + Exemplars: exemplars, + } + + type parsedClassicBucket struct { + ub float64 + fVal float64 + uVal uint64 + isInt bool + } + var classicBuckets []parsedClassicBucket + + if classicNode != nil { + for _, lp := range labels { + if lp.GetName() == model.BucketLabel { + return nil, ParseError{Line: lineNum, Msg: fmt.Sprintf("histogram %q with classic buckets must not contain %q label", mfName, model.BucketLabel)} + } + } + + var extractBucket func(n *goabnf.ParseTree) error + extractBucket = func(n *goabnf.ParseTree) error { + for _, c := range n.Children { + switch c.Rule { + case "ch-le-counts": + if err := extractBucket(c); err != nil { + return err + } + case "ch-neg-inf-bucket": + vStr := extractFirstRuleText(input, c, "number") + fv, err := parseOpenMetricsFloat(vStr) + if err != nil || math.IsNaN(fv) { + return ParseError{Line: lineNum, Msg: fmt.Sprintf("invalid bucket value %q", vStr)} + } + if fv < 0 { + return ParseError{Line: lineNum, Msg: "classic bucket value must not be negative"} + } + uv, isInt := parsePlainUint64(vStr) + if !isInt { + isFloatHistogram = true + } + classicBuckets = append(classicBuckets, parsedClassicBucket{ + ub: math.Inf(-1), fVal: fv, uVal: uv, isInt: isInt, + }) + case "ch-le-bucket": + ubStr := extractFirstRuleText(input, c, "realnumber") + vStr := extractFirstRuleText(input, c, "number") + ub, err := parseOpenMetricsFloat(ubStr) + if err != nil || math.IsNaN(ub) { + return ParseError{Line: lineNum, Msg: fmt.Sprintf("invalid bucket threshold %q", ubStr)} + } + fv, err := parseOpenMetricsFloat(vStr) + if err != nil || math.IsNaN(fv) { + return ParseError{Line: lineNum, Msg: fmt.Sprintf("invalid bucket value %q", vStr)} + } + if fv < 0 { + return ParseError{Line: lineNum, Msg: "classic bucket value must not be negative"} + } + uv, isInt := parsePlainUint64(vStr) + if !isInt { + isFloatHistogram = true + } + classicBuckets = append(classicBuckets, parsedClassicBucket{ + ub: ub, fVal: fv, uVal: uv, isInt: isInt, + }) + case "ch-pos-inf-bucket": + vStr := extractFirstRuleText(input, c, "number") + fv, err := parseOpenMetricsFloat(vStr) + if err != nil || math.IsNaN(fv) { + return ParseError{Line: lineNum, Msg: fmt.Sprintf("invalid bucket value %q", vStr)} + } + if fv < 0 { + return ParseError{Line: lineNum, Msg: "classic bucket value must not be negative"} + } + uv, isInt := parsePlainUint64(vStr) + if !isInt { + isFloatHistogram = true + } + classicBuckets = append(classicBuckets, parsedClassicBucket{ + ub: math.Inf(1), fVal: fv, uVal: uv, isInt: isInt, + }) + } + } + return nil + } + if err := extractBucket(classicNode); err != nil { + return nil, err + } + } + + var ( + zeroCountFloat float64 + zeroCountUint uint64 + negBucketStrs []string + posBucketStrs []string + ) + + if nativeNode != nil { + for _, c := range nativeNode.Children { + switch c.Rule { + case "nh-schema": + sStr := extractFirstRuleText(input, c, "integer") + schemaVal, err := strconv.ParseInt(sStr, 10, 64) + if err != nil || schemaVal < -4 || schemaVal > 8 { + return nil, ParseError{Line: lineNum, Msg: fmt.Sprintf("schema must be between -4 and 8, got %q", sStr)} + } + h.Schema = proto.Int32(int32(schemaVal)) + + case "nh-zero-threshold": + ztStr := extractFirstRuleText(input, c, "realnumber") + ztVal, err := parseOpenMetricsFloat(ztStr) + if err != nil || math.IsNaN(ztVal) || math.IsInf(ztVal, 0) || ztVal < 0 { + return nil, ParseError{Line: lineNum, Msg: fmt.Sprintf("zero_threshold must be a non-negative, finite number, got %q", ztStr)} + } + h.ZeroThreshold = proto.Float64(ztVal) + + case "nh-zero-count": + zcStr := extractFirstRuleText(input, c, "number") + zcVal, err := parseOpenMetricsFloat(zcStr) + if err != nil || math.IsNaN(zcVal) { + return nil, ParseError{Line: lineNum, Msg: fmt.Sprintf("invalid zero_count %q", zcStr)} + } + if zcVal < 0 { + return nil, ParseError{Line: lineNum, Msg: "zero_count must not be negative"} + } + zeroCountFloat = zcVal + var zcIsInt bool + zeroCountUint, zcIsInt = parsePlainUint64(zcStr) + if !zcIsInt { + isFloatHistogram = true + } + + case "nh-negative-spans": + spans, err := parseNativeSpans(lineNum, input, c) + if err != nil { + return nil, err + } + h.NegativeSpan = spans + + case "nh-positive-spans": + spans, err := parseNativeSpans(lineNum, input, c) + if err != nil { + return nil, err + } + h.PositiveSpan = spans + + case "nh-negative-buckets": + negBucketStrs = extractNumberList(input, c) + for _, bs := range negBucketStrs { + if _, ok := parsePlainInt64(bs); !ok { + isFloatHistogram = true + } + } + + case "nh-positive-buckets": + posBucketStrs = extractNumberList(input, c) + for _, bs := range posBucketStrs { + if _, ok := parsePlainInt64(bs); !ok { + isFloatHistogram = true + } + } + } + } + } + + if isFloatHistogram { + h.SampleCountFloat = proto.Float64(countFloat) + } else { + h.SampleCount = proto.Uint64(countUint) + } + + if nativeNode != nil { + if isFloatHistogram { + h.ZeroCountFloat = proto.Float64(zeroCountFloat) + } else { + h.ZeroCount = proto.Uint64(zeroCountUint) + } + + if err := populateNativeBuckets(lineNum, h, isFloatHistogram, negBucketStrs, posBucketStrs); err != nil { + return nil, err + } + } + + if len(classicBuckets) > 0 { + h.Bucket = make([]*dto.Bucket, 0, len(classicBuckets)) + for i, cb := range classicBuckets { + if i > 0 { + if cb.ub <= classicBuckets[i-1].ub { + return nil, ParseError{Line: lineNum, Msg: "classic histogram buckets must be sorted in increasing order"} + } + if cb.fVal < classicBuckets[i-1].fVal { + return nil, ParseError{Line: lineNum, Msg: fmt.Sprintf("classic bucket counts must be monotonically increasing: %g < %g", cb.fVal, classicBuckets[i-1].fVal)} + } + } + if math.IsInf(cb.ub, +1) { + if isFloatHistogram { + if cb.fVal != countFloat { + return nil, ParseError{Line: lineNum, Msg: fmt.Sprintf("classic bucket +Inf count (%g) does not match sample count (%g)", cb.fVal, countFloat)} + } + } else if cb.uVal != countUint { + return nil, ParseError{Line: lineNum, Msg: fmt.Sprintf("classic bucket +Inf count (%d) does not match sample count (%d)", cb.uVal, countUint)} + } + } + b := &dto.Bucket{ + UpperBound: proto.Float64(cb.ub), + } + if isFloatHistogram { + b.CumulativeCountFloat = proto.Float64(cb.fVal) + } else { + b.CumulativeCount = proto.Uint64(cb.uVal) + } + h.Bucket = append(h.Bucket, b) + } + } + + return h, nil +} + +func parseNativeSpans(lineNum int, input []byte, node *goabnf.ParseTree) ([]*dto.BucketSpan, error) { + var spans []*dto.BucketSpan + for _, c := range node.Children { + if c.Rule != "nh-spans" { + continue + } + for _, sc := range c.Children { + if sc.Rule != "nh-start-span" && sc.Rule != "nh-span" { + continue + } + var offStr, lenStr string + for _, part := range sc.Children { + switch part.Rule { + case "integer": + offStr = string(input[part.Start:part.End]) + case "non-negative-integer": + if offStr == "" && sc.Rule == "nh-span" { + offStr = string(input[part.Start:part.End]) + } else { + lenStr = string(input[part.Start:part.End]) + } + } + } + off, err := strconv.ParseInt(offStr, 10, 32) + if err != nil { + return nil, ParseError{Line: lineNum, Msg: fmt.Sprintf("invalid span offset %q: %v", offStr, err)} + } + length, err := strconv.ParseUint(strings.TrimPrefix(lenStr, "+"), 10, 32) + if err != nil { + return nil, ParseError{Line: lineNum, Msg: fmt.Sprintf("invalid span length %q: %v", lenStr, err)} + } + spans = append(spans, &dto.BucketSpan{ + Offset: proto.Int32(int32(off)), + Length: proto.Uint32(uint32(length)), + }) + } + } + return spans, nil +} + +func populateNativeBuckets( + lineNum int, + h *dto.Histogram, + isFloat bool, + negStrs, posStrs []string, +) error { + var negSpanLen uint64 + for _, s := range h.NegativeSpan { + negSpanLen += uint64(s.GetLength()) + } + if negSpanLen != uint64(len(negStrs)) { + return ParseError{Line: lineNum, Msg: fmt.Sprintf("negative_spans length (%d) does not match negative_buckets count (%d)", negSpanLen, len(negStrs))} + } + + var posSpanLen uint64 + for _, s := range h.PositiveSpan { + posSpanLen += uint64(s.GetLength()) + } + if posSpanLen != uint64(len(posStrs)) { + return ParseError{Line: lineNum, Msg: fmt.Sprintf("positive_spans length (%d) does not match positive_buckets count (%d)", posSpanLen, len(posStrs))} + } + + if isFloat { + // NOTE: For float native histograms, we intentionally omit the exact + // bucket-observation-sum vs sample-count check to match Prometheus's + // histogram.FloatHistogram.Validate(). Summing many scaled IEEE-754 float64 + // bucket counts is subject to rounding drift and would cause false-positive + // rejections, whereas classic histogram "+Inf == count" compares two single + // cumulative numbers directly. + if len(negStrs) > 0 { + h.NegativeCount = make([]float64, 0, len(negStrs)) + for _, s := range negStrs { + fv, err := parseOpenMetricsFloat(s) + if err != nil || math.IsNaN(fv) || fv < 0 { + return ParseError{Line: lineNum, Msg: fmt.Sprintf("invalid negative_buckets value %q", s)} + } + h.NegativeCount = append(h.NegativeCount, fv) + } + } + if len(posStrs) > 0 { + h.PositiveCount = make([]float64, 0, len(posStrs)) + for _, s := range posStrs { + fv, err := parseOpenMetricsFloat(s) + if err != nil || math.IsNaN(fv) || fv < 0 { + return ParseError{Line: lineNum, Msg: fmt.Sprintf("invalid positive_buckets value %q", s)} + } + h.PositiveCount = append(h.PositiveCount, fv) + } + } + return nil + } + + var negTotal, posTotal uint64 + if len(negStrs) > 0 { + h.NegativeDelta = make([]int64, 0, len(negStrs)) + var prev int64 + for _, s := range negStrs { + iv, ok := parsePlainInt64(s) + if !ok || iv < 0 { + return ParseError{Line: lineNum, Msg: fmt.Sprintf("invalid negative_buckets value %q", s)} + } + var carry uint64 + negTotal, carry = bits.Add64(negTotal, uint64(iv), 0) + if carry != 0 { + return ParseError{Line: lineNum, Msg: "native histogram bucket observations overflow uint64"} + } + h.NegativeDelta = append(h.NegativeDelta, iv-prev) + prev = iv + } + } + if len(posStrs) > 0 { + h.PositiveDelta = make([]int64, 0, len(posStrs)) + var prev int64 + for _, s := range posStrs { + iv, ok := parsePlainInt64(s) + if !ok || iv < 0 { + return ParseError{Line: lineNum, Msg: fmt.Sprintf("invalid positive_buckets value %q", s)} + } + var carry uint64 + posTotal, carry = bits.Add64(posTotal, uint64(iv), 0) + if carry != 0 { + return ParseError{Line: lineNum, Msg: "native histogram bucket observations overflow uint64"} + } + h.PositiveDelta = append(h.PositiveDelta, iv-prev) + prev = iv + } + } + if h.SampleCount != nil { + obs, c1 := bits.Add64(h.GetZeroCount(), negTotal, 0) + obs, c2 := bits.Add64(obs, posTotal, c1) + if c2 != 0 { + return ParseError{Line: lineNum, Msg: "native histogram bucket observations overflow uint64"} + } + if math.IsNaN(h.GetSampleSum()) { + if obs > h.GetSampleCount() { + return ParseError{Line: lineNum, Msg: fmt.Sprintf("native histogram bucket observations (%d) exceed sample count (%d)", obs, h.GetSampleCount())} + } + } else if obs != h.GetSampleCount() { + return ParseError{Line: lineNum, Msg: fmt.Sprintf("native histogram bucket observations (%d) do not match sample count (%d)", obs, h.GetSampleCount())} + } + } + return nil +} + +func extractFirstRuleText(input []byte, node *goabnf.ParseTree, rule string) string { + for _, c := range node.Children { + if c.Rule == rule { + return string(input[c.Start:c.End]) + } + } + return "" +} + +func extractNumberList(input []byte, node *goabnf.ParseTree) []string { + var out []string + for _, c := range node.Children { + if c.Rule != "nh-buckets" { + continue + } + for _, nc := range c.Children { + if nc.Rule == "number" { + out = append(out, string(input[nc.Start:nc.End])) + } + } + } + return out +} + +func parsePlainUint64(s string) (uint64, bool) { + if s == "" || strings.ContainsAny(s, ".eE") { + return 0, false + } + s = strings.TrimPrefix(s, "+") + v, err := strconv.ParseUint(s, 10, 64) + if err != nil { + return 0, false + } + return v, true +} + +func parsePlainInt64(s string) (int64, bool) { + if s == "" || strings.ContainsAny(s, ".eE") { + return 0, false + } + v, err := strconv.ParseInt(s, 10, 64) + if err != nil { + return 0, false + } + return v, true +} diff --git a/vendor/github.com/prometheus/common/expfmt/openmetrics_parse.go b/vendor/github.com/prometheus/common/expfmt/openmetrics_parse.go new file mode 100644 index 0000000..6eb424d --- /dev/null +++ b/vendor/github.com/prometheus/common/expfmt/openmetrics_parse.go @@ -0,0 +1,1129 @@ +// Copyright The Prometheus Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package expfmt + +import ( + "bufio" + "errors" + "fmt" + "io" + "math" + "strconv" + "strings" + "sync" + "time" + "unicode/utf8" + + goabnf "github.com/pandatix/go-abnf" + dto "github.com/prometheus/client_model/go" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/types/known/timestamppb" + + "github.com/prometheus/common/model" +) + +const openMetricsExemplarMaxRunes = 128 + +// openMetrics10ABNF is the OpenMetrics 1.0 ABNF grammar (RFC 5234) from +// https://github.com/prometheus/OpenMetrics/blob/v1.0.0/specification/OpenMetrics.md#abnf, +// extended with UTF-8 quoted metric and label names. When legacy validation is +// active on the decoder, quoted names that fail legacy validation are rejected +// during semantic validation. +// +// NOTE: Every OpenMetrics 1.0 metric-descriptor, sample, and eof construct is +// strictly single-line (normal-char excludes LF %x0A). Adding the `line` rule +// allows streaming line-by-line from an io.Reader via goabnf.ParseForest per +// line while keeping the full exposition grammar intact. +const openMetrics10ABNF = `exposition = metricset eof-line + +metricset = *(metric-descriptor / sample) + +line = metric-descriptor / sample / eof-line +eof-line = HASH SP eof [ LF ] + +metric-descriptor = HASH SP type SP metric-descriptor-name SP metric-type LF +metric-descriptor =/ HASH SP help SP metric-descriptor-name SP help-value LF +metric-descriptor =/ HASH SP unit SP metric-descriptor-name SP unit-value LF + +metric-descriptor-name = metricname / metricname-utf8 +help-value = escaped-string +unit-value = *metricname-char + +metric-type = counter / gauge / histogram / gaugehistogram / stateset +metric-type =/ info / summary / unknown + +sample = metricname-and-labels SP sample-value [SP sample-timestamp] [exemplar] LF + +sample-value = number +sample-timestamp = timestamp + +exemplar = SP HASH SP labels SP exemplar-value [SP exemplar-timestamp] +exemplar-value = number +exemplar-timestamp = timestamp + +metricname-and-labels = (metricname / metricname-utf8) [labels] / labels-with-metricname +labels = "{" [label *(COMMA label)] "}" +labels-with-metricname = "{" [label *(COMMA label) COMMA] metricname-utf8 *(COMMA label) "}" + +label = label-key EQ DQUOTE label-value DQUOTE +label-key = label-name / label-name-utf8 +label-name-utf8 = DQUOTE escaped-string-non-empty DQUOTE +label-value = escaped-string + +number = realnumber +; Case insensitive +number =/ [SIGN] ("inf" / "infinity") +number =/ "nan" + +timestamp = realnumber + +; Leading 0s explicitly okay +realnumber = [SIGN] 1*DIGIT +realnumber =/ [SIGN] 1*DIGIT ["." *DIGIT] [ "e" [SIGN] 1*DIGIT ] +realnumber =/ [SIGN] *DIGIT "." 1*DIGIT [ "e" [SIGN] 1*DIGIT ] + +; RFC 5234 is case insensitive. +; Uppercase +eof = %d69.79.70 +type = %d84.89.80.69 +help = %d72.69.76.80 +unit = %d85.78.73.84 +; Lowercase +counter = %d99.111.117.110.116.101.114 +gauge = %d103.97.117.103.101 +histogram = %d104.105.115.116.111.103.114.97.109 +gaugehistogram = gauge histogram +stateset = %d115.116.97.116.101.115.101.116 +info = %d105.110.102.111 +summary = %d115.117.109.109.97.114.121 +unknown = %d117.110.107.110.111.119.110 + +BS = "\" +EQ = "=" +COMMA = "," +HASH = "#" +SIGN = "-" / "+" + +metricname = metricname-initial-char 0*metricname-char + +metricname-char = metricname-initial-char / DIGIT +metricname-initial-char = ALPHA / "_" / ":" +metricname-utf8 = DQUOTE escaped-string-non-empty DQUOTE + +label-name = label-name-initial-char *label-name-char + +label-name-char = label-name-initial-char / DIGIT +label-name-initial-char = ALPHA / "_" + +escaped-string = *escaped-char +escaped-string-non-empty = 1*escaped-char + +escaped-char = normal-char +escaped-char =/ BS (DQUOTE / BS / normal-char) + +; Any unicode character, except newline, double quote, and backslash +normal-char = %x00-09 / %x0B-21 / %x23-5B / %x5D-D7FF / %xE000-10FFFF +` + +var ( + om10GrammarOnce sync.Once + om10Grammar *goabnf.Grammar + om10GrammarErr error + + omEscapedReplacer = strings.NewReplacer( + `\"`, `"`, + `\\`, `\`, + `\n`, "\n", + ) +) + +func getOpenMetrics10Grammar() (*goabnf.Grammar, error) { + om10GrammarOnce.Do(func() { + raw := strings.ReplaceAll(openMetrics10ABNF, "\r\n", "\n") + raw = strings.ReplaceAll(raw, "\n", "\r\n") + om10Grammar, om10GrammarErr = goabnf.ParseABNF([]byte(raw)) + }) + return om10Grammar, om10GrammarErr +} + +type openMetricsFamilyState struct { + mf *dto.MetricFamily + hasType bool + hasHelp bool + hasUnit bool + hasSamples bool + emitted bool + + counters map[uint64]*dto.Metric + summaries map[uint64]*dto.Metric + histograms map[uint64]*dto.Metric +} + +// openMetricsParser streams OpenMetrics 1.0 text exposition format line-by-line +// using the OpenMetrics 1.0 ABNF grammar. +type openMetricsParser struct { + br *bufio.Reader + g *goabnf.Grammar + initErr error + scheme model.ValidationScheme + families map[string]*openMetricsFamilyState + curFamily *openMetricsFamilyState + scratchLbl map[string]string + lineNum int + pendingLine []byte + pendingNode *goabnf.ParseTree + done bool +} + +func newOpenMetricsParser(r io.Reader, scheme model.ValidationScheme) *openMetricsParser { + br, ok := r.(*bufio.Reader) + if !ok { + br = bufio.NewReader(r) + } + g, err := getOpenMetrics10Grammar() + if err != nil { + err = fmt.Errorf("failed to initialize OpenMetrics 1.0 ABNF grammar: %w", err) + } + return &openMetricsParser{ + br: br, + g: g, + initErr: err, + scheme: scheme, + families: make(map[string]*openMetricsFamilyState), + scratchLbl: make(map[string]string), + } +} + +func (p *openMetricsParser) validationScheme() model.ValidationScheme { + if p.scheme == model.UnsetValidation { + return model.LegacyValidation + } + return p.scheme +} + +func emitOpenMetricsFamily(st *openMetricsFamilyState, v *dto.MetricFamily, lineNum int) error { + if st.mf.Type == nil { + st.mf.Type = dto.MetricType_UNTYPED.Enum() + } + name := st.mf.Name + if st.mf.GetType() == dto.MetricType_COUNTER { + for _, m := range st.mf.Metric { + if m.GetCounter().Value == nil { + return ParseError{ + Line: lineNum, + Msg: fmt.Sprintf("counter %q missing _total value", st.mf.GetName()), + } + } + } + name = proto.String(st.mf.GetName() + "_total") + } + for _, m := range st.histograms { + normalizeHistogram(m.GetHistogram()) + } + v.Name = name + v.Help = st.mf.Help + v.Type = st.mf.Type + v.Metric = st.mf.Metric + v.Unit = st.mf.Unit + st.emitted = true + st.mf.Metric = nil + st.counters = nil + st.summaries = nil + st.histograms = nil + return nil +} + +// next reads from the input stream until the next MetricFamily is complete and +// populates v, or returns io.EOF when # EOF is reached. +func (p *openMetricsParser) next(v *dto.MetricFamily) error { + if p.initErr != nil { + return p.initErr + } + for { + if p.done { + return io.EOF + } + + var ( + line []byte + node *goabnf.ParseTree + ) + if p.pendingNode != nil { + line = p.pendingLine + node = p.pendingNode + p.pendingLine = nil + p.pendingNode = nil + } else { + rawLine, readErr := p.br.ReadBytes('\n') + if len(rawLine) == 0 { + if errors.Is(readErr, io.EOF) { + return ParseError{ + Line: max(1, p.lineNum+1), + Msg: "data does not end with # EOF", + } + } + return readErr + } + if readErr != nil && !errors.Is(readErr, io.EOF) { + return readErr + } + p.lineNum++ + line = rawLine + + forest, err := goabnf.ParseForest(line, p.g, "line") + if err != nil { + return err + } + if !forest.Valid() { + return formatABNFLineParseError(p.lineNum, forest.ParseError()) + } + tree := forest.Tree() + if tree == nil || len(tree.Children) == 0 { + return ParseError{Line: p.lineNum, Msg: "failed to extract parse tree"} + } + node = tree.Children[0] + } + + switch node.Rule { + case "eof-line": + if _, peekErr := p.br.Peek(1); !errors.Is(peekErr, io.EOF) { + if peekErr != nil { + return peekErr + } + return ParseError{ + Line: p.lineNum + 1, + Msg: "unexpected data after # EOF", + } + } + p.done = true + if p.curFamily != nil && p.curFamily.hasSamples && !p.curFamily.emitted { + st := p.curFamily + p.curFamily = nil + return emitOpenMetricsFamily(st, v, p.lineNum) + } + return io.EOF + + case "metric-descriptor": + if err := p.handleDescriptor(line, node); err != nil { + return err + } + + case "sample": + if p.curFamily != nil && p.curFamily.hasSamples && !p.curFamily.emitted { + sampleName := extractSampleMetricName(line, node) + if _, ok := matchFamilySample(p.curFamily, sampleName); !ok && sampleName != p.curFamily.mf.GetName() { + p.pendingLine = line + p.pendingNode = node + st := p.curFamily + p.curFamily = nil + return emitOpenMetricsFamily(st, v, p.lineNum) + } + } + if err := p.handleSample(line, node); err != nil { + return err + } + } + } +} + +func (p *openMetricsParser) getOrCreateDescriptorFamily(name string) (*openMetricsFamilyState, error) { + if !p.validationScheme().IsValidMetricName(name) { + return nil, ParseError{Line: p.lineNum, Msg: fmt.Sprintf("invalid metric name %q", name)} + } + if p.curFamily != nil && !p.curFamily.emitted && p.curFamily.mf.GetName() == name { + if p.curFamily.hasSamples { + return nil, ParseError{Line: p.lineNum, Msg: fmt.Sprintf("metadata for metric %q after samples", name)} + } + return p.curFamily, nil + } + if prev, exists := p.families[name]; exists { + if prev.hasSamples { + return nil, ParseError{Line: p.lineNum, Msg: fmt.Sprintf("metadata for metric %q after samples", name)} + } + return prev, nil + } + st := &openMetricsFamilyState{ + mf: &dto.MetricFamily{ + Name: proto.String(name), + }, + } + p.families[name] = st + if p.curFamily == nil || !p.curFamily.hasSamples { + p.curFamily = st + } + return st, nil +} + +func (p *openMetricsParser) handleDescriptor(input []byte, node *goabnf.ParseTree) error { + var ( + descKind string + mfName string + valNode *goabnf.ParseTree + ) + for _, c := range node.Children { + switch c.Rule { + case "type", "help", "unit": + descKind = c.Rule + case "metric-descriptor-name": + mfName = extractMetricNameNode(input, c) + case "metric-type", "help-value", "unit-value": + valNode = c + } + } + + st, err := p.getOrCreateDescriptorFamily(mfName) + if err != nil { + return err + } + + switch descKind { + case "type": + if st.hasType { + return ParseError{Line: p.lineNum, Msg: fmt.Sprintf("second TYPE line for metric name %q", mfName)} + } + st.hasType = true + rawType := string(input[valNode.Start:valNode.End]) + switch rawType { + case "counter": + st.mf.Type = dto.MetricType_COUNTER.Enum() + case "gauge": + st.mf.Type = dto.MetricType_GAUGE.Enum() + case "histogram": + st.mf.Type = dto.MetricType_HISTOGRAM.Enum() + case "gaugehistogram": + st.mf.Type = dto.MetricType_GAUGE_HISTOGRAM.Enum() + case "summary": + st.mf.Type = dto.MetricType_SUMMARY.Enum() + case "unknown": + st.mf.Type = dto.MetricType_UNTYPED.Enum() + case "info", "stateset": + // TODO(bwplotka): Expand client_model (dto.MetricType) to support INFO and STATESET metric types. + return ParseError{Line: p.lineNum, Msg: fmt.Sprintf("unsupported metric type %q", rawType)} + default: + return ParseError{Line: p.lineNum, Msg: fmt.Sprintf("unknown metric type %q", rawType)} + } + case "help": + if st.hasHelp { + return ParseError{Line: p.lineNum, Msg: fmt.Sprintf("second HELP line for metric name %q", mfName)} + } + st.hasHelp = true + rawHelp := string(input[valNode.Start:valNode.End]) + if strings.HasSuffix(rawHelp, "\r") { + return ParseError{Line: p.lineNum, Msg: fmt.Sprintf("unexpected carriage return in HELP for metric %q", mfName)} + } + st.mf.Help = proto.String(unescapeOpenMetricsString(rawHelp)) + case "unit": + if st.hasUnit { + return ParseError{Line: p.lineNum, Msg: fmt.Sprintf("second UNIT line for metric name %q", mfName)} + } + st.hasUnit = true + unit := string(input[valNode.Start:valNode.End]) + if unit != "" { + if !strings.HasSuffix(mfName, "_"+unit) { + return ParseError{Line: p.lineNum, Msg: fmt.Sprintf("unit %q not a suffix of metric %q", unit, mfName)} + } + st.mf.Unit = proto.String(unit) + } + } + return nil +} + +type sampleRole int + +const ( + roleValue sampleRole = iota + roleCreated + roleCount + roleSum + roleBucket + roleQuantile +) + +func (p *openMetricsParser) resolveSampleFamily(sampleName string) (*openMetricsFamilyState, sampleRole, error) { + if !p.validationScheme().IsValidMetricName(sampleName) { + return nil, roleValue, ParseError{Line: p.lineNum, Msg: fmt.Sprintf("invalid metric name %q", sampleName)} + } + + if p.curFamily != nil && !p.curFamily.emitted { + if role, ok := matchFamilySample(p.curFamily, sampleName); ok { + if p.curFamily.mf.Type == nil { + p.curFamily.mf.Type = dto.MetricType_UNTYPED.Enum() + } + p.curFamily.hasSamples = true + return p.curFamily, role, nil + } + // If curFamily was explicitly typed as counter/histogram/gaugehistogram, + // a bare sample matching the base family name is missing its required suffix. + if p.curFamily.hasType && sampleName == p.curFamily.mf.GetName() { + return nil, roleValue, ParseError{Line: p.lineNum, Msg: fmt.Sprintf("sample %q missing required suffix for type %s", sampleName, p.curFamily.mf.GetType())} + } + } + + if st, exists := p.families[sampleName]; exists { + if role, ok := matchFamilySample(st, sampleName); ok { + if st.emitted { + return nil, roleValue, ParseError{Line: p.lineNum, Msg: fmt.Sprintf("interleaved metric family %q", st.mf.GetName())} + } + if st.mf.Type == nil { + st.mf.Type = dto.MetricType_UNTYPED.Enum() + } + st.hasSamples = true + p.curFamily = st + return st, role, nil + } + if st.hasType { + return nil, roleValue, ParseError{Line: p.lineNum, Msg: fmt.Sprintf("sample %q missing required suffix for type %s", sampleName, st.mf.GetType())} + } + } + + for _, st := range p.families { + if role, ok := matchFamilySample(st, sampleName); ok { + if st.emitted { + return nil, roleValue, ParseError{Line: p.lineNum, Msg: fmt.Sprintf("interleaved metric family %q", st.mf.GetName())} + } + if st.mf.Type == nil { + st.mf.Type = dto.MetricType_UNTYPED.Enum() + } + st.hasSamples = true + p.curFamily = st + return st, role, nil + } + } + + st := &openMetricsFamilyState{ + mf: &dto.MetricFamily{ + Name: proto.String(sampleName), + Type: dto.MetricType_UNTYPED.Enum(), + }, + hasSamples: true, + } + p.families[sampleName] = st + p.curFamily = st + return st, roleValue, nil +} + +func matchFamilySample(st *openMetricsFamilyState, sampleName string) (sampleRole, bool) { + if st == nil || st.mf == nil { + return roleValue, false + } + mfName := st.mf.GetName() + if st.mf.Type == nil { + if sampleName == mfName { + return roleValue, true + } + return roleValue, false + } + + switch st.mf.GetType() { + case dto.MetricType_COUNTER: + switch sampleName { + case mfName + "_total": + return roleValue, true + case mfName + "_created": + return roleCreated, true + } + case dto.MetricType_GAUGE, dto.MetricType_UNTYPED: + if sampleName == mfName { + return roleValue, true + } + case dto.MetricType_SUMMARY: + switch sampleName { + case mfName: + return roleQuantile, true + case mfName + "_count": + return roleCount, true + case mfName + "_sum": + return roleSum, true + case mfName + "_created": + return roleCreated, true + } + case dto.MetricType_HISTOGRAM: + switch sampleName { + case mfName + "_bucket": + return roleBucket, true + case mfName + "_count": + return roleCount, true + case mfName + "_sum": + return roleSum, true + case mfName + "_created": + return roleCreated, true + } + case dto.MetricType_GAUGE_HISTOGRAM: + switch sampleName { + case mfName + "_bucket": + return roleBucket, true + case mfName + "_gcount", mfName + "_count": + return roleCount, true + case mfName + "_gsum", mfName + "_sum": + return roleSum, true + case mfName + "_created": + return roleCreated, true + } + } + return roleValue, false +} + +func (p *openMetricsParser) handleSample(input []byte, node *goabnf.ParseTree) error { + var ( + nameAndLabelsNode *goabnf.ParseTree + valStr string + hasTS bool + tsStr string + exemplarNode *goabnf.ParseTree + ) + for _, c := range node.Children { + switch c.Rule { + case "metricname-and-labels": + nameAndLabelsNode = c + case "sample-value": + valStr = string(input[c.Start:c.End]) + case "sample-timestamp": + hasTS = true + tsStr = string(input[c.Start:c.End]) + case "exemplar": + exemplarNode = c + } + } + + sampleName, rawLabels := extractNameAndLabels(input, nameAndLabelsNode) + st, role, err := p.resolveSampleFamily(sampleName) + if err != nil { + return err + } + + val, err := parseOpenMetricsFloat(valStr) + if err != nil { + return ParseError{Line: p.lineNum, Msg: fmt.Sprintf("invalid sample value %q: %v", valStr, err)} + } + + var tsMs *int64 + if hasTS { + parsedTS, err := parseSampleTimestampMs(tsStr) + if err != nil { + return ParseError{Line: p.lineNum, Msg: fmt.Sprintf("invalid timestamp %q: %v", tsStr, err)} + } + tsMs = proto.Int64(parsedTS) + } + + var ex *dto.Exemplar + if exemplarNode != nil { + ex, err = p.parseExemplar(input, exemplarNode, true) + if err != nil { + return err + } + } + + // Validate labels and extract special 'quantile' or 'le' label if applicable. + clear(p.scratchLbl) + p.scratchLbl[string(model.MetricNameLabel)] = st.mf.GetName() + var ( + labelPairs []*dto.LabelPair + quantile = math.NaN() + bucketLE = math.NaN() + ) + seenLabels := make(map[string]struct{}, len(rawLabels)) + for _, rl := range rawLabels { + if rl.name == string(model.MetricNameLabel) { + return ParseError{Line: p.lineNum, Msg: fmt.Sprintf("label name %q is reserved", model.MetricNameLabel)} + } + if !p.validationScheme().IsValidLabelName(rl.name) { + return ParseError{Line: p.lineNum, Msg: fmt.Sprintf("invalid label name %q", rl.name)} + } + if !model.LabelValue(rl.value).IsValid() { + return ParseError{Line: p.lineNum, Msg: fmt.Sprintf("invalid label value %q", rl.value)} + } + if _, dup := seenLabels[rl.name]; dup { + return ParseError{Line: p.lineNum, Msg: fmt.Sprintf("duplicate label %q for metric %q", rl.name, st.mf.GetName())} + } + seenLabels[rl.name] = struct{}{} + + if role == roleQuantile && rl.name == model.QuantileLabel { + q, err := parseOpenMetricsFloat(rl.value) + if err != nil || math.IsNaN(q) || q < 0 || q > 1 { + return ParseError{Line: p.lineNum, Msg: fmt.Sprintf("invalid quantile %q for summary %q", rl.value, st.mf.GetName())} + } + quantile = q + continue + } + if role == roleBucket && rl.name == model.BucketLabel { + le, err := parseOpenMetricsFloat(rl.value) + if err != nil || math.IsNaN(le) { + return ParseError{Line: p.lineNum, Msg: fmt.Sprintf("invalid bucket bound %q for histogram %q", rl.value, st.mf.GetName())} + } + bucketLE = le + continue + } + p.scratchLbl[rl.name] = rl.value + labelPairs = append(labelPairs, &dto.LabelPair{ + Name: proto.String(rl.name), + Value: proto.String(rl.value), + }) + } + + switch st.mf.GetType() { + case dto.MetricType_GAUGE: + if ex != nil { + return ParseError{Line: p.lineNum, Msg: fmt.Sprintf("exemplar not allowed on gauge metric %q", st.mf.GetName())} + } + st.mf.Metric = append(st.mf.Metric, &dto.Metric{ + Label: labelPairs, + Gauge: &dto.Gauge{Value: proto.Float64(val)}, + TimestampMs: tsMs, + }) + + case dto.MetricType_UNTYPED: + if ex != nil { + return ParseError{Line: p.lineNum, Msg: fmt.Sprintf("exemplar not allowed on untyped metric %q", st.mf.GetName())} + } + st.mf.Metric = append(st.mf.Metric, &dto.Metric{ + Label: labelPairs, + Untyped: &dto.Untyped{Value: proto.Float64(val)}, + TimestampMs: tsMs, + }) + + case dto.MetricType_COUNTER: + if st.counters == nil { + st.counters = make(map[uint64]*dto.Metric) + } + sig := model.LabelsToSignature(p.scratchLbl) + switch role { + case roleValue: + if math.IsNaN(val) || val < 0 { + return ParseError{Line: p.lineNum, Msg: fmt.Sprintf("counter value must not be negative or NaN for %q", st.mf.GetName())} + } + m := st.counters[sig] + if m == nil || m.Counter.Value != nil { + m = &dto.Metric{ + Label: labelPairs, + Counter: &dto.Counter{}, + } + st.counters[sig] = m + st.mf.Metric = append(st.mf.Metric, m) + } + m.Counter.Value = proto.Float64(val) + m.Counter.Exemplar = ex + m.TimestampMs = tsMs + case roleCreated: + if ex != nil { + return ParseError{Line: p.lineNum, Msg: fmt.Sprintf("exemplar not allowed on _created line for %q", st.mf.GetName())} + } + createdTS, err := parseTimestampToProto(valStr) + if err != nil { + return ParseError{Line: p.lineNum, Msg: fmt.Sprintf("invalid created timestamp %q: %v", valStr, err)} + } + m := st.counters[sig] + if m == nil || m.Counter.CreatedTimestamp != nil { + m = &dto.Metric{ + Label: labelPairs, + Counter: &dto.Counter{}, + } + st.counters[sig] = m + st.mf.Metric = append(st.mf.Metric, m) + } + m.Counter.CreatedTimestamp = createdTS + } + + case dto.MetricType_SUMMARY: + if ex != nil { + return ParseError{Line: p.lineNum, Msg: fmt.Sprintf("exemplar not allowed on summary metric %q", st.mf.GetName())} + } + if st.summaries == nil { + st.summaries = make(map[uint64]*dto.Metric) + } + sig := model.LabelsToSignature(p.scratchLbl) + m := st.summaries[sig] + if m == nil { + m = &dto.Metric{ + Label: labelPairs, + Summary: &dto.Summary{}, + } + st.summaries[sig] = m + st.mf.Metric = append(st.mf.Metric, m) + } + if role != roleCreated && tsMs != nil { + m.TimestampMs = tsMs + } + switch role { + case roleQuantile: + if math.IsNaN(quantile) { + return ParseError{Line: p.lineNum, Msg: fmt.Sprintf("missing quantile label for summary %q", st.mf.GetName())} + } + if !math.IsNaN(val) && val < 0 { + return ParseError{Line: p.lineNum, Msg: fmt.Sprintf("negative quantile value for summary %q", st.mf.GetName())} + } + m.Summary.Quantile = append(m.Summary.Quantile, &dto.Quantile{ + Quantile: proto.Float64(quantile), + Value: proto.Float64(val), + }) + case roleCount: + if math.IsNaN(val) || val < 0 || float64(uint64(val)) != val { + return ParseError{Line: p.lineNum, Msg: fmt.Sprintf("invalid count %q for summary %q", valStr, st.mf.GetName())} + } + m.Summary.SampleCount = proto.Uint64(uint64(val)) + case roleSum: + if math.IsNaN(val) || val < 0 { + return ParseError{Line: p.lineNum, Msg: fmt.Sprintf("invalid sum %q for summary %q", valStr, st.mf.GetName())} + } + m.Summary.SampleSum = proto.Float64(val) + case roleCreated: + createdTS, err := parseTimestampToProto(valStr) + if err != nil { + return ParseError{Line: p.lineNum, Msg: fmt.Sprintf("invalid created timestamp %q: %v", valStr, err)} + } + m.Summary.CreatedTimestamp = createdTS + } + + case dto.MetricType_HISTOGRAM, dto.MetricType_GAUGE_HISTOGRAM: + if st.histograms == nil { + st.histograms = make(map[uint64]*dto.Metric) + } + sig := model.LabelsToSignature(p.scratchLbl) + m := st.histograms[sig] + if m == nil { + m = &dto.Metric{ + Label: labelPairs, + Histogram: &dto.Histogram{}, + } + st.histograms[sig] = m + st.mf.Metric = append(st.mf.Metric, m) + } + if role != roleCreated && tsMs != nil { + m.TimestampMs = tsMs + } + switch role { + case roleBucket: + if math.IsNaN(bucketLE) { + return ParseError{Line: p.lineNum, Msg: fmt.Sprintf("missing le label for histogram %q", st.mf.GetName())} + } + if math.IsNaN(val) || val < 0 { + return ParseError{Line: p.lineNum, Msg: fmt.Sprintf("negative or NaN bucket count for histogram %q", st.mf.GetName())} + } + b := &dto.Bucket{ + UpperBound: proto.Float64(bucketLE), + Exemplar: ex, + } + if uintVal := uint64(val); float64(uintVal) == val { + b.CumulativeCount = proto.Uint64(uintVal) + } else { + b.CumulativeCountFloat = proto.Float64(val) + } + m.Histogram.Bucket = append(m.Histogram.Bucket, b) + case roleCount: + if ex != nil { + return ParseError{Line: p.lineNum, Msg: fmt.Sprintf("exemplar not allowed on count sample for histogram %q", st.mf.GetName())} + } + if math.IsNaN(val) || val < 0 { + return ParseError{Line: p.lineNum, Msg: fmt.Sprintf("negative or NaN count for histogram %q", st.mf.GetName())} + } + if uintVal := uint64(val); float64(uintVal) == val { + m.Histogram.SampleCount = proto.Uint64(uintVal) + } else { + m.Histogram.SampleCountFloat = proto.Float64(val) + } + case roleSum: + if ex != nil { + return ParseError{Line: p.lineNum, Msg: fmt.Sprintf("exemplar not allowed on sum sample for histogram %q", st.mf.GetName())} + } + if math.IsNaN(val) || (st.mf.GetType() == dto.MetricType_HISTOGRAM && val < 0) { + return ParseError{Line: p.lineNum, Msg: fmt.Sprintf("invalid sum %q for histogram %q", valStr, st.mf.GetName())} + } + m.Histogram.SampleSum = proto.Float64(val) + case roleCreated: + if ex != nil { + return ParseError{Line: p.lineNum, Msg: fmt.Sprintf("exemplar not allowed on _created sample for histogram %q", st.mf.GetName())} + } + createdTS, err := parseTimestampToProto(valStr) + if err != nil { + return ParseError{Line: p.lineNum, Msg: fmt.Sprintf("invalid created timestamp %q: %v", valStr, err)} + } + m.Histogram.CreatedTimestamp = createdTS + } + } + + return nil +} + +func (p *openMetricsParser) parseExemplar(input []byte, node *goabnf.ParseTree, isOM1 bool) (*dto.Exemplar, error) { + var ( + rawLabels []parsedLabel + valStr string + hasTS bool + tsStr string + ) + for _, c := range node.Children { + switch c.Rule { + case "labels", "labels-in-braces": + rawLabels = extractLabelsFromList(input, c) + case "exemplar-value", "number": + valStr = string(input[c.Start:c.End]) + case "exemplar-timestamp", "timestamp": + hasTS = true + tsStr = string(input[c.Start:c.End]) + } + } + + val, err := parseOpenMetricsFloat(valStr) + if err != nil || (isOM1 && (math.IsNaN(val) || math.IsInf(val, 0))) { + return nil, ParseError{Line: p.lineNum, Msg: fmt.Sprintf("invalid exemplar value %q", valStr)} + } + + var ( + pairs = make([]*dto.LabelPair, 0, len(rawLabels)) + seenNames = make(map[string]struct{}, len(rawLabels)) + totalRune int + ) + for _, rl := range rawLabels { + if rl.name == string(model.MetricNameLabel) { + return nil, ParseError{Line: p.lineNum, Msg: fmt.Sprintf("exemplar label name %q is reserved", model.MetricNameLabel)} + } + if !p.validationScheme().IsValidLabelName(rl.name) { + return nil, ParseError{Line: p.lineNum, Msg: fmt.Sprintf("invalid exemplar label name %q", rl.name)} + } + if !model.LabelValue(rl.value).IsValid() { + return nil, ParseError{Line: p.lineNum, Msg: fmt.Sprintf("invalid exemplar label value %q", rl.value)} + } + if _, dup := seenNames[rl.name]; dup { + return nil, ParseError{Line: p.lineNum, Msg: fmt.Sprintf("duplicate exemplar label name %q", rl.name)} + } + seenNames[rl.name] = struct{}{} + totalRune += utf8.RuneCountInString(rl.name) + utf8.RuneCountInString(rl.value) + pairs = append(pairs, &dto.LabelPair{ + Name: proto.String(rl.name), + Value: proto.String(rl.value), + }) + } + if isOM1 && totalRune > openMetricsExemplarMaxRunes { + return nil, ParseError{Line: p.lineNum, Msg: fmt.Sprintf("exemplar label set exceeds %d runes (%d)", openMetricsExemplarMaxRunes, totalRune)} + } + + ex := &dto.Exemplar{ + Label: pairs, + Value: proto.Float64(val), + } + if hasTS { + tsProto, err := parseTimestampToProto(tsStr) + if err != nil { + return nil, ParseError{Line: p.lineNum, Msg: fmt.Sprintf("invalid exemplar timestamp %q: %v", tsStr, err)} + } + ex.Timestamp = tsProto + } + return ex, nil +} + +type parsedLabel struct { + name string + value string +} + +func extractSampleMetricName(input []byte, sampleNode *goabnf.ParseTree) string { + for _, c := range sampleNode.Children { + if c.Rule == "metricname-and-labels" { + name, _ := extractNameAndLabels(input, c) + return name + } + } + return "" +} + +func extractMetricNameNode(input []byte, node *goabnf.ParseTree) string { + for _, c := range node.Children { + switch c.Rule { + case "metricname": + return string(input[c.Start:c.End]) + case "metricname-utf8": + return unescapeOpenMetricsString(string(input[c.Start+1 : c.End-1])) + } + } + return "" +} + +func extractNameAndLabels(input []byte, node *goabnf.ParseTree) (string, []parsedLabel) { + var ( + metricName string + labels []parsedLabel + ) + var walk func(n *goabnf.ParseTree) + walk = func(n *goabnf.ParseTree) { + for _, c := range n.Children { + switch c.Rule { + case "metricname": + metricName = string(input[c.Start:c.End]) + case "metricname-utf8": + metricName = unescapeOpenMetricsString(string(input[c.Start+1 : c.End-1])) + case "label": + labels = append(labels, extractSingleLabel(input, c)) + case "labels", "labels-in-braces", "labels-with-metricname", "name-and-labels-in-braces": + walk(c) + } + } + } + walk(node) + return metricName, labels +} + +func extractLabelsFromList(input []byte, node *goabnf.ParseTree) []parsedLabel { + var labels []parsedLabel + for _, c := range node.Children { + if c.Rule == "label" { + labels = append(labels, extractSingleLabel(input, c)) + } + } + return labels +} + +func extractSingleLabel(input []byte, node *goabnf.ParseTree) parsedLabel { + var out parsedLabel + for _, c := range node.Children { + switch c.Rule { + case "label-key": + for _, kc := range c.Children { + switch kc.Rule { + case "label-name": + out.name = string(input[kc.Start:kc.End]) + case "label-name-utf8": + out.name = unescapeOpenMetricsString(string(input[kc.Start+1 : kc.End-1])) + default: + if kc.Rule == "" && kc.End > kc.Start+2 && input[kc.Start] == '"' && input[kc.End-1] == '"' { + out.name = unescapeOpenMetricsString(string(input[kc.Start+1 : kc.End-1])) + } + } + } + case "label-value": + out.value = unescapeOpenMetricsString(string(input[c.Start:c.End])) + } + } + return out +} + +func unescapeOpenMetricsString(s string) string { + if strings.IndexByte(s, '\\') < 0 { + return s + } + return omEscapedReplacer.Replace(s) +} + +func parseOpenMetricsFloat(s string) (float64, error) { + if strings.ContainsAny(s, "pP_") { + return 0, fmt.Errorf("unsupported character in float %q", s) + } + return strconv.ParseFloat(s, 64) +} + +func parseSampleTimestampMs(s string) (int64, error) { + f, err := parseOpenMetricsFloat(s) + if err != nil { + return 0, err + } + ms := math.Round(f * 1000) + if math.IsNaN(ms) || math.IsInf(ms, 0) || ms < float64(math.MinInt64) || ms >= math.Exp2(63) { + return 0, fmt.Errorf("invalid timestamp %v", f) + } + return int64(ms), nil +} + +func parseTimestampToProto(s string) (*timestamppb.Timestamp, error) { + if ts, ok := parseExactDecimalTimestamp(s); ok { + if err := ts.CheckValid(); err != nil { + return nil, fmt.Errorf("invalid timestamp %q: %w", s, err) + } + return ts, nil + } + f, err := parseOpenMetricsFloat(s) + if err != nil { + return nil, err + } + if math.IsNaN(f) || math.IsInf(f, 0) || f < float64(math.MinInt64) || f >= math.Exp2(63) { + return nil, fmt.Errorf("invalid timestamp %v", f) + } + sec, frac := math.Modf(f) + nanos := int64(math.Round(frac * 1e9)) + ts := timestamppb.New(time.Unix(int64(sec), nanos)) + if err := ts.CheckValid(); err != nil { + return nil, fmt.Errorf("invalid timestamp %q: %w", s, err) + } + return ts, nil +} + +func parseExactDecimalTimestamp(s string) (*timestamppb.Timestamp, bool) { + neg := false + switch { + case strings.HasPrefix(s, "-"): + neg = true + s = s[1:] + case strings.HasPrefix(s, "+"): + s = s[1:] + } + var exp int + if idx := strings.IndexAny(s, "eE"); idx >= 0 { + eVal, err := strconv.Atoi(s[idx+1:]) + if err != nil || eVal < -18 || eVal > 18 { + return nil, false + } + exp = eVal + s = s[:idx] + } + secPart, fracPart, _ := strings.Cut(s, ".") + digits := secPart + fracPart + if digits == "" { + return nil, false + } + decPos := len(secPart) + exp + switch { + case decPos <= 0: + secPart = "0" + fracPart = strings.Repeat("0", -decPos) + digits + case decPos >= len(digits): + secPart = digits + strings.Repeat("0", decPos-len(digits)) + fracPart = "" + default: + secPart = digits[:decPos] + fracPart = digits[decPos:] + } + var sec int64 + if secPart != "" { + v, err := strconv.ParseInt(secPart, 10, 64) + if err != nil { + return nil, false + } + sec = v + } + var nanos int64 + if fracPart != "" { + if len(fracPart) > 9 { + fracPart = fracPart[:9] + } else { + fracPart += strings.Repeat("0", 9-len(fracPart)) + } + v, err := strconv.ParseInt(fracPart, 10, 64) + if err != nil { + return nil, false + } + nanos = v + } + if neg { + sec = -sec + nanos = -nanos + } + return timestamppb.New(time.Unix(sec, nanos)), true +} + +func formatABNFLineParseError(lineNum int, perr *goabnf.ParseError) error { + if perr == nil { + return ParseError{Line: lineNum, Msg: "syntax error"} + } + return ParseError{ + Line: lineNum, + Msg: perr.Error(), + } +} diff --git a/vendor/github.com/prometheus/common/expfmt/text_parse.go b/vendor/github.com/prometheus/common/expfmt/text_parse.go index 4ce1f40..1052930 100644 --- a/vendor/github.com/prometheus/common/expfmt/text_parse.go +++ b/vendor/github.com/prometheus/common/expfmt/text_parse.go @@ -194,6 +194,7 @@ func (p *TextParser) reset(in io.Reader) { // start of a line (or whitespace leading up to it). func (p *TextParser) startOfLine() stateFn { p.lineCount++ + p.currentMetric = nil p.currentMetricIsInsideBraces = false p.currentMetricInsideBracesIsPresent = false if p.skipBlankTab(); p.err != nil { @@ -339,12 +340,11 @@ func (p *TextParser) startLabelName() stateFn { return nil // Unexpected end of input. } if p.currentByte == '}' { - if p.currentMF == nil { + if p.currentMetric == nil { // The closing brace was reached before any metric name was read, // e.g. for the input "{}". There is no metric to attach labels to, // so this is a malformed exposition. This mirrors the guard in - // startLabelValue. currentMF (not currentMetric) is checked because - // reset only clears currentMF between parses. + // startLabelValue. currentMetric is cleared at the start of each line. p.parseError("invalid metric name") p.currentLabelPairs = nil return nil @@ -495,7 +495,7 @@ func (p *TextParser) startLabelValue() stateFn { return p.startLabelName case '}': - if p.currentMF == nil { + if p.currentMetric == nil { p.parseError("invalid metric name") return nil } diff --git a/vendor/github.com/prometheus/common/model/signature.go b/vendor/github.com/prometheus/common/model/signature.go index dc8a002..b723e3b 100644 --- a/vendor/github.com/prometheus/common/model/signature.go +++ b/vendor/github.com/prometheus/common/model/signature.go @@ -14,7 +14,7 @@ package model import ( - "sort" + "slices" ) // SeparatorByte is a byte that cannot occur in valid UTF-8 sequences and is @@ -37,7 +37,7 @@ func LabelsToSignature(labels map[string]string) uint64 { for labelName := range labels { labelNames = append(labelNames, labelName) } - sort.Strings(labelNames) + slices.Sort(labelNames) sum := hashNew() for _, labelName := range labelNames { @@ -60,7 +60,7 @@ func labelSetToFingerprint(ls LabelSet) Fingerprint { for labelName := range ls { labelNames = append(labelNames, labelName) } - sort.Sort(labelNames) + slices.Sort(labelNames) sum := hashNew() for _, labelName := range labelNames { @@ -100,7 +100,7 @@ func SignatureForLabels(m Metric, labels ...LabelName) uint64 { return emptyLabelSignature } - sort.Sort(LabelNames(labels)) + slices.Sort(labels) sum := hashNew() for _, label := range labels { @@ -129,7 +129,7 @@ func SignatureWithoutLabels(m Metric, labels map[LabelName]struct{}) uint64 { if len(labelNames) == 0 { return emptyLabelSignature } - sort.Sort(labelNames) + slices.Sort(labelNames) sum := hashNew() for _, labelName := range labelNames { diff --git a/vendor/github.com/prometheus/common/model/time.go b/vendor/github.com/prometheus/common/model/time.go index 0854753..9860717 100644 --- a/vendor/github.com/prometheus/common/model/time.go +++ b/vendor/github.com/prometheus/common/model/time.go @@ -164,6 +164,34 @@ func (t *Time) UnmarshalJSON(b []byte) error { // This type should not propagate beyond the scope of input/output processing. type Duration time.Duration +// Common durations. Day and Week are included because ParseDuration supports +// those units (unlike the standard time package). +// +// To count the number of units in a Duration, divide: +// +// second := model.Second +// fmt.Print(int64(second/model.Millisecond)) // prints 1000 +// +// To convert an integer number of units to a Duration, multiply: +// +// seconds := 10 +// fmt.Print(model.Duration(seconds)*model.Second) // prints 10s +const ( + Nanosecond Duration = 1 + Microsecond = 1000 * Nanosecond + Millisecond = 1000 * Microsecond + Second = 1000 * Millisecond + Minute = 60 * Second + Hour = 60 * Minute + Day = 24 * Hour + Week = 7 * Day +) + +// Milliseconds returns the duration as an integer millisecond count. +// Prometheus stores timestamps in milliseconds; time.Duration already +// covers the other units. +func (d Duration) Milliseconds() int64 { return time.Duration(d).Milliseconds() } + // Set implements pflag/flag.Value. func (d *Duration) Set(s string) error { var err error diff --git a/vendor/github.com/prometheus/common/model/value.go b/vendor/github.com/prometheus/common/model/value.go index 8dffd9c..eed5c9e 100644 --- a/vendor/github.com/prometheus/common/model/value.go +++ b/vendor/github.com/prometheus/common/model/value.go @@ -224,28 +224,6 @@ func (ss SampleStream) MarshalJSON() ([]byte, error) { } } -func (ss *SampleStream) UnmarshalJSON(b []byte) error { - v := struct { - Metric Metric `json:"metric"` - Values []SamplePair `json:"values"` - Histograms []SampleHistogramPair `json:"histograms"` - }{ - Metric: ss.Metric, - Values: ss.Values, - Histograms: ss.Histograms, - } - - if err := json.Unmarshal(b, &v); err != nil { - return err - } - - ss.Metric = v.Metric - ss.Values = v.Values - ss.Histograms = v.Histograms - - return nil -} - // Scalar is a scalar value evaluated at the set timestamp. type Scalar struct { Value SampleValue `json:"value"` diff --git a/vendor/github.com/prometheus/common/model/value_float127.go b/vendor/github.com/prometheus/common/model/value_float127.go new file mode 100644 index 0000000..821cc1e --- /dev/null +++ b/vendor/github.com/prometheus/common/model/value_float127.go @@ -0,0 +1,70 @@ +// Copyright The Prometheus Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//go:build go1.27 + +package model + +import ( + "bytes" + "encoding/json/jsontext" + "errors" +) + +var nullBytes = []byte("null") + +func (s *SamplePair) UnmarshalJSONFrom(dec *jsontext.Decoder) error { + if t, err := dec.ReadToken(); err != nil { + return err + } else if t.Kind() == jsontext.KindNull { + return nil + } else if t.Kind() != jsontext.KindBeginArray { + return errors.New("expected [") + } + + // Loop until we see the end of the array (tolerate arrays of any length). + for i := 0; dec.PeekKind() != jsontext.KindEndArray; i++ { + switch i { + case 0: + if v, err := dec.ReadValue(); err != nil { + return err + } else if bytes.Equal(v, nullBytes) { + // Skip null values to match SamplePair#UnmarshalJSON behavior. + } else if err := s.Timestamp.UnmarshalJSON(v); err != nil { + return err + } + case 1: + if v, err := dec.ReadValue(); err != nil { + return err + } else if bytes.Equal(v, nullBytes) { + // Skip null values to match SamplePair#UnmarshalJSON behavior. + } else if err := s.Value.UnmarshalJSON(v); err != nil { + return err + } + default: + // Skip any remaining array items to match UnmarshalJSON behavior. + if err := dec.SkipValue(); err != nil { + return err + } + } + } + + // Read the final end array token. + if t, err := dec.ReadToken(); err != nil { + return err + } else if t.Kind() != jsontext.KindEndArray { + return errors.New("expected ]") + } + + return nil +} diff --git a/vendor/github.com/prometheus/common/model/value_histogram127.go b/vendor/github.com/prometheus/common/model/value_histogram127.go new file mode 100644 index 0000000..fbcfb3f --- /dev/null +++ b/vendor/github.com/prometheus/common/model/value_histogram127.go @@ -0,0 +1,95 @@ +// Copyright The Prometheus Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//go:build go1.27 + +package model + +import ( + "bytes" + "encoding/json/jsontext" + "encoding/json/v2" + "errors" +) + +func (s *SampleHistogramPair) UnmarshalJSONFrom(dec *jsontext.Decoder) error { + if t, err := dec.ReadToken(); err != nil { + return err + } else if t.Kind() != jsontext.KindBeginArray { + return errors.New("expected [") + } + + if v, err := dec.ReadValue(); err != nil { + return err + } else if bytes.Equal(v, nullBytes) { + // Skip null values to match SamplePair#UnmarshalJSON behavior. + } else if err := s.Timestamp.UnmarshalJSON(v); err != nil { + return err + } + + if err := json.UnmarshalDecode(dec, &s.Histogram); err != nil { + return err + } else if s.Histogram == nil { + return errors.New("histogram is nil") + } + + if t, err := dec.ReadToken(); err != nil { + return err + } else if t.Kind() != jsontext.KindEndArray { + return errors.New("expected ]") + } + return nil +} + +func (s *HistogramBucket) UnmarshalJSONFrom(dec *jsontext.Decoder) error { + if t, err := dec.ReadToken(); err != nil { + return err + } else if t.Kind() != jsontext.KindBeginArray { + return errors.New("expected [") + } + + if err := json.UnmarshalDecode(dec, &s.Boundaries); err != nil { + return err + } + + if v, err := dec.ReadValue(); err != nil { + return err + } else if bytes.Equal(v, nullBytes) { + // Skip null values to match SamplePair#UnmarshalJSON behavior. + } else if err := s.Lower.UnmarshalJSON(v); err != nil { + return err + } + + if v, err := dec.ReadValue(); err != nil { + return err + } else if bytes.Equal(v, nullBytes) { + // Skip null values to match SamplePair#UnmarshalJSON behavior. + } else if err := s.Upper.UnmarshalJSON(v); err != nil { + return err + } + + if v, err := dec.ReadValue(); err != nil { + return err + } else if bytes.Equal(v, nullBytes) { + // Skip null values to match SamplePair#UnmarshalJSON behavior. + } else if err := s.Count.UnmarshalJSON(v); err != nil { + return err + } + + if t, err := dec.ReadToken(); err != nil { + return err + } else if t.Kind() != jsontext.KindEndArray { + return errors.New("expected ]") + } + return nil +} diff --git a/vendor/github.com/prometheus/procfs/.golangci.yml b/vendor/github.com/prometheus/procfs/.golangci.yml index eac920b..29d847c 100644 --- a/vendor/github.com/prometheus/procfs/.golangci.yml +++ b/vendor/github.com/prometheus/procfs/.golangci.yml @@ -6,6 +6,8 @@ linters: - gocritic - godot - misspell + - modernize + - perfsprint - revive - testifylint settings: @@ -34,14 +36,6 @@ linters: capital: true misspell: locale: US - revive: - rules: - - name: var-naming - # TODO(SuperQ): See: https://github.com/prometheus/prometheus/issues/17766 - arguments: - - [] - - [] - - - skip-package-name-checks: true exclusions: presets: - comments @@ -51,9 +45,18 @@ linters: warn-unused: true formatters: enable: - - gofmt + - gci + - gofumpt - goimports settings: + gci: + sections: + - standard + - default + - prefix(github.com/prometheus/procfs) + gofumpt: + extra: + group-params: true goimports: local-prefixes: - github.com/prometheus/procfs diff --git a/vendor/github.com/prometheus/procfs/CONTRIBUTING.md b/vendor/github.com/prometheus/procfs/CONTRIBUTING.md index 853eb9d..812a71b 100644 --- a/vendor/github.com/prometheus/procfs/CONTRIBUTING.md +++ b/vendor/github.com/prometheus/procfs/CONTRIBUTING.md @@ -96,7 +96,7 @@ The `proc` and `sys` filesystems are pseudo file systems and work a bit differen Many of the files are changing continuously and the data being read can in some cases change between subsequent reads in the same file. Also, most of the files are relatively small (less than a few KBs), and system calls to the `stat` function will often return the wrong size. Therefore, for most files it's recommended to read the -full file in a single operation using an internal utility function called `util.ReadFileNoStat`. +full file in a single operation using an internal utility function called `parsers.ReadFileNoStat`. This function is similar to `os.ReadFile`, but it avoids the system call to `stat` to get the current size of the file. @@ -104,7 +104,7 @@ Note that parsing the file's contents can still be performed one line at a time. the full file, and then using a scanner on the `[]byte` or `string` containing the data. ``` - data, err := util.ReadFileNoStat("/proc/cpuinfo") + data, err := parsers.ReadFileNoStat("/proc/cpuinfo") if err != nil { return err } @@ -113,9 +113,9 @@ the full file, and then using a scanner on the `[]byte` or `string` containing t ``` The `/sys` filesystem contains many very small files which contain only a single numeric or text value. These files -can be read using an internal function called `util.SysReadFile` which is similar to `os.ReadFile` but does +can be read using an internal function called `parsers.SysReadFile` which is similar to `os.ReadFile` but does not bother to check the size of the file before reading. ``` - data, err := util.SysReadFile("/sys/class/power_supply/BAT0/capacity") + data, err := parsers.SysReadFile("/sys/class/power_supply/BAT0/capacity") ``` diff --git a/vendor/github.com/prometheus/procfs/Makefile.common b/vendor/github.com/prometheus/procfs/Makefile.common index a7c5f55..efc2730 100644 --- a/vendor/github.com/prometheus/procfs/Makefile.common +++ b/vendor/github.com/prometheus/procfs/Makefile.common @@ -61,7 +61,7 @@ PROMU_URL := https://github.com/prometheus/promu/releases/download/v$(PROMU_ SKIP_GOLANGCI_LINT := GOLANGCI_LINT := GOLANGCI_LINT_OPTS ?= -GOLANGCI_LINT_VERSION ?= v2.11.4 +GOLANGCI_LINT_VERSION ?= v2.14.0 GOLANGCI_FMT_OPTS ?= # golangci-lint only supports linux, darwin and windows platforms on i386/amd64/arm64. # windows isn't included here because of the path separator being different. @@ -165,8 +165,9 @@ common-deps: .PHONY: update-go-deps update-go-deps: @echo ">> updating Go dependencies" + # GOTOOLCHAIN prevents go get from pulling deps that require a newer Go version. @for m in $$($(GO) list -mod=readonly -m -f '{{ if and (not .Indirect) (not .Main)}}{{.Path}}{{end}}' all); do \ - $(GO) get $$m; \ + GOTOOLCHAIN=go$$($(GO) mod edit -json | jq -r .Go) $(GO) get $$m; \ done $(GO) mod tidy @@ -246,6 +247,12 @@ common-docker-repo-name: .PHONY: common-docker $(BUILD_DOCKER_ARCHS) common-docker: $(BUILD_DOCKER_ARCHS) + +.PHONY: common-docker-current-arch +common-docker-current-arch: + $(MAKE) common-docker-$(GOHOSTARCH) + +# DOCKER_ARCHS holds promu architecture names, which are not OCI platform strings. $(BUILD_DOCKER_ARCHS): common-docker-%: @for variant in $(DOCKERFILE_VARIANTS_WITH_NAMES); do \ dockerfile=$${variant#*:}; \ @@ -254,10 +261,16 @@ $(BUILD_DOCKER_ARCHS): common-docker-%: if [ "$*" = "armv7" ]; then \ distroless_arch="arm"; \ fi; \ + arch="$*"; \ + case "$$arch" in \ + armv*) docker_platform="linux/arm/v$${arch#armv}";; \ + *) docker_platform="linux/$$arch";; \ + esac; \ if [ "$$dockerfile" = "Dockerfile" ]; then \ echo "Building default variant ($$variant_name) for linux-$* using $$dockerfile"; \ docker build -t "$(DOCKER_REPO)/$(DOCKER_IMAGE_NAME)-linux-$*:$(SANITIZED_DOCKER_IMAGE_TAG)" \ -f $$dockerfile \ + --platform "$$docker_platform" \ --build-arg ARCH="$*" \ --build-arg OS="linux" \ --build-arg DISTROLESS_ARCH="$$distroless_arch" \ @@ -271,6 +284,7 @@ $(BUILD_DOCKER_ARCHS): common-docker-%: echo "Building $$variant_name variant for linux-$* using $$dockerfile"; \ docker build -t "$(DOCKER_REPO)/$(DOCKER_IMAGE_NAME)-linux-$*:$(SANITIZED_DOCKER_IMAGE_TAG)-$$variant_name" \ -f $$dockerfile \ + --platform "$$docker_platform" \ --build-arg ARCH="$*" \ --build-arg OS="linux" \ --build-arg DISTROLESS_ARCH="$$distroless_arch" \ diff --git a/vendor/github.com/prometheus/procfs/cmdline.go b/vendor/github.com/prometheus/procfs/cmdline.go index 4f1cac1..6a2e7bb 100644 --- a/vendor/github.com/prometheus/procfs/cmdline.go +++ b/vendor/github.com/prometheus/procfs/cmdline.go @@ -16,12 +16,12 @@ package procfs import ( "strings" - "github.com/prometheus/procfs/internal/util" + "github.com/prometheus/procfs/internal/parsers" ) // CmdLine returns the command line of the kernel. func (fs FS) CmdLine() ([]string, error) { - data, err := util.ReadFileNoStat(fs.proc.Path("cmdline")) + data, err := parsers.ReadFileNoStat(fs.proc.Path("cmdline")) if err != nil { return nil, err } diff --git a/vendor/github.com/prometheus/procfs/cpuinfo.go b/vendor/github.com/prometheus/procfs/cpuinfo.go index 4b23d8d..f30c5a4 100644 --- a/vendor/github.com/prometheus/procfs/cpuinfo.go +++ b/vendor/github.com/prometheus/procfs/cpuinfo.go @@ -24,7 +24,7 @@ import ( "strconv" "strings" - "github.com/prometheus/procfs/internal/util" + "github.com/prometheus/procfs/internal/parsers" ) // CPUInfo contains general information about a system CPU found in /proc/cpuinfo. @@ -65,7 +65,7 @@ var ( // CPUInfo returns information about current system CPUs. // See https://www.kernel.org/doc/Documentation/filesystems/proc.txt func (fs FS) CPUInfo() ([]CPUInfo, error) { - data, err := util.ReadFileNoStat(fs.proc.Path("cpuinfo")) + data, err := parsers.ReadFileNoStat(fs.proc.Path("cpuinfo")) if err != nil { return nil, err } @@ -187,6 +187,24 @@ func parseCPUInfoX86(info []byte) ([]CPUInfo, error) { return cpuinfo, nil } +func formatSteppingARM(variant, revision string) string { + if variant == "" && revision == "" { + return "" + } + varNum, errV := strconv.ParseUint(variant, 0, 64) + revNum, errR := strconv.ParseUint(revision, 0, 64) + if errV == nil && errR == nil { + return fmt.Sprintf("r%dp%d", varNum, revNum) + } + if errV == nil { + return fmt.Sprintf("r%d", varNum) + } + if errR == nil { + return fmt.Sprintf("p%d", revNum) + } + return fmt.Sprintf("r%sp%s", variant, revision) +} + func parseCPUInfoARM(info []byte) ([]CPUInfo, error) { scanner := bufio.NewScanner(bytes.NewReader(info)) @@ -194,12 +212,13 @@ func parseCPUInfoARM(info []byte) ([]CPUInfo, error) { match, err := regexp.MatchString("^[Pp]rocessor", firstLine) if !match || !strings.Contains(firstLine, ":") { return nil, fmt.Errorf("%w: Cannot parse line: %q: %w", ErrFileParse, firstLine, err) - } field := strings.SplitN(firstLine, ": ", 2) cpuinfo := []CPUInfo{} featuresLine := "" commonCPUInfo := CPUInfo{} + variants := make(map[int]string) + revisions := make(map[int]string) i := 0 if strings.TrimSpace(field[0]) == "Processor" { commonCPUInfo = CPUInfo{ModelName: field[1]} @@ -219,6 +238,9 @@ func parseCPUInfoARM(info []byte) ([]CPUInfo, error) { continue } field := strings.SplitN(line, ": ", 2) + if len(field) < 2 { + continue + } switch strings.TrimSpace(field[0]) { case "processor": cpuinfo = append(cpuinfo, commonCPUInfo) // start of the next processor @@ -242,15 +264,75 @@ func parseCPUInfoARM(info []byte) ([]CPUInfo, error) { case "Features": featuresLine = line case "model name": - cpuinfo[i].ModelName = field[1] + if i == -1 { + commonCPUInfo.ModelName = field[1] + } else { + cpuinfo[i].ModelName = field[1] + } + case "CPU implementer", "cpu implementer": + val := strings.TrimSpace(field[1]) + if i == -1 { + commonCPUInfo.VendorID = val + } else { + cpuinfo[i].VendorID = val + } + case "CPU architecture", "cpu architecture": + val := strings.TrimSpace(field[1]) + if i == -1 { + commonCPUInfo.CPUFamily = val + } else { + cpuinfo[i].CPUFamily = val + } + case "CPU part", "cpu part": + val := strings.TrimSpace(field[1]) + if i == -1 { + commonCPUInfo.Model = val + } else { + cpuinfo[i].Model = val + } + case "CPU variant", "cpu variant": + variants[i] = strings.TrimSpace(field[1]) + case "CPU revision", "cpu revision": + revisions[i] = strings.TrimSpace(field[1]) } } - fields := strings.SplitN(featuresLine, ": ", 2) - for i := range cpuinfo { - cpuinfo[i].Flags = strings.Fields(fields[1]) + + for j := range cpuinfo { + stepping := formatSteppingARM(variants[j], revisions[j]) + if stepping == "" { + stepping = formatSteppingARM(variants[-1], revisions[-1]) + } + cpuinfo[j].Stepping = stepping + } + + if len(cpuinfo) > 0 && cpuinfo[0].VendorID == "" && cpuinfo[len(cpuinfo)-1].VendorID != "" { + last := cpuinfo[len(cpuinfo)-1] + for j := range cpuinfo { + if cpuinfo[j].VendorID == "" { + cpuinfo[j].VendorID = last.VendorID + } + if cpuinfo[j].CPUFamily == "" { + cpuinfo[j].CPUFamily = last.CPUFamily + } + if cpuinfo[j].Model == "" { + cpuinfo[j].Model = last.Model + } + if cpuinfo[j].Stepping == "" { + cpuinfo[j].Stepping = last.Stepping + } + } + } + + if featuresLine != "" { + fields := strings.SplitN(featuresLine, ": ", 2) + if len(fields) > 1 { + flags := strings.Fields(fields[1]) + for i := range cpuinfo { + cpuinfo[i].Flags = flags + } + } } return cpuinfo, nil - } func parseCPUInfoS390X(info []byte) ([]CPUInfo, error) { diff --git a/vendor/github.com/prometheus/procfs/crypto.go b/vendor/github.com/prometheus/procfs/crypto.go index d93b712..8b6a263 100644 --- a/vendor/github.com/prometheus/procfs/crypto.go +++ b/vendor/github.com/prometheus/procfs/crypto.go @@ -20,7 +20,7 @@ import ( "io" "strings" - "github.com/prometheus/procfs/internal/util" + "github.com/prometheus/procfs/internal/parsers" ) // Crypto holds info parsed from /proc/crypto. @@ -55,10 +55,9 @@ var cryptoFile = "crypto" // https://kernel.readthedocs.io/en/sphinx-samples/crypto-API.html func (fs FS) Crypto() ([]Crypto, error) { path := fs.proc.Path(cryptoFile) - b, err := util.ReadFileNoStat(path) + b, err := parsers.ReadFileNoStat(path) if err != nil { return nil, fmt.Errorf("%w: Cannot read file %v: %w", ErrFileRead, b, err) - } crypto, err := parseCrypto(bytes.NewReader(b)) @@ -112,7 +111,7 @@ func parseCrypto(r io.Reader) ([]Crypto, error) { // parseKV parses a key/value pair into the appropriate field of c. func (c *Crypto) parseKV(k, v string) error { - vp := util.NewValueParser(v) + vp := parsers.NewValueParser(v) switch k { case "async": diff --git a/vendor/github.com/prometheus/procfs/fs_statfs_notype.go b/vendor/github.com/prometheus/procfs/fs_statfs_notype.go index 0bef25b..fc16802 100644 --- a/vendor/github.com/prometheus/procfs/fs_statfs_notype.go +++ b/vendor/github.com/prometheus/procfs/fs_statfs_notype.go @@ -15,8 +15,8 @@ package procfs -// isRealProc returns true on architectures that don't have a Type argument +// isRealProc returns false on architectures that don't have a Type argument // in their Statfs_t struct. func isRealProc(_ string) (bool, error) { - return true, nil + return false, nil } diff --git a/vendor/github.com/prometheus/procfs/fscache.go b/vendor/github.com/prometheus/procfs/fscache.go index 9dde857..388295c 100644 --- a/vendor/github.com/prometheus/procfs/fscache.go +++ b/vendor/github.com/prometheus/procfs/fscache.go @@ -21,7 +21,7 @@ import ( "strconv" "strings" - "github.com/prometheus/procfs/internal/util" + "github.com/prometheus/procfs/internal/parsers" ) // Fscacheinfo represents fscache statistics. @@ -229,7 +229,7 @@ type Fscacheinfo struct { // Fscacheinfo returns information about current fscache statistics. // See https://www.kernel.org/doc/Documentation/filesystems/caching/fscache.txt func (fs FS) Fscacheinfo() (Fscacheinfo, error) { - b, err := util.ReadFileNoStat(fs.proc.Path("fs/fscache/stats")) + b, err := parsers.ReadFileNoStat(fs.proc.Path("fs/fscache/stats")) if err != nil { return Fscacheinfo{}, err } diff --git a/vendor/github.com/prometheus/procfs/internal/fs/fs.go b/vendor/github.com/prometheus/procfs/internal/fs/fs.go index e7ccad6..bdd8010 100644 --- a/vendor/github.com/prometheus/procfs/internal/fs/fs.go +++ b/vendor/github.com/prometheus/procfs/internal/fs/fs.go @@ -31,6 +31,9 @@ const ( // DefaultSelinuxMountPoint is the common mount point of the selinuxfs. DefaultSelinuxMountPoint = "/sys/fs/selinux" + + // DefaultResctrlMountPoint is the common mount point of the resctrl filesystem. + DefaultResctrlMountPoint = "/sys/fs/resctrl" ) // FS represents a pseudo-filesystem, normally /proc or /sys, which provides an diff --git a/vendor/github.com/prometheus/procfs/internal/util/parse.go b/vendor/github.com/prometheus/procfs/internal/parsers/parse.go similarity index 99% rename from vendor/github.com/prometheus/procfs/internal/util/parse.go rename to vendor/github.com/prometheus/procfs/internal/parsers/parse.go index 30c5872..5789ae5 100644 --- a/vendor/github.com/prometheus/procfs/internal/util/parse.go +++ b/vendor/github.com/prometheus/procfs/internal/parsers/parse.go @@ -11,7 +11,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package util +package parsers import ( "errors" diff --git a/vendor/github.com/prometheus/procfs/internal/util/readfile.go b/vendor/github.com/prometheus/procfs/internal/parsers/readfile.go similarity index 98% rename from vendor/github.com/prometheus/procfs/internal/util/readfile.go rename to vendor/github.com/prometheus/procfs/internal/parsers/readfile.go index 0e41f71..c68d292 100644 --- a/vendor/github.com/prometheus/procfs/internal/util/readfile.go +++ b/vendor/github.com/prometheus/procfs/internal/parsers/readfile.go @@ -11,7 +11,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package util +package parsers import ( "io" diff --git a/vendor/github.com/prometheus/procfs/internal/util/sysreadfile.go b/vendor/github.com/prometheus/procfs/internal/parsers/sysreadfile.go similarity index 99% rename from vendor/github.com/prometheus/procfs/internal/util/sysreadfile.go rename to vendor/github.com/prometheus/procfs/internal/parsers/sysreadfile.go index f6a4a4d..0f72f60 100644 --- a/vendor/github.com/prometheus/procfs/internal/util/sysreadfile.go +++ b/vendor/github.com/prometheus/procfs/internal/parsers/sysreadfile.go @@ -13,7 +13,7 @@ //go:build (linux || darwin) && !appengine -package util +package parsers import ( "bytes" diff --git a/vendor/github.com/prometheus/procfs/internal/util/sysreadfile_compat.go b/vendor/github.com/prometheus/procfs/internal/parsers/sysreadfile_compat.go similarity index 98% rename from vendor/github.com/prometheus/procfs/internal/util/sysreadfile_compat.go rename to vendor/github.com/prometheus/procfs/internal/parsers/sysreadfile_compat.go index c80e082..6e19c45 100644 --- a/vendor/github.com/prometheus/procfs/internal/util/sysreadfile_compat.go +++ b/vendor/github.com/prometheus/procfs/internal/parsers/sysreadfile_compat.go @@ -13,7 +13,7 @@ //go:build (linux && appengine) || (!linux && !darwin) -package util +package parsers import ( "fmt" diff --git a/vendor/github.com/prometheus/procfs/internal/util/valueparser.go b/vendor/github.com/prometheus/procfs/internal/parsers/valueparser.go similarity index 99% rename from vendor/github.com/prometheus/procfs/internal/util/valueparser.go rename to vendor/github.com/prometheus/procfs/internal/parsers/valueparser.go index e0ed671..6289fd6 100644 --- a/vendor/github.com/prometheus/procfs/internal/util/valueparser.go +++ b/vendor/github.com/prometheus/procfs/internal/parsers/valueparser.go @@ -11,7 +11,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package util +package parsers import ( "strconv" diff --git a/vendor/github.com/prometheus/procfs/ipvs.go b/vendor/github.com/prometheus/procfs/ipvs.go index 5374da9..b909a3d 100644 --- a/vendor/github.com/prometheus/procfs/ipvs.go +++ b/vendor/github.com/prometheus/procfs/ipvs.go @@ -25,7 +25,7 @@ import ( "strconv" "strings" - "github.com/prometheus/procfs/internal/util" + "github.com/prometheus/procfs/internal/parsers" ) // IPVSStats holds IPVS statistics, as exposed by the kernel in `/proc/net/ip_vs_stats`. @@ -66,7 +66,7 @@ type IPVSBackendStatus struct { // IPVSStats reads the IPVS statistics from the specified `proc` filesystem. func (fs FS) IPVSStats() (IPVSStats, error) { - data, err := util.ReadFileNoStat(fs.proc.Path("net/ip_vs_stats")) + data, err := parsers.ReadFileNoStat(fs.proc.Path("net/ip_vs_stats")) if err != nil { return IPVSStats{}, err } @@ -149,6 +149,9 @@ func parseIPVSBackendStatus(file io.Reader) ([]IPVSBackendStatus, error) { if len(fields) == 0 { continue } + if len(fields) < 2 { + return nil, fmt.Errorf("%w: Malformed line %q", ErrFileParse, scanner.Text()) + } switch { case fields[0] == "IP" || fields[0] == "Prot" || fields[1] == "RemoteAddress:Port": continue diff --git a/vendor/github.com/prometheus/procfs/kernel_random.go b/vendor/github.com/prometheus/procfs/kernel_random.go index e7c5b8c..cbcd12b 100644 --- a/vendor/github.com/prometheus/procfs/kernel_random.go +++ b/vendor/github.com/prometheus/procfs/kernel_random.go @@ -18,7 +18,7 @@ package procfs import ( "os" - "github.com/prometheus/procfs/internal/util" + "github.com/prometheus/procfs/internal/parsers" ) // KernelRandom contains information about to the kernel's random number generator. @@ -48,7 +48,7 @@ func (fs FS) KernelRandom() (KernelRandom, error) { "write_wakeup_threshold": &random.WriteWakeupThreshold, "read_wakeup_threshold": &random.ReadWakeupThreshold, } { - val, err := util.ReadUintFromFile(fs.proc.Path("sys", "kernel", "random", file)) + val, err := parsers.ReadUintFromFile(fs.proc.Path("sys", "kernel", "random", file)) if os.IsNotExist(err) { continue } diff --git a/vendor/github.com/prometheus/procfs/kernel_tainted.go b/vendor/github.com/prometheus/procfs/kernel_tainted.go new file mode 100644 index 0000000..9707f02 --- /dev/null +++ b/vendor/github.com/prometheus/procfs/kernel_tainted.go @@ -0,0 +1,95 @@ +// Copyright The Prometheus Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//go:build linux + +package procfs + +import ( + "github.com/prometheus/procfs/internal/parsers" +) + +// KernelTaintBit represents a single kernel taint flag. +type KernelTaintBit struct { + // Index is the zero-based bit position in the tainted bitmask. + Index int + // Flag is the letter code identifying this taint (e.g. "L" for soft lockup). + // See https://www.kernel.org/doc/html/latest/admin-guide/tainted-kernels.html + Flag string + // Description is a human-readable explanation of what this taint means. + Description string + // Set indicates whether this taint flag is currently active. + Set bool +} + +// KernelTainted holds the kernel taint state read from /proc/sys/kernel/tainted. +type KernelTainted struct { + // Value is the raw integer from /proc/sys/kernel/tainted. + Value uint64 + // Bits contains each known taint flag and whether it is currently set. + // Flags are listed in bit-position order (bit 0 first). + Bits []KernelTaintBit +} + +// kernelTaintBitDefs lists all known kernel taint flags in bit-position order. +// Reference: https://www.kernel.org/doc/html/latest/admin-guide/tainted-kernels.html +var kernelTaintBitDefs = []struct { + flag string + description string +}{ + {"P", "Proprietary module was loaded."}, + {"F", "Module was force loaded."}, + {"S", "SMP kernel oops on an officially SMP incapable processor."}, + {"R", "Module was force unloaded."}, + {"M", "Processor reported a Machine Check Exception (MCE)."}, + {"B", "Bad page referenced or some unexpected page flags."}, + {"U", "Taint requested by userspace application."}, + {"D", "Kernel died recently, i.e. there was an OOPS or BUG."}, + {"A", "An ACPI table was overridden by user."}, + {"W", "Kernel issued warning."}, + {"C", "Staging driver was loaded."}, + {"I", "Workaround for bug in platform firmware applied."}, + {"O", "Externally-built (out-of-tree) module was loaded."}, + {"E", "Unsigned module was loaded."}, + {"L", "Soft lockup occurred."}, + {"K", "Kernel has been live patched."}, + {"X", "Auxiliary taint, defined and used by distros."}, + {"T", "The kernel was built with the struct randomization plugin."}, + {"N", "An in-kernel test such as a KUnit test has been run."}, + {"J", "Userspace used a mutating debug operation in fwctl."}, +} + +// KernelTainted reads /proc/sys/kernel/tainted and returns the raw taint value +// along with each known flag parsed into a KernelTainted struct. +// See https://www.kernel.org/doc/html/latest/admin-guide/tainted-kernels.html +func (fs FS) KernelTainted() (KernelTainted, error) { + value, err := parsers.SysReadUintFromFile(fs.proc.Path("sys", "kernel", "tainted")) + if err != nil { + return KernelTainted{}, err + } + return parseTainted(value), nil +} + +// parseTainted builds a KernelTainted from the raw taint bitmask value. +func parseTainted(value uint64) KernelTainted { + bits := make([]KernelTaintBit, len(kernelTaintBitDefs)) + for i, def := range kernelTaintBitDefs { + bits[i] = KernelTaintBit{ + Index: i, + Flag: def.flag, + Description: def.description, + Set: value&(1< 3 { + return nil, fmt.Errorf("%w: Malformed line %q", ErrFileParse, s.Text()) + } var val, valBytes uint64 val, err := strconv.ParseUint(fields[1], 0, 64) diff --git a/vendor/github.com/prometheus/procfs/mountinfo.go b/vendor/github.com/prometheus/procfs/mountinfo.go index 8594ae7..9cb3397 100644 --- a/vendor/github.com/prometheus/procfs/mountinfo.go +++ b/vendor/github.com/prometheus/procfs/mountinfo.go @@ -72,17 +72,18 @@ func parseMountInfo(info []byte) ([]*MountInfo, error) { // Parses a mountinfo file line, and converts it to a MountInfo struct. // An important check here is to see if the hyphen separator, as if it does not exist, // it means that the line is malformed. +// See: https://man7.org/linux/man-pages/man5/proc_pid_mountinfo.5.html func parseMountInfoString(mountString string) (*MountInfo, error) { var err error - mountInfo := strings.Split(mountString, " ") - mountInfoLength := len(mountInfo) - if mountInfoLength < 10 { - return nil, fmt.Errorf("%w: Too few fields in mount string: %s", ErrFileParse, mountString) + fields := strings.Split(mountString, " - ") + if len(fields) != 2 { + return nil, fmt.Errorf("%w: Could not split hyphen separator: %s", ErrFileParse, mountString) } - if mountInfo[mountInfoLength-4] != "-" { - return nil, fmt.Errorf("%w: couldn't find separator in expected field: %s", ErrFileParse, mountInfo[mountInfoLength-4]) + mountInfo := strings.Split(fields[0], " ") + if len(mountInfo) < 6 { + return nil, fmt.Errorf("%w: Too few fields in mount string: %s", ErrFileParse, mountString) } mount := &MountInfo{ @@ -90,28 +91,36 @@ func parseMountInfoString(mountString string) (*MountInfo, error) { Root: mountInfo[3], MountPoint: mountInfo[4], Options: mountOptionsParser(mountInfo[5]), - OptionalFields: nil, - FSType: mountInfo[mountInfoLength-3], - Source: mountInfo[mountInfoLength-2], - SuperOptions: mountOptionsParser(mountInfo[mountInfoLength-1]), + OptionalFields: map[string]string{}, } mount.MountID, err = strconv.Atoi(mountInfo[0]) if err != nil { - return nil, fmt.Errorf("%w: mount ID: %q", ErrFileParse, mount.MountID) + return nil, fmt.Errorf("%w: mount ID: %q", ErrFileParse, mountInfo[0]) } mount.ParentID, err = strconv.Atoi(mountInfo[1]) if err != nil { - return nil, fmt.Errorf("%w: parent ID: %q", ErrFileParse, mount.ParentID) + return nil, fmt.Errorf("%w: parent ID: %q", ErrFileParse, mountInfo[1]) } + // Has optional fields, which is a space separated list of values. // Example: shared:2 master:7 - if mountInfo[6] != "" { - mount.OptionalFields, err = mountOptionsParseOptionalFields(mountInfo[6 : mountInfoLength-4]) + if len(mountInfo) > 6 { + mount.OptionalFields, err = mountOptionsParseOptionalFields(mountInfo[6:]) if err != nil { return nil, fmt.Errorf("%w: %w", ErrFileParse, err) } } + + mountInfo = strings.SplitN(fields[1], " ", 3) + if len(mountInfo) != 3 { + return nil, fmt.Errorf("%w: Too few fields after separator: %s", ErrFileParse, mountString) + } + + mount.FSType = mountInfo[0] + mount.Source = mountInfo[1] + mount.SuperOptions = mountOptionsParser(mountInfo[2]) + return mount, nil } @@ -148,19 +157,17 @@ func mountOptionsParseOptionalFields(o []string) (map[string]string, error) { func mountOptionsParser(mountOptions string) map[string]string { opts := make(map[string]string) for opt := range strings.SplitSeq(mountOptions, ",") { - splitOption := strings.Split(opt, "=") + splitOption := strings.SplitN(opt, "=", 2) if len(splitOption) < 2 { - key := splitOption[0] - opts[key] = "" + opts[splitOption[0]] = "" } else { - key, value := splitOption[0], splitOption[1] - opts[key] = value + opts[splitOption[0]] = splitOption[1] } } return opts } -// readMountInfo reads a full mountinfo file (no 1 MiB cap, unlike util.ReadFileNoStat). +// readMountInfo reads a full mountinfo file (no 1 MiB cap, unlike parsers.ReadFileNoStat). func readMountInfo(path string) ([]byte, error) { f, err := os.Open(path) if err != nil { diff --git a/vendor/github.com/prometheus/procfs/net_conntrackstat.go b/vendor/github.com/prometheus/procfs/net_conntrackstat.go index e9ca357..2d8c72a 100644 --- a/vendor/github.com/prometheus/procfs/net_conntrackstat.go +++ b/vendor/github.com/prometheus/procfs/net_conntrackstat.go @@ -20,7 +20,7 @@ import ( "io" "strings" - "github.com/prometheus/procfs/internal/util" + "github.com/prometheus/procfs/internal/parsers" ) // A ConntrackStatEntry represents one line from net/stat/nf_conntrack @@ -49,7 +49,7 @@ func (fs FS) ConntrackStat() ([]ConntrackStatEntry, error) { // Parses a slice of ConntrackStatEntries from the given filepath. func readConntrackStat(path string) ([]ConntrackStatEntry, error) { // This file is small and can be read with one syscall. - b, err := util.ReadFileNoStat(path) + b, err := parsers.ReadFileNoStat(path) if err != nil { // Do not wrap this error so the caller can detect os.IsNotExist and // similar conditions. @@ -84,7 +84,7 @@ func parseConntrackStat(r io.Reader) ([]ConntrackStatEntry, error) { // Parses a ConntrackStatEntry from given array of fields. func parseConntrackStatEntry(fields []string) (*ConntrackStatEntry, error) { - entries, err := util.ParseHexUint64s(fields) + entries, err := parsers.ParseHexUint64s(fields) if err != nil { return nil, fmt.Errorf("%w: Cannot parse entry: %d: %w", ErrFileParse, entries, err) } diff --git a/vendor/github.com/prometheus/procfs/net_ip_socket.go b/vendor/github.com/prometheus/procfs/net_ip_socket.go index 9291f8c..b3b6ec3 100644 --- a/vendor/github.com/prometheus/procfs/net_ip_socket.go +++ b/vendor/github.com/prometheus/procfs/net_ip_socket.go @@ -178,7 +178,7 @@ func parseNetIPSocketLine(fields []string, isUDP bool) (*netIPSocketLine, error) } if line.Sl, err = strconv.ParseUint(s[0], 0, 64); err != nil { - return nil, fmt.Errorf("%w: Unable to parse sl field in %q: %w", ErrFileParse, line.Sl, err) + return nil, fmt.Errorf("%w: Unable to parse sl field in %q: %w", ErrFileParse, s[0], err) } // local_address l := strings.Split(fields[1], ":") @@ -189,7 +189,7 @@ func parseNetIPSocketLine(fields []string, isUDP bool) (*netIPSocketLine, error) return nil, err } if line.LocalPort, err = strconv.ParseUint(l[1], 16, 64); err != nil { - return nil, fmt.Errorf("%w: Unable to parse local_address port value line %q: %w", ErrFileParse, line.LocalPort, err) + return nil, fmt.Errorf("%w: Unable to parse local_address port value line %q: %w", ErrFileParse, l[1], err) } // remote_address @@ -201,12 +201,12 @@ func parseNetIPSocketLine(fields []string, isUDP bool) (*netIPSocketLine, error) return nil, err } if line.RemPort, err = strconv.ParseUint(r[1], 16, 64); err != nil { - return nil, fmt.Errorf("%w: Cannot parse rem_address port value in %q: %w", ErrFileParse, line.RemPort, err) + return nil, fmt.Errorf("%w: Cannot parse rem_address port value in %q: %w", ErrFileParse, r[1], err) } // st if line.St, err = strconv.ParseUint(fields[3], 16, 64); err != nil { - return nil, fmt.Errorf("%w: Cannot parse st value in %q: %w", ErrFileParse, line.St, err) + return nil, fmt.Errorf("%w: Cannot parse st value in %q: %w", ErrFileParse, fields[3], err) } // tx_queue and rx_queue @@ -219,27 +219,27 @@ func parseNetIPSocketLine(fields []string, isUDP bool) (*netIPSocketLine, error) ) } if line.TxQueue, err = strconv.ParseUint(q[0], 16, 64); err != nil { - return nil, fmt.Errorf("%w: Cannot parse tx_queue value in %q: %w", ErrFileParse, line.TxQueue, err) + return nil, fmt.Errorf("%w: Cannot parse tx_queue value in %q: %w", ErrFileParse, q[0], err) } if line.RxQueue, err = strconv.ParseUint(q[1], 16, 64); err != nil { - return nil, fmt.Errorf("%w: Cannot parse trx_queue value in %q: %w", ErrFileParse, line.RxQueue, err) + return nil, fmt.Errorf("%w: Cannot parse trx_queue value in %q: %w", ErrFileParse, q[1], err) } // uid if line.UID, err = strconv.ParseUint(fields[7], 0, 64); err != nil { - return nil, fmt.Errorf("%w: Cannot parse UID value in %q: %w", ErrFileParse, line.UID, err) + return nil, fmt.Errorf("%w: Cannot parse UID value in %q: %w", ErrFileParse, fields[7], err) } // inode if line.Inode, err = strconv.ParseUint(fields[9], 0, 64); err != nil { - return nil, fmt.Errorf("%w: Cannot parse inode value in %q: %w", ErrFileParse, line.Inode, err) + return nil, fmt.Errorf("%w: Cannot parse inode value in %q: %w", ErrFileParse, fields[9], err) } // drops if isUDP { drops, err := strconv.ParseUint(fields[12], 0, 64) if err != nil { - return nil, fmt.Errorf("%w: Cannot parse drops value in %q: %w", ErrFileParse, drops, err) + return nil, fmt.Errorf("%w: Cannot parse drops value in %q: %w", ErrFileParse, fields[12], err) } line.Drops = &drops } diff --git a/vendor/github.com/prometheus/procfs/net_protocols.go b/vendor/github.com/prometheus/procfs/net_protocols.go index eaa996c..829802c 100644 --- a/vendor/github.com/prometheus/procfs/net_protocols.go +++ b/vendor/github.com/prometheus/procfs/net_protocols.go @@ -20,7 +20,7 @@ import ( "strconv" "strings" - "github.com/prometheus/procfs/internal/util" + "github.com/prometheus/procfs/internal/parsers" ) // NetProtocolStats stores the contents from /proc/net/protocols. @@ -71,7 +71,7 @@ type NetProtocolCapabilities struct { // Linux 2.6.12-rc2 - https://elixir.bootlin.com/linux/v2.6.12-rc2/source/net/core/sock.c#L1452 // Linux 5.10 - https://elixir.bootlin.com/linux/v5.10.4/source/net/core/sock.c#L3586 func (fs FS) NetProtocols() (NetProtocolStats, error) { - data, err := util.ReadFileNoStat(fs.proc.Path("net/protocols")) + data, err := parsers.ReadFileNoStat(fs.proc.Path("net/protocols")) if err != nil { return NetProtocolStats{}, err } diff --git a/vendor/github.com/prometheus/procfs/net_route.go b/vendor/github.com/prometheus/procfs/net_route.go index fa3812d..6c7c480 100644 --- a/vendor/github.com/prometheus/procfs/net_route.go +++ b/vendor/github.com/prometheus/procfs/net_route.go @@ -21,7 +21,7 @@ import ( "strconv" "strings" - "github.com/prometheus/procfs/internal/util" + "github.com/prometheus/procfs/internal/parsers" ) const ( @@ -50,7 +50,7 @@ func (fs FS) NetRoute() ([]NetRouteLine, error) { } func readNetRoute(path string) ([]NetRouteLine, error) { - b, err := util.ReadFileNoStat(path) + b, err := parsers.ReadFileNoStat(path) if err != nil { return nil, err } diff --git a/vendor/github.com/prometheus/procfs/net_sockstat.go b/vendor/github.com/prometheus/procfs/net_sockstat.go index 8b221eb..9470f02 100644 --- a/vendor/github.com/prometheus/procfs/net_sockstat.go +++ b/vendor/github.com/prometheus/procfs/net_sockstat.go @@ -20,7 +20,7 @@ import ( "io" "strings" - "github.com/prometheus/procfs/internal/util" + "github.com/prometheus/procfs/internal/parsers" ) // A NetSockstat contains the output of /proc/net/sockstat{,6} for IPv4 or IPv6, @@ -60,7 +60,7 @@ func (fs FS) NetSockstat6() (*NetSockstat, error) { // readSockstat opens and parses a NetSockstat from the input file. func readSockstat(name string) (*NetSockstat, error) { // This file is small and can be read with one syscall. - b, err := util.ReadFileNoStat(name) + b, err := parsers.ReadFileNoStat(name) if err != nil { // Do not wrap this error so the caller can detect os.IsNotExist and // similar conditions. @@ -124,7 +124,7 @@ func parseSockstatKVs(kvs []string) (map[string]int, error) { // Iterate two values at a time to gather key/value pairs. out := make(map[string]int, len(kvs)/2) for i := 0; i < len(kvs); i += 2 { - vp := util.NewValueParser(kvs[i+1]) + vp := parsers.NewValueParser(kvs[i+1]) out[kvs[i]] = vp.Int() if err := vp.Err(); err != nil { diff --git a/vendor/github.com/prometheus/procfs/net_softnet.go b/vendor/github.com/prometheus/procfs/net_softnet.go index 4a2dfa1..455ec85 100644 --- a/vendor/github.com/prometheus/procfs/net_softnet.go +++ b/vendor/github.com/prometheus/procfs/net_softnet.go @@ -21,7 +21,7 @@ import ( "strconv" "strings" - "github.com/prometheus/procfs/internal/util" + "github.com/prometheus/procfs/internal/parsers" ) // For the proc file format details, @@ -57,7 +57,7 @@ var softNetProcFile = "net/softnet_stat" // NetSoftnetStat reads data from /proc/net/softnet_stat. func (fs FS) NetSoftnetStat() ([]SoftnetStat, error) { - b, err := util.ReadFileNoStat(fs.proc.Path(softNetProcFile)) + b, err := parsers.ReadFileNoStat(fs.proc.Path(softNetProcFile)) if err != nil { return nil, err } diff --git a/vendor/github.com/prometheus/procfs/net_tls_stat.go b/vendor/github.com/prometheus/procfs/net_tls_stat.go index b1b3f6a..fe8bbad 100644 --- a/vendor/github.com/prometheus/procfs/net_tls_stat.go +++ b/vendor/github.com/prometheus/procfs/net_tls_stat.go @@ -32,9 +32,9 @@ type TLSStat struct { TLSCurrTxDevice int // number of RX sessions currently installed where NIC handles cryptography TLSCurrRxDevice int - //number of TX sessions opened with host cryptography + // number of TX sessions opened with host cryptography TLSTxSw int - //number of RX sessions opened with host cryptography + // number of RX sessions opened with host cryptography TLSRxSw int // number of TX sessions opened with NIC cryptography TLSTxDevice int diff --git a/vendor/github.com/prometheus/procfs/net_wireless.go b/vendor/github.com/prometheus/procfs/net_wireless.go index f74dd3b..350a328 100644 --- a/vendor/github.com/prometheus/procfs/net_wireless.go +++ b/vendor/github.com/prometheus/procfs/net_wireless.go @@ -21,7 +21,7 @@ import ( "strconv" "strings" - "github.com/prometheus/procfs/internal/util" + "github.com/prometheus/procfs/internal/parsers" ) // Wireless models the content of /proc/net/wireless. @@ -61,7 +61,7 @@ type Wireless struct { // Wireless returns kernel wireless statistics. func (fs FS) Wireless() ([]*Wireless, error) { - b, err := util.ReadFileNoStat(fs.proc.Path("net/wireless")) + b, err := parsers.ReadFileNoStat(fs.proc.Path("net/wireless")) if err != nil { return nil, err } diff --git a/vendor/github.com/prometheus/procfs/netstat.go b/vendor/github.com/prometheus/procfs/netstat.go index dbdae47..6196b3f 100644 --- a/vendor/github.com/prometheus/procfs/netstat.go +++ b/vendor/github.com/prometheus/procfs/netstat.go @@ -61,7 +61,12 @@ func parseNetstat(filePath string) (NetStat, error) { defer file.Close() scanner := bufio.NewScanner(file) - scanner.Scan() + if !scanner.Scan() { + if err := scanner.Err(); err != nil { + return NetStat{}, err + } + return netStat, nil + } // First string is always a header for stats var headers []string @@ -78,5 +83,9 @@ func parseNetstat(filePath string) (NetStat, error) { } } + if err := scanner.Err(); err != nil { + return NetStat{}, err + } + return netStat, nil } diff --git a/vendor/github.com/prometheus/procfs/nfnetlink_queue.go b/vendor/github.com/prometheus/procfs/nfnetlink_queue.go index b0a73b1..54fbcf4 100644 --- a/vendor/github.com/prometheus/procfs/nfnetlink_queue.go +++ b/vendor/github.com/prometheus/procfs/nfnetlink_queue.go @@ -18,7 +18,7 @@ import ( "bytes" "fmt" - "github.com/prometheus/procfs/internal/util" + "github.com/prometheus/procfs/internal/parsers" ) const nfNetLinkQueueFormat = "%d %d %d %d %d %d %d %d %d" @@ -48,7 +48,7 @@ type NFNetLinkQueue struct { // NFNetLinkQueue returns information about current state of netfilter queues. func (fs FS) NFNetLinkQueue() ([]NFNetLinkQueue, error) { - data, err := util.ReadFileNoStat(fs.proc.Path("net/netfilter/nfnetlink_queue")) + data, err := parsers.ReadFileNoStat(fs.proc.Path("net/netfilter/nfnetlink_queue")) if err != nil { return nil, err } diff --git a/vendor/github.com/prometheus/procfs/proc.go b/vendor/github.com/prometheus/procfs/proc.go index 39c14aa..16b9a5e 100644 --- a/vendor/github.com/prometheus/procfs/proc.go +++ b/vendor/github.com/prometheus/procfs/proc.go @@ -22,7 +22,7 @@ import ( "strconv" "strings" - "github.com/prometheus/procfs/internal/util" + "github.com/prometheus/procfs/internal/parsers" ) // Proc provides information about a running process. @@ -128,7 +128,7 @@ func (fs FS) AllProcs() (Procs, error) { // CmdLine returns the command line of a process. func (p Proc) CmdLine() ([]string, error) { - data, err := util.ReadFileNoStat(p.path("cmdline")) + data, err := parsers.ReadFileNoStat(p.path("cmdline")) if err != nil { return nil, err } @@ -163,7 +163,7 @@ func (p Proc) Wchan() (string, error) { // Comm returns the command name of a process. func (p Proc) Comm() (string, error) { - data, err := util.ReadFileNoStat(p.path("comm")) + data, err := parsers.ReadFileNoStat(p.path("comm")) if err != nil { return "", err } @@ -281,7 +281,7 @@ func (p Proc) MountStats() ([]*Mount, error) { // It supplies information missing in `/proc/self/mounts` and // fixes various other problems with that file too. func (p Proc) MountInfo() ([]*MountInfo, error) { - data, err := util.ReadFileNoStat(p.path("mountinfo")) + data, err := parsers.ReadFileNoStat(p.path("mountinfo")) if err != nil { return nil, err } diff --git a/vendor/github.com/prometheus/procfs/proc_cgroup.go b/vendor/github.com/prometheus/procfs/proc_cgroup.go index 7e8a122..a5f9ffe 100644 --- a/vendor/github.com/prometheus/procfs/proc_cgroup.go +++ b/vendor/github.com/prometheus/procfs/proc_cgroup.go @@ -20,7 +20,7 @@ import ( "strconv" "strings" - "github.com/prometheus/procfs/internal/util" + "github.com/prometheus/procfs/internal/parsers" ) // Cgroup models one line from /proc/[pid]/cgroup. Each Cgroup struct describes the placement of a PID inside a @@ -90,7 +90,7 @@ func parseCgroups(data []byte) ([]Cgroup, error) { // control hierarchy running on this system. On every system (v1 and v2), all hierarchies contain all processes, // so the len of the returned struct is equal to the number of active hierarchies on this system. func (p Proc) Cgroups() ([]Cgroup, error) { - data, err := util.ReadFileNoStat(p.path("cgroup")) + data, err := parsers.ReadFileNoStat(p.path("cgroup")) if err != nil { return nil, err } diff --git a/vendor/github.com/prometheus/procfs/proc_cgroups.go b/vendor/github.com/prometheus/procfs/proc_cgroups.go index 0b275c3..dbf5e88 100644 --- a/vendor/github.com/prometheus/procfs/proc_cgroups.go +++ b/vendor/github.com/prometheus/procfs/proc_cgroups.go @@ -20,7 +20,7 @@ import ( "strconv" "strings" - "github.com/prometheus/procfs/internal/util" + "github.com/prometheus/procfs/internal/parsers" ) // CgroupSummary models one line from /proc/cgroups. @@ -90,7 +90,7 @@ func parseCgroupSummary(data []byte) ([]CgroupSummary, error) { // CgroupSummarys returns information about current /proc/cgroups. func (fs FS) CgroupSummarys() ([]CgroupSummary, error) { - data, err := util.ReadFileNoStat(fs.proc.Path("cgroups")) + data, err := parsers.ReadFileNoStat(fs.proc.Path("cgroups")) if err != nil { return nil, err } diff --git a/vendor/github.com/prometheus/procfs/proc_environ.go b/vendor/github.com/prometheus/procfs/proc_environ.go index 5b941de..f61eac3 100644 --- a/vendor/github.com/prometheus/procfs/proc_environ.go +++ b/vendor/github.com/prometheus/procfs/proc_environ.go @@ -16,20 +16,20 @@ package procfs import ( "strings" - "github.com/prometheus/procfs/internal/util" + "github.com/prometheus/procfs/internal/parsers" ) // Environ reads process environments from `/proc//environ`. func (p Proc) Environ() ([]string, error) { environments := make([]string, 0) - data, err := util.ReadFileNoStat(p.path("environ")) + data, err := parsers.ReadFileNoStat(p.path("environ")) if err != nil { return environments, err } environments = strings.Split(string(data), "\000") - if len(environments) > 0 { + if environments[len(environments)-1] == "" { environments = environments[:len(environments)-1] } diff --git a/vendor/github.com/prometheus/procfs/proc_fdinfo.go b/vendor/github.com/prometheus/procfs/proc_fdinfo.go index fa57761..9e3e313 100644 --- a/vendor/github.com/prometheus/procfs/proc_fdinfo.go +++ b/vendor/github.com/prometheus/procfs/proc_fdinfo.go @@ -19,7 +19,7 @@ import ( "fmt" "regexp" - "github.com/prometheus/procfs/internal/util" + "github.com/prometheus/procfs/internal/parsers" ) var ( @@ -49,7 +49,7 @@ type ProcFDInfo struct { // FDInfo constructor. On kernels older than 3.8, InotifyInfos will always be empty. func (p Proc) FDInfo(fd string) (*ProcFDInfo, error) { - data, err := util.ReadFileNoStat(p.path("fdinfo", fd)) + data, err := parsers.ReadFileNoStat(p.path("fdinfo", fd)) if err != nil { return nil, err } diff --git a/vendor/github.com/prometheus/procfs/proc_interrupts.go b/vendor/github.com/prometheus/procfs/proc_interrupts.go index 643b500..2a2412c 100644 --- a/vendor/github.com/prometheus/procfs/proc_interrupts.go +++ b/vendor/github.com/prometheus/procfs/proc_interrupts.go @@ -22,7 +22,7 @@ import ( "strconv" "strings" - "github.com/prometheus/procfs/internal/util" + "github.com/prometheus/procfs/internal/parsers" ) // Interrupt represents a single interrupt line. @@ -42,7 +42,7 @@ type Interrupts map[string]Interrupt // Interrupts creates a new instance from a given Proc instance. func (p Proc) Interrupts() (Interrupts, error) { - data, err := util.ReadFileNoStat(p.fs.proc.Path("interrupts")) + data, err := parsers.ReadFileNoStat(p.fs.proc.Path("interrupts")) if err != nil { return nil, err } diff --git a/vendor/github.com/prometheus/procfs/proc_io.go b/vendor/github.com/prometheus/procfs/proc_io.go index dd8086b..ca221bb 100644 --- a/vendor/github.com/prometheus/procfs/proc_io.go +++ b/vendor/github.com/prometheus/procfs/proc_io.go @@ -16,7 +16,7 @@ package procfs import ( "fmt" - "github.com/prometheus/procfs/internal/util" + "github.com/prometheus/procfs/internal/parsers" ) // ProcIO models the content of /proc//io. @@ -43,7 +43,7 @@ type ProcIO struct { func (p Proc) IO() (ProcIO, error) { pio := ProcIO{} - data, err := util.ReadFileNoStat(p.path("io")) + data, err := parsers.ReadFileNoStat(p.path("io")) if err != nil { return pio, err } diff --git a/vendor/github.com/prometheus/procfs/proc_limits.go b/vendor/github.com/prometheus/procfs/proc_limits.go index 4b7d337..4e94041 100644 --- a/vendor/github.com/prometheus/procfs/proc_limits.go +++ b/vendor/github.com/prometheus/procfs/proc_limits.go @@ -74,9 +74,7 @@ const ( limitsUnlimited = "unlimited" ) -var ( - limitsMatch = regexp.MustCompile(`(Max \w+\s??\w*\s?\w*)\s{2,}(\w+)\s+(\w+)`) -) +var limitsMatch = regexp.MustCompile(`(Max \w+\s??\w*\s?\w*)\s{2,}(\w+)\s+(\w+)`) // NewLimits returns the current soft limits of the process. // @@ -101,7 +99,6 @@ func (p Proc) Limits() (ProcLimits, error) { s.Scan() // Skip limits header for s.Scan() { - //fields := limitsMatch.Split(s.Text(), limitsFields) fields := limitsMatch.FindStringSubmatch(s.Text()) if len(fields) != limitsFields { return ProcLimits{}, fmt.Errorf("%w: couldn't parse %q line %q", ErrFileParse, f.Name(), s.Text()) diff --git a/vendor/github.com/prometheus/procfs/proc_maps.go b/vendor/github.com/prometheus/procfs/proc_maps.go index 08b89a6..6b04ef9 100644 --- a/vendor/github.com/prometheus/procfs/proc_maps.go +++ b/vendor/github.com/prometheus/procfs/proc_maps.go @@ -61,17 +61,17 @@ type ProcMap struct { // parseDevice parses the device token of a line and converts it to a dev_t // (mkdev) like structure. func parseDevice(s string) (uint64, error) { - i := strings.Index(s, ":") - if i == -1 { + before, after, ok := strings.Cut(s, ":") + if !ok { return 0, fmt.Errorf("%w: expected separator `:` in %s", ErrFileParse, s) } - major, err := strconv.ParseUint(s[0:i], 16, 0) + major, err := strconv.ParseUint(before, 16, 0) if err != nil { return 0, err } - minor, err := strconv.ParseUint(s[i+1:], 16, 0) + minor, err := strconv.ParseUint(after, 16, 0) if err != nil { return 0, err } @@ -91,17 +91,17 @@ func parseAddress(s string) (uintptr, error) { // parseAddresses parses the start-end address. func parseAddresses(s string) (uintptr, uintptr, error) { - idx := strings.Index(s, "-") - if idx == -1 { + before, after, ok := strings.Cut(s, "-") + if !ok { return 0, 0, fmt.Errorf("%w: expected separator `-` in %s", ErrFileParse, s) } - saddr, err := parseAddress(s[0:idx]) + saddr, err := parseAddress(before) if err != nil { return 0, 0, err } - eaddr, err := parseAddress(s[idx+1:]) + eaddr, err := parseAddress(after) if err != nil { return 0, 0, err } diff --git a/vendor/github.com/prometheus/procfs/proc_netstat.go b/vendor/github.com/prometheus/procfs/proc_netstat.go index 7f94cc8..6a118f5 100644 --- a/vendor/github.com/prometheus/procfs/proc_netstat.go +++ b/vendor/github.com/prometheus/procfs/proc_netstat.go @@ -21,7 +21,7 @@ import ( "strconv" "strings" - "github.com/prometheus/procfs/internal/util" + "github.com/prometheus/procfs/internal/parsers" ) // ProcNetstat models the content of /proc//net/netstat. @@ -146,6 +146,20 @@ type TcpExt struct { // nolint:revive TCPMTUPFail *float64 TCPMTUPSuccess *float64 TCPWqueueTooBig *float64 + + // Legacy TcpExt counters dropped from recent kernels' TcpExt table; + // modeled so consumers retain metric parity with older kernels that + // still print them in /proc/net/netstat. + TCPLoss *float64 + PAWSPassive *float64 + TCPForwardRetrans *float64 + TCPSchedulerFailed *float64 + TCPPrequeued *float64 + TCPDirectCopyFromBacklog *float64 + TCPDirectCopyFromPrequeue *float64 + TCPPrequeueDropped *float64 + TCPFACKReorder *float64 + TCPHPHitsToUser *float64 } type IpExt struct { // nolint:revive @@ -171,7 +185,7 @@ type IpExt struct { // nolint:revive func (p Proc) Netstat() (ProcNetstat, error) { filename := p.path("net/netstat") - data, err := util.ReadFileNoStat(filename) + data, err := parsers.ReadFileNoStat(filename) if err != nil { return ProcNetstat{PID: p.PID}, err } @@ -396,6 +410,26 @@ func parseProcNetstat(r io.Reader, fileName string) (ProcNetstat, error) { procNetstat.TCPMTUPSuccess = &value case "TCPWqueueTooBig": procNetstat.TCPWqueueTooBig = &value + case "TCPLoss": + procNetstat.TCPLoss = &value + case "PAWSPassive": + procNetstat.PAWSPassive = &value + case "TCPForwardRetrans": + procNetstat.TCPForwardRetrans = &value + case "TCPSchedulerFailed": + procNetstat.TCPSchedulerFailed = &value + case "TCPPrequeued": + procNetstat.TCPPrequeued = &value + case "TCPDirectCopyFromBacklog": + procNetstat.TCPDirectCopyFromBacklog = &value + case "TCPDirectCopyFromPrequeue": + procNetstat.TCPDirectCopyFromPrequeue = &value + case "TCPPrequeueDropped": + procNetstat.TCPPrequeueDropped = &value + case "TCPFACKReorder": + procNetstat.TCPFACKReorder = &value + case "TCPHPHitsToUser": + procNetstat.TCPHPHitsToUser = &value } case "IpExt": switch key { diff --git a/vendor/github.com/prometheus/procfs/proc_psi.go b/vendor/github.com/prometheus/procfs/proc_psi.go index cc2c5de..2143d67 100644 --- a/vendor/github.com/prometheus/procfs/proc_psi.go +++ b/vendor/github.com/prometheus/procfs/proc_psi.go @@ -30,7 +30,7 @@ import ( "io" "strings" - "github.com/prometheus/procfs/internal/util" + "github.com/prometheus/procfs/internal/parsers" ) const lineFormat = "avg10=%f avg60=%f avg300=%f total=%d" @@ -59,7 +59,7 @@ type PSIStats struct { // resource from /proc/pressure/. At time of writing this can be // either "cpu", "memory" or "io". func (fs FS) PSIStatsForResource(resource string) (PSIStats, error) { - data, err := util.ReadFileNoStat(fs.proc.Path(fmt.Sprintf("%s/%s", "pressure", resource))) + data, err := parsers.ReadFileNoStat(fs.proc.Path(fmt.Sprintf("%s/%s", "pressure", resource))) if err != nil { return PSIStats{}, fmt.Errorf("%w: psi_stats: unavailable for %q: %w", ErrFileRead, resource, err) } @@ -74,18 +74,18 @@ func parsePSIStats(r io.Reader) (PSIStats, error) { scanner := bufio.NewScanner(r) for scanner.Scan() { l := scanner.Text() - prefix := strings.Split(l, " ")[0] + prefix, _, _ := strings.Cut(l, " ") switch prefix { case "some": psi := PSILine{} - _, err := fmt.Sscanf(l, fmt.Sprintf("some %s", lineFormat), &psi.Avg10, &psi.Avg60, &psi.Avg300, &psi.Total) + _, err := fmt.Sscanf(l, "some "+lineFormat, &psi.Avg10, &psi.Avg60, &psi.Avg300, &psi.Total) if err != nil { return PSIStats{}, err } psiStats.Some = &psi case "full": psi := PSILine{} - _, err := fmt.Sscanf(l, fmt.Sprintf("full %s", lineFormat), &psi.Avg10, &psi.Avg60, &psi.Avg300, &psi.Total) + _, err := fmt.Sscanf(l, "full "+lineFormat, &psi.Avg10, &psi.Avg60, &psi.Avg300, &psi.Total) if err != nil { return PSIStats{}, err } diff --git a/vendor/github.com/prometheus/procfs/proc_smaps.go b/vendor/github.com/prometheus/procfs/proc_smaps.go index f637309..2383b59 100644 --- a/vendor/github.com/prometheus/procfs/proc_smaps.go +++ b/vendor/github.com/prometheus/procfs/proc_smaps.go @@ -23,13 +23,11 @@ import ( "strconv" "strings" - "github.com/prometheus/procfs/internal/util" + "github.com/prometheus/procfs/internal/parsers" ) -var ( - // Match the header line before each mapped zone in `/proc/pid/smaps`. - procSMapsHeaderLine = regexp.MustCompile(`^[a-f0-9].*$`) -) +// Match the header line before each mapped zone in `/proc/pid/smaps`. +var procSMapsHeaderLine = regexp.MustCompile(`^[a-f0-9].*$`) type ProcSMapsRollup struct { // Amount of the mapping that is currently resident in RAM. @@ -60,7 +58,7 @@ type ProcSMapsRollup struct { // If smaps_rollup does not exists (require kernel >= 4.15), the content of /proc/pid/smaps will // we read and summed. func (p Proc) ProcSMapsRollup() (ProcSMapsRollup, error) { - data, err := util.ReadFileNoStat(p.path("smaps_rollup")) + data, err := parsers.ReadFileNoStat(p.path("smaps_rollup")) if err != nil && os.IsNotExist(err) { return p.procSMapsRollupManual() } diff --git a/vendor/github.com/prometheus/procfs/proc_snmp.go b/vendor/github.com/prometheus/procfs/proc_snmp.go index 8d9a9bc..531bc83 100644 --- a/vendor/github.com/prometheus/procfs/proc_snmp.go +++ b/vendor/github.com/prometheus/procfs/proc_snmp.go @@ -21,7 +21,7 @@ import ( "strconv" "strings" - "github.com/prometheus/procfs/internal/util" + "github.com/prometheus/procfs/internal/parsers" ) // ProcSnmp models the content of /proc//net/snmp. @@ -135,7 +135,7 @@ type UdpLite struct { // nolint:revive func (p Proc) Snmp() (ProcSnmp, error) { filename := p.path("net/snmp") - data, err := util.ReadFileNoStat(filename) + data, err := parsers.ReadFileNoStat(filename) if err != nil { return ProcSnmp{PID: p.PID}, err } diff --git a/vendor/github.com/prometheus/procfs/proc_snmp6.go b/vendor/github.com/prometheus/procfs/proc_snmp6.go index 841fef4..8296a4a 100644 --- a/vendor/github.com/prometheus/procfs/proc_snmp6.go +++ b/vendor/github.com/prometheus/procfs/proc_snmp6.go @@ -22,7 +22,7 @@ import ( "strconv" "strings" - "github.com/prometheus/procfs/internal/util" + "github.com/prometheus/procfs/internal/parsers" ) // ProcSnmp6 models the content of /proc//net/snmp6. @@ -140,7 +140,7 @@ type UdpLite6 struct { // nolint:revive func (p Proc) Snmp6() (ProcSnmp6, error) { filename := p.path("net/snmp6") - data, err := util.ReadFileNoStat(filename) + data, err := parsers.ReadFileNoStat(filename) if err != nil { // On systems with IPv6 disabled, this file won't exist. // Do nothing. diff --git a/vendor/github.com/prometheus/procfs/proc_stat.go b/vendor/github.com/prometheus/procfs/proc_stat.go index 02e3f9e..d9e544b 100644 --- a/vendor/github.com/prometheus/procfs/proc_stat.go +++ b/vendor/github.com/prometheus/procfs/proc_stat.go @@ -18,7 +18,7 @@ import ( "fmt" "os" - "github.com/prometheus/procfs/internal/util" + "github.com/prometheus/procfs/internal/parsers" ) // Originally, this USER_HZ value was dynamically retrieved via a sysconf call @@ -134,7 +134,7 @@ func (p Proc) NewStat() (ProcStat, error) { // Stat returns the current status information of the process. func (p Proc) Stat() (ProcStat, error) { - data, err := util.ReadFileNoStat(p.path("stat")) + data, err := parsers.ReadFileNoStat(p.path("stat")) if err != nil { return ProcStat{}, err } diff --git a/vendor/github.com/prometheus/procfs/proc_statm.go b/vendor/github.com/prometheus/procfs/proc_statm.go index 6bcc97e..5fbe279 100644 --- a/vendor/github.com/prometheus/procfs/proc_statm.go +++ b/vendor/github.com/prometheus/procfs/proc_statm.go @@ -18,7 +18,7 @@ import ( "strconv" "strings" - "github.com/prometheus/procfs/internal/util" + "github.com/prometheus/procfs/internal/parsers" ) // - https://man7.org/linux/man-pages/man5/proc_pid_statm.5.html @@ -53,7 +53,7 @@ func (p Proc) NewStatm() (ProcStatm, error) { // Statm returns the current memory usage information of the process. func (p Proc) Statm() (ProcStatm, error) { - data, err := util.ReadFileNoStat(p.path("statm")) + data, err := parsers.ReadFileNoStat(p.path("statm")) if err != nil { return ProcStatm{}, err } diff --git a/vendor/github.com/prometheus/procfs/proc_status.go b/vendor/github.com/prometheus/procfs/proc_status.go index 12d6558..c3775c3 100644 --- a/vendor/github.com/prometheus/procfs/proc_status.go +++ b/vendor/github.com/prometheus/procfs/proc_status.go @@ -20,7 +20,7 @@ import ( "strconv" "strings" - "github.com/prometheus/procfs/internal/util" + "github.com/prometheus/procfs/internal/parsers" ) // ProcStatus provides status information about the process, @@ -100,7 +100,7 @@ type ProcStatus struct { // NewStatus returns the current status information of the process. func (p Proc) NewStatus() (ProcStatus, error) { - data, err := util.ReadFileNoStat(p.path("status")) + data, err := parsers.ReadFileNoStat(p.path("status")) if err != nil { return ProcStatus{}, err } @@ -135,7 +135,7 @@ func (p Proc) NewStatus() (ProcStatus, error) { return s, nil } -func (s *ProcStatus) fillStatus(k string, vString string, vUint uint64, vUintBytes uint64) error { +func (s *ProcStatus) fillStatus(k, vString string, vUint, vUintBytes uint64) error { switch k { case "Tgid": s.TGID = int(vUint) @@ -261,7 +261,6 @@ func calcCpusAllowedList(cpuString string) []uint64 { cpu, _ := strconv.ParseUint(l[0], 10, 64) g = append(g, cpu) } - } slices.Sort(g) diff --git a/vendor/github.com/prometheus/procfs/proc_sys.go b/vendor/github.com/prometheus/procfs/proc_sys.go index 52658a4..efa3646 100644 --- a/vendor/github.com/prometheus/procfs/proc_sys.go +++ b/vendor/github.com/prometheus/procfs/proc_sys.go @@ -17,7 +17,7 @@ import ( "fmt" "strings" - "github.com/prometheus/procfs/internal/util" + "github.com/prometheus/procfs/internal/parsers" ) func sysctlToPath(sysctl string) string { @@ -25,12 +25,11 @@ func sysctlToPath(sysctl string) string { } func (fs FS) SysctlStrings(sysctl string) ([]string, error) { - value, err := util.SysReadFile(fs.proc.Path("sys", sysctlToPath(sysctl))) + value, err := parsers.SysReadFile(fs.proc.Path("sys", sysctlToPath(sysctl))) if err != nil { return nil, err } return strings.Fields(value), nil - } func (fs FS) SysctlInts(sysctl string) ([]int, error) { @@ -41,7 +40,7 @@ func (fs FS) SysctlInts(sysctl string) ([]int, error) { values := make([]int, len(fields)) for i, f := range fields { - vp := util.NewValueParser(f) + vp := parsers.NewValueParser(f) values[i] = vp.Int() if err := vp.Err(); err != nil { return nil, fmt.Errorf("%w: field %d in sysctl %s is not a valid int: %w", ErrFileParse, i, sysctl, err) diff --git a/vendor/github.com/prometheus/procfs/slab.go b/vendor/github.com/prometheus/procfs/slab.go index 32a0467..b78bac6 100644 --- a/vendor/github.com/prometheus/procfs/slab.go +++ b/vendor/github.com/prometheus/procfs/slab.go @@ -21,7 +21,7 @@ import ( "strconv" "strings" - "github.com/prometheus/procfs/internal/util" + "github.com/prometheus/procfs/internal/parsers" ) var ( @@ -142,7 +142,7 @@ func (fs FS) SlabInfo() (SlabInfo, error) { // TODO: Consider passing options to allow for parsing different // slabinfo versions. However, slabinfo 2.1 has been stable since // kernel 2.6.10 and later. - data, err := util.ReadFileNoStat(fs.proc.Path("slabinfo")) + data, err := parsers.ReadFileNoStat(fs.proc.Path("slabinfo")) if err != nil { return SlabInfo{}, err } diff --git a/vendor/github.com/prometheus/procfs/softirqs.go b/vendor/github.com/prometheus/procfs/softirqs.go index 47b73a7..dcd5859 100644 --- a/vendor/github.com/prometheus/procfs/softirqs.go +++ b/vendor/github.com/prometheus/procfs/softirqs.go @@ -21,7 +21,7 @@ import ( "strconv" "strings" - "github.com/prometheus/procfs/internal/util" + "github.com/prometheus/procfs/internal/parsers" ) // Softirqs represents the softirq statistics. @@ -40,7 +40,7 @@ type Softirqs struct { func (fs FS) Softirqs() (Softirqs, error) { fileName := fs.proc.Path("softirqs") - data, err := util.ReadFileNoStat(fileName) + data, err := parsers.ReadFileNoStat(fileName) if err != nil { return Softirqs{}, err } diff --git a/vendor/github.com/prometheus/procfs/stat.go b/vendor/github.com/prometheus/procfs/stat.go index 593ad0f..77b8d2e 100644 --- a/vendor/github.com/prometheus/procfs/stat.go +++ b/vendor/github.com/prometheus/procfs/stat.go @@ -23,7 +23,7 @@ import ( "strings" "github.com/prometheus/procfs/internal/fs" - "github.com/prometheus/procfs/internal/util" + "github.com/prometheus/procfs/internal/parsers" ) // CPUStat shows how much time the cpu spend in various stages. @@ -135,7 +135,6 @@ func parseSoftIRQStat(line string) (SoftIRQStat, uint64, error) { &softIRQStat.Block, &softIRQStat.BlockIoPoll, &softIRQStat.Tasklet, &softIRQStat.Sched, &softIRQStat.Hrtimer, &softIRQStat.Rcu) - if err != nil { return SoftIRQStat{}, 0, fmt.Errorf("%w: couldn't parse %q (softirq): %w", ErrFileParse, line, err) } @@ -167,7 +166,7 @@ func (fs FS) NewStat() (Stat, error) { // See: https://www.kernel.org/doc/Documentation/filesystems/proc.txt func (fs FS) Stat() (Stat, error) { fileName := fs.proc.Path("stat") - data, err := util.ReadFileNoStat(fileName) + data, err := parsers.ReadFileNoStat(fileName) if err != nil { return Stat{}, err } @@ -178,7 +177,7 @@ func (fs FS) Stat() (Stat, error) { return procStat, nil } -// parseStat parses the metrics from /proc/[pid]/stat. +// parseStat parses the metrics from /proc/stat. func parseStat(r io.Reader, fileName string) (Stat, error) { var ( scanner = bufio.NewScanner(r) @@ -194,7 +193,7 @@ func parseStat(r io.Reader, fileName string) (Stat, error) { for scanner.Scan() { line := scanner.Text() - parts := strings.Fields(scanner.Text()) + parts := strings.Fields(line) // require at least if len(parts) < 2 { continue diff --git a/vendor/github.com/prometheus/procfs/swaps.go b/vendor/github.com/prometheus/procfs/swaps.go index ee17bf4..8f9bbfb 100644 --- a/vendor/github.com/prometheus/procfs/swaps.go +++ b/vendor/github.com/prometheus/procfs/swaps.go @@ -20,7 +20,7 @@ import ( "strconv" "strings" - "github.com/prometheus/procfs/internal/util" + "github.com/prometheus/procfs/internal/parsers" ) // Swap represents an entry in /proc/swaps. @@ -34,7 +34,7 @@ type Swap struct { // Swaps returns a slice of all configured swap devices on the system. func (fs FS) Swaps() ([]*Swap, error) { - data, err := util.ReadFileNoStat(fs.proc.Path("swaps")) + data, err := parsers.ReadFileNoStat(fs.proc.Path("swaps")) if err != nil { return nil, err } diff --git a/vendor/github.com/prometheus/procfs/vm.go b/vendor/github.com/prometheus/procfs/vm.go index 52180c0..62725b4 100644 --- a/vendor/github.com/prometheus/procfs/vm.go +++ b/vendor/github.com/prometheus/procfs/vm.go @@ -21,7 +21,7 @@ import ( "path/filepath" "strings" - "github.com/prometheus/procfs/internal/util" + "github.com/prometheus/procfs/internal/parsers" ) // The VM interface is described at @@ -102,11 +102,11 @@ func (fs FS) VM() (*VM, error) { name := filepath.Join(path, f.Name()) // ignore errors on read, as there are some write only // in /proc/sys/vm - value, err := util.SysReadFile(name) + value, err := parsers.SysReadFile(name) if err != nil { continue } - vp := util.NewValueParser(value) + vp := parsers.NewValueParser(value) switch f.Name() { case "admin_reserve_kbytes": @@ -143,7 +143,7 @@ func (fs FS) VM() (*VM, error) { stringSlice := strings.Fields(value) pint64Slice := make([]*int64, 0, len(stringSlice)) for _, value := range stringSlice { - vp := util.NewValueParser(value) + vp := parsers.NewValueParser(value) pint64Slice = append(pint64Slice, vp.PInt64()) } vm.LowmemReserveRatio = pint64Slice diff --git a/vendor/github.com/prometheus/procfs/zoneinfo.go b/vendor/github.com/prometheus/procfs/zoneinfo.go index 63d1898..60ee335 100644 --- a/vendor/github.com/prometheus/procfs/zoneinfo.go +++ b/vendor/github.com/prometheus/procfs/zoneinfo.go @@ -22,7 +22,7 @@ import ( "regexp" "strings" - "github.com/prometheus/procfs/internal/util" + "github.com/prometheus/procfs/internal/parsers" ) // Zoneinfo holds info parsed from /proc/zoneinfo. @@ -84,7 +84,6 @@ func (fs FS) Zoneinfo() ([]Zoneinfo, error) { } func parseZoneinfo(zoneinfoData []byte) ([]Zoneinfo, error) { - zoneinfo := []Zoneinfo{} for block := range bytes.SplitSeq(zoneinfoData, []byte("\nNode")) { @@ -103,7 +102,7 @@ func parseZoneinfo(zoneinfoData []byte) ([]Zoneinfo, error) { if len(parts) < 2 { continue } - vp := util.NewValueParser(parts[1]) + vp := parsers.NewValueParser(parts[1]) switch parts[0] { case "nr_free_pages": zoneinfoElement.NrFreePages = vp.PInt64() @@ -179,7 +178,7 @@ func parseZoneinfo(zoneinfoData []byte) ([]Zoneinfo, error) { protectionValues = strings.Replace(protectionValues, ")", "", 1) protectionValues = strings.TrimSpace(protectionValues) protectionStringMap := strings.Split(protectionValues, ", ") - val, err := util.ParsePInt64s(protectionStringMap) + val, err := parsers.ParsePInt64s(protectionStringMap) if err == nil { zoneinfoElement.Protection = val } diff --git a/vendor/github.com/sethvargo/go-retry/README.md b/vendor/github.com/sethvargo/go-retry/README.md index 3464965..531b6a1 100644 --- a/vendor/github.com/sethvargo/go-retry/README.md +++ b/vendor/github.com/sethvargo/go-retry/README.md @@ -94,7 +94,7 @@ NewExponential(1 * time.Second) The Fibonacci backoff uses the Fibonacci sequence to calculate the backoff. The next value is the sum of the current value and the previous value. This means -retires happen quickly at first, but then gradually take slower, ideal for +retries happen quickly at first, but then gradually slow down, ideal for network-type issues. Here is an example: ```text diff --git a/vendor/github.com/sethvargo/go-retry/backoff.go b/vendor/github.com/sethvargo/go-retry/backoff.go index 47f7475..c0614a0 100644 --- a/vendor/github.com/sethvargo/go-retry/backoff.go +++ b/vendor/github.com/sethvargo/go-retry/backoff.go @@ -1,6 +1,7 @@ package retry import ( + "math" "math/rand/v2" "sync" "time" @@ -25,7 +26,7 @@ func (b BackoffFunc) Next() (time.Duration, bool) { // WithJitter wraps a backoff function and adds the specified jitter. j can be // interpreted as "+/- j". For example, if j were 5 seconds and the backoff // returned 20s, the value could be between 15 and 25 seconds. The value can -// never be less than 0. +// never be less than 0 or greater than the maximum time.Duration. func WithJitter(j time.Duration, next Backoff) Backoff { return BackoffFunc(func() (time.Duration, bool) { val, stop := next.Next() @@ -37,17 +38,30 @@ func WithJitter(j time.Duration, next Backoff) Backoff { return val, false } - diff := time.Duration(rand.Int64N(int64(j)*2) - int64(j)) - val = max(val+diff, 0) - return val, false + // The unsigned bound fits even when twice j exceeds MaxInt64. + diff := time.Duration(rand.Uint64N(uint64(j)*2) - uint64(j)) + return addClamp(val, diff), false }) } +func addClamp(a, b time.Duration) time.Duration { + if b > 0 && a > math.MaxInt64-b { + return math.MaxInt64 + } + if b < 0 && a < math.MinInt64-b { + return 0 + } + return max(a+b, 0) +} + // WithJitterPercent wraps a backoff function and adds the specified jitter // percentage. j can be interpreted as "+/- j%". For example, if j were 5 and // the backoff returned 20s, the value could be between 19 and 21 seconds. The // value can never be less than 0 or greater than 100. func WithJitterPercent(j uint64, next Backoff) Backoff { + // Above 100 the computed percentage goes negative and int64(j)*2 overflows. + j = min(j, 100) + return BackoffFunc(func() (time.Duration, bool) { val, stop := next.Next() if stop { @@ -62,11 +76,20 @@ func WithJitterPercent(j uint64, next Backoff) Backoff { top := rand.Int64N(int64(j)*2) - int64(j) pct := 1 - float64(top)/100.0 - val = max(time.Duration(float64(val)*pct), 0) - return val, false + return durationFromFloat(float64(val) * pct), false }) } +func durationFromFloat(f float64) time.Duration { + if f >= math.MaxInt64 { + return math.MaxInt64 + } + if f <= 0 { + return 0 + } + return time.Duration(f) +} + // WithFullJitter wraps a backoff function and returns a random value between // zero (inclusive) and the wrapped backoff's returned value (exclusive). For // example, if the backoff returned 20s, the value could be anywhere in [0, 20s). @@ -124,7 +147,7 @@ func WithCappedDuration(cap time.Duration, next Backoff) Backoff { return 0, true } - if val <= 0 || val > cap { + if val > cap { val = cap } return val, false @@ -148,7 +171,7 @@ func WithMaxDuration(timeout time.Duration, next Backoff) Backoff { return 0, true } - if val <= 0 || val > diff { + if val > diff { val = diff } return val, false diff --git a/vendor/github.com/txix-open/isp-kit/bgjobx/handler/sync.go b/vendor/github.com/txix-open/isp-kit/bgjobx/handler/sync.go index 27f924d..eb4511d 100644 --- a/vendor/github.com/txix-open/isp-kit/bgjobx/handler/sync.go +++ b/vendor/github.com/txix-open/isp-kit/bgjobx/handler/sync.go @@ -2,6 +2,7 @@ package handler import ( "context" + "slices" "github.com/txix-open/bgjob" ) @@ -38,8 +39,8 @@ type Sync struct { // will be the outermost wrapper. func NewSync(adapter SyncHandlerAdapter, middlewares ...Middleware) Sync { s := Sync{} - for i := len(middlewares) - 1; i >= 0; i-- { - adapter = middlewares[i](adapter) + for _, middleware := range slices.Backward(middlewares) { + adapter = middleware(adapter) } s.handler = adapter return s diff --git a/vendor/github.com/txix-open/isp-kit/bootstrap/bootstrap.go b/vendor/github.com/txix-open/isp-kit/bootstrap/bootstrap.go index 57b86e0..227f3fd 100644 --- a/vendor/github.com/txix-open/isp-kit/bootstrap/bootstrap.go +++ b/vendor/github.com/txix-open/isp-kit/bootstrap/bootstrap.go @@ -308,6 +308,7 @@ func initClusterClient( }, EndpointsResolver: endpointsResolver, MetricsAutodiscovery: metricsServiceDiscovery(localConfig, broadcastHost), + ModuleLeaderMode: localConfig.ModuleLeaderMode, } schema := rc.GenerateConfigSchema(remoteConfig) diff --git a/vendor/github.com/txix-open/isp-kit/bootstrap/local_config.go b/vendor/github.com/txix-open/isp-kit/bootstrap/local_config.go index a1b8a01..6af9d3e 100644 --- a/vendor/github.com/txix-open/isp-kit/bootstrap/local_config.go +++ b/vendor/github.com/txix-open/isp-kit/bootstrap/local_config.go @@ -41,6 +41,7 @@ type LocalConfig struct { // - DefaultRemoteConfigPath: Custom path for default remote configuration file (optional) // - RemoteConfigReceiverTimeout: Timeout for receiving remote configuration updates // - MetricsAutodiscovery: Configuration for Prometheus metrics auto-discovery +// - ModuleLeaderMode: Module leader election mode announced in MODULE:READY (optional) type ClusteredLocalConfig struct { LocalConfig @@ -48,6 +49,7 @@ type ClusteredLocalConfig struct { DefaultRemoteConfigPath string RemoteConfigReceiverTimeout time.Duration MetricsAutodiscovery MetricsAutodiscovery + ModuleLeaderMode string } // Logs configures log sampling and rate limiting. diff --git a/vendor/github.com/txix-open/isp-kit/cluster/client.go b/vendor/github.com/txix-open/isp-kit/cluster/client.go index 9c542d9..3409486 100644 --- a/vendor/github.com/txix-open/isp-kit/cluster/client.go +++ b/vendor/github.com/txix-open/isp-kit/cluster/client.go @@ -348,6 +348,7 @@ func (c *Client) notifyModuleReady(ctx context.Context, cli *clientWrapper, requ RequiredModules: moduleDependencies, Address: c.moduleInfo.GrpcOuterAddress, MetricsAutodiscovery: c.moduleInfo.MetricsAutodiscovery, + ModuleLeaderMode: c.moduleInfo.ModuleLeaderMode, } _, err := cli.EmitJsonWithAck(ctx, ModuleReady, declaration) if err != nil { diff --git a/vendor/github.com/txix-open/isp-kit/cluster/domain.go b/vendor/github.com/txix-open/isp-kit/cluster/domain.go index 2b592c3..a8b7c81 100644 --- a/vendor/github.com/txix-open/isp-kit/cluster/domain.go +++ b/vendor/github.com/txix-open/isp-kit/cluster/domain.go @@ -10,12 +10,19 @@ const ( GrpcTransport = "grpc" HttpTransport = "http" EmptyTransport = "empty" + + ModuleLeaderModeNone = "" + ModuleLeaderModeRequestElection = "REQUEST_ELECTION" + ModuleLeaderModeImLeader = "IM_LEADER" + ModuleLeaderModeImFollower = "IM_FOLLOWER" ) -// AddressConfiguration represents the IP address and port for a service endpoint. +// AddressConfiguration represents the IP address and port for a service endpoint, +// and whether this instance is the module leader. type AddressConfiguration struct { - IP string `json:"ip"` - Port string `json:"port"` + IP string `json:"ip"` + Port string `json:"port"` + IsModuleLeader bool } // ConfigData contains configuration data for a module, including version information @@ -36,6 +43,7 @@ type ModuleInfo struct { GrpcOuterAddress AddressConfiguration EndpointsResolver EndpointsResolver MetricsAutodiscovery *MetricsAutodiscovery + ModuleLeaderMode string } // RoutingConfig represents a list of backend declarations for routing configuration. @@ -52,6 +60,7 @@ type BackendDeclaration struct { RequiredModules []ModuleDependency Address AddressConfiguration MetricsAutodiscovery *MetricsAutodiscovery + ModuleLeaderMode string } // EndpointDescriptor describes an HTTP endpoint, including its path, method, authentication diff --git a/vendor/github.com/txix-open/isp-kit/grpc/client/client.go b/vendor/github.com/txix-open/isp-kit/grpc/client/client.go index 2dc9498..99a156e 100644 --- a/vendor/github.com/txix-open/isp-kit/grpc/client/client.go +++ b/vendor/github.com/txix-open/isp-kit/grpc/client/client.go @@ -7,6 +7,7 @@ package client import ( "context" + "slices" "strings" "sync/atomic" @@ -96,8 +97,8 @@ func New(initialHosts []string, opts ...Option) (*Client, error) { cli.grpcCli = grpcCli roundTripper := cli.do - for i := len(cli.middlewares) - 1; i >= 0; i-- { - roundTripper = cli.middlewares[i](roundTripper) + for _, v := range slices.Backward(cli.middlewares) { + roundTripper = v(roundTripper) } cli.roundTripper = roundTripper diff --git a/vendor/github.com/txix-open/isp-kit/http/httpcli/client.go b/vendor/github.com/txix-open/isp-kit/http/httpcli/client.go index f1c86e8..cd0a879 100644 --- a/vendor/github.com/txix-open/isp-kit/http/httpcli/client.go +++ b/vendor/github.com/txix-open/isp-kit/http/httpcli/client.go @@ -8,6 +8,7 @@ import ( "net" "net/http" "net/url" + "slices" "strings" "time" @@ -289,8 +290,8 @@ func defaultTransportDialContext(dialer *net.Dialer) func(context.Context, strin // nolint:ireturn func joinMiddlewares(root RoundTripper, mws ...Middleware) RoundTripper { roundTripper := root - for i := len(mws) - 1; i >= 0; i-- { - roundTripper = mws[i](roundTripper) + for _, mw := range slices.Backward(mws) { + roundTripper = mw(roundTripper) } return roundTripper } diff --git a/vendor/github.com/txix-open/isp-kit/log/logutil/err_log_func.go b/vendor/github.com/txix-open/isp-kit/log/logutil/err_log_func.go index 8a900d4..4590f7e 100644 --- a/vendor/github.com/txix-open/isp-kit/log/logutil/err_log_func.go +++ b/vendor/github.com/txix-open/isp-kit/log/logutil/err_log_func.go @@ -27,7 +27,7 @@ func LogLevelForError(err error) log.Level { // It uses LogLevelForError to determine the log level and returns the corresponding Logger method. func LogLevelFuncForError(err error, logger log.Logger) func(ctx context.Context, message any, fields ...log.Field) { logLevel := LogLevelForError(err) - switch logLevel { + switch logLevel { //nolint:exhaustive case log.ErrorLevel: return logger.Error case log.WarnLevel: diff --git a/vendor/github.com/txix-open/isp-kit/test/rct/README.md b/vendor/github.com/txix-open/isp-kit/test/rct/README.md index b91a440..68ca6a7 100644 --- a/vendor/github.com/txix-open/isp-kit/test/rct/README.md +++ b/vendor/github.com/txix-open/isp-kit/test/rct/README.md @@ -8,14 +8,9 @@ Проверяет, что удалённая конфигурация соответствует сгенерированной JSON-схеме и проходит валидацию. -* Проверяет отсутствие устаревшего тега `valid` * Проверяет соответствие структуры JSON-схеме * Выполняет валидацию значений с помощью `validator.Default` -### `FindTag[T any](v T, tag string) bool` - -Рекурсивно проверяет, содержит ли структура тег с указанным именем. - ## Usage ### Example usage in test diff --git a/vendor/github.com/txix-open/isp-kit/test/rct/remote_config.go b/vendor/github.com/txix-open/isp-kit/test/rct/remote_config.go index 32a63dd..1cf6eb6 100644 --- a/vendor/github.com/txix-open/isp-kit/test/rct/remote_config.go +++ b/vendor/github.com/txix-open/isp-kit/test/rct/remote_config.go @@ -5,7 +5,6 @@ package rct import ( "os" - "reflect" "testing" "github.com/stretchr/testify/require" @@ -21,7 +20,6 @@ import ( // validator tag validation. // // The function checks: -// - No deprecated 'valid' tags are present // - The default configuration file is valid against the generated schema // - The configuration can be unmarshaled from the file // - The configuration passes validation @@ -30,9 +28,6 @@ import ( func Test[T any](t *testing.T, defaultRemoteConfigPath string, remoteConfig T) { require := require.New(t) - validatorTag := "valid" - require.Falsef(FindTag(remoteConfig, validatorTag), "'%s' tag is not longer supported, you must use https://github.com/go-playground/validator", validatorTag) - defaultRemoteConfig, err := os.ReadFile(defaultRemoteConfigPath) require.NoError(err) @@ -58,34 +53,3 @@ func Test[T any](t *testing.T, defaultRemoteConfigPath string, remoteConfig T) { err = validator.Default.ValidateToError(remoteConfig) require.NoError(err) } - -// FindTag recursively searches a type for the specified struct tag. -// It traverses structs, maps, arrays, and slices to find any field -// that has the given tag. Returns true if the tag is found. -func FindTag[T any](v T, tag string) bool { - t := reflect.TypeOf(v) - if t == nil { - return false - } - queue := []reflect.Type{t} - for len(queue) > 0 { - cur := queue[0] - queue = queue[1:] - if cur.Kind() == reflect.Ptr { - cur = cur.Elem() - } - // nolint:exhaustive - switch cur.Kind() { - case reflect.Struct: - for field := range cur.Fields() { - if field.Tag.Get(tag) != "" { - return true - } - queue = append(queue, field.Type) - } - case reflect.Map, reflect.Array, reflect.Slice: - queue = append(queue, cur.Elem()) - } - } - return false -} diff --git a/vendor/github.com/txix-open/validator/v10/.gitignore b/vendor/github.com/txix-open/validator/v10/.gitignore index 6305e52..087a2ea 100644 --- a/vendor/github.com/txix-open/validator/v10/.gitignore +++ b/vendor/github.com/txix-open/validator/v10/.gitignore @@ -7,6 +7,8 @@ _obj _test bin +.gocache/ +.gomodcache/ # Architecture specific extensions/prefixes *.[568vq] @@ -30,3 +32,4 @@ _testmain.go cover.html README.html .idea +.claude/ diff --git a/vendor/github.com/txix-open/validator/v10/.golangci.yaml b/vendor/github.com/txix-open/validator/v10/.golangci.yaml index d3d8e39..65efd23 100644 --- a/vendor/github.com/txix-open/validator/v10/.golangci.yaml +++ b/vendor/github.com/txix-open/validator/v10/.golangci.yaml @@ -2,6 +2,8 @@ version: "2" linters: default: all disable: + - noinlineerr + - wsl_v5 - copyloopvar - cyclop - depguard @@ -12,6 +14,7 @@ linters: - errorlint - exhaustive - exhaustruct + - exhaustruct_v5 - forbidigo - forcetypeassert - funlen @@ -30,6 +33,7 @@ linters: - maintidx - misspell - mnd + - modernize - nakedret - nestif - nilnil @@ -50,3 +54,8 @@ linters: - varnamelen - wrapcheck - wsl + - gomodguard + settings: + govet: + disable: + - inline diff --git a/vendor/github.com/txix-open/validator/v10/CLAUDE.md b/vendor/github.com/txix-open/validator/v10/CLAUDE.md new file mode 100644 index 0000000..ac6b6d7 --- /dev/null +++ b/vendor/github.com/txix-open/validator/v10/CLAUDE.md @@ -0,0 +1,78 @@ +# CLAUDE.md + +This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. + +## Repository + +`github.com/go-playground/validator/v10` — struct and field validation library based on struct tags. The module path ends in `/v10`; changes must preserve v10 API compatibility. Contributions require test coverage (see `.github/CONTRIBUTING.md`). + +## Commands + +```bash +make test # go test -cover -race ./... +make lint # installs golangci-lint v2.0.2 if missing, then runs it +make bench # go test -run=NONE -bench=. -benchmem ./... + +# Single test / subtest +go test -run TestName ./... +go test -run TestName/subtest_name ./... + +# Single benchmark +go test -run=NONE -bench=BenchmarkFieldSuccess -benchmem ./... +``` + +Tests live alongside source in the package root (`validator_test.go`, `benchmarks_test.go`); run them from the repo root. Non-standard validators and translations are separate packages (`./non-standard/validators`, `./translations/...`) and are included by `./...`. + +## Architecture + +The library compiles validation tags into cached execution plans, then runs them against values via reflection. Understanding three layers is enough to be productive: + +### 1. Registration & configuration — [validator_instance.go](validator_instance.go) +`Validate` is the singleton entry point. It holds: +- `validations` — tag → `FuncCtx` (the validator functions) +- `aliases` — shorthand tag → expanded tag expression +- `customFuncs` — `reflect.Type` → value extractor (for types like `sql.NullString` or anything implementing the `Valuer` interface, see [doc.go](doc.go)) +- `structLevelFuncs` — struct-level validators +- `tagCache` and `structCache` — parsed-tag and parsed-struct caches (critical for performance; `Validate` is thread-safe and must be used as a singleton) + +Options live in [options.go](options.go) (`WithRequiredStructEnabled`, `WithPrivateFieldValidation`, etc.). `WithRequiredStructEnabled` is the forward-compatible default users should adopt before v11. + +### 2. Baked-in validators — [baked_in.go](baked_in.go) +All built-in tags (`required`, `email`, `uuid`, `oneof`, `gt`, cross-field `eqfield`, etc.) are registered here as `Func`/`FuncCtx` receiving a `FieldLevel` (see [field_level.go](field_level.go)). `restrictedTags` enumerates names that cannot be overridden. Cross-field validators resolve the other field via `fl.GetStructFieldOK*` against the parent struct captured in the execution context. + +Adjacent data tables: +- [regexes.go](regexes.go), [postcode_regexes.go](postcode_regexes.go) — compiled regexps used by validators +- [country_codes.go](country_codes.go), [currency_codes.go](currency_codes.go), [language_codes.go](language_codes.go) — lookup tables + +When adding a new tag: register it in `bakedInValidators` in [baked_in.go](baked_in.go), add its description to the table in [README.md](README.md), and add tests in [validator_test.go](validator_test.go). + +### 3. Execution — [validator.go](validator.go) + [cache.go](cache.go) +- [cache.go](cache.go) parses struct tags into `cField` and `cTag` linked lists once per type and stores them in `structCache`/`tagCache`. `cTag.typeof` (`typeDefault`, `typeOmitEmpty`, `typeDive`, `typeStructOnly`, `typeOr`, etc.) tells the executor what to do. +- [validator.go](validator.go) contains the per-call `validate` struct (pooled via `sync.Pool`) and the `validateStruct` / `traverseField` mutual recursion. `ns`/`actualNs` are the accumulated dotted namespaces used in error paths; `dive`, `keys`, `endkeys` push/pop through slices/maps. + +Public entry points live on `Validate`: `Struct`, `StructCtx`, `StructPartial`, `StructExcept`, `StructFiltered`, `Var`, `VarWithValue`, and their `Ctx` variants. + +### Errors +[errors.go](errors.go) defines `ValidationErrors` (a `[]FieldError`) and `InvalidValidationError`. Per [README.md](README.md) and [doc.go](doc.go), callers type-assert `err.(validator.ValidationErrors)` after checking `err != nil`. Only `InvalidValidationError` signals misuse (e.g. passing a non-struct to `Struct`). + +### Struct-level & field-level custom validators +[struct_level.go](struct_level.go) and [field_level.go](field_level.go) define the contexts passed to user-registered functions. Struct-level validators report errors via `StructLevel.ReportError` / `ReportValidationErrors` — they operate on the whole struct instead of a single field. + +### Translations — [translations.go](translations.go) + [translations/](translations/) +Each locale under `translations/` registers a human-readable message per tag against a `ut.Translator`. `FieldError.Translate(trans)` consumes the registered `TranslationFunc`. When adding a new tag with a translation, add an entry in each locale package — translations are parallel packages, not a single table. + +### Non-standard validators — [non-standard/validators/](non-standard/validators/) +Opt-in validators (`NotBlank`) users register manually. Keep niche or opinionated validators here rather than expanding `baked_in.go`. + +## Performance-sensitive areas + +Validation is on the hot path for many users. When touching [cache.go](cache.go), [validator.go](validator.go), or `baked_in.go` hot functions: +- Avoid allocations in the success path — several baked-in validators and the executor reuse pooled buffers (`validate.misc`, `str1`, `str2`). +- Benchmarks in [benchmarks_test.go](benchmarks_test.go) gate regressions; run `make bench` before and after significant changes and include results in the PR if they move. + +## Conventions + +- Go module minimum version is pinned in [go.mod](go.mod); don't lower it. +- Don't introduce new top-level exported types without need — most extension happens through `Register*` methods on `Validate`. +- `restrictedTags` (in [baked_in.go](baked_in.go)) is intentionally a denylist for aliases and registrations; adding a tag with one of those names will break the parser. +- Examples live under `_examples/` (underscore prefix excludes them from the module build). Keep them runnable as standalone `main` packages. diff --git a/vendor/github.com/txix-open/validator/v10/Makefile b/vendor/github.com/txix-open/validator/v10/Makefile index e7caab7..bb494a2 100644 --- a/vendor/github.com/txix-open/validator/v10/Makefile +++ b/vendor/github.com/txix-open/validator/v10/Makefile @@ -3,7 +3,7 @@ GOCMD=go linters-install: @golangci-lint --version >/dev/null 2>&1 || { \ echo "installing linting tools..."; \ - curl -sfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh| sh -s v2.0.2; \ + curl -sfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh| sh -s v2.13.1; \ } lint: linters-install diff --git a/vendor/github.com/txix-open/validator/v10/README.md b/vendor/github.com/txix-open/validator/v10/README.md index 25b6e21..c0b85cf 100644 --- a/vendor/github.com/txix-open/validator/v10/README.md +++ b/vendor/github.com/txix-open/validator/v10/README.md @@ -15,7 +15,7 @@ It has the following **unique** features: - Slice, Array and Map diving, which allows any or all levels of a multidimensional field to be validated. - Ability to dive into both map keys and values for validation - Handles type interface by determining it's underlying type prior to validation. -- Handles custom field types such as sql driver Valuer see [Valuer](https://golang.org/src/database/sql/driver/types.go?s=1210:1293#L29) +- Handles custom field types such as sql driver [Valuer](https://golang.org/src/database/sql/driver/types.go?s=1210:1293#L29) and the [Valuer interface](https://github.com/go-playground/validator/blob/master/_examples/valuer/main.go) - Alias validation tags, which allows for mapping of several validations to a single tag for easier defining of validations on structs - Extraction of custom defined Field Name e.g. can specify to extract the JSON name while validating and have it available in the resulting FieldError - Customizable i18n aware error messages. @@ -24,7 +24,7 @@ It has the following **unique** features: A Call for Maintainers ---------------------- -Please read the discussiong started [here](https://github.com/go-playground/validator/discussions/1330) if you are interested in contributing/helping maintain this package. +Please read the discussion started [here](https://github.com/go-playground/validator/discussions/1330) if you are interested in contributing/helping maintain this package. Installation ------------ @@ -51,7 +51,8 @@ Validator returns only InvalidValidationError for bad validation input, nil or V ```go err := validate.Struct(mystruct) -validationErrors := err.(validator.ValidationErrors) +var validationErrors validator.ValidationErrors +errors.As(err, &validationErrors) ``` Usage and documentation @@ -84,7 +85,7 @@ validate := validator.New(validator.WithRequiredStructEnabled()) | eqcsfield | Field Equals Another Field (relative)| | eqfield | Field Equals Another Field | | fieldcontains | Check the indicated characters are present in the Field | -| fieldexcludes | Check the indicated characters are not present in the field | +| fieldexcludes | Current field does not contain another field's value | | gtcsfield | Field Greater Than Another Relative Field | | gtecsfield | Field Greater Than or Equal To Another Relative Field | | gtefield | Field Greater Than or Equal To Another Field | @@ -106,8 +107,9 @@ validate := validator.New(validator.WithRequiredStructEnabled()) | datauri | Data URL | | fqdn | Full Qualified Domain Name (FQDN) | | hostname | Hostname RFC 952 | -| hostname_port | HostPort | | hostname_rfc1123 | Hostname RFC 1123 | +| hostname_port | HostPort | +| port | Port number | | ip | Internet Protocol Address IP | | ip4_addr | Internet Protocol Address IPv4 | | ip6_addr | Internet Protocol Address IPv6 | @@ -122,18 +124,24 @@ validate := validator.New(validator.WithRequiredStructEnabled()) | udp6_addr | User Datagram Protocol Address UDPv6 | | udp_addr | User Datagram Protocol Address UDP | | unix_addr | Unix domain socket end point Address | +| uds_exists | Unix domain socket exists (checks filesystem sockets and Linux abstract sockets) | | uri | URI String | | url | URL String | -| http_url | HTTP URL String | +| http_url | HTTP(s) URL String | +| https_url | HTTPS-only URL String | +| origin | Web origin (URL with HTTP(S) scheme and host, but no path/query/fragment) | | url_encoded | URL Encoded | | urn_rfc2141 | Urn RFC 2141 String | +| urn_rfc8141 | Urn RFC 8141 String | ### Strings: | Tag | Description | | - | - | | alpha | Alpha Only | +| alphaspace | Alpha Space | | alphanum | Alphanumeric | +| alphanumspace | Alphanumeric Space | | alphanumunicode | Alphanumeric Unicode | | alphaunicode | Alpha Unicode | | ascii | ASCII | @@ -161,8 +169,10 @@ validate := validator.New(validator.WithRequiredStructEnabled()) | base64 | Base64 String | | base64url | Base64URL String | | base64rawurl | Base64RawURL String | -| bic | Business Identifier Code (ISO 9362) | +| bic_iso_9362_2014 | Business Identifier Code (ISO 9362:2014) | +| bic | Business Identifier Code (ISO 9362:2022) | | bcp47_language_tag | Language tag (BCP 47) | +| bcp47_strict_language_tag | Language tag (BCP 47), strictly following RFC 5646 | | btc_addr | Bitcoin Address | | btc_addr_bech32 | Bitcoin Bech32 Address (segwit) | | credit_card | Credit Card Number | @@ -171,14 +181,16 @@ validate := validator.New(validator.WithRequiredStructEnabled()) | cron | Cron | | spicedb | SpiceDb ObjectID/Permission/Type | | datetime | Datetime | +| duration | Duration string (Go time.ParseDuration format) | | e164 | e164 formatted phone number | -| ein | U.S. Employeer Identification Number | +| ein | U.S. Employer Identification Number | | email | E-mail String | eth_addr | Ethereum Address | | hexadecimal | Hexadecimal String | | hexcolor | Hexcolor String | | hsl | HSL String | | hsla | HSLA String | +| cmyk | CMYK String | | html | HTML Tags | | html_encoded | HTML Encoded | | isbn | International Standard Book Number | @@ -215,7 +227,7 @@ validate := validator.New(validator.WithRequiredStructEnabled()) | sha384 | SHA384 hash | | sha512 | SHA512 hash | | ripemd128 | RIPEMD-128 hash | -| ripemd128 | RIPEMD-160 hash | +| ripemd160 | RIPEMD-160 hash | | tiger128 | TIGER128 hash | | tiger160 | TIGER160 hash | | tiger192 | TIGER192 hash | @@ -243,11 +255,13 @@ validate := validator.New(validator.WithRequiredStructEnabled()) | file | Existing File | | filepath | File Path | | image | Image | +| mimetype | MIME Type | | isdefault | Is Default | | len | Length | | max | Maximum | | min | Minimum | | oneof | One Of | +| noneof | None Of | | required | Required | | required_if | Required If | | required_unless | Required Unless | @@ -268,8 +282,9 @@ validate := validator.New(validator.WithRequiredStructEnabled()) #### Aliases: | Tag | Description | | - | - | -| iscolor | hexcolor\|rgb\|rgba\|hsl\|hsla | +| iscolor | hexcolor\|rgb\|rgba\|hsl\|hsla\|cmyk | | country_code | iso3166_1_alpha2\|iso3166_1_alpha3\|iso3166_1_alpha_numeric | +| eu_country_code | iso3166_1_alpha2_eu\|iso3166_1_alpha3_eu\|iso3166_1_alpha_numeric_eu | Benchmarks ------ diff --git a/vendor/github.com/txix-open/validator/v10/baked_in.go b/vendor/github.com/txix-open/validator/v10/baked_in.go index f7e8948..80e0277 100644 --- a/vendor/github.com/txix-open/validator/v10/baked_in.go +++ b/vendor/github.com/txix-open/validator/v10/baked_in.go @@ -1,8 +1,8 @@ package validator import ( + "bufio" "bytes" - "cmp" "context" "crypto/sha256" "encoding/hex" @@ -15,6 +15,9 @@ import ( "net/url" "os" "reflect" + "regexp" + "runtime" + "slices" "strconv" "strings" "sync" @@ -68,7 +71,7 @@ var ( // defines a common or complex set of validation(s) to simplify // adding validation to structs. bakedInAliases = map[string]string{ - "iscolor": "hexcolor|rgb|rgba|hsl|hsla", + "iscolor": "hexcolor|rgb|rgba|hsl|hsla|cmyk", "country_code": "iso3166_1_alpha2|iso3166_1_alpha3|iso3166_1_alpha_numeric", "eu_country_code": "iso3166_1_alpha2_eu|iso3166_1_alpha3_eu|iso3166_1_alpha_numeric_eu", } @@ -118,7 +121,9 @@ var ( "fieldcontains": fieldContains, "fieldexcludes": fieldExcludes, "alpha": isAlpha, + "alphaspace": isAlphaSpace, "alphanum": isAlphanum, + "alphanumspace": isAlphaNumericSpace, "alphaunicode": isAlphaUnicode, "alphanumunicode": isAlphanumUnicode, "boolean": isBoolean, @@ -130,11 +135,15 @@ var ( "rgba": isRGBA, "hsl": isHSL, "hsla": isHSLA, + "cmyk": isCMYK, "e164": isE164, "email": isEmail, "url": isURL, "http_url": isHttpURL, + "https_url": isHttpsURL, "uri": isURI, + "origin": isOrigin, + "urn_rfc8141": isUrnRFC8141, // RFC 8141 "urn_rfc2141": isUrnRFC2141, // RFC 2141 "file": isFile, "filepath": isFilePath, @@ -153,6 +162,7 @@ var ( "startsnotwith": startsNotWith, "endsnotwith": endsNotWith, "image": isImage, + "mimetype": isMIMEType, "isbn": isISBN, "isbn10": isISBN10, "isbn13": isISBN13, @@ -203,13 +213,17 @@ var ( "ip6_addr": isIP6AddrResolvable, "ip_addr": isIPAddrResolvable, "unix_addr": isUnixAddrResolvable, + "uds_exists": isUnixDomainSocketExists, "mac": isMAC, "hostname": isHostnameRFC952, // RFC 952 "hostname_rfc1123": isHostnameRFC1123, // RFC 1123 + "hostname_label": isHostnameLabel, "fqdn": isFQDN, "unique": isUnique, "oneof": isOneOf, "oneofci": isOneOfCI, + "noneof": isNoneOf, + "noneofci": isNoneOfCI, "html": isHTML, "html_encoded": isHTMLEncoded, "url_encoded": isURLEncoded, @@ -233,9 +247,11 @@ var ( "iso4217": isIso4217, "iso4217_numeric": isIso4217Numeric, "bcp47_language_tag": isBCP47LanguageTag, + "bcp47_strict_language_tag": isBCP47StrictLanguageTag, "postcode_iso3166_alpha2": isPostcodeByIso3166Alpha2, "postcode_iso3166_alpha2_field": isPostcodeByIso3166Alpha2Field, - "bic": isIsoBicFormat, + "bic_iso_9362_2014": isIsoBic2014Format, + "bic": isIsoBic2022Format, "semver": isSemverFormat, "dns_rfc1035_label": isDnsRFC1035LabelFormat, "credit_card": isCreditCard, @@ -246,6 +262,7 @@ var ( "cron": isCron, "spicedb": isSpiceDB, "ein": isEIN, + "duration": isDuration, "validateFn": isValidateFn, } ) @@ -253,6 +270,33 @@ var ( var ( oneofValsCache = map[string][]string{} oneofValsCacheRWLock = sync.RWMutex{} + + // BCP47 language tag + // according to https://www.rfc-editor.org/rfc/bcp/bcp47.txt + bcp47LanguageTagRe = regexp.MustCompile(strings.Join([]string{ + // group 1: + `^(`, + // irregular + `en-gb-oed|i-ami|i-bnn|i-default|i-enochian|i-hak|i-klingon|i-lux|i-mingo|i-navajo|i-pwn|i-tao|i-tay|i-tsu|`, + `sgn-be-fr|sgn-be-nl|sgn-ch-de|`, + // regular + `art-lojban|cel-gaulish|no-bok|no-nyn|zh-guoyu|zh-hakka|zh-min|zh-min-nan|zh-xiang|`, + // privateuse + `x-[a-z0-9]{1,8}`, + `)$`, + + `|`, + + // langtag + `^`, + `((?:[a-z]{2,3}(?:-[a-z]{3}){0,3})|[a-z]{4}|[a-z]{5,8})`, // group 2: language + `(?:-([a-z]{4}))?`, // group 3: script + `(?:-([a-z]{2}|[0-9]{3}))?`, // group 4: region + `(?:-((?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3})(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*))?`, // group 5: variant + `(?:-((?:[a-wyz0-9](?:-[a-z0-9]{2,8})+)(?:-(?:[a-wyz0-9](?:-[a-z0-9]{2,8})+))*))?`, // group 6: extension + `(?:-x(?:-[a-z0-9]{1,8})+)?`, + `$`, + }, "")) ) func parseOneOfParam2(s string) []string { @@ -297,14 +341,10 @@ func isOneOf(fl FieldLevel) bool { case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: v = strconv.FormatUint(field.Uint(), 10) default: - panic(fmt.Sprintf("Bad field type %T", field.Interface())) + panic(fmt.Sprintf("Bad field type %s", field.Type())) } - for i := 0; i < len(vals); i++ { - if vals[i] == v { - return true - } - } - return false + + return slices.Contains(vals, v) } // isOneOfCI is the validation function for validating if the current field's value is one of the provided string values (case insensitive). @@ -313,87 +353,143 @@ func isOneOfCI(fl FieldLevel) bool { field := fl.Field() if field.Kind() != reflect.String { - panic(fmt.Sprintf("Bad field type %T", field.Interface())) + panic(fmt.Sprintf("Bad field type %s", field.Type())) } - v := field.String() - for _, val := range vals { - if strings.EqualFold(val, v) { - return true - } - } - return false + + return slices.ContainsFunc(vals, func(val string) bool { + return strings.EqualFold(val, field.String()) + }) +} + +// isNoneOf validates that the current field's value is not one of the provided string or integer values +func isNoneOf(fl FieldLevel) bool { + return !isOneOf(fl) +} + +// isNoneOfCI validates that the current field's value is not one of the provided string values (case insensitive) +func isNoneOfCI(fl FieldLevel) bool { + return !isOneOfCI(fl) } // isUnique is the validation function for validating if each array|slice|map value is unique func isUnique(fl FieldLevel) bool { field := fl.Field() param := fl.Param() - v := reflect.ValueOf(struct{}{}) + + // sentinel used as map key for nil values + var nilKey = struct{}{} switch field.Kind() { case reflect.Slice, reflect.Array: - elem := field.Type().Elem() - if elem.Kind() == reflect.Ptr { - elem = elem.Elem() - } + seen := make(map[interface{}]struct{}) - if param == "" { - m := reflect.MakeMap(reflect.MapOf(elem, v.Type())) - - for i := 0; i < field.Len(); i++ { - m.SetMapIndex(reflect.Indirect(field.Index(i)), v) - } - return field.Len() == m.Len() - } - - sf, ok := elem.FieldByName(param) - if !ok { - panic(fmt.Sprintf("Bad field name %s", param)) - } - - sfTyp := sf.Type - if sfTyp.Kind() == reflect.Ptr { - sfTyp = sfTyp.Elem() - } - - m := reflect.MakeMap(reflect.MapOf(sfTyp, v.Type())) - var fieldlen int for i := 0; i < field.Len(); i++ { - key := reflect.Indirect(reflect.Indirect(field.Index(i)).FieldByName(param)) - if key.IsValid() { - fieldlen++ - m.SetMapIndex(key, v) + elem := field.Index(i) + + // -------- unique (no param) -------- + if param == "" { + var key interface{} + + if elem.Kind() == reflect.Ptr { + if elem.IsNil() { + key = nilKey + } else { + key = elem.Elem().Interface() // <-- compare underlying value + } + } else { + key = elem.Interface() + } + + if _, ok := seen[key]; ok { + return false + } + seen[key] = struct{}{} + continue } + + // -------- unique=Field -------- + + if elem.Kind() == reflect.Ptr { + if elem.IsNil() { + if _, ok := seen[nilKey]; ok { + return false + } + seen[nilKey] = struct{}{} + continue + } + elem = elem.Elem() + } + + if elem.Kind() != reflect.Struct { + panic(fmt.Sprintf("Bad field type %s", elem.Type())) + } + + sf := elem.FieldByName(param) + if !sf.IsValid() { + panic(fmt.Sprintf("Bad field name %s", param)) + } + + var key interface{} + + if sf.Kind() == reflect.Ptr { + if sf.IsNil() { + key = nilKey + } else { + key = sf.Elem().Interface() + } + } else { + key = sf.Interface() + } + + if _, ok := seen[key]; ok { + return false + } + seen[key] = struct{}{} } - return fieldlen == m.Len() + + return true + case reflect.Map: - var m reflect.Value - if field.Type().Elem().Kind() == reflect.Ptr { - m = reflect.MakeMap(reflect.MapOf(field.Type().Elem().Elem(), v.Type())) - } else { - m = reflect.MakeMap(reflect.MapOf(field.Type().Elem(), v.Type())) - } + seen := make(map[interface{}]struct{}) for _, k := range field.MapKeys() { - m.SetMapIndex(reflect.Indirect(field.MapIndex(k)), v) + val := field.MapIndex(k) + + var key interface{} + + if val.Kind() == reflect.Ptr { + if val.IsNil() { + key = nilKey + } else { + key = val.Elem().Interface() // <-- compare underlying value + } + } else { + key = val.Interface() + } + + if _, ok := seen[key]; ok { + return false + } + seen[key] = struct{}{} } - return field.Len() == m.Len() + return true + default: if parent := fl.Parent(); parent.Kind() == reflect.Struct { uniqueField := parent.FieldByName(param) - if uniqueField == reflect.ValueOf(nil) { + if !uniqueField.IsValid() { panic(fmt.Sprintf("Bad field name provided %s", param)) } if uniqueField.Kind() != field.Kind() { - panic(fmt.Sprintf("Bad field type %T:%T", field.Interface(), uniqueField.Interface())) + panic(fmt.Sprintf("Bad field type %s:%s", field.Type(), uniqueField.Type())) } - return field.Interface() != uniqueField.Interface() + return getValue(field) != getValue(uniqueField) } - panic(fmt.Sprintf("Bad field type %T", field.Interface())) + panic(fmt.Sprintf("Bad field type %s", field.Type())) } } @@ -474,7 +570,7 @@ func isLongitude(fl FieldLevel) bool { case reflect.Float64: v = strconv.FormatFloat(field.Float(), 'f', -1, 64) default: - panic(fmt.Sprintf("Bad field type %T", field.Interface())) + panic(fmt.Sprintf("Bad field type %s", field.Type())) } return longitudeRegex().MatchString(v) @@ -497,7 +593,7 @@ func isLatitude(fl FieldLevel) bool { case reflect.Float64: v = strconv.FormatFloat(field.Float(), 'f', -1, 64) default: - panic(fmt.Sprintf("Bad field type %T", field.Interface())) + panic(fmt.Sprintf("Bad field type %s", field.Type())) } return latitudeRegex().MatchString(v) @@ -531,12 +627,20 @@ func hasMultiByteCharacter(fl FieldLevel) bool { // isPrintableASCII is the validation function for validating if the field's value is a valid printable ASCII character. func isPrintableASCII(fl FieldLevel) bool { - return printableASCIIRegex().MatchString(fl.Field().String()) + field := fl.Field() + if field.Kind() == reflect.String { + return printableASCIIRegex().MatchString(field.String()) + } + return false } // isASCII is the validation function for validating if the field's value is a valid ASCII character. func isASCII(fl FieldLevel) bool { - return aSCIIRegex().MatchString(fl.Field().String()) + field := fl.Field() + if field.Kind() == reflect.String { + return aSCIIRegex().MatchString(field.String()) + } + return false } // isUUID5 is the validation function for validating if the field's value is a valid v5 UUID. @@ -968,8 +1072,8 @@ func isNeField(fl FieldLevel) bool { fieldType := field.Type() if fieldType.ConvertibleTo(timeType) && currentField.Type().ConvertibleTo(timeType) { - t := currentField.Interface().(time.Time) - fieldTime := field.Interface().(time.Time) + t := getValue(currentField).(time.Time) + fieldTime := getValue(field).(time.Time) return !fieldTime.Equal(t) } @@ -1023,8 +1127,8 @@ func isLteCrossStructField(fl FieldLevel) bool { fieldType := field.Type() if fieldType.ConvertibleTo(timeType) && topField.Type().ConvertibleTo(timeType) { - fieldTime := field.Convert(timeType).Interface().(time.Time) - topTime := topField.Convert(timeType).Interface().(time.Time) + fieldTime := getValue(field.Convert(timeType)).(time.Time) + topTime := getValue(topField.Convert(timeType)).(time.Time) return fieldTime.Before(topTime) || fieldTime.Equal(topTime) } @@ -1068,8 +1172,8 @@ func isLtCrossStructField(fl FieldLevel) bool { fieldType := field.Type() if fieldType.ConvertibleTo(timeType) && topField.Type().ConvertibleTo(timeType) { - fieldTime := field.Convert(timeType).Interface().(time.Time) - topTime := topField.Convert(timeType).Interface().(time.Time) + fieldTime := getValue(field.Convert(timeType)).(time.Time) + topTime := getValue(topField.Convert(timeType)).(time.Time) return fieldTime.Before(topTime) } @@ -1112,8 +1216,8 @@ func isGteCrossStructField(fl FieldLevel) bool { fieldType := field.Type() if fieldType.ConvertibleTo(timeType) && topField.Type().ConvertibleTo(timeType) { - fieldTime := field.Convert(timeType).Interface().(time.Time) - topTime := topField.Convert(timeType).Interface().(time.Time) + fieldTime := getValue(field.Convert(timeType)).(time.Time) + topTime := getValue(topField.Convert(timeType)).(time.Time) return fieldTime.After(topTime) || fieldTime.Equal(topTime) } @@ -1156,8 +1260,8 @@ func isGtCrossStructField(fl FieldLevel) bool { fieldType := field.Type() if fieldType.ConvertibleTo(timeType) && topField.Type().ConvertibleTo(timeType) { - fieldTime := field.Convert(timeType).Interface().(time.Time) - topTime := topField.Convert(timeType).Interface().(time.Time) + fieldTime := getValue(field.Convert(timeType)).(time.Time) + topTime := getValue(topField.Convert(timeType)).(time.Time) return fieldTime.After(topTime) } @@ -1203,8 +1307,8 @@ func isNeCrossStructField(fl FieldLevel) bool { fieldType := field.Type() if fieldType.ConvertibleTo(timeType) && topField.Type().ConvertibleTo(timeType) { - t := field.Convert(timeType).Interface().(time.Time) - fieldTime := topField.Convert(timeType).Interface().(time.Time) + t := getValue(field.Convert(timeType)).(time.Time) + fieldTime := getValue(topField.Convert(timeType)).(time.Time) return !fieldTime.Equal(t) } @@ -1250,8 +1354,8 @@ func isEqCrossStructField(fl FieldLevel) bool { fieldType := field.Type() if fieldType.ConvertibleTo(timeType) && topField.Type().ConvertibleTo(timeType) { - t := field.Convert(timeType).Interface().(time.Time) - fieldTime := topField.Convert(timeType).Interface().(time.Time) + t := getValue(field.Convert(timeType)).(time.Time) + fieldTime := getValue(topField.Convert(timeType)).(time.Time) return fieldTime.Equal(t) } @@ -1297,8 +1401,8 @@ func isEqField(fl FieldLevel) bool { fieldType := field.Type() if fieldType.ConvertibleTo(timeType) && currentField.Type().ConvertibleTo(timeType) { - t := currentField.Convert(timeType).Interface().(time.Time) - fieldTime := field.Convert(timeType).Interface().(time.Time) + t := getValue(currentField.Convert(timeType)).(time.Time) + fieldTime := getValue(field.Convert(timeType)).(time.Time) return fieldTime.Equal(t) } @@ -1353,7 +1457,7 @@ func isEq(fl FieldLevel) bool { return field.Bool() == p } - panic(fmt.Sprintf("Bad field type %T", field.Interface())) + panic(fmt.Sprintf("Bad field type %s", field.Type())) } // isEqIgnoreCase is the validation function for validating if the current field's string value is @@ -1368,7 +1472,7 @@ func isEqIgnoreCase(fl FieldLevel) bool { return strings.EqualFold(field.String(), param) } - panic(fmt.Sprintf("Bad field type %T", field.Interface())) + panic(fmt.Sprintf("Bad field type %s", field.Type())) } // isPostcodeByIso3166Alpha2 validates by value which is country code in iso 3166 alpha 2 @@ -1402,7 +1506,7 @@ func isPostcodeByIso3166Alpha2Field(fl FieldLevel) bool { } if kind != reflect.String { - panic(fmt.Sprintf("Bad field type %T", currentField.Interface())) + panic(fmt.Sprintf("Bad field type %s", currentField.Type())) } postcodeRegexInit.Do(initPostcodes) @@ -1458,16 +1562,65 @@ func isURI(fl FieldLevel) bool { return err == nil } - panic(fmt.Sprintf("Bad field type %T", field.Interface())) + panic(fmt.Sprintf("Bad field type %s", field.Type())) } -// isFileURL is the helper function for validating if the `path` valid file URL as per RFC8089 -func isFileURL(path string) bool { - if !strings.HasPrefix(path, "file:/") { - return false +// isOrigin checks if a field value is a valid web origin URL with HTTP(S) scheme and host defined, but no path, query, or fragment. +func isOrigin(fl FieldLevel) bool { + field := fl.Field() + + if field.Kind() == reflect.String { + s := field.String() + + if len(s) == 0 { + return false + } + + // Fragments with empty content ("#") are not detectable after parse and + // u.Fragment will be empty even if # is present in the URL. + if strings.Contains(s, "#") { + return false + } + + u, err := url.Parse(s) + if err != nil { + return false + } + + if u.Scheme != "http" && u.Scheme != "https" { + return false + } + + if u.Path != "" || u.RawQuery != "" || u.ForceQuery || u.Fragment != "" { + return false + } + + if u.User != nil { + return false + } + + hostname := u.Hostname() + if hostname == "" { + return false + } + if net.ParseIP(hostname) == nil && !hostnameRegexRFC1123().MatchString(hostname) { + return false + } + + portStr := u.Port() + if portStr != "" { + // Port 0 is reserved (RFC 6335) and has no valid use as an origin port. + // https://www.rfc-editor.org/rfc/rfc6335.html#section-6 + port, portErr := strconv.ParseUint(portStr, 10, 16) + if portErr != nil || port == 0 { + return false + } + } + + return true } - _, err := url.ParseRequestURI(path) - return err == nil + + panic(fmt.Sprintf("Bad field type %s", field.Type())) } // isURL is the validation function for validating if the current field's value is a valid URL. @@ -1483,23 +1636,20 @@ func isURL(fl FieldLevel) bool { return false } - if isFileURL(s) { - return true - } - url, err := url.Parse(s) if err != nil || url.Scheme == "" { return false } + isFileScheme := url.Scheme == "file" - if url.Host == "" && url.Fragment == "" && url.Opaque == "" { + if (isFileScheme && (len(url.Path) == 0 || url.Path == "/")) || (!isFileScheme && len(url.Host) == 0 && len(url.Fragment) == 0 && len(url.Opaque) == 0) { return false } return true } - panic(fmt.Sprintf("Bad field type %T", field.Interface())) + panic(fmt.Sprintf("Bad field type %s", field.Type())) } // isHttpURL is the validation function for validating if the current field's value is a valid HTTP(s) URL. @@ -1522,6 +1672,49 @@ func isHttpURL(fl FieldLevel) bool { return url.Scheme == "http" || url.Scheme == "https" } + panic(fmt.Sprintf("Bad field type %s", field.Type())) +} + +// isHttpsURL is the validation function for validating if the current field's value is a valid HTTPS-only URL. +func isHttpsURL(fl FieldLevel) bool { + if !isURL(fl) { + return false + } + + field := fl.Field() + switch field.Kind() { + case reflect.String: + + s := strings.ToLower(field.String()) + + url, err := url.Parse(s) + if err != nil || url.Host == "" { + return false + } + + return url.Scheme == "https" + } + + panic(fmt.Sprintf("Bad field type %s", field.Type())) +} + +// isUrnRFC8141 is the validation function for validating if the current field's value is a valid URN as per RFC 8141. +func isUrnRFC8141(fl FieldLevel) bool { + field := fl.Field() + + switch field.Kind() { + case reflect.String: + + str := field.String() + if str == "" { + return false + } + + _, match := urn.Parse([]byte(str), urn.WithParsingMode(urn.RFC8141Only)) + + return match + } + panic(fmt.Sprintf("Bad field type %T", field.Interface())) } @@ -1539,7 +1732,7 @@ func isUrnRFC2141(fl FieldLevel) bool { return match } - panic(fmt.Sprintf("Bad field type %T", field.Interface())) + panic(fmt.Sprintf("Bad field type %s", field.Type())) } // isFile is the validation function for validating if the current field's value is a valid existing file path. @@ -1556,7 +1749,64 @@ func isFile(fl FieldLevel) bool { return !fileInfo.IsDir() } - panic(fmt.Sprintf("Bad field type %T", field.Interface())) + panic(fmt.Sprintf("Bad field type %s", field.Type())) +} + +func detectFileMIMEType(field reflect.Value) (string, bool) { + switch field.Kind() { + case reflect.String: + filePath := field.String() + fileInfo, err := os.Stat(filePath) + if err != nil || fileInfo.IsDir() { + return "", false + } + + file, err := os.Open(filePath) + if err != nil { + return "", false + } + defer func() { + _ = file.Close() + }() + + mime, err := mimetype.DetectReader(file) + if err != nil { + return "", false + } + + return mime.String(), true + } + + panic(fmt.Sprintf("Bad field type %s", field.Type())) +} + +func matchesMIMEType(mime, expected string) bool { + expectedType, expectedSubtype, ok := strings.Cut(strings.TrimSpace(expected), "/") + if !ok || expectedType == "" || expectedSubtype == "" { + return false + } + + mimeType, mimeSubtype, ok := strings.Cut(mime, "/") + if !ok || mimeType == "" || mimeSubtype == "" { + return false + } + + if expectedSubtype == "*" { + return mimeType == expectedType + } + + return mimeType == expectedType && mimeSubtype == expectedSubtype +} + +// isMIMEType is the validation function for validating if the current field's value contains the path to a file +// whose detected MIME type matches the provided validator param in the form type/subtype or type/*. +func isMIMEType(fl FieldLevel) bool { + mime, ok := detectFileMIMEType(fl.Field()) + if !ok { + return false + } + + return matchesMIMEType(mime, fl.Param()) } // isImage is the validation function for validating if the current field's value contains the path to a valid image file @@ -1587,38 +1837,14 @@ func isImage(fl FieldLevel) bool { "image/x-xpixmap": true, "image/x-xwindowdump": true, } - field := fl.Field() - switch field.Kind() { - case reflect.String: - filePath := field.String() - fileInfo, err := os.Stat(filePath) - if err != nil { - return false - } - - if fileInfo.IsDir() { - return false - } - - file, err := os.Open(filePath) - if err != nil { - return false - } - defer func() { - _ = file.Close() - }() - - mime, err := mimetype.DetectReader(file) - if err != nil { - return false - } - - if _, ok := mimetypes[mime.String()]; ok { - return true - } + mime, ok := detectFileMIMEType(fl.Field()) + if !ok { + return false } - return false + + _, ok = mimetypes[mime] + return ok } // isFilePath is the validation function for validating if the current field's value is a valid file path. @@ -1672,7 +1898,7 @@ func isFilePath(fl FieldLevel) bool { } } - panic(fmt.Sprintf("Bad field type %T", field.Interface())) + panic(fmt.Sprintf("Bad field type %s", field.Type())) } // isE164 is the validation function for validating if the current field's value is a valid e.164 formatted phone number. @@ -1694,6 +1920,11 @@ func isHSLA(fl FieldLevel) bool { return hslaRegex().MatchString(fl.Field().String()) } +// isCMYK is the validation function for validating if the current field's value is a valid CMYK color. +func isCMYK(fl FieldLevel) bool { + return cmykRegex().MatchString(fl.Field().String()) +} + // isHSL is the validation function for validating if the current field's value is a valid HSL color. func isHSL(fl FieldLevel) bool { return hslRegex().MatchString(fl.Field().String()) @@ -1754,6 +1985,16 @@ func isAlphanumUnicode(fl FieldLevel) bool { return alphaUnicodeNumericRegex().MatchString(fl.Field().String()) } +// isAlphaSpace is the validation function for validating if the current field's value is a valid alpha value with spaces. +func isAlphaSpace(fl FieldLevel) bool { + return alphaSpaceRegex().MatchString(fl.Field().String()) +} + +// isAlphaNumericSpace is the validation function for validating if the current field's value is a valid alphanumeric value with spaces. +func isAlphaNumericSpace(fl FieldLevel) bool { + return alphanNumericSpaceRegex().MatchString(fl.Field().String()) +} + // isAlphaUnicode is the validation function for validating if the current field's value is a valid alpha unicode value. func isAlphaUnicode(fl FieldLevel) bool { return alphaUnicodeRegex().MatchString(fl.Field().String()) @@ -1782,7 +2023,7 @@ func hasValue(fl FieldLevel) bool { case reflect.Slice, reflect.Map, reflect.Ptr, reflect.Interface, reflect.Chan, reflect.Func: return !field.IsNil() default: - if fl.(*validate).fldIsPointer && field.Interface() != nil { + if fl.(*validate).fldIsPointer && getValue(field) != nil { return true } return field.IsValid() && !field.IsZero() @@ -1793,10 +2034,13 @@ func hasValue(fl FieldLevel) bool { func hasNotZeroValue(fl FieldLevel) bool { field := fl.Field() switch field.Kind() { - case reflect.Slice, reflect.Map, reflect.Ptr, reflect.Interface, reflect.Chan, reflect.Func: + case reflect.Slice, reflect.Map: + // For slices and maps, consider them "not zero" only if they're both non-nil AND have elements + return !field.IsNil() && field.Len() > 0 + case reflect.Ptr, reflect.Interface, reflect.Chan, reflect.Func: return !field.IsNil() default: - if fl.(*validate).fldIsPointer && field.Interface() != nil { + if fl.(*validate).fldIsPointer && getValue(field) != nil { return !field.IsZero() } return field.IsValid() && !field.IsZero() @@ -1820,7 +2064,7 @@ func requireCheckFieldKind(fl FieldLevel, param string, defaultNotFoundValue boo case reflect.Slice, reflect.Map, reflect.Ptr, reflect.Interface, reflect.Chan, reflect.Func: return field.IsNil() default: - if nullable && field.Interface() != nil { + if nullable && getValue(field) != nil { return false } return field.IsValid() && field.IsZero() @@ -1849,7 +2093,13 @@ func requireCheckFieldValue( case reflect.Float64: return field.Float() == asFloat64(value) - case reflect.Slice, reflect.Map, reflect.Array: + case reflect.Slice, reflect.Map: + if value == "nil" { + return field.IsNil() + } + return int64(field.Len()) == asInt(value) + case reflect.Array: + // Arrays can't be nil, so only compare lengths return int64(field.Len()) == asInt(value) case reflect.Bool: @@ -1874,6 +2124,15 @@ func requiredIf(fl FieldLevel) bool { if len(params)%2 != 0 { panic(fmt.Sprintf("Bad param number for required_if %s", fl.FieldName())) } + + seen := make(map[string]struct{}) + for i := 0; i < len(params); i += 2 { + if _, ok := seen[params[i]]; ok { + panic(fmt.Sprintf("Duplicate param %s for required_if %s", params[i], fl.FieldName())) + } + seen[params[i]] = struct{}{} + } + for i := 0; i < len(params); i += 2 { if !requireCheckFieldValue(fl, params[i], params[i+1], false) { return true @@ -1937,11 +2196,12 @@ func excludedUnless(fl FieldLevel) bool { panic(fmt.Sprintf("Bad param number for excluded_unless %s", fl.FieldName())) } for i := 0; i < len(params); i += 2 { - if !requireCheckFieldValue(fl, params[i], params[i+1], false) { - return !hasValue(fl) + if requireCheckFieldValue(fl, params[i], params[i+1], false) { + return true } } - return true + + return !hasValue(fl) } // excludedWith is the validation function @@ -1995,8 +2255,11 @@ func requiredWithAll(fl FieldLevel) bool { // excludedWithout is the validation function // The field under validation must not be present or is empty when any of the other specified fields are not present. func excludedWithout(fl FieldLevel) bool { - if requireCheckFieldKind(fl, strings.TrimSpace(fl.Param()), true) { - return !hasValue(fl) + params := parseOneOfParam2(fl.Param()) + for _, param := range params { + if requireCheckFieldKind(fl, param, true) { + return !hasValue(fl) + } } return true } @@ -2065,8 +2328,8 @@ func isGteField(fl FieldLevel) bool { fieldType := field.Type() if fieldType.ConvertibleTo(timeType) && currentField.Type().ConvertibleTo(timeType) { - t := currentField.Convert(timeType).Interface().(time.Time) - fieldTime := field.Convert(timeType).Interface().(time.Time) + t := getValue(currentField.Convert(timeType)).(time.Time) + fieldTime := getValue(field.Convert(timeType)).(time.Time) return fieldTime.After(t) || fieldTime.Equal(t) } @@ -2109,8 +2372,8 @@ func isGtField(fl FieldLevel) bool { fieldType := field.Type() if fieldType.ConvertibleTo(timeType) && currentField.Type().ConvertibleTo(timeType) { - t := currentField.Convert(timeType).Interface().(time.Time) - fieldTime := field.Convert(timeType).Interface().(time.Time) + t := getValue(currentField.Convert(timeType)).(time.Time) + fieldTime := getValue(field.Convert(timeType)).(time.Time) return fieldTime.After(t) } @@ -2165,13 +2428,13 @@ func isGte(fl FieldLevel) bool { if field.Type().ConvertibleTo(timeType) { now := time.Now().UTC() - t := field.Convert(timeType).Interface().(time.Time) + t := getValue(field.Convert(timeType)).(time.Time) return t.After(now) || t.Equal(now) } } - panic(fmt.Sprintf("Bad field type %T", field.Interface())) + panic(fmt.Sprintf("Bad field type %s", field.Type())) } // isGt is the validation function for validating if the current field's value is greater than the param's value. @@ -2213,11 +2476,11 @@ func isGt(fl FieldLevel) bool { case reflect.Struct: if field.Type().ConvertibleTo(timeType) { - return field.Convert(timeType).Interface().(time.Time).After(time.Now().UTC()) + return getValue(field.Convert(timeType)).(time.Time).After(time.Now().UTC()) } } - panic(fmt.Sprintf("Bad field type %T", field.Interface())) + panic(fmt.Sprintf("Bad field type %s", field.Type())) } // hasLengthOf is the validation function for validating if the current field's value is equal to the param's value. @@ -2257,7 +2520,7 @@ func hasLengthOf(fl FieldLevel) bool { return field.Float() == p } - panic(fmt.Sprintf("Bad field type %T", field.Interface())) + panic(fmt.Sprintf("Bad field type %s", field.Type())) } // hasMinOf is the validation function for validating if the current field's value is greater than or equal to the param's value. @@ -2293,8 +2556,8 @@ func isLteField(fl FieldLevel) bool { fieldType := field.Type() if fieldType.ConvertibleTo(timeType) && currentField.Type().ConvertibleTo(timeType) { - t := currentField.Convert(timeType).Interface().(time.Time) - fieldTime := field.Convert(timeType).Interface().(time.Time) + t := getValue(currentField.Convert(timeType)).(time.Time) + fieldTime := getValue(field.Convert(timeType)).(time.Time) return fieldTime.Before(t) || fieldTime.Equal(t) } @@ -2337,8 +2600,8 @@ func isLtField(fl FieldLevel) bool { fieldType := field.Type() if fieldType.ConvertibleTo(timeType) && currentField.Type().ConvertibleTo(timeType) { - t := currentField.Convert(timeType).Interface().(time.Time) - fieldTime := field.Convert(timeType).Interface().(time.Time) + t := getValue(currentField.Convert(timeType)).(time.Time) + fieldTime := getValue(field.Convert(timeType)).(time.Time) return fieldTime.Before(t) } @@ -2393,13 +2656,13 @@ func isLte(fl FieldLevel) bool { if field.Type().ConvertibleTo(timeType) { now := time.Now().UTC() - t := field.Convert(timeType).Interface().(time.Time) + t := getValue(field.Convert(timeType)).(time.Time) return t.Before(now) || t.Equal(now) } } - panic(fmt.Sprintf("Bad field type %T", field.Interface())) + panic(fmt.Sprintf("Bad field type %s", field.Type())) } // isLt is the validation function for validating if the current field's value is less than the param's value. @@ -2441,11 +2704,11 @@ func isLt(fl FieldLevel) bool { case reflect.Struct: if field.Type().ConvertibleTo(timeType) { - return field.Convert(timeType).Interface().(time.Time).Before(time.Now().UTC()) + return getValue(field.Convert(timeType)).(time.Time).Before(time.Now().UTC()) } } - panic(fmt.Sprintf("Bad field type %T", field.Interface())) + panic(fmt.Sprintf("Bad field type %s", field.Type())) } // hasMaxOf is the validation function for validating if the current field's value is less than or equal to the param's value. @@ -2558,6 +2821,70 @@ func isUnixAddrResolvable(fl FieldLevel) bool { return err == nil } +// isUnixDomainSocketExists is the validation function for validating if the field's value is an existing Unix domain socket. +// It handles both filesystem-based sockets and Linux abstract sockets. +// It always returns false for Windows. +func isUnixDomainSocketExists(fl FieldLevel) bool { + if runtime.GOOS == "windows" { + return false + } + + sockpath := fl.Field().String() + + if sockpath == "" { + return false + } + + // On Linux, check for abstract sockets (prefixed with @) + if runtime.GOOS == "linux" && strings.HasPrefix(sockpath, "@") { + return isAbstractSocketExists(sockpath) + } + + // For filesystem-based sockets, check if the path exists and is a socket + stats, err := os.Stat(sockpath) + if err != nil { + return false + } + + return stats.Mode().Type() == fs.ModeSocket +} + +// isAbstractSocketExists checks if a Linux abstract socket exists by reading /proc/net/unix. +// Abstract sockets are identified by an @ prefix in human-readable form. +func isAbstractSocketExists(sockpath string) bool { + file, err := os.Open("/proc/net/unix") + if err != nil { + return false + } + defer func() { + _ = file.Close() + }() + + scanner := bufio.NewScanner(file) + + // Skip the header line + if !scanner.Scan() { + return false + } + + // Abstract sockets in /proc/net/unix are represented with @ prefix + // The socket path is the last field in each line + for scanner.Scan() { + line := scanner.Text() + fields := strings.Fields(line) + + // The path is the last field (8th field typically) + if len(fields) >= 8 { + path := fields[len(fields)-1] + if path == sockpath { + return true + } + } + } + + return false +} + func isIP4Addr(fl FieldLevel) bool { val := fl.Field().String() @@ -2592,10 +2919,39 @@ func isHostnameRFC1123(fl FieldLevel) bool { return hostnameRegexRFC1123().MatchString(fl.Field().String()) } +func isHostnameLabel(fl FieldLevel) bool { + v := fl.Field().String() + n := len(v) + + // A valid hostname label must be between 1 and 63 characters long. + if n <= 0 || n > 63 { + return false + } + + for i := range n { + c := v[i] + + // 1. Allow alphanumeric characters anywhere + if (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') { + continue + } + + // 2. Allow hyphens only in the middle (not at the start or end) + if c == '-' && i > 0 && i < n-1 { + continue + } + + // 3. Any other character, or a hyphen at the boundaries, is invalid + return false + } + + return true +} + func isFQDN(fl FieldLevel) bool { val := fl.Field().String() - if val == "" { + if val == "" || len(strings.TrimSuffix(val, ".")) > 253 { return false } @@ -2615,7 +2971,7 @@ func isDir(fl FieldLevel) bool { return fileInfo.IsDir() } - panic(fmt.Sprintf("Bad field type %T", field.Interface())) + panic(fmt.Sprintf("Bad field type %s", field.Type())) } // isDirPath is the validation function for validating if the current field's value is a valid directory. @@ -2672,7 +3028,7 @@ func isDirPath(fl FieldLevel) bool { } } - panic(fmt.Sprintf("Bad field type %T", field.Interface())) + panic(fmt.Sprintf("Bad field type %s", field.Type())) } // isJSON is the validation function for validating if the current field's value is a valid json string. @@ -2687,12 +3043,12 @@ func isJSON(fl FieldLevel) bool { fieldType := field.Type() if fieldType.ConvertibleTo(byteSliceType) { - b := field.Convert(byteSliceType).Interface().([]byte) + b := getValue(field.Convert(byteSliceType)).([]byte) return json.Valid(b) } } - panic(fmt.Sprintf("Bad field type %T", field.Interface())) + panic(fmt.Sprintf("Bad field type %s", field.Type())) } // isJWT is the validation function for validating if the current field's value is a valid JWT string. @@ -2723,9 +3079,18 @@ func isHostnamePort(fl FieldLevel) bool { // IsPort validates if the current field's value represents a valid port func isPort(fl FieldLevel) bool { - val := fl.Field().Uint() + field := fl.Field() - return val >= 1 && val <= 65535 + switch field.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + val := field.Int() + return val >= 1 && val <= 65535 + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + val := field.Uint() + return val >= 1 && val <= 65535 + default: + panic(fmt.Sprintf("Bad field type %s", field.Type())) + } } // isLowercase is the validation function for validating if the current field's value is a lowercase string. @@ -2739,7 +3104,7 @@ func isLowercase(fl FieldLevel) bool { return field.String() == strings.ToLower(field.String()) } - panic(fmt.Sprintf("Bad field type %T", field.Interface())) + panic(fmt.Sprintf("Bad field type %s", field.Type())) } // isUppercase is the validation function for validating if the current field's value is an uppercase string. @@ -2753,7 +3118,7 @@ func isUppercase(fl FieldLevel) bool { return field.String() == strings.ToUpper(field.String()) } - panic(fmt.Sprintf("Bad field type %T", field.Interface())) + panic(fmt.Sprintf("Bad field type %s", field.Type())) } // isDatetime is the validation function for validating if the current field's value is a valid datetime string. @@ -2767,7 +3132,7 @@ func isDatetime(fl FieldLevel) bool { return err == nil } - panic(fmt.Sprintf("Bad field type %T", field.Interface())) + panic(fmt.Sprintf("Bad field type %s", field.Type())) } // isTimeZone is the validation function for validating if the current field's value is a valid time zone string. @@ -2789,7 +3154,7 @@ func isTimeZone(fl FieldLevel) bool { return err == nil } - panic(fmt.Sprintf("Bad field type %T", field.Interface())) + panic(fmt.Sprintf("Bad field type %s", field.Type())) } // isIso3166Alpha2 is the validation function for validating if the current field's value is a valid iso3166-1 alpha-2 country code. @@ -2833,7 +3198,7 @@ func isIso3166AlphaNumeric(fl FieldLevel) bool { case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: code = int(field.Uint() % 1000) default: - panic(fmt.Sprintf("Bad field type %T", field.Interface())) + panic(fmt.Sprintf("Bad field type %s", field.Type())) } _, ok := iso3166_1_alpha_numeric[code] @@ -2857,7 +3222,7 @@ func isIso3166AlphaNumericEU(fl FieldLevel) bool { case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: code = int(field.Uint() % 1000) default: - panic(fmt.Sprintf("Bad field type %T", field.Interface())) + panic(fmt.Sprintf("Bad field type %s", field.Type())) } _, ok := iso3166_1_alpha_numeric_eu[code] @@ -2887,7 +3252,7 @@ func isIso4217Numeric(fl FieldLevel) bool { case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: code = int(field.Uint()) default: - panic(fmt.Sprintf("Bad field type %T", field.Interface())) + panic(fmt.Sprintf("Bad field type %s", field.Type())) } _, ok := iso4217_numeric[code] @@ -2903,14 +3268,165 @@ func isBCP47LanguageTag(fl FieldLevel) bool { return err == nil } - panic(fmt.Sprintf("Bad field type %T", field.Interface())) + panic(fmt.Sprintf("Bad field type %s", field.Type())) } -// isIsoBicFormat is the validation function for validating if the current field's value is a valid Business Identifier Code (SWIFT code), defined in ISO 9362 -func isIsoBicFormat(fl FieldLevel) bool { +// isBCP47StrictLanguageTag is the validation function for validating if the current field's value is a valid BCP 47 language tag +// according to https://www.rfc-editor.org/rfc/bcp/bcp47.txt +func isBCP47StrictLanguageTag(fl FieldLevel) bool { + field := fl.Field() + + if field.Kind() != reflect.String { + panic(fmt.Sprintf("Bad field type %s", field.Type())) + } + + lower := strings.ToLower(field.String()) + lowerTagDash := lower + "-" + + m := bcp47LanguageTagRe.FindStringSubmatch(lower) + if m == nil { + return false + } + + grandfatheredOrPrivateuse := m[1] + lang := m[2] + script := m[3] + region := m[4] + variant := m[5] + extension := m[6] + + if grandfatheredOrPrivateuse != "" { + return true + } + + // language = 2*3ALPHA ; shortest ISO 639 code + // ["-" extlang] ; sometimes followed by + // ; extended language subtags + // / 4ALPHA ; or reserved for future use + // / 5*8ALPHA ; or registered language subtag + switch n := len(lang); { + // 2*3ALPHA "-" extlang + case strings.Contains(lang, "-"): + parts := strings.Split(lang, "-") + + baseLang := parts[0] + base, err := language.ParseBase(baseLang) + if err != nil { + return false + } + // base.String() normalizes the base to the shortest code + // for the language + if base.String() != baseLang { + return false + } + + for _, e := range parts[1:] { + prefixes, ok := iana_subtag_registry_extlangs[e] + if !ok { + return false + } + + if len(prefixes) > 0 { + found := false + for _, p := range prefixes { + if strings.HasPrefix(lowerTagDash, p) { + found = true + break + } + } + if !found { + return false + } + } + } + // 2*3ALPHA ; shortest ISO 639 code + case n <= 3: + base, err := language.ParseBase(lang) + if err != nil { + return false + } + + // base.String() normalizes the base to the shortest code + // for the language + if base.String() != lang { + return false + } + // 4ALPHA ; or reserved for future use + case n == 4: + return false + // 5*8ALPHA ; or registered language subtag + default: + // registered language subtag with 5+ characters. + // As of today there aren't any. + // https://www.iana.org/assignments/language-subtag-registry/language-subtag-registry + return false + } + + // script = 4ALPHA ; ISO 15924 code + if script != "" { + _, err := language.ParseScript(script) + if err != nil { + return false + } + } + + // region = 2ALPHA ; ISO 3166-1 code + // 3DIGIT ; UN M.49 code + if region != "" { + if len(region) == 2 { + _, err := language.ParseRegion(region) + if err != nil { + return false + } + } else { + // Can't use language.ParseRegion() here because not all + // UN M.49 region codes are allowed, just the subset present + // in the IANA subtag registry. + _, ok := iana_subtag_registry_m49_codes[region] + if !ok { + return false + } + } + } + + // variant = 5*8alphanum ; registered variants + // / (DIGIT 3alphanum) + if variant != "" { + for v := range strings.SplitSeq(variant, "-") { + _, err := language.ParseVariant(v) + if err != nil { + return false + } + + _, ok := iana_subtag_registry_variants[v] + if !ok { + return false + } + } + } + + if extension != "" { + _, err := language.ParseExtension(extension) + if err != nil { + return false + } + } + + return true +} + +// isIsoBic2014Format is the validation function for validating if the current field's value is a valid Business Identifier Code (SWIFT code), defined in ISO 9362 2014 +func isIsoBic2014Format(fl FieldLevel) bool { bicString := fl.Field().String() - return bicRegex().MatchString(bicString) + return bic2014Regex().MatchString(bicString) +} + +// isIsoBic2022Format is the validation function for validating if the current field's value is a valid Business Identifier Code (SWIFT code), defined in ISO 9362 2022 +func isIsoBic2022Format(fl FieldLevel) bool { + bicString := fl.Field().String() + + return bic2022Regex().MatchString(bicString) } // isSemverFormat is the validation function for validating if the current field's value is a valid semver version, defined in Semantic Versioning 2.0.0 @@ -3026,7 +3542,7 @@ func hasLuhnChecksum(fl FieldLevel) bool { case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: str = strconv.FormatUint(field.Uint(), 10) default: - panic(fmt.Sprintf("Bad field type %T", field.Interface())) + panic(fmt.Sprintf("Bad field type %s", field.Type())) } size := len(str) if size < 2 { // there has to be at least one digit that carries a meaning + the checksum @@ -3053,18 +3569,15 @@ func isEIN(fl FieldLevel) bool { return einRegex().MatchString(field.String()) } -func isValidateFn(fl FieldLevel) bool { - const defaultParam = `Validate` - +func isDuration(fl FieldLevel) bool { field := fl.Field() - validateFn := cmp.Or(fl.Param(), defaultParam) - ok, err := tryCallValidateFn(field, validateFn) - if err != nil { + if field.Kind() != reflect.String { return false } - return ok + _, err := time.ParseDuration(field.String()) + return err == nil } var ( @@ -3072,40 +3585,3 @@ var ( errMethodReturnNoValues = errors.New(`method return o values (void)`) errMethodReturnInvalidType = errors.New(`method should return invalid type`) ) - -func tryCallValidateFn(field reflect.Value, validateFn string) (bool, error) { - method := field.MethodByName(validateFn) - if field.CanAddr() && !method.IsValid() { - method = field.Addr().MethodByName(validateFn) - } - - if !method.IsValid() { - return false, fmt.Errorf("unable to call %q on type %q: %w", - validateFn, field.Type().String(), errMethodNotFound) - } - - returnValues := method.Call([]reflect.Value{}) - if len(returnValues) == 0 { - return false, fmt.Errorf("unable to use result of method %q on type %q: %w", - validateFn, field.Type().String(), errMethodReturnNoValues) - } - - firstReturnValue := returnValues[0] - - switch firstReturnValue.Kind() { - case reflect.Bool: - return firstReturnValue.Bool(), nil - case reflect.Interface: - errorType := reflect.TypeOf((*error)(nil)).Elem() - - if firstReturnValue.Type().Implements(errorType) { - return firstReturnValue.IsNil(), nil - } - - return false, fmt.Errorf("unable to use result of method %q on type %q: %w (got interface %v expect error)", - validateFn, field.Type().String(), errMethodReturnInvalidType, firstReturnValue.Type().String()) - default: - return false, fmt.Errorf("unable to use result of method %q on type %q: %w (got %v expect error or bool)", - validateFn, field.Type().String(), errMethodReturnInvalidType, firstReturnValue.Type().String()) - } -} diff --git a/vendor/github.com/txix-open/validator/v10/cache.go b/vendor/github.com/txix-open/validator/v10/cache.go index fb101b0..b8052aa 100644 --- a/vendor/github.com/txix-open/validator/v10/cache.go +++ b/vendor/github.com/txix-open/validator/v10/cache.go @@ -144,7 +144,7 @@ func (v *Validate) extractStructCache(current reflect.Value, sName string) *cStr if v.hasTagNameFunc { name := v.tagNameFunc(fld) - if len(name) > 0 { + if len(name) > 0 || v.omitBlankFieldNames { customName = name } } @@ -289,6 +289,24 @@ func (v *Validate) parseFieldTagsRecursive(tag string, fieldName string, alias s if wrapper, ok := v.validations[current.tag]; ok { current.fn = wrapper.fn current.runValidationWhenNil = wrapper.runValidationOnNil + } else if aliasTag, isAlias := v.aliases[current.tag]; isAlias { + aliasFirst, aliasLast := v.parseFieldTagsRecursive(aliasTag, fieldName, current.tag, true) + + current.tag = aliasFirst.tag + current.fn = aliasFirst.fn + current.runValidationWhenNil = aliasFirst.runValidationWhenNil + current.hasParam = aliasFirst.hasParam + current.param = aliasFirst.param + current.typeof = aliasFirst.typeof + current.hasAlias = true + + if aliasFirst.next != nil { + nextInChain := current.next + current.next = aliasFirst.next + aliasLast.next = nextInChain + aliasLast.isBlockEnd = false + current = aliasLast + } } else { panic(strings.TrimSpace(fmt.Sprintf(undefinedValidation, current.tag, fieldName))) } diff --git a/vendor/github.com/txix-open/validator/v10/country_codes.go b/vendor/github.com/txix-open/validator/v10/country_codes.go index b5f10d3..f208e93 100644 --- a/vendor/github.com/txix-open/validator/v10/country_codes.go +++ b/vendor/github.com/txix-open/validator/v10/country_codes.go @@ -258,7 +258,7 @@ var iso3166_2 = map[string]struct{}{ "BD-56": {}, "BD-57": {}, "BD-58": {}, "BD-59": {}, "BD-60": {}, "BD-61": {}, "BD-62": {}, "BD-63": {}, "BD-64": {}, "BD-A": {}, "BD-B": {}, "BD-C": {}, "BD-D": {}, "BD-E": {}, "BD-F": {}, - "BD-G": {}, "BE-BRU": {}, "BE-VAN": {}, "BE-VBR": {}, "BE-VLG": {}, + "BD-G": {}, "BD-H": {}, "BE-BRU": {}, "BE-VAN": {}, "BE-VBR": {}, "BE-VLG": {}, "BE-VLI": {}, "BE-VOV": {}, "BE-VWV": {}, "BE-WAL": {}, "BE-WBR": {}, "BE-WHT": {}, "BE-WLG": {}, "BE-WLX": {}, "BE-WNA": {}, "BF-01": {}, "BF-02": {}, "BF-03": {}, "BF-04": {}, "BF-05": {}, "BF-06": {}, @@ -573,7 +573,7 @@ var iso3166_2 = map[string]struct{}{ "ID-KB": {}, "ID-KI": {}, "ID-KU": {}, "ID-KR": {}, "ID-KS": {}, "ID-KT": {}, "ID-LA": {}, "ID-MA": {}, "ID-ML": {}, "ID-MU": {}, "ID-NB": {}, "ID-NT": {}, "ID-NU": {}, "ID-PA": {}, "ID-PB": {}, - "ID-PE": {}, "ID-PP": {}, "ID-PS": {}, "ID-PT": {}, "ID-RI": {}, + "ID-PD": {}, "ID-PE": {}, "ID-PP": {}, "ID-PS": {}, "ID-PT": {}, "ID-RI": {}, "ID-SA": {}, "ID-SB": {}, "ID-SG": {}, "ID-SL": {}, "ID-SM": {}, "ID-SN": {}, "ID-SR": {}, "ID-SS": {}, "ID-ST": {}, "ID-SU": {}, "ID-YO": {}, "IE-C": {}, "IE-CE": {}, "IE-CN": {}, "IE-CO": {}, @@ -587,7 +587,7 @@ var iso3166_2 = map[string]struct{}{ "IN-AS": {}, "IN-BR": {}, "IN-CH": {}, "IN-CT": {}, "IN-DH": {}, "IN-DL": {}, "IN-DN": {}, "IN-GA": {}, "IN-GJ": {}, "IN-HP": {}, "IN-HR": {}, "IN-JH": {}, "IN-JK": {}, "IN-KA": {}, "IN-KL": {}, - "IN-LD": {}, "IN-MH": {}, "IN-ML": {}, "IN-MN": {}, "IN-MP": {}, + "IN-LA": {}, "IN-LD": {}, "IN-MH": {}, "IN-ML": {}, "IN-MN": {}, "IN-MP": {}, "IN-MZ": {}, "IN-NL": {}, "IN-TG": {}, "IN-OR": {}, "IN-PB": {}, "IN-PY": {}, "IN-RJ": {}, "IN-SK": {}, "IN-TN": {}, "IN-TR": {}, "IN-UP": {}, "IN-UT": {}, "IN-WB": {}, "IQ-AN": {}, "IQ-AR": {}, "IQ-BA": {}, @@ -667,7 +667,7 @@ var iso3166_2 = map[string]struct{}{ "KP-08": {}, "KP-09": {}, "KP-10": {}, "KP-13": {}, "KR-11": {}, "KR-26": {}, "KR-27": {}, "KR-28": {}, "KR-29": {}, "KR-30": {}, "KR-31": {}, "KR-41": {}, "KR-42": {}, "KR-43": {}, "KR-44": {}, - "KR-45": {}, "KR-46": {}, "KR-47": {}, "KR-48": {}, "KR-49": {}, + "KR-45": {}, "KR-46": {}, "KR-47": {}, "KR-48": {}, "KR-49": {}, "KR-50": {}, "KW-AH": {}, "KW-FA": {}, "KW-HA": {}, "KW-JA": {}, "KW-KU": {}, "KW-MU": {}, "KZ-10": {}, "KZ-75": {}, "KZ-19": {}, "KZ-11": {}, "KZ-15": {}, "KZ-71": {}, "KZ-23": {}, "KZ-27": {}, "KZ-47": {}, @@ -758,7 +758,7 @@ var iso3166_2 = map[string]struct{}{ "ME-02": {}, "ME-03": {}, "ME-04": {}, "ME-05": {}, "ME-06": {}, "ME-07": {}, "ME-08": {}, "ME-09": {}, "ME-10": {}, "ME-11": {}, "ME-12": {}, "ME-13": {}, "ME-14": {}, "ME-15": {}, "ME-16": {}, - "ME-17": {}, "ME-18": {}, "ME-19": {}, "ME-20": {}, "ME-21": {}, "ME-24": {}, + "ME-17": {}, "ME-18": {}, "ME-19": {}, "ME-20": {}, "ME-21": {}, "ME-22": {}, "ME-23": {}, "ME-24": {}, "ME-25": {}, "MG-A": {}, "MG-D": {}, "MG-F": {}, "MG-M": {}, "MG-T": {}, "MG-U": {}, "MH-ALK": {}, "MH-ALL": {}, "MH-ARN": {}, "MH-AUR": {}, "MH-EBO": {}, "MH-ENI": {}, "MH-JAB": {}, "MH-JAL": {}, "MH-KIL": {}, @@ -856,7 +856,7 @@ var iso3166_2 = map[string]struct{}{ "NO-22": {}, "NP-1": {}, "NP-2": {}, "NP-3": {}, "NP-4": {}, "NP-5": {}, "NP-BA": {}, "NP-BH": {}, "NP-DH": {}, "NP-GA": {}, "NP-JA": {}, "NP-KA": {}, "NP-KO": {}, "NP-LU": {}, "NP-MA": {}, - "NP-ME": {}, "NP-NA": {}, "NP-RA": {}, "NP-SA": {}, "NP-SE": {}, + "NP-ME": {}, "NP-NA": {}, "NP-P1": {}, "NP-P2": {}, "NP-P3": {}, "NP-P4": {}, "NP-P5": {}, "NP-P6": {}, "NP-P7": {}, "NP-RA": {}, "NP-SA": {}, "NP-SE": {}, "NR-01": {}, "NR-02": {}, "NR-03": {}, "NR-04": {}, "NR-05": {}, "NR-06": {}, "NR-07": {}, "NR-08": {}, "NR-09": {}, "NR-10": {}, "NR-11": {}, "NR-12": {}, "NR-13": {}, "NR-14": {}, "NZ-AUK": {}, @@ -1175,3 +1175,15 @@ var iso3166_2 = map[string]struct{}{ "ZW-BU": {}, "ZW-HA": {}, "ZW-MA": {}, "ZW-MC": {}, "ZW-ME": {}, "ZW-MI": {}, "ZW-MN": {}, "ZW-MS": {}, "ZW-MV": {}, "ZW-MW": {}, } + +// Subset of UN M.49 region codes present in the IANA Language Subtag Registry: +// https://www.iana.org/assignments/language-subtag-registry/language-subtag-registry +var iana_subtag_registry_m49_codes = map[string]struct{}{ + "001": {}, "002": {}, "003": {}, "005": {}, "009": {}, + "011": {}, "013": {}, "014": {}, "015": {}, "017": {}, + "018": {}, "019": {}, "021": {}, "029": {}, "030": {}, + "034": {}, "035": {}, "039": {}, "053": {}, "054": {}, + "057": {}, "061": {}, "142": {}, "143": {}, "145": {}, + "150": {}, "151": {}, "154": {}, "155": {}, "202": {}, + "419": {}, +} diff --git a/vendor/github.com/txix-open/validator/v10/currency_codes.go b/vendor/github.com/txix-open/validator/v10/currency_codes.go index d0317f8..83b6729 100644 --- a/vendor/github.com/txix-open/validator/v10/currency_codes.go +++ b/vendor/github.com/txix-open/validator/v10/currency_codes.go @@ -10,33 +10,33 @@ var iso4217 = map[string]struct{}{ "BIF": {}, "CVE": {}, "KHR": {}, "XAF": {}, "CAD": {}, "KYD": {}, "CLP": {}, "CLF": {}, "CNY": {}, "COP": {}, "COU": {}, "KMF": {}, "CDF": {}, "NZD": {}, "CRC": {}, - "HRK": {}, "CUP": {}, "CUC": {}, "ANG": {}, "CZK": {}, - "DKK": {}, "DJF": {}, "DOP": {}, "EGP": {}, "SVC": {}, - "ERN": {}, "SZL": {}, "ETB": {}, "FKP": {}, "FJD": {}, - "XPF": {}, "GMD": {}, "GEL": {}, "GHS": {}, "GIP": {}, - "GTQ": {}, "GBP": {}, "GNF": {}, "GYD": {}, "HTG": {}, - "HNL": {}, "HKD": {}, "HUF": {}, "ISK": {}, "IDR": {}, - "XDR": {}, "IRR": {}, "IQD": {}, "ILS": {}, "JMD": {}, - "JPY": {}, "JOD": {}, "KZT": {}, "KES": {}, "KPW": {}, - "KRW": {}, "KWD": {}, "KGS": {}, "LAK": {}, "LBP": {}, - "LSL": {}, "ZAR": {}, "LRD": {}, "LYD": {}, "CHF": {}, - "MOP": {}, "MKD": {}, "MGA": {}, "MWK": {}, "MYR": {}, - "MVR": {}, "MRU": {}, "MUR": {}, "XUA": {}, "MXN": {}, - "MXV": {}, "MDL": {}, "MNT": {}, "MAD": {}, "MZN": {}, - "MMK": {}, "NAD": {}, "NPR": {}, "NIO": {}, "NGN": {}, - "OMR": {}, "PKR": {}, "PAB": {}, "PGK": {}, "PYG": {}, - "PEN": {}, "PHP": {}, "PLN": {}, "QAR": {}, "RON": {}, - "RUB": {}, "RWF": {}, "SHP": {}, "WST": {}, "STN": {}, - "SAR": {}, "RSD": {}, "SCR": {}, "SLL": {}, "SGD": {}, - "XSU": {}, "SBD": {}, "SOS": {}, "SSP": {}, "LKR": {}, - "SDG": {}, "SRD": {}, "SEK": {}, "CHE": {}, "CHW": {}, - "SYP": {}, "TWD": {}, "TJS": {}, "TZS": {}, "THB": {}, - "TOP": {}, "TTD": {}, "TND": {}, "TRY": {}, "TMT": {}, - "UGX": {}, "UAH": {}, "AED": {}, "USN": {}, "UYU": {}, - "UYI": {}, "UYW": {}, "UZS": {}, "VUV": {}, "VES": {}, - "VND": {}, "YER": {}, "ZMW": {}, "ZWL": {}, "XBA": {}, - "XBB": {}, "XBC": {}, "XBD": {}, "XTS": {}, "XXX": {}, - "XAU": {}, "XPD": {}, "XPT": {}, "XAG": {}, + "CUP": {}, "CZK": {}, "DKK": {}, "DJF": {}, "DOP": {}, + "EGP": {}, "SVC": {}, "ERN": {}, "SZL": {}, "ETB": {}, + "FKP": {}, "FJD": {}, "XPF": {}, "GMD": {}, "GEL": {}, + "GHS": {}, "GIP": {}, "GTQ": {}, "GBP": {}, "GNF": {}, + "GYD": {}, "HTG": {}, "HNL": {}, "HKD": {}, "HUF": {}, + "ISK": {}, "IDR": {}, "XDR": {}, "IRR": {}, "IQD": {}, + "ILS": {}, "JMD": {}, "JPY": {}, "JOD": {}, "KZT": {}, + "KES": {}, "KPW": {}, "KRW": {}, "KWD": {}, "KGS": {}, + "LAK": {}, "LBP": {}, "LSL": {}, "ZAR": {}, "LRD": {}, + "LYD": {}, "CHF": {}, "MOP": {}, "MKD": {}, "MGA": {}, + "MWK": {}, "MYR": {}, "MVR": {}, "MRU": {}, "MUR": {}, + "XUA": {}, "MXN": {}, "MXV": {}, "MDL": {}, "MNT": {}, + "MAD": {}, "MZN": {}, "MMK": {}, "NAD": {}, "NPR": {}, + "NIO": {}, "NGN": {}, "OMR": {}, "PKR": {}, "PAB": {}, + "PGK": {}, "PYG": {}, "PEN": {}, "PHP": {}, "PLN": {}, + "QAR": {}, "RON": {}, "RUB": {}, "RWF": {}, "SHP": {}, + "WST": {}, "STN": {}, "SAR": {}, "RSD": {}, "SCR": {}, + "SLE": {}, "SGD": {}, "XSU": {}, "SBD": {}, "SOS": {}, + "SSP": {}, "LKR": {}, "SDG": {}, "SRD": {}, "SEK": {}, + "CHE": {}, "CHW": {}, "SYP": {}, "TWD": {}, "TJS": {}, + "TZS": {}, "THB": {}, "TOP": {}, "TTD": {}, "TND": {}, + "TRY": {}, "TMT": {}, "UGX": {}, "UAH": {}, "AED": {}, + "USN": {}, "UYU": {}, "UYI": {}, "UYW": {}, "UZS": {}, + "VUV": {}, "VES": {}, "VED": {}, "VND": {}, "YER": {}, + "ZMW": {}, "ZWG": {}, "XBA": {}, "XBB": {}, "XBC": {}, + "XBD": {}, "XCG": {}, "XTS": {}, "XXX": {}, "XAU": {}, + "XPD": {}, "XPT": {}, "XAG": {}, } var iso4217_numeric = map[int]struct{}{ @@ -45,35 +45,35 @@ var iso4217_numeric = map[int]struct{}{ 64: {}, 68: {}, 72: {}, 84: {}, 90: {}, 96: {}, 104: {}, 108: {}, 116: {}, 124: {}, 132: {}, 136: {}, 144: {}, 152: {}, 156: {}, - 170: {}, 174: {}, 188: {}, 191: {}, 192: {}, - 203: {}, 208: {}, 214: {}, 222: {}, 230: {}, - 232: {}, 238: {}, 242: {}, 262: {}, 270: {}, - 292: {}, 320: {}, 324: {}, 328: {}, 332: {}, - 340: {}, 344: {}, 348: {}, 352: {}, 356: {}, - 360: {}, 364: {}, 368: {}, 376: {}, 388: {}, - 392: {}, 398: {}, 400: {}, 404: {}, 408: {}, - 410: {}, 414: {}, 417: {}, 418: {}, 422: {}, - 426: {}, 430: {}, 434: {}, 446: {}, 454: {}, - 458: {}, 462: {}, 480: {}, 484: {}, 496: {}, - 498: {}, 504: {}, 512: {}, 516: {}, 524: {}, - 532: {}, 533: {}, 548: {}, 554: {}, 558: {}, - 566: {}, 578: {}, 586: {}, 590: {}, 598: {}, - 600: {}, 604: {}, 608: {}, 634: {}, 643: {}, - 646: {}, 654: {}, 682: {}, 690: {}, 694: {}, - 702: {}, 704: {}, 706: {}, 710: {}, 728: {}, - 748: {}, 752: {}, 756: {}, 760: {}, 764: {}, - 776: {}, 780: {}, 784: {}, 788: {}, 800: {}, - 807: {}, 818: {}, 826: {}, 834: {}, 840: {}, - 858: {}, 860: {}, 882: {}, 886: {}, 901: {}, - 927: {}, 928: {}, 929: {}, 930: {}, 931: {}, - 932: {}, 933: {}, 934: {}, 936: {}, 938: {}, - 940: {}, 941: {}, 943: {}, 944: {}, 946: {}, - 947: {}, 948: {}, 949: {}, 950: {}, 951: {}, - 952: {}, 953: {}, 955: {}, 956: {}, 957: {}, - 958: {}, 959: {}, 960: {}, 961: {}, 962: {}, - 963: {}, 964: {}, 965: {}, 967: {}, 968: {}, - 969: {}, 970: {}, 971: {}, 972: {}, 973: {}, - 975: {}, 976: {}, 977: {}, 978: {}, 979: {}, - 980: {}, 981: {}, 984: {}, 985: {}, 986: {}, - 990: {}, 994: {}, 997: {}, 999: {}, + 170: {}, 174: {}, 188: {}, 192: {}, 203: {}, + 208: {}, 214: {}, 222: {}, 230: {}, 232: {}, + 238: {}, 242: {}, 262: {}, 270: {}, 292: {}, + 320: {}, 324: {}, 328: {}, 332: {}, 340: {}, + 344: {}, 348: {}, 352: {}, 356: {}, 360: {}, + 364: {}, 368: {}, 376: {}, 388: {}, 392: {}, + 398: {}, 400: {}, 404: {}, 408: {}, 410: {}, + 414: {}, 417: {}, 418: {}, 422: {}, 426: {}, + 430: {}, 434: {}, 446: {}, 454: {}, 458: {}, + 462: {}, 480: {}, 484: {}, 496: {}, 498: {}, + 504: {}, 512: {}, 516: {}, 524: {}, 532: {}, + 533: {}, 548: {}, 554: {}, 558: {}, 566: {}, + 578: {}, 586: {}, 590: {}, 598: {}, 600: {}, + 604: {}, 608: {}, 634: {}, 643: {}, 646: {}, + 654: {}, 682: {}, 690: {}, 702: {}, 704: {}, + 706: {}, 710: {}, 728: {}, 748: {}, 752: {}, + 756: {}, 760: {}, 764: {}, 776: {}, 780: {}, + 784: {}, 788: {}, 800: {}, 807: {}, 818: {}, + 826: {}, 834: {}, 840: {}, 858: {}, 860: {}, + 882: {}, 886: {}, 901: {}, 924: {}, 925: {}, + 926: {}, 927: {}, 928: {}, 929: {}, 930: {}, + 933: {}, 934: {}, 936: {}, 938: {}, 940: {}, + 941: {}, 943: {}, 944: {}, 946: {}, 947: {}, + 948: {}, 949: {}, 950: {}, 951: {}, 952: {}, + 953: {}, 955: {}, 956: {}, 957: {}, 958: {}, + 959: {}, 960: {}, 961: {}, 962: {}, 963: {}, + 964: {}, 965: {}, 967: {}, 968: {}, 969: {}, + 970: {}, 971: {}, 972: {}, 973: {}, 975: {}, + 976: {}, 977: {}, 978: {}, 979: {}, 980: {}, + 981: {}, 984: {}, 985: {}, 986: {}, 990: {}, + 994: {}, 997: {}, 999: {}, } diff --git a/vendor/github.com/txix-open/validator/v10/doc.go b/vendor/github.com/txix-open/validator/v10/doc.go index 91bace7..a1aa661 100644 --- a/vendor/github.com/txix-open/validator/v10/doc.go +++ b/vendor/github.com/txix-open/validator/v10/doc.go @@ -52,6 +52,40 @@ Custom Validation functions can be added. Example: // NOTES: using the same tag name as an existing function // will overwrite the existing one +# Valuer Interface + +Custom types can implement the Valuer interface to return the value that should +be validated. This is useful when a type wraps another value and you want +validation to run against the unwrapped value. + + type Nullable[T any] struct { + Data T + } + + func (n Nullable[T]) ValidatorValue() any { + return n.Data + } + + type Config struct { + Name string `validate:"required"` + } + + type Record struct { + Config Nullable[Config] `validate:"required"` + } + + r := Record{ + Config: Nullable[Config]{ + Data: Config{Name: "validator"}, + }, + } + + err := validate.Struct(r) + +The library also supports types like sql/driver.Valuer using +RegisterCustomTypeFunc. See _examples/valuer/main.go and +_examples/custom/main.go for both approaches. + # Cross-Field Validation Cross-Field Validation can be done via the following tags: @@ -104,7 +138,7 @@ used "eqcsfield" it could be multiple levels down. Example: // into the function // when calling validate.VarWithValue(val, field, tag) val will be // whatever you pass, struct, field... - // when calling validate.Field(field, tag) val will be nil + // when calling validate.Var(field, tag) val will be the field itself # Multiple Validators @@ -150,6 +184,12 @@ so the above will become excludesall=0x7C Field `validate:"excludesall=0x7C"` // GOOD! Use the UTF-8 hex representation. } +# Build tags + +The library provides a build tag for build size optimizations. If you are not using +`validateFn` you can add the `validator_novalidatefn` build tag to enabled better dead +code elimination. With this build tag, any usage of `validateFn` tags will panic. + # Baked In Validators and Tags Here is a list of the current built in validators: @@ -188,7 +228,7 @@ Same as structonly tag except that any struct level validations will not run. # Omit Empty -Allows conditional validation, for example if a field is not set with +Allows conditional validation, for example, if a field is not set with a value (Determined by the "required" validator) then other validation such as min or max won't run, but if a value is set validation will run. @@ -201,6 +241,15 @@ only for the nil-values). Usage: omitnil +# Omit Zero + +Allows to skip the validation if the value is a zero value. +For pointers, it checks if the pointer is nil or the underlying value is a zero value. +For slices and maps, it checks if the value is nil or empty. +Otherwise, behaves the same as omitempty. + + Usage: omitzero + # Dive This tells the validator to dive into a slice, array or map and validate that @@ -264,6 +313,7 @@ The field under validation must be present and not empty only if all the other specified fields are equal to the value following the specified field. For strings ensures value is not "". For slices, maps, pointers, interfaces, channels and functions ensures the value is not nil. For structs ensures value is not the zero value. +Using the same field name multiple times in the parameters will result in a panic at runtime. Usage: required_if @@ -502,6 +552,23 @@ Works the same as oneof but is case insensitive and therefore only accepts strin Usage: oneofci=red green oneofci='red green' 'blue yellow' +# None Of + +For strings, ints, and uints, noneof will ensure that the value is not one of +the values in the parameter. The parameter should be a list of values separated by whitespace. +Values may be strings or numbers. To inversely match strings with spaces in them, include the target string between single quotes. +Kind of like an 'enum'. + + Usage: noneof=red green + noneof='red green' 'blue yellow' + noneof=5 7 9 + +# None Of Case Insensitive +Works the same as noneof but is case insensitive and therefore only accepts strings. + + Usage: noneofci=red green + noneofci='red green' 'blue yellow' + # Greater Than For numbers, this will ensure that the value is greater than the @@ -733,15 +800,16 @@ This does the same as contains except for struct fields. It should only be used with string types. See the behavior of reflect.Value.String() for behavior on other types. - Usage: containsfield=InnerStructField.Field + Usage: fieldcontains=InnerStructField.Field -# Field Excludes Another Field +# Field Excludes Another Field's Value -This does the same as excludes except for struct fields. It should only be used -with string types. See the behavior of reflect.Value.String() for behavior on -other types. +This validates that the current field's string value does not contain the +string value of the field named by the parameter. It should only be used with +string types. If the referenced field cannot be resolved, validation succeeds. +See the behavior of reflect.Value.String() for behavior on other types. - Usage: excludesfield=InnerStructField.Field + Usage: fieldexcludes=InnerStructField.Field # Unique @@ -776,12 +844,24 @@ This validates that a string value contains ASCII alpha characters only Usage: alpha +# Alpha Space + +This validates that a string value contains ASCII alpha characters and spaces only + + Usage: alphaspace + # Alphanumeric This validates that a string value contains ASCII alphanumeric characters only Usage: alphanum +# Alphanumeric Space + +This validates that a string value contains ASCII alphanumeric characters and spaces only + + Usage: alphanumspace + # Alpha Unicode This validates that a string value contains unicode alpha characters only @@ -864,6 +944,12 @@ This validates that a string value contains a valid hsla color Usage: hsla +# CMYK String + +This validates that a string value contains a valid cmyk color + + Usage: cmyk + # E.164 Phone Number String This validates that a string value contains a valid E.164 Phone number @@ -907,6 +993,16 @@ This is done using os.Stat and github.com/gabriel-vasile/mimetype Usage: image +# MIME type path + +This validates that a string value contains a valid file path and that +the file exists on the machine and matches the provided MIME type in the +form type/subtype or type/*. +This is done using os.Stat and github.com/gabriel-vasile/mimetype + + Usage: mimetype=image/png + Usage: mimetype=image/* + # File Path This validates that a string value contains a valid file path but does not @@ -930,6 +1026,13 @@ This will accept any uri the golang request uri accepts Usage: uri +# Urn RFC 8141 String + +This validataes that a string value contains a valid URN +according to the RFC 8141 spec. + + Usage: urn_rfc8141 + # Urn RFC 2141 String This validates that a string value contains a valid URN @@ -1080,7 +1183,7 @@ This validates that a string value contains a valid isbn13 value. # Universally Unique Identifier UUID -This validates that a string value contains a valid UUID. Uppercase UUID values will not pass - use `uuid_rfc4122` instead. +This validates that a string value contains a valid UUID. Both lowercase and uppercase hex digits are accepted. Usage: uuid @@ -1148,7 +1251,7 @@ This validates that a string value contains a valid longitude. Usage: longitude -# Employeer Identification Number EIN +# Employer Identification Number EIN This validates that a string value contains a valid U.S. Employer Identification Number. @@ -1256,6 +1359,15 @@ This validates that a string value contains a valid Unix Address. Usage: unix_addr +# Unix Domain Socket Exists + +This validates that a Unix domain socket file exists at the specified path. +It checks both filesystem-based sockets and Linux abstract sockets (prefixed with @). +For filesystem sockets, it verifies the path exists and is a socket file. +For abstract sockets on Linux, it checks /proc/net/unix. + + Usage: uds_exists + # Media Access Control Address MAC This validates that a string value contains a valid MAC Address. @@ -1278,6 +1390,13 @@ This validates that a string value is a valid Hostname according to RFC 1123 htt Usage: hostname_rfc1123 or if you want to continue to use 'hostname' in your tags, create an alias. +# Hostname Label + +This validates that a string value is a valid hostname label (The 'label' in 'label.domain.name') according to +RFC 1123 https://tools.ietf.org/rfc1123. + + Usage: hostname_label + Full Qualified Domain Name (FQDN) This validates that a string value contains a valid FQDN. @@ -1315,11 +1434,13 @@ This is done using os.Stat, which is a platform independent function. # Directory Path -This validates that a string value contains a valid directory but does -not validate the existence of that directory. -This is done using os.Stat, which is a platform independent function. -It is safest to suffix the string with os.PathSeparator if the directory -may not exist at the time of validation. +This validates that a string value contains a valid directory path without +requiring the directory to exist. An existing directory is accepted with or +without a trailing separator, as determined by os.Stat. +If the directory does not exist, the path must end with os.PathSeparator; +otherwise it is rejected because it cannot be distinguished from a file path. +For example, filepath.Join("parent", "new-directory") + string(os.PathSeparator) +can be used to validate a directory path before creating it. Usage: dirpath @@ -1330,6 +1451,12 @@ can be used to validate fields typically passed to sockets and connections. Usage: hostname_port +# Port + +This validates that an integer value (signed or unsigned) falls within the valid port range of 1-65,535. + + Usage: port + # Datetime This validates that a string value is a valid datetime based on the supplied datetime format. @@ -1337,6 +1464,14 @@ Supplied format must match the official Go time format layout as documented in h Usage: datetime=2006-01-02 +# Duration + +This validates that a string value is a valid duration as accepted by time.ParseDuration, +such as "300ms", "-1.5h" or "2h45m". Non-string fields, including time.Duration, fail validation. +see: https://pkg.go.dev/time#ParseDuration + + Usage: duration + # Iso3166-1 alpha-2 This validates that a string value is a valid country code based on iso3166-1 alpha-2 standard. @@ -1365,13 +1500,28 @@ More information on https://pkg.go.dev/golang.org/x/text/language Usage: bcp47_language_tag -BIC (SWIFT code) +# BCP 47 Strict Language Tag -This validates that a string value is a valid Business Identifier Code (SWIFT code), defined in ISO 9362. -More information on https://www.iso.org/standard/60390.html +This validates that a string value is a valid BCP 47 language tag strictly following RFC 5646 rules, +unlike language.Parse which also accepts Unicode extensions. +see https://www.rfc-editor.org/rfc/bcp/bcp47.txt + + Usage: bcp47_strict_language_tag + +BIC (SWIFT code - 2022 standard) + +This validates that a string value is a valid Business Identifier Code (SWIFT code), defined in ISO 9362:2022. +More information on https://www.iso.org/standard/84108.html Usage: bic +BIC (SWIFT code - 2014 standard) + +This validates that a string value is a valid Business Identifier Code (SWIFT code), defined in ISO 9362:2014. +More information on https://www.iso.org/standard/60390.html + + Usage: bic_iso_9362_2014 + # RFC 1035 label This validates that a string value is a valid dns RFC 1035 label, defined in RFC 1035. @@ -1450,9 +1600,11 @@ case will be the actual tag within the alias that failed. Here is a list of the current built in alias tags: "iscolor" - alias is "hexcolor|rgb|rgba|hsl|hsla" (Usage: iscolor) + alias is "hexcolor|rgb|rgba|hsl|hsla|cmyk" (Usage: iscolor) "country_code" alias is "iso3166_1_alpha2|iso3166_1_alpha3|iso3166_1_alpha_numeric" (Usage: country_code) + "eu_country_code" + alias is "iso3166_1_alpha2_eu|iso3166_1_alpha3_eu|iso3166_1_alpha_numeric_eu" (Usage: eu_country_code) Validator notes: @@ -1485,7 +1637,7 @@ Example of registration and use: } t := &Test{ - TestField: "Test" + TestField: "Test", } validate := validator.New() @@ -1506,11 +1658,11 @@ This package panics when bad input is provided, this is by design, bad code like that should not make it to production. type Test struct { - TestField string `validate:"nonexistantfunction=1"` + TestField string `validate:"nonexistentfunction=1"` } t := &Test{ - TestField: "Test" + TestField: "Test", } validate.Struct(t) // this will panic diff --git a/vendor/github.com/txix-open/validator/v10/errors.go b/vendor/github.com/txix-open/validator/v10/errors.go index 2b99d0e..d9949ae 100644 --- a/vendor/github.com/txix-open/validator/v10/errors.go +++ b/vendor/github.com/txix-open/validator/v10/errors.go @@ -79,7 +79,7 @@ type FieldError interface { // validation was an alias, this will return the // alias name and not the underlying tag that failed. // - // eg. alias "iscolor": "hexcolor|rgb|rgba|hsl|hsla" + // eg. alias "iscolor": "hexcolor|rgb|rgba|hsl|hsla|cmyk" // will return "iscolor" Tag() string @@ -87,8 +87,8 @@ type FieldError interface { // alias the actual tag within the alias will be returned. // If an 'or' validation fails the entire or will be returned. // - // eg. alias "iscolor": "hexcolor|rgb|rgba|hsl|hsla" - // will return "hexcolor|rgb|rgba|hsl|hsla" + // eg. alias "iscolor": "hexcolor|rgb|rgba|hsl|hsla|cmyk" + // will return "hexcolor|rgb|rgba|hsl|hsla|cmyk" ActualTag() string // Namespace returns the namespace for the field error, with the tag @@ -105,24 +105,24 @@ type FieldError interface { // StructNamespace returns the namespace for the field error, with the field's // actual name. // - // eq. "User.FirstName" see Namespace for comparison + // eg. "User.FirstName" see Namespace for comparison // // NOTE: this field can be blank when validating a single primitive field // using validate.Field(...) as there is no way to extract its name StructNamespace() string - // Field returns the fields name with the tag name taking precedence over the + // Field returns the field's name with the tag name taking precedence over the // field's actual name. // // `RegisterTagNameFunc` must be registered to get tag value. // - // eq. JSON name "fname" + // eg. JSON name "fname" // see StructField for comparison Field() string // StructField returns the field's actual name from the struct, when able to determine. // - // eq. "FirstName" + // eg. "FirstName" // see Field for comparison StructField() string diff --git a/vendor/github.com/txix-open/validator/v10/language_codes.go b/vendor/github.com/txix-open/validator/v10/language_codes.go new file mode 100644 index 0000000..16cda6c --- /dev/null +++ b/vendor/github.com/txix-open/validator/v10/language_codes.go @@ -0,0 +1,403 @@ +package validator + +// Type: variant and their associated primary language prefixes from the +// IANA Language Subtag Registry: +// https://www.iana.org/assignments/language-subtag-registry/language-subtag-registry +var iana_subtag_registry_variants = map[string][]string{ + "1606nict": {"frm"}, + "1694acad": {"fr"}, + "1901": {"de"}, + "1959acad": {"be"}, + "1994": {"sl-rozaj", "sl-rozaj-biske", "sl-rozaj-njiva", "sl-rozaj-osojs", "sl-rozaj-solba"}, + "1996": {"de"}, + "abl1943": {"pt-BR"}, + "akhmimic": {"cop"}, + "akuapem": {"tw"}, + "alalc97": {}, + "aluku": {"djk"}, + "anpezo": {"lld"}, + "ao1990": {"pt", "gl"}, + "aranes": {"oc"}, + "arevela": {"hy"}, + "arevmda": {"hy"}, + "arkaika": {"eo"}, + "asante": {"tw"}, + "auvern": {"oc"}, + "baku1926": {"az", "ba", "crh", "kk", "krc", "ky", "sah", "tk", "tt", "uz"}, + "balanka": {"blo"}, + "barla": {"kea"}, + "basiceng": {"en"}, + "bauddha": {"sa"}, + "bciav": {"zbl"}, + "bcizbl": {"zbl"}, + "biscayan": {"eu"}, + "biske": {"sl-rozaj"}, + "blasl": {"ase", "sgn-ase"}, + "bohairic": {"cop"}, + "bohoric": {"sl"}, + "boont": {"en"}, + "bornholm": {"da"}, + "cisaup": {"oc"}, + "colb1945": {"pt"}, + "cornu": {"en"}, + "creiss": {"oc"}, + "dajnko": {"sl"}, + "ekavsk": {"sr", "sr-Latn", "sr-Cyrl"}, + "emodeng": {"en"}, + "fascia": {"lld"}, + "fayyumic": {"cop"}, + "fodom": {"lld"}, + "fonipa": {}, + "fonkirsh": {}, + "fonnapa": {}, + "fonupa": {}, + "fonxsamp": {}, + "gallo": {"fr"}, + "gascon": {"oc"}, + "gherd": {"lld"}, + "grclass": {"oc", "oc-aranes", "oc-auvern", "oc-cisaup", "oc-creiss", "oc-gascon", "oc-lemosin", "oc-lengadoc", "oc-nicard", "oc-provenc", "oc-vivaraup"}, + "grital": {"oc", "oc-cisaup", "oc-nicard", "oc-provenc"}, + "grmistr": {"oc", "oc-aranes", "oc-auvern", "oc-cisaup", "oc-creiss", "oc-gascon", "oc-lemosin", "oc-lengadoc", "oc-nicard", "oc-provenc", "oc-vivaraup"}, + "hanoi": {"vi"}, + "hepburn": {"ja-Latn"}, + "heploc": {"ja-Latn-hepburn"}, + "hognorsk": {"nn"}, + "hsistemo": {"eo"}, + "huett": {"vi"}, + "ijekavsk": {"sr", "sr-Latn", "sr-Cyrl"}, + "itihasa": {"sa"}, + "ivanchov": {"bg"}, + "jauer": {"rm"}, + "jyutping": {"yue"}, + "kkcor": {"kw"}, + "kleinsch": {"kl", "kl-tunumiit"}, + "kociewie": {"pl"}, + "kscor": {"kw"}, + "laukika": {"sa"}, + "leidentr": {"egy"}, + "lemosin": {"oc"}, + "lengadoc": {"oc"}, + "lipaw": {"sl-rozaj"}, + "ltg1929": {"ltg"}, + "ltg2007": {"ltg"}, + "luna1918": {"ru"}, + "lycopol": {"cop"}, + "mdcegyp": {"egy"}, + "mdctrans": {"egy"}, + "mesokem": {"cop"}, + "metelko": {"sl"}, + "monoton": {"el"}, + "ndyuka": {"djk"}, + "nedis": {"sl"}, + "newfound": {"en-CA"}, + "nicard": {"oc"}, + "njiva": {"sl-rozaj"}, + "nulik": {"vo"}, + "osojs": {"sl-rozaj"}, + "oxendict": {"en"}, + "pahawh2": {"mww", "hnj"}, + "pahawh3": {"mww", "hnj"}, + "pahawh4": {"mww", "hnj"}, + "pamaka": {"djk"}, + "peano": {"la"}, + "pehoeji": {"nan-Latn"}, + "petr1708": {"ru"}, + "pinyin": {"zh-Latn", "bo-Latn"}, + "polyton": {"el"}, + "provenc": {"oc"}, + "puter": {"rm"}, + "rigik": {"vo"}, + "rozaj": {"sl"}, + "rumgr": {"rm"}, + "sahidic": {"cop"}, + "saigon": {"vi"}, + "scotland": {"en"}, + "scouse": {"en"}, + "simple": {}, + "solba": {"sl-rozaj"}, + "sotav": {"kea"}, + "spanglis": {"en", "es"}, + "surmiran": {"rm"}, + "sursilv": {"rm"}, + "sutsilv": {"rm"}, + "synnejyl": {"da"}, + "tailo": {"nan-Latn"}, + "tarask": {"be"}, + "tongyong": {"zh-Latn"}, + "tunumiit": {"kl"}, + "uccor": {"kw"}, + "ucrcor": {"kw"}, + "ulster": {"sco"}, + "unifon": {"en", "hup", "kyh", "tol", "yur"}, + "vaidika": {"sa"}, + "valbadia": {"lld"}, + "valencia": {"ca"}, + "vallader": {"rm"}, + "vecdruka": {"lv"}, + "viennese": {"de"}, + "vivaraup": {"oc"}, + "wadegile": {"zh-Latn"}, + "xsistemo": {"eo"}, +} + +// Type: extlang and their associated primary language prefixes from the +// IANA Language Subtag Registry: +// https://www.iana.org/assignments/language-subtag-registry/language-subtag-registry +var iana_subtag_registry_extlangs = map[string][]string{ + "aao": {"ar"}, + "abh": {"ar"}, + "abv": {"ar"}, + "acm": {"ar"}, + "acq": {"ar"}, + "acw": {"ar"}, + "acx": {"ar"}, + "acy": {"ar"}, + "adf": {"ar"}, + "ads": {"sgn"}, + "aeb": {"ar"}, + "aec": {"ar"}, + "aed": {"sgn"}, + "aen": {"sgn"}, + "afb": {"ar"}, + "afg": {"sgn"}, + "ajp": {"ar"}, + "ajs": {"sgn"}, + "apc": {"ar"}, + "apd": {"ar"}, + "arb": {"ar"}, + "arq": {"ar"}, + "ars": {"ar"}, + "ary": {"ar"}, + "arz": {"ar"}, + "ase": {"sgn"}, + "asf": {"sgn"}, + "asp": {"sgn"}, + "asq": {"sgn"}, + "asw": {"sgn"}, + "auz": {"ar"}, + "avl": {"ar"}, + "ayh": {"ar"}, + "ayl": {"ar"}, + "ayn": {"ar"}, + "ayp": {"ar"}, + "bbz": {"ar"}, + "bfi": {"sgn"}, + "bfk": {"sgn"}, + "bjn": {"ms"}, + "bog": {"sgn"}, + "bqn": {"sgn"}, + "bqy": {"sgn"}, + "btj": {"ms"}, + "bve": {"ms"}, + "bvl": {"sgn"}, + "bvu": {"ms"}, + "bzs": {"sgn"}, + "cdo": {"zh"}, + "cds": {"sgn"}, + "cjy": {"zh"}, + "cmn": {"zh"}, + "cnp": {"zh"}, + "coa": {"ms"}, + "cpx": {"zh"}, + "csc": {"sgn"}, + "csd": {"sgn"}, + "cse": {"sgn"}, + "csf": {"sgn"}, + "csg": {"sgn"}, + "csl": {"sgn"}, + "csn": {"sgn"}, + "csp": {"zh"}, + "csq": {"sgn"}, + "csr": {"sgn"}, + "csx": {"sgn"}, + "czh": {"zh"}, + "czo": {"zh"}, + "doq": {"sgn"}, + "dse": {"sgn"}, + "dsl": {"sgn"}, + "dsz": {"sgn"}, + "dup": {"ms"}, + "ecs": {"sgn"}, + "ehs": {"sgn"}, + "esl": {"sgn"}, + "esn": {"sgn"}, + "eso": {"sgn"}, + "eth": {"sgn"}, + "fcs": {"sgn"}, + "fse": {"sgn"}, + "fsl": {"sgn"}, + "fss": {"sgn"}, + "gan": {"zh"}, + "gds": {"sgn"}, + "gom": {"kok"}, + "gse": {"sgn"}, + "gsg": {"sgn"}, + "gsm": {"sgn"}, + "gss": {"sgn"}, + "gus": {"sgn"}, + "hab": {"sgn"}, + "haf": {"sgn"}, + "hak": {"zh"}, + "hds": {"sgn"}, + "hji": {"ms"}, + "hks": {"sgn"}, + "hnm": {"zh"}, + "hos": {"sgn"}, + "hps": {"sgn"}, + "hsh": {"sgn"}, + "hsl": {"sgn"}, + "hsn": {"zh"}, + "icl": {"sgn"}, + "iks": {"sgn"}, + "ils": {"sgn"}, + "inl": {"sgn"}, + "ins": {"sgn"}, + "ise": {"sgn"}, + "isg": {"sgn"}, + "isr": {"sgn"}, + "jak": {"ms"}, + "jax": {"ms"}, + "jcs": {"sgn"}, + "jhs": {"sgn"}, + "jks": {"sgn"}, + "jls": {"sgn"}, + "jos": {"sgn"}, + "jsl": {"sgn"}, + "jus": {"sgn"}, + "kgi": {"sgn"}, + "knn": {"kok"}, + "kvb": {"ms"}, + "kvk": {"sgn"}, + "kvr": {"ms"}, + "kxd": {"ms"}, + "lbs": {"sgn"}, + "lce": {"ms"}, + "lcf": {"ms"}, + "lgs": {"sgn"}, + "liw": {"ms"}, + "lls": {"sgn"}, + "lsb": {"sgn"}, + "lsc": {"sgn"}, + "lsg": {"sgn"}, + "lsl": {"sgn"}, + "lsn": {"sgn"}, + "lso": {"sgn"}, + "lsp": {"sgn"}, + "lst": {"sgn"}, + "lsv": {"sgn"}, + "lsw": {"sgn"}, + "lsy": {"sgn"}, + "ltg": {"lv"}, + "luh": {"zh"}, + "lvs": {"lv"}, + "lws": {"sgn"}, + "lzh": {"zh"}, + "max": {"ms"}, + "mdl": {"sgn"}, + "meo": {"ms"}, + "mfa": {"ms"}, + "mfb": {"ms"}, + "mfs": {"sgn"}, + "min": {"ms"}, + "mnp": {"zh"}, + "mqg": {"ms"}, + "mre": {"sgn"}, + "msd": {"sgn"}, + "msi": {"ms"}, + "msr": {"sgn"}, + "mui": {"ms"}, + "mzc": {"sgn"}, + "mzg": {"sgn"}, + "mzy": {"sgn"}, + "nan": {"zh"}, + "nbs": {"sgn"}, + "ncs": {"sgn"}, + "nsi": {"sgn"}, + "nsl": {"sgn"}, + "nsp": {"sgn"}, + "nsr": {"sgn"}, + "nzs": {"sgn"}, + "okl": {"sgn"}, + "orn": {"ms"}, + "ors": {"ms"}, + "pel": {"ms"}, + "pga": {"ar"}, + "pgz": {"sgn"}, + "pks": {"sgn"}, + "prl": {"sgn"}, + "prz": {"sgn"}, + "psc": {"sgn"}, + "psd": {"sgn"}, + "pse": {"ms"}, + "psg": {"sgn"}, + "psl": {"sgn"}, + "pso": {"sgn"}, + "psp": {"sgn"}, + "psr": {"sgn"}, + "pys": {"sgn"}, + "rib": {"sgn"}, + "rms": {"sgn"}, + "rnb": {"sgn"}, + "rsi": {"sgn"}, + "rsl": {"sgn"}, + "rsm": {"sgn"}, + "rsn": {"sgn"}, + "sdl": {"sgn"}, + "sfb": {"sgn"}, + "sfs": {"sgn"}, + "sgg": {"sgn"}, + "sgx": {"sgn"}, + "shu": {"ar"}, + "sjc": {"zh"}, + "slf": {"sgn"}, + "sls": {"sgn"}, + "sqk": {"sgn"}, + "sqs": {"sgn"}, + "sqx": {"sgn"}, + "ssh": {"ar"}, + "ssp": {"sgn"}, + "ssr": {"sgn"}, + "svk": {"sgn"}, + "swc": {"sw"}, + "swh": {"sw"}, + "swl": {"sgn"}, + "syy": {"sgn"}, + "szs": {"sgn"}, + "tmw": {"ms"}, + "tse": {"sgn"}, + "tsm": {"sgn"}, + "tsq": {"sgn"}, + "tss": {"sgn"}, + "tsy": {"sgn"}, + "tza": {"sgn"}, + "ugn": {"sgn"}, + "ugy": {"sgn"}, + "ukl": {"sgn"}, + "uks": {"sgn"}, + "urk": {"ms"}, + "uzn": {"uz"}, + "uzs": {"uz"}, + "vgt": {"sgn"}, + "vkk": {"ms"}, + "vkt": {"ms"}, + "vsi": {"sgn"}, + "vsl": {"sgn"}, + "vsv": {"sgn"}, + "wbs": {"sgn"}, + "wuu": {"zh"}, + "xki": {"sgn"}, + "xml": {"sgn"}, + "xmm": {"ms"}, + "xms": {"sgn"}, + "yds": {"sgn"}, + "ygs": {"sgn"}, + "yhs": {"sgn"}, + "ysl": {"sgn"}, + "ysm": {"sgn"}, + "yue": {"zh"}, + "zib": {"sgn"}, + "zlm": {"ms"}, + "zmi": {"ms"}, + "zsl": {"sgn"}, + "zsm": {"ms"}, +} diff --git a/vendor/github.com/txix-open/validator/v10/no_validate_fn.go b/vendor/github.com/txix-open/validator/v10/no_validate_fn.go new file mode 100644 index 0000000..603af53 --- /dev/null +++ b/vendor/github.com/txix-open/validator/v10/no_validate_fn.go @@ -0,0 +1,60 @@ +//go:build !validator_novalidatefn + +package validator + +import ( + "cmp" + "fmt" + "reflect" +) + +func isValidateFn(fl FieldLevel) bool { + const defaultParam = `Validate` + + field := fl.Field() + validateFn := cmp.Or(fl.Param(), defaultParam) + + ok, err := tryCallValidateFn(field, validateFn) + if err != nil { + return false + } + + return ok +} + +func tryCallValidateFn(field reflect.Value, validateFn string) (bool, error) { + method := field.MethodByName(validateFn) + if field.CanAddr() && !method.IsValid() { + method = field.Addr().MethodByName(validateFn) + } + + if !method.IsValid() { + return false, fmt.Errorf("unable to call %q on type %q: %w", + validateFn, field.Type().String(), errMethodNotFound) + } + + returnValues := method.Call([]reflect.Value{}) + if len(returnValues) == 0 { + return false, fmt.Errorf("unable to use result of method %q on type %q: %w", + validateFn, field.Type().String(), errMethodReturnNoValues) + } + + firstReturnValue := returnValues[0] + + switch firstReturnValue.Kind() { + case reflect.Bool: + return firstReturnValue.Bool(), nil + case reflect.Interface: + errorType := reflect.TypeOf((*error)(nil)).Elem() + + if firstReturnValue.Type().Implements(errorType) { + return firstReturnValue.IsNil(), nil + } + + return false, fmt.Errorf("unable to use result of method %q on type %q: %w (got interface %v expect error)", + validateFn, field.Type().String(), errMethodReturnInvalidType, firstReturnValue.Type().String()) + default: + return false, fmt.Errorf("unable to use result of method %q on type %q: %w (got %v expect error or bool)", + validateFn, field.Type().String(), errMethodReturnInvalidType, firstReturnValue.Type().String()) + } +} diff --git a/vendor/github.com/txix-open/validator/v10/options.go b/vendor/github.com/txix-open/validator/v10/options.go index 86a0db2..2178d38 100644 --- a/vendor/github.com/txix-open/validator/v10/options.go +++ b/vendor/github.com/txix-open/validator/v10/options.go @@ -24,3 +24,17 @@ func WithPrivateFieldValidation() Option { v.privateFieldValidation = true } } + +// WithTagNameFuncBlankOmit makes a blank return from a RegisterTagNameFunc omit +// the field from the error namespace instead of silently falling back to the +// struct field name. +// +// This was made opt-in behaviour to maintain backward compatibility with +// existing callers that rely on the fallback for error namespaces. +// +// It is recommended you enable this as it will be the default behaviour in v11+. +func WithTagNameFuncBlankOmit() Option { + return func(v *Validate) { + v.omitBlankFieldNames = true + } +} diff --git a/vendor/github.com/txix-open/validator/v10/postcode_regexes.go b/vendor/github.com/txix-open/validator/v10/postcode_regexes.go index 326b8f7..c8ac152 100644 --- a/vendor/github.com/txix-open/validator/v10/postcode_regexes.go +++ b/vendor/github.com/txix-open/validator/v10/postcode_regexes.go @@ -6,7 +6,7 @@ import ( ) var postCodePatternDict = map[string]string{ - "GB": `^GIR[ ]?0AA|((AB|AL|B|BA|BB|BD|BH|BL|BN|BR|BS|BT|CA|CB|CF|CH|CM|CO|CR|CT|CV|CW|DA|DD|DE|DG|DH|DL|DN|DT|DY|E|EC|EH|EN|EX|FK|FY|G|GL|GY|GU|HA|HD|HG|HP|HR|HS|HU|HX|IG|IM|IP|IV|JE|KA|KT|KW|KY|L|LA|LD|LE|LL|LN|LS|LU|M|ME|MK|ML|N|NE|NG|NN|NP|NR|NW|OL|OX|PA|PE|PH|PL|PO|PR|RG|RH|RM|S|SA|SE|SG|SK|SL|SM|SN|SO|SP|SR|SS|ST|SW|SY|TA|TD|TF|TN|TQ|TR|TS|TW|UB|W|WA|WC|WD|WF|WN|WR|WS|WV|YO|ZE)(\d[\dA-Z]?[ ]?\d[ABD-HJLN-UW-Z]{2}))|BFPO[ ]?\d{1,4}$`, + "GB": `^(?:GIR[ ]?0AA|((AB|AL|B|BA|BB|BD|BH|BL|BN|BR|BS|BT|CA|CB|CF|CH|CM|CO|CR|CT|CV|CW|DA|DD|DE|DG|DH|DL|DN|DT|DY|E|EC|EH|EN|EX|FK|FY|G|GL|GY|GU|HA|HD|HG|HP|HR|HS|HU|HX|IG|IM|IP|IV|JE|KA|KT|KW|KY|L|LA|LD|LE|LL|LN|LS|LU|M|ME|MK|ML|N|NE|NG|NN|NP|NR|NW|OL|OX|PA|PE|PH|PL|PO|PR|RG|RH|RM|S|SA|SE|SG|SK|SL|SM|SN|SO|SP|SR|SS|ST|SW|SY|TA|TD|TF|TN|TQ|TR|TS|TW|UB|W|WA|WC|WD|WF|WN|WR|WS|WV|YO|ZE)(\d[\dA-Z]?[ ]?\d[ABD-HJLN-UW-Z]{2}))|BFPO[ ]?\d{1,4})$`, "JE": `^JE\d[\dA-Z]?[ ]?\d[ABD-HJLN-UW-Z]{2}$`, "GG": `^GY\d[\dA-Z]?[ ]?\d[ABD-HJLN-UW-Z]{2}$`, "IM": `^IM\d[\dA-Z]?[ ]?\d[ABD-HJLN-UW-Z]{2}$`, @@ -29,12 +29,13 @@ var postCodePatternDict = map[string]string{ "PT": `^\d{4}([\-]\d{3})?$`, "FI": `^\d{5}$`, "AX": `^22\d{3}$`, - "KR": `^\d{3}[\-]\d{3}$`, + "KR": `^\d{5}$`, "CN": `^\d{6}$`, - "TW": `^\d{3}(\d{2})?$`, + "TW": `^\d{3}(\d{2,3})?$`, "SG": `^\d{6}$`, "DZ": `^\d{5}$`, "AD": `^AD\d{3}$`, + "AL": `^\d{4}$`, "AR": `^([A-HJ-NP-Z])?\d{4}([A-Z]{3})?$`, "AM": `^(37)?\d{4}$`, "AZ": `^\d{4}$`, @@ -50,7 +51,8 @@ var postCodePatternDict = map[string]string{ "KH": `^\d{5}$`, "CV": `^\d{4}$`, "CL": `^\d{7}$`, - "CR": `^\d{4,5}|\d{3}-\d{4}$`, + "CO": `^\d{6}$`, + "CR": `^\d{5}$`, "HR": `^\d{5}$`, "CY": `^\d{4}$`, "CZ": `^\d{3}[ ]?\d{2}$`, @@ -60,16 +62,18 @@ var postCodePatternDict = map[string]string{ "EE": `^\d{5}$`, "FO": `^\d{3}$`, "GE": `^\d{4}$`, + "GI": `^GI\d{1,2}[ ]?\d[A-Z]{2}$`, "GR": `^\d{3}[ ]?\d{2}$`, "GL": `^39\d{2}$`, "GT": `^\d{5}$`, "HT": `^\d{4}$`, "HN": `^(?:\d{5})?$`, "HU": `^\d{4}$`, + "IE": `^[A-Z]\d[A-Z0-9][ ]?[A-Z0-9]{4}$`, "IS": `^\d{3}$`, "IN": `^\d{6}$`, "ID": `^\d{5}$`, - "IL": `^\d{5}$`, + "IL": `^\d{5}(\d{2})?$`, "JO": `^\d{5}$`, "KZ": `^\d{6}$`, "KE": `^\d{5}$`, @@ -77,7 +81,7 @@ var postCodePatternDict = map[string]string{ "LA": `^\d{5}$`, "LV": `^\d{4}$`, "LB": `^(\d{4}([ ]?\d{4})?)?$`, - "LI": `^(948[5-9])|(949[0-7])$`, + "LI": `^(?:(948[5-9])|(949[0-7]))$`, "LT": `^\d{5}$`, "LU": `^\d{4}$`, "MK": `^\d{4}$`, @@ -92,7 +96,7 @@ var postCodePatternDict = map[string]string{ "NP": `^\d{5}$`, "NZ": `^\d{4}$`, "NI": `^((\d{4}-)?\d{3}-\d{3}(-\d{1})?)?$`, - "NG": `^(\d{6})?$`, + "NG": `^(\d{6}|[A-Z]{2}[ -]?(0[1-9]|[1-9]\d)[ -]?[A-Z0-9]{3}[ -]?[A-Z]{2}[ -]?(0[1-9]|[1-9]\d))?$`, "OM": `^(PC )?\d{3}$`, "PK": `^\d{5}$`, "PY": `^\d{4}$`, @@ -149,6 +153,7 @@ var postCodePatternDict = map[string]string{ "MQ": `^9[78]2\d{2}$`, "NC": `^988\d{2}$`, "NE": `^\d{4}$`, + "VG": `^VG\d{4}$`, "VI": `^008(([0-4]\d)|(5[01]))([ \-]\d{4})?$`, "VN": `^[0-9]{1,6}$`, "PF": `^987\d{2}$`, diff --git a/vendor/github.com/txix-open/validator/v10/regexes.go b/vendor/github.com/txix-open/validator/v10/regexes.go index 93909b2..20c03b8 100644 --- a/vendor/github.com/txix-open/validator/v10/regexes.go +++ b/vendor/github.com/txix-open/validator/v10/regexes.go @@ -7,7 +7,9 @@ import ( const ( alphaRegexString = "^[a-zA-Z]+$" + alphaSpaceRegexString = "^[a-zA-Z ]+$" alphaNumericRegexString = "^[a-zA-Z0-9]+$" + alphaNumericSpaceRegexString = "^[a-zA-Z0-9 ]+$" alphaUnicodeRegexString = "^[\\p{L}]+$" alphaUnicodeNumericRegexString = "^[\\p{L}\\p{N}]+$" numericRegexString = "^[-+]?[0-9]+(?:\\.[0-9]+)?$" @@ -18,8 +20,9 @@ const ( rgbaRegexString = "^rgba\\(\\s*(?:(?:0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])\\s*,\\s*(?:0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])\\s*,\\s*(?:0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])|(?:0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])%\\s*,\\s*(?:0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])%\\s*,\\s*(?:0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])%)\\s*,\\s*(?:(?:0.[1-9]*)|[01])\\s*\\)$" hslRegexString = "^hsl\\(\\s*(?:0|[1-9]\\d?|[12]\\d\\d|3[0-5]\\d|360)\\s*,\\s*(?:(?:0|[1-9]\\d?|100)%)\\s*,\\s*(?:(?:0|[1-9]\\d?|100)%)\\s*\\)$" hslaRegexString = "^hsla\\(\\s*(?:0|[1-9]\\d?|[12]\\d\\d|3[0-5]\\d|360)\\s*,\\s*(?:(?:0|[1-9]\\d?|100)%)\\s*,\\s*(?:(?:0|[1-9]\\d?|100)%)\\s*,\\s*(?:(?:0.[1-9]*)|[01])\\s*\\)$" + cmykRegexString = "^cmyk\\((100|[1-9]?\\d)%\\s*,\\s*(100|[1-9]?\\d)%\\s*,\\s*(100|[1-9]?\\d)%\\s*,\\s*(100|[1-9]?\\d)%\\)$" emailRegexString = "^(?:(?:(?:(?:[a-zA-Z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])+(?:\\.([a-zA-Z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])+)*)|(?:(?:\\x22)(?:(?:(?:(?:\\x20|\\x09)*(?:\\x0d\\x0a))?(?:\\x20|\\x09)+)?(?:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(?:(?:[\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}]))))*(?:(?:(?:\\x20|\\x09)*(?:\\x0d\\x0a))?(\\x20|\\x09)+)?(?:\\x22))))@(?:(?:(?:[a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(?:(?:[a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])(?:[a-zA-Z]|\\d|-|\\.|~|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])*(?:[a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])))\\.)+(?:(?:[a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(?:(?:[a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])(?:[a-zA-Z]|\\d|-|\\.|~|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])*(?:[a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])))\\.?$" - e164RegexString = "^\\+[1-9]?[0-9]{7,14}$" + e164RegexString = "^\\+?[1-9]\\d{7,14}$" base32RegexString = "^(?:[A-Z2-7]{8})*(?:[A-Z2-7]{2}={6}|[A-Z2-7]{4}={4}|[A-Z2-7]{5}={3}|[A-Z2-7]{7}=|[A-Z2-7]{8})$" base64RegexString = "^(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\\/]{3}=|[A-Za-z0-9+\\/]{4})$" base64URLRegexString = "^(?:[A-Za-z0-9-_]{4})*(?:[A-Za-z0-9-_]{2}==|[A-Za-z0-9-_]{3}=|[A-Za-z0-9-_]{4})$" @@ -30,7 +33,7 @@ const ( uUID3RegexString = "^[0-9a-f]{8}-[0-9a-f]{4}-3[0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12}$" uUID4RegexString = "^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$" uUID5RegexString = "^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$" - uUIDRegexString = "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + uUIDRegexString = "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$" uUID3RFC4122RegexString = "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-3[0-9a-fA-F]{3}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$" uUID4RFC4122RegexString = "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$" uUID5RFC4122RegexString = "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-5[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$" @@ -53,12 +56,12 @@ const ( latitudeRegexString = "^[-+]?([1-8]?\\d(\\.\\d+)?|90(\\.0+)?)$" longitudeRegexString = "^[-+]?(180(\\.0+)?|((1[0-7]\\d)|([1-9]?\\d))(\\.\\d+)?)$" sSNRegexString = `^[0-9]{3}[ -]?(0[1-9]|[1-9][0-9])[ -]?([1-9][0-9]{3}|[0-9][1-9][0-9]{2}|[0-9]{2}[1-9][0-9]|[0-9]{3}[1-9])$` - hostnameRegexStringRFC952 = `^[a-zA-Z]([a-zA-Z0-9\-]+[\.]?)*[a-zA-Z0-9]$` // https://tools.ietf.org/html/rfc952 - hostnameRegexStringRFC1123 = `^([a-zA-Z0-9]{1}[a-zA-Z0-9-]{0,62}){1}(\.[a-zA-Z0-9]{1}[a-zA-Z0-9-]{0,62})*?$` // accepts hostname starting with a digit https://tools.ietf.org/html/rfc1123 - fqdnRegexStringRFC1123 = `^([a-zA-Z0-9]{1}[a-zA-Z0-9-]{0,62})(\.[a-zA-Z0-9]{1}[a-zA-Z0-9-]{0,62})*?(\.[a-zA-Z]{1}[a-zA-Z0-9]{0,62})\.?$` // same as hostnameRegexStringRFC1123 but must contain a non numerical TLD (possibly ending with '.') - btcAddressRegexString = `^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$` // bitcoin address - btcAddressUpperRegexStringBech32 = `^BC1[02-9AC-HJ-NP-Z]{7,76}$` // bitcoin bech32 address https://en.bitcoin.it/wiki/Bech32 - btcAddressLowerRegexStringBech32 = `^bc1[02-9ac-hj-np-z]{7,76}$` // bitcoin bech32 address https://en.bitcoin.it/wiki/Bech32 + hostnameRegexStringRFC952 = `^[a-zA-Z]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$` // https://tools.ietf.org/html/rfc952 + hostnameRegexStringRFC1123 = `^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$` // accepts hostname starting with a digit https://tools.ietf.org/html/rfc1123 + fqdnRegexStringRFC1123 = `^([a-zA-Z0-9]{1}[a-zA-Z0-9-]{0,62})(\.[a-zA-Z0-9]{1}[a-zA-Z0-9-]{0,62})*?(\.[a-zA-Z]{1}[a-zA-Z0-9-]{0,62})\.?$` // same as hostnameRegexStringRFC1123 but must contain a non numerical TLD (possibly ending with '.') + btcAddressRegexString = `^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$` // bitcoin address + btcAddressUpperRegexStringBech32 = `^BC1[02-9AC-HJ-NP-Z]{7,76}$` // bitcoin bech32 address https://en.bitcoin.it/wiki/Bech32 + btcAddressLowerRegexStringBech32 = `^bc1[02-9ac-hj-np-z]{7,76}$` // bitcoin bech32 address https://en.bitcoin.it/wiki/Bech32 ethAddressRegexString = `^0x[0-9a-fA-F]{40}$` ethAddressUpperRegexString = `^0x[0-9A-F]{40}$` ethAddressLowerRegexString = `^0x[0-9a-f]{40}$` @@ -67,13 +70,14 @@ const ( hTMLRegexString = `<[/]?([a-zA-Z]+).*?>` jWTRegexString = "^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]*$" splitParamsRegexString = `'[^']*'|\S+` - bicRegexString = `^[A-Za-z]{6}[A-Za-z0-9]{2}([A-Za-z0-9]{3})?$` + bic2014RegexString = `^[A-Za-z]{6}[A-Za-z0-9]{2}([A-Za-z0-9]{3})?$` + bic2022RegexString = `^[A-Z0-9]{4}[A-Z]{2}[A-Z0-9]{2}(?:[A-Z0-9]{3})?$` semverRegexString = `^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$` // numbered capture groups https://semver.org/ dnsRegexStringRFC1035Label = "^[a-z]([-a-z0-9]*[a-z0-9])?$" cveRegexString = `^CVE-(1999|2\d{3})-(0[^0]\d{2}|0\d[^0]\d{1}|0\d{2}[^0]|[1-9]{1}\d{3,})$` // CVE Format Id https://cve.mitre.org/cve/identifiers/syntaxchange.html mongodbIdRegexString = "^[a-f\\d]{24}$" mongodbConnStringRegexString = "^mongodb(\\+srv)?:\\/\\/(([a-zA-Z\\d]+):([a-zA-Z\\d$:\\/?#\\[\\]@]+)@)?(([a-z\\d.-]+)(:[\\d]+)?)((,(([a-z\\d.-]+)(:(\\d+))?))*)?(\\/[a-zA-Z-_]{1,64})?(\\?(([a-zA-Z]+)=([a-zA-Z\\d]+))(&(([a-zA-Z\\d]+)=([a-zA-Z\\d]+))?)*)?$" - cronRegexString = `(@(annually|yearly|monthly|weekly|daily|hourly|reboot))|(@every (\d+(ns|us|µs|ms|s|m|h))+)|((((\d+,)+\d+|((\*|\d+)(\/|-)\d+)|\d+|\*) ?){5,7})` + cronRegexString = `^((@(annually|yearly|monthly|weekly|daily|hourly|reboot))|(@every (\d+(ns|us|µs|ms|s|m|h))+)|(([A-Za-z0-9*?][A-Za-z0-9*?/,#L-]+|[*?0-9])( +([A-Za-z0-9*?][A-Za-z0-9*?/,#L-]+|[*?0-9])){4,6}))$` spicedbIDRegexString = `^(([a-zA-Z0-9/_|\-=+]{1,})|\*)$` spicedbPermissionRegexString = "^([a-z][a-z0-9_]{1,62}[a-z0-9])?$" spicedbTypeRegexString = "^([a-z][a-z0-9_]{1,61}[a-z0-9]/)?[a-z][a-z0-9_]{1,62}[a-z0-9]$" @@ -93,6 +97,8 @@ func lazyRegexCompile(str string) func() *regexp.Regexp { var ( alphaRegex = lazyRegexCompile(alphaRegexString) + alphaSpaceRegex = lazyRegexCompile(alphaSpaceRegexString) + alphanNumericSpaceRegex = lazyRegexCompile(alphaNumericSpaceRegexString) alphaNumericRegex = lazyRegexCompile(alphaNumericRegexString) alphaUnicodeRegex = lazyRegexCompile(alphaUnicodeRegexString) alphaUnicodeNumericRegex = lazyRegexCompile(alphaUnicodeNumericRegexString) @@ -104,6 +110,7 @@ var ( rgbaRegex = lazyRegexCompile(rgbaRegexString) hslRegex = lazyRegexCompile(hslRegexString) hslaRegex = lazyRegexCompile(hslaRegexString) + cmykRegex = lazyRegexCompile(cmykRegexString) e164Regex = lazyRegexCompile(e164RegexString) emailRegex = lazyRegexCompile(emailRegexString) base32Regex = lazyRegexCompile(base32RegexString) @@ -151,7 +158,8 @@ var ( hTMLRegex = lazyRegexCompile(hTMLRegexString) jWTRegex = lazyRegexCompile(jWTRegexString) splitParamsRegex = lazyRegexCompile(splitParamsRegexString) - bicRegex = lazyRegexCompile(bicRegexString) + bic2014Regex = lazyRegexCompile(bic2014RegexString) + bic2022Regex = lazyRegexCompile(bic2022RegexString) semverRegex = lazyRegexCompile(semverRegexString) dnsRegexRFC1035Label = lazyRegexCompile(dnsRegexStringRFC1035Label) cveRegex = lazyRegexCompile(cveRegexString) diff --git a/vendor/github.com/txix-open/validator/v10/struct_level.go b/vendor/github.com/txix-open/validator/v10/struct_level.go index ffe295e..129b287 100644 --- a/vendor/github.com/txix-open/validator/v10/struct_level.go +++ b/vendor/github.com/txix-open/validator/v10/struct_level.go @@ -147,7 +147,7 @@ func (v *validate) ReportError(field interface{}, fieldName, structFieldName, ta structNs: v.str2, fieldLen: uint8(len(fieldName)), structfieldLen: uint8(len(structFieldName)), - value: fv.Interface(), + value: getValue(fv), param: param, kind: kind, typ: fv.Type(), diff --git a/vendor/github.com/txix-open/validator/v10/translations/en/en.go b/vendor/github.com/txix-open/validator/v10/translations/en/en.go index bf9e7fa..0328423 100644 --- a/vendor/github.com/txix-open/validator/v10/translations/en/en.go +++ b/vendor/github.com/txix-open/validator/v10/translations/en/en.go @@ -310,7 +310,7 @@ func RegisterDefaultTranslations(v *validator.Validate, trans ut.Translator) (er return } - if err = ut.Add("max-items", "{0} must contain at maximum {1}", false); err != nil { + if err = ut.Add("max-items", "{0} must contain at most {1}", false); err != nil { return } if err = ut.AddCardinal("max-items-item", "{0} item", locales.PluralRuleOne, false); err != nil { @@ -548,7 +548,7 @@ func RegisterDefaultTranslations(v *validator.Validate, trans ut.Translator) (er { tag: "lte", customRegisFunc: func(ut ut.Translator) (err error) { - if err = ut.Add("lte-string", "{0} must be at maximum {1} in length", false); err != nil { + if err = ut.Add("lte-string", "{0} must be at most {1} in length", false); err != nil { return } @@ -564,7 +564,7 @@ func RegisterDefaultTranslations(v *validator.Validate, trans ut.Translator) (er return } - if err = ut.Add("lte-items", "{0} must contain at maximum {1}", false); err != nil { + if err = ut.Add("lte-items", "{0} must contain at most {1}", false); err != nil { return } @@ -1074,6 +1074,26 @@ func RegisterDefaultTranslations(v *validator.Validate, trans ut.Translator) (er translation: "{0} can only contain alphanumeric characters", override: false, }, + { + tag: "alphaspace", + translation: "{0} can only contain alphabetic and space characters", + override: false, + }, + { + tag: "alphanumspace", + translation: "{0} can only contain alphanumeric and space characters", + override: false, + }, + { + tag: "alphaunicode", + translation: "{0} can only contain unicode alphabetic characters", + override: false, + }, + { + tag: "alphanumunicode", + translation: "{0} can only contain unicode alphanumeric characters", + override: false, + }, { tag: "numeric", translation: "{0} must be a valid numeric value", @@ -1167,6 +1187,62 @@ func RegisterDefaultTranslations(v *validator.Validate, trans ut.Translator) (er return t }, }, + { + tag: "startswith", + translation: "{0} must start with '{1}'", + override: false, + customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { + t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) + if err != nil { + log.Printf("warning: error translating FieldError: %#v", fe) + return fe.(error).Error() + } + + return t + }, + }, + { + tag: "endswith", + translation: "{0} must end with '{1}'", + override: false, + customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { + t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) + if err != nil { + log.Printf("warning: error translating FieldError: %#v", fe) + return fe.(error).Error() + } + + return t + }, + }, + { + tag: "startsnotwith", + translation: "{0} must not start with '{1}'", + override: false, + customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { + t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) + if err != nil { + log.Printf("warning: error translating FieldError: %#v", fe) + return fe.(error).Error() + } + + return t + }, + }, + { + tag: "endsnotwith", + translation: "{0} must not end with '{1}'", + override: false, + customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { + t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) + if err != nil { + log.Printf("warning: error translating FieldError: %#v", fe) + return fe.(error).Error() + } + + return t + }, + }, { tag: "excludes", translation: "{0} cannot contain the text '{1}'", @@ -1229,6 +1305,11 @@ func RegisterDefaultTranslations(v *validator.Validate, trans ut.Translator) (er translation: "{0} must be a valid ISSN number", override: false, }, + { + tag: "urn_rfc2141", + translation: "{0} must be a valid RFC 2141 URN", + override: false, + }, { tag: "uuid", translation: "{0} must be a valid UUID", @@ -1441,6 +1522,11 @@ func RegisterDefaultTranslations(v *validator.Validate, trans ut.Translator) (er return t }, }, + { + tag: "timezone", + translation: "{0} must be a valid time zone", + override: false, + }, { tag: "postcode_iso3166_alpha2", translation: "{0} does not match postcode format of {1} country", @@ -1479,11 +1565,21 @@ func RegisterDefaultTranslations(v *validator.Validate, trans ut.Translator) (er translation: "{0} must be a valid image", override: false, }, + { + tag: "mimetype", + translation: "{0} must be a valid MIME type", + override: false, + }, { tag: "cve", translation: "{0} must be a valid cve identifier", override: false, }, + { + tag: "bcp47_strict_language_tag", + translation: "{0} must be a valid BCP 47 language tag", + override: false, + }, { tag: "validateFn", translation: "{0} must be a valid object", diff --git a/vendor/github.com/txix-open/validator/v10/util.go b/vendor/github.com/txix-open/validator/v10/util.go index fb7fa78..0922ce2 100644 --- a/vendor/github.com/txix-open/validator/v10/util.go +++ b/vendor/github.com/txix-open/validator/v10/util.go @@ -9,6 +9,13 @@ import ( "time" ) +// Valuer is an interface that allows you to expose a method on a type +// (including generic types) that returns a value that is supposed to be validated. +type Valuer interface { + // ValidatorValue returns the value that is supposed to be validated. + ValidatorValue() any +} + // extractTypeInternal gets the actual underlying type of field value. // It will dive into pointers, customTypes and return you the // underlying value and it's kind. @@ -23,6 +30,13 @@ BEGIN: return current, reflect.Ptr, nullable } + if current.CanInterface() { + if v, ok := current.Interface().(Valuer); ok { + current = reflect.ValueOf(v.ValidatorValue()) + goto BEGIN + } + } + current = current.Elem() goto BEGIN @@ -34,6 +48,13 @@ BEGIN: return current, reflect.Interface, nullable } + if current.CanInterface() { + if v, ok := current.Interface().(Valuer); ok { + current = reflect.ValueOf(v.ValidatorValue()) + goto BEGIN + } + } + current = current.Elem() goto BEGIN @@ -42,6 +63,13 @@ BEGIN: default: + if current.CanInterface() { + if v, ok := current.Interface().(Valuer); ok { + current = reflect.ValueOf(v.ValidatorValue()) + goto BEGIN + } + } + if v.v.hasCustomFuncs { if fn, ok := v.v.customFuncs[current.Type()]; ok { current = reflect.ValueOf(fn(current)) @@ -214,10 +242,12 @@ BEGIN: } // if got here there was more namespace, cannot go any deeper - panic("Invalid field namespace") + // return found=false instead of panicking to handle cases like ValidateMap + // where cross-field validators (required_if, etc.) can't navigate non-struct parents + return } -// asInt returns the parameter as a int64 +// asInt returns the parameter as an int64 // or panics if it can't convert func asInt(param string) int64 { i, err := strconv.ParseInt(param, 0, 64) @@ -296,7 +326,7 @@ func fieldMatchesRegexByStringerValOrString(regexFn func() *regexp.Regexp, fl Fi case reflect.String: return regex.MatchString(fl.Field().String()) default: - if stringer, ok := fl.Field().Interface().(fmt.Stringer); ok { + if stringer, ok := getValue(fl.Field()).(fmt.Stringer); ok { return regex.MatchString(stringer.String()) } else { return regex.MatchString(fl.Field().String()) diff --git a/vendor/github.com/txix-open/validator/v10/validate_fn.go b/vendor/github.com/txix-open/validator/v10/validate_fn.go new file mode 100644 index 0000000..ec874be --- /dev/null +++ b/vendor/github.com/txix-open/validator/v10/validate_fn.go @@ -0,0 +1,7 @@ +//go:build validator_novalidatefn + +package validator + +func isValidateFn(fl FieldLevel) bool { + panic("validateFn is not supported with 'no-validate-fn' tag") +} diff --git a/vendor/github.com/txix-open/validator/v10/validator.go b/vendor/github.com/txix-open/validator/v10/validator.go index 02a0d9d..d9ac5fb 100644 --- a/vendor/github.com/txix-open/validator/v10/validator.go +++ b/vendor/github.com/txix-open/validator/v10/validator.go @@ -116,7 +116,7 @@ func (v *validate) traverseField(ctx context.Context, parent reflect.Value, curr if ct.hasTag { if kind == reflect.Invalid { - v.str1 = string(append(ns, cf.altName...)) + v.str1 = appendAltName(ns, cf.altName) if v.v.hasTagNameFunc { v.str2 = string(append(structNs, cf.name...)) } else { @@ -138,7 +138,7 @@ func (v *validate) traverseField(ctx context.Context, parent reflect.Value, curr return } - v.str1 = string(append(ns, cf.altName...)) + v.str1 = appendAltName(ns, cf.altName) if v.v.hasTagNameFunc { v.str2 = string(append(structNs, cf.name...)) } else { @@ -192,7 +192,9 @@ OUTER: // VarWithField - this allows for validating against each field within the struct against a specific value // pretty handy in certain situations if len(cf.name) > 0 { - ns = append(append(ns, cf.altName...), '.') + if len(cf.altName) > 0 { + ns = append(append(ns, cf.altName...), '.') + } structNs = append(append(structNs, cf.name...), '.') } v.validateStruct(ctx, parent, current, typ, ns, structNs, ct) @@ -218,7 +220,9 @@ OUTER: // VarWithField - this allows for validating against each field within the struct against a specific value // pretty handy in certain situations if len(cf.name) > 0 { - ns = append(append(ns, cf.altName...), '.') + if len(cf.altName) > 0 { + ns = append(append(ns, cf.altName...), '.') + } structNs = append(append(structNs, cf.name...), '.') } @@ -266,7 +270,7 @@ OUTER: return } default: - if v.fldIsPointer && field.Interface() == nil { + if v.fldIsPointer && getValue(field) == nil { return } } @@ -318,7 +322,7 @@ OUTER: reusableCF := &cField{} for _, key := range current.MapKeys() { - pv = fmt.Sprintf("%v", key.Interface()) + pv = fmt.Sprintf("%v", key) v.misc = append(v.misc[0:0], cf.name...) v.misc = append(v.misc, '[') @@ -343,6 +347,18 @@ OUTER: // can be nil when just keys being validated if ct.next != nil { v.traverseField(ctx, parent, current.MapIndex(key), ns, structNs, reusableCF, ct.next) + } else { + // Struct fallback when map values are structs + val := current.MapIndex(key) + switch val.Kind() { + case reflect.Ptr: + if val.Elem().Kind() == reflect.Struct { + // Dive into the struct so its own tags run + v.traverseField(ctx, parent, val, ns, structNs, reusableCF, nil) + } + case reflect.Struct: + v.traverseField(ctx, parent, val, ns, structNs, reusableCF, nil) + } } } else { v.traverseField(ctx, parent, current.MapIndex(key), ns, structNs, reusableCF, ct) @@ -403,7 +419,7 @@ OUTER: if ct.isBlockEnd || ct.next == nil { // if we get here, no valid 'or' value and no more tags - v.str1 = string(append(ns, cf.altName...)) + v.str1 = appendAltName(ns, cf.altName) if v.v.hasTagNameFunc { v.str2 = string(append(structNs, cf.name...)) @@ -462,7 +478,7 @@ OUTER: v.ct = ct if !ct.fn(ctx, v) { - v.str1 = string(append(ns, cf.altName...)) + v.str1 = appendAltName(ns, cf.altName) if v.v.hasTagNameFunc { v.str2 = string(append(structNs, cf.name...)) @@ -493,6 +509,16 @@ OUTER: } } +func appendAltName(ns []byte, altName string) string { + if len(altName) > 0 { + return string(append(ns, altName...)) + } + if n := len(ns); n > 0 && ns[n-1] == '.' { + return string(ns[:n-1]) + } + return string(ns) +} + func getValue(val reflect.Value) interface{} { if val.CanInterface() { return val.Interface() diff --git a/vendor/github.com/txix-open/validator/v10/validator_instance.go b/vendor/github.com/txix-open/validator/v10/validator_instance.go index 9362cd7..320cce6 100644 --- a/vendor/github.com/txix-open/validator/v10/validator_instance.go +++ b/vendor/github.com/txix-open/validator/v10/validator_instance.go @@ -68,7 +68,7 @@ type FilterFunc func(ns []byte) bool // CustomTypeFunc allows for overriding or adding custom field type handler functions // field = field value of the type to return a value to be validated -// example Valuer from sql drive see https://golang.org/src/database/sql/driver/types.go?s=1210:1293#L29 +// example Valuer from sql driver see https://golang.org/src/database/sql/driver/types.go?s=1210:1293#L29 type CustomTypeFunc func(field reflect.Value) interface{} // TagNameFunc allows for adding of a custom tag name parser @@ -96,6 +96,7 @@ type Validate struct { hasTagNameFunc bool requiredStructEnabled bool privateFieldValidation bool + omitBlankFieldNames bool } // New returns a new instance of 'validate' with sane defaults. @@ -181,7 +182,7 @@ func (v Validate) ValidateMapCtx(ctx context.Context, data map[string]interface{ errs[field] = errors.New("The field: '" + field + "' is not a map to dive") } } else if ruleStr, ok := rule.(string); ok { - err := v.VarCtx(ctx, data[field], ruleStr) + err := v.VarWithKeyCtx(ctx, field, data[field], ruleStr) if err != nil { errs[field] = err } @@ -428,7 +429,7 @@ func (v *Validate) StructFilteredCtx(ctx context.Context, s interface{}, fn Filt } // StructPartial validates the fields passed in only, ignoring all others. -// Fields may be provided in a namespaced fashion relative to the struct provided +// Fields may be provided in a namespaced fashion relative to the struct provided // eg. NestedStruct.Field or NestedArrayField[0].Struct.Name // // It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. @@ -439,7 +440,7 @@ func (v *Validate) StructPartial(s interface{}, fields ...string) error { // StructPartialCtx validates the fields passed in only, ignoring all others and allows passing of contextual // validation information via context.Context -// Fields may be provided in a namespaced fashion relative to the struct provided +// Fields may be provided in a namespaced fashion relative to the struct provided // eg. NestedStruct.Field or NestedArrayField[0].Struct.Name // // It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. @@ -514,7 +515,7 @@ func (v *Validate) StructPartialCtx(ctx context.Context, s interface{}, fields . } // StructExcept validates all fields except the ones passed in. -// Fields may be provided in a namespaced fashion relative to the struct provided +// Fields may be provided in a namespaced fashion relative to the struct provided // i.e. NestedStruct.Field or NestedArrayField[0].Struct.Name // // It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. @@ -525,7 +526,7 @@ func (v *Validate) StructExcept(s interface{}, fields ...string) error { // StructExceptCtx validates all fields except the ones passed in and allows passing of contextual // validation information via context.Context -// Fields may be provided in a namespaced fashion relative to the struct provided +// Fields may be provided in a namespaced fashion relative to the struct provided // i.e. NestedStruct.Field or NestedArrayField[0].Struct.Name // // It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. @@ -681,6 +682,64 @@ func (v *Validate) VarWithValueCtx(ctx context.Context, field interface{}, other return } +// VarWithKey validates a single variable with a key to be included in the returned error using tag style validation +// eg. +// var s string +// validate.VarWithKey("email_address", s, "required,email") +// +// WARNING: a struct can be passed for validation eg. time.Time is a struct or +// if you have a custom type and have registered a custom type handler, so must +// allow it; however unforeseen validations will occur if trying to validate a +// struct that is meant to be passed to 'validate.Struct' +// +// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. +// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. +// validate Array, Slice and maps fields which may contain more than one error +func (v *Validate) VarWithKey(key string, field interface{}, tag string) error { + return v.VarWithKeyCtx(context.Background(), key, field, tag) +} + +// VarWithKeyCtx validates a single variable with a key to be included in the returned error using tag style validation +// and allows passing of contextual validation information via context.Context. +// eg. +// var s string +// validate.VarWithKeyCtx("email_address", s, "required,email") +// +// WARNING: a struct can be passed for validation eg. time.Time is a struct or +// if you have a custom type and have registered a custom type handler, so must +// allow it; however unforeseen validations will occur if trying to validate a +// struct that is meant to be passed to 'validate.Struct' +// +// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. +// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. +// validate Array, Slice and maps fields which may contain more than one error +func (v *Validate) VarWithKeyCtx(ctx context.Context, key string, field interface{}, tag string) (err error) { + if len(tag) == 0 || tag == skipValidationTag { + return nil + } + + ctag := v.fetchCacheTag(tag) + + cField := &cField{ + name: key, + altName: key, + namesEqual: true, + } + + val := reflect.ValueOf(field) + vd := v.pool.Get().(*validate) + vd.top = val + vd.isPartial = false + vd.traverseField(ctx, val, val, vd.ns[0:0], vd.actualNs[0:0], cField, ctag) + + if len(vd.errs) > 0 { + err = vd.errs + vd.errs = nil + } + v.pool.Put(vd) + return +} + func (v *Validate) registerValidation(tag string, fn FuncCtx, bakedIn bool, nilCheckable bool) error { if len(tag) == 0 { return errors.New("function Key cannot be empty") diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace/internal/semconv/util.go b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace/internal/semconv/util.go index 0de0bd8..1ec064b 100644 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace/internal/semconv/util.go +++ b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace/internal/semconv/util.go @@ -38,11 +38,9 @@ func SplitHostPort(hostport string) (host string, port int) { host = hostport[1:addrEnd] return host, port } - } else { - if i := strings.LastIndexByte(hostport, ':'); i < 0 { - host = hostport - return host, port - } + } else if !strings.Contains(hostport, ":") { + host = hostport + return host, port } host, pStr, err := net.SplitHostPort(hostport) diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace/version.go b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace/version.go index 3a144d2..dc6907f 100644 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace/version.go +++ b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace/version.go @@ -4,4 +4,4 @@ package otelhttptrace // Version is the current release version of the httptrace instrumentation. -const Version = "0.71.0" +const Version = "0.72.0" diff --git a/vendor/go.opentelemetry.io/otel/.golangci.yml b/vendor/go.opentelemetry.io/otel/.golangci.yml index a0ba708..1fef852 100644 --- a/vendor/go.opentelemetry.io/otel/.golangci.yml +++ b/vendor/go.opentelemetry.io/otel/.golangci.yml @@ -230,13 +230,6 @@ linters: - revive path: schema/v.*/types/.* text: avoid meaningless package names - # TODO: Having appropriate comments for exported objects helps development, - # even for objects in internal packages. Appropriate comments for all - # exported objects should be added and this exclusion removed. - - linters: - - revive - path: .*internal/.* - text: exported (method|function|type|const) (.+) should have comment or be unexported # Yes, they are, but it's okay in a test. - linters: - revive @@ -272,7 +265,10 @@ formatters: - golines settings: gofumpt: - extra-rules: true + extra: + group-params: true + clothe-returns: true + balance-calls: true goimports: local-prefixes: - go.opentelemetry.io/otel diff --git a/vendor/go.opentelemetry.io/otel/CHANGELOG.md b/vendor/go.opentelemetry.io/otel/CHANGELOG.md index 4d473a1..18903c8 100644 --- a/vendor/go.opentelemetry.io/otel/CHANGELOG.md +++ b/vendor/go.opentelemetry.io/otel/CHANGELOG.md @@ -11,6 +11,93 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm +## [1.47.0/0.69.0/0.23.0/0.1.0] - 2026-10-02 + +This release contains the first stable release of the OpenTelemetry Go Logs API and SDK. +Our project stability guarantees now apply to the following modules: + +- `go.opentelemetry.io/otel/log` +- `go.opentelemetry.io/otel/sdk/log` + +See our [versioning policy](VERSIONING.md) for more information about these stability guarantees. + +### Added + +- Add `String` method for `KeyValue` type in `go.opentelemetry.io/otel/attribute`. (#8205) +- Add `String` method for `Set` type in `go.opentelemetry.io/otel/attribute`. (#8347) +- Add `WithMaxExportBatchSize` to `go.opentelemetry.io/otel/sdk/metric` to configure the maximum export batch size for `PeriodicReader`. (#8960) +- Add `WithAttributeValueDepthLimit`, `DefaultAttributeValueDepthLimit`, and `SpanLimits.AttributeValueDepthLimit` in `go.opentelemetry.io/otel/sdk/trace` to configure the maximum depth of span, event, link, and instrumentation scope attribute values. (#8938) +- Add `WithAttributeValueDepthLimit` in `go.opentelemetry.io/otel/sdk/log` to configure the maximum depth of log record and instrumentation scope attribute values. (#8938) +- Add `WithMaxResponseSize` to `go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp`, + `go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp`, and + `go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp`. (#8941) +- Add experimental `ProbabilitySampler` in `go.opentelemetry.io/otel/sdk/trace/x` that conforms to the [OpenTelemetry specification's threshold-based sampling algorithm](https://opentelemetry.io/docs/specs/otel/trace/sdk/#probabilitysampler). (#8123) +- Add experimental `*Binder` extension interfaces in `go.opentelemetry.io/otel/metric/x` for instruments that support binding attributes ahead of time. (#8760) +- Add the experimental `Finisher` synchronous metric instrument extension interface to `go.opentelemetry.io/otel/metric/x`. (#8906) + +### Changed + +- Use the [OpenTelemetry Attribute Collection representation for non-OTLP protocols](https://opentelemetry.io/docs/specs/otel/common/#attribute-collection-representation-for-non-otlp) for metric data diffs in `go.opentelemetry.io/otel/sdk/metric/metricdata/metricdatatest`. (#8993) +- Apply a maximum depth of 64 by default to span, event, link, log record, and instrumentation scope attribute values in `go.opentelemetry.io/otel/sdk/trace` and `go.opentelemetry.io/otel/sdk/log`. (#8938) +- Reduce allocations when applying attribute value length limits in `go.opentelemetry.io/otel/sdk/trace` and `go.opentelemetry.io/otel/sdk/log` by rebuilding composite values only when truncation is needed. (#8912) +- Decode `traceparent` using a hex lookup table in `go.opentelemetry.io/otel/propagation`, which rejects the specification-disallowed upper-case characters without a separate scan of the header. (#8739) +- Decode all characters at constant indices in `TraceIDFromHex` and `SpanIDFromHex` in `go.opentelemetry.io/otel/trace` to eliminate bounds checks. (#8740) + +### Fixed + +- Count valid U+FFFD replacement characters toward attribute value length limits in `go.opentelemetry.io/otel/trace`, `go.opentelemetry.io/otel/sdk/trace`, and `go.opentelemetry.io/otel/sdk/log`. +- Truncate string attribute values to empty strings when the configured length limit is zero, including malformed UTF-8, in `go.opentelemetry.io/otel/trace`, `go.opentelemetry.io/otel/sdk/trace`, and `go.opentelemetry.io/otel/sdk/log`. (#9054) +- Fix a data race in `NewPeriodicReader` where `r.inst` was assigned after the background goroutine was launched in `go.opentelemetry.io/otel/sdk/metric`. (#9028) +- Prevent precision loss for large `int64` values in `Sum`, `Histogram`, and `ExponentialHistogram` aggregations in `go.opentelemetry.io/otel/sdk/metric`. (#8981) +- Ensure `grpc.DialOption` values passed via `WithDialOption` take precedence over conflicting internally-computed defaults in + `go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc`, + `go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc`, and + `go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc`. (#8805, #8834, #8836) +- Treat overflowing `OTEL_METRIC_EXPORT_INTERVAL` and `OTEL_METRIC_EXPORT_TIMEOUT` values as invalid in `go.opentelemetry.io/otel/sdk/metric`. (#8800) +- Prevent a panic in `NewFixedSizeReservoir` and `FixedSizeReservoirProvider` when given a negative size in `go.opentelemetry.io/otel/sdk/metric/exemplar`; negative sizes are now clamped to zero, consistent with a size of zero. (#8832) +- Preserve exponential histogram `ZeroThreshold` during OTLP metric export in `go.opentelemetry.io/otel/exporters/otlp/otlpmetric`. (#8801) +- Ensure metric helpers in `go.opentelemetry.io/otel/semconv/v1.32.0`, `go.opentelemetry.io/otel/semconv/v1.33.0`, and `go.opentelemetry.io/otel/semconv/v1.34.0` record measurements only once when no attributes are provided. (#8849) +- Treat empty `OTEL_TRACES_SAMPLER` and `OTEL_TRACES_SAMPLER_ARG` values as unset in `go.opentelemetry.io/otel/sdk/trace`. (#8873) +- Normalize global `OTEL_EXPORTER_OTLP_ENDPOINT` path joining in `go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp` so trailing-slash base URLs do not produce double-slash log export paths. (#8864) +- Prevent a deadlock when formatting an error passed to `RecordError` calls back into the span in `go.opentelemetry.io/otel/sdk/trace`. (#8815) +- Prevent `SimpleSpanProcessor.Shutdown` from panicking when constructed with a nil exporter in `go.opentelemetry.io/otel/sdk/trace`. (#8844) +- Propagate invalid exponential histogram scale errors to Prometheus exporter self-observability metrics in `go.opentelemetry.io/otel/exporters/prometheus`. (#8839) +- Retain instrument advisory attributes configured with `go.opentelemetry.io/otel/metric/x.WithDefaultAttributes` when a matching View in `go.opentelemetry.io/otel/sdk/metric` does not specify an attribute filter. (#8859) +- Ignore HTTP URL paths when building OTLP/gRPC metric exporter targets from `OTEL_EXPORTER_OTLP_ENDPOINT` and `OTEL_EXPORTER_OTLP_METRICS_ENDPOINT`, while preserving `unix://` and `unix-abstract://` targets; treat `unix-abstract://` endpoints as insecure in `go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc` and `go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp`. (#8862) +- Ignore HTTP(S) paths when deriving gRPC trace exporter endpoints from `OTEL_EXPORTER_OTLP_ENDPOINT` and `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` in `go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc`. (#8852) +- Bound memory used while parsing dense W3C property metadata by storing it compactly and materializing `Property` values on demand in `go.opentelemetry.io/otel/baggage` and `go.opentelemetry.io/otel/propagation`. + +### Removed + +- Remove the experimental `OTEL_GO_X_METRIC_EXPORT_BATCH_SIZE` environment variable in `go.opentelemetry.io/otel/sdk/metric`. + Use the `WithMaxExportBatchSize` option instead. (#8960) + +## [1.47.0-rc.1] - 2026-08-28 + +This is a release candidate for the v1.47.0 release. +That release is expected to include the `v1` release of the OpenTelemetry Go Logs API and SDK and will provide stability guarantees for the following modules: + +- `go.opentelemetry.io/otel/log` +- `go.opentelemetry.io/otel/sdk/log` + +See our [versioning policy](VERSIONING.md) for more information about these stability guarantees. + +### Added + +- Add `Logger`, `GetLoggerProvider`, and `SetLoggerProvider` to `go.opentelemetry.io/otel`. (#8874) + +### Deprecated + +- Deprecate `go.opentelemetry.io/otel/log/global`; use the equivalent APIs in `go.opentelemetry.io/otel`. (#8874) + +### Fixed + +- Ignore attempts to unregister unknown span processors in `go.opentelemetry.io/otel/sdk/trace`. (#8840) + +### Removed + +- Drop support for [Go 1.25]. (#8876) + ## [1.46.0/0.68.0/0.22.0/0.0.19] - 2026-08-25 This release is the last to support [Go 1.25]. @@ -3810,7 +3897,9 @@ It contains api and sdk for trace and meter. - CircleCI build CI manifest files. - CODEOWNERS file to track owners of this project. -[Unreleased]: https://github.com/open-telemetry/opentelemetry-go/compare/v1.46.0...HEAD +[Unreleased]: https://github.com/open-telemetry/opentelemetry-go/compare/v1.47.0...HEAD +[1.47.0/0.69.0/0.23.0/0.1.0]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/v1.47.0 +[1.47.0-rc.1]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/v1.47.0-rc.1 [1.46.0/0.68.0/0.22.0/0.0.19]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/v1.46.0 [1.45.0/0.67.0/0.21.0/0.0.18]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/v1.45.0 [1.44.0/0.66.0/0.20.0/0.0.17]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/v1.44.0 diff --git a/vendor/go.opentelemetry.io/otel/CLAUDE.md b/vendor/go.opentelemetry.io/otel/CLAUDE.md deleted file mode 100644 index dd3c459..0000000 --- a/vendor/go.opentelemetry.io/otel/CLAUDE.md +++ /dev/null @@ -1,3 +0,0 @@ -# Instructions for Claude Code - -@AGENTS.md diff --git a/vendor/go.opentelemetry.io/otel/CODEOWNERS b/vendor/go.opentelemetry.io/otel/CODEOWNERS index 26a03ae..41937a3 100644 --- a/vendor/go.opentelemetry.io/otel/CODEOWNERS +++ b/vendor/go.opentelemetry.io/otel/CODEOWNERS @@ -12,6 +12,6 @@ # https://help.github.com/en/articles/about-code-owners # -* @MrAlias @XSAM @dashpole @pellared @dmathieu @flc1125 +* @MrAlias @XSAM @dashpole @pellared @dmathieu @flc1125 @ps-mir CODEOWNERS @MrAlias @pellared @dashpole @XSAM @dmathieu diff --git a/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md b/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md index 2aba71e..958a698 100644 --- a/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md +++ b/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md @@ -779,7 +779,7 @@ func newInstrumentation() (*instrumentation, error) { if !x.Observability.Enabled() { return nil, nil } - + meter := otel.GetMeterProvider().Meter( "", metric.WithInstrumentationVersion(sdk.Version()), @@ -949,7 +949,7 @@ func BenchmarkExportSpans(b *testing.B) { {"ObsDisabled", false}, {"ObsEnabled", true}, } - + for _, scenario := range scenarios { b.Run(scenario.name, func(b *testing.B) { b.Setenv( @@ -980,7 +980,7 @@ func newInstrumentation() (*instrumentation, error) { if !x.Observability.Enabled() { return nil, nil } - + m := otel.GetMeterProvider().Meter(/* initialize meter */) counter, err := otelconv.NewSDKComponentCounter(m) // Use the partially initialized counter if available. @@ -996,7 +996,7 @@ func newInstrumentation() *instrumentation { if !x.Observability.Enabled() { return nil, nil } - + m := otel.GetMeterProvider().Meter(/* initialize meter */) counter, err := otelconv.NewSDKComponentCounter(m) if err != nil { @@ -1023,7 +1023,7 @@ func (e *Exporter) ExportSpans(ctx context.Context, spans []trace.ReadOnlySpan) if e.inst.Enabled(ctx) { e.inst.recordSpanExportStarted(ctx, len(spans)) } - + err := e.doExport(ctx, spans) if e.inst.Enabled(ctx) { @@ -1043,11 +1043,11 @@ func (e *Exporter) ExportSpans(ctx context.Context, spans []trace.ReadOnlySpan) func (e *Exporter) ExportSpans(ctx context.Context, spans []trace.ReadOnlySpan) error { // ❌ Do not break the context propagation. e.inst.recordSpanExportStarted(context.Background(), len(spans)) - + err := e.doExport(ctx, spans) /* ... */ - + return err } ``` @@ -1118,7 +1118,7 @@ func TestObservability(t *testing.T) { // Reset component ID counter to ensure deterministic component names. componentIDCounter.Store(0) - + /* ... test code ... */ } ``` @@ -1203,18 +1203,20 @@ For more information about the maintainer role, see the [community repository](h ### Approvers - [Flc](https://github.com/flc1125), Independent +- [Puneet Singh](https://github.com/ps-mir), Independent For more information about the approver role, see the [community repository](https://github.com/open-telemetry/community/blob/main/guides/contributor/membership.md#approver). ### Triagers -- [Alex Kats](https://github.com/akats7), Capital One +- [Marc Schäfer](https://github.com/marcschaeferger), T&A SYSTEME GmbH For more information about the triager role, see the [community repository](https://github.com/open-telemetry/community/blob/main/guides/contributor/membership.md#triager). ### Emeritus - [Aaron Clawson](https://github.com/MadVikingGod) +- [Alex Kats](https://github.com/akats7) - [Anthony Mirabella](https://github.com/Aneurysm9) - [Cheng-Zhen Yang](https://github.com/scorpionknifes) - [Chester Cheung](https://github.com/hanyuancheung) diff --git a/vendor/go.opentelemetry.io/otel/README.md b/vendor/go.opentelemetry.io/otel/README.md index 9291d14..bcdb73e 100644 --- a/vendor/go.opentelemetry.io/otel/README.md +++ b/vendor/go.opentelemetry.io/otel/README.md @@ -3,12 +3,11 @@ [![ci](https://github.com/open-telemetry/opentelemetry-go/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/open-telemetry/opentelemetry-go/actions/workflows/ci.yml) [![codecov.io](https://codecov.io/gh/open-telemetry/opentelemetry-go/coverage.svg?branch=main)](https://app.codecov.io/gh/open-telemetry/opentelemetry-go?branch=main) [![PkgGoDev](https://pkg.go.dev/badge/go.opentelemetry.io/otel)](https://pkg.go.dev/go.opentelemetry.io/otel) -[![Go Report Card](https://goreportcard.com/badge/go.opentelemetry.io/otel)](https://goreportcard.com/report/go.opentelemetry.io/otel) [![OpenSSF Scorecard](https://api.scorecard.dev/projects/github.com/open-telemetry/opentelemetry-go/badge)](https://scorecard.dev/viewer/?uri=github.com/open-telemetry/opentelemetry-go) [![OpenSSF Best Practices](https://www.bestpractices.dev/projects/9996/badge)](https://www.bestpractices.dev/projects/9996) [![Fuzzing Status](https://oss-fuzz-build-logs.storage.googleapis.com/badges/opentelemetry-go.svg)](https://issues.oss-fuzz.com/issues?q=project:opentelemetry-go) [![FOSSA Status](https://app.fossa.com/api/projects/custom%2B162%2Fgithub.com%2Fopen-telemetry%2Fopentelemetry-go.svg?type=shield&issueType=license)](https://app.fossa.com/projects/custom%2B162%2Fgithub.com%2Fopen-telemetry%2Fopentelemetry-go?ref=badge_shield&issueType=license) -[![Slack](https://img.shields.io/badge/slack-@cncf/otel--go-brightgreen.svg?logo=slack)](https://cloud-native.slack.com/archives/C01NPAXACKT) +[![Slack](https://img.shields.io/badge/slack-@cncf/otel--go-brightgreen.svg?logo=slack)](https://slack.cncf.io/) OpenTelemetry-Go is the [Go](https://golang.org/) implementation of [OpenTelemetry](https://opentelemetry.io/). It provides a set of APIs to directly measure performance and behavior of your software and send this data to observability platforms. @@ -19,7 +18,7 @@ It provides a set of APIs to directly measure performance and behavior of your s |---------|--------------------| | Traces | Stable | | Metrics | Stable | -| Logs | Beta[^1] | +| Logs | Stable | Progress and status specific to this repository is tracked in our [project boards](https://github.com/open-telemetry/opentelemetry-go/projects) @@ -29,8 +28,6 @@ and Project versioning information and stability guarantees can be found in the [versioning documentation](VERSIONING.md). -[^1]: https://github.com/orgs/open-telemetry/projects/43 - ### Compatibility OpenTelemetry-Go ensures compatibility with the current supported versions of @@ -55,25 +52,18 @@ Currently, this project supports the following environments. |----------|------------|--------------| | Ubuntu | 1.27 | amd64 | | Ubuntu | 1.26 | amd64 | -| Ubuntu | 1.25 | amd64 | | Ubuntu | 1.27 | 386 | | Ubuntu | 1.26 | 386 | -| Ubuntu | 1.25 | 386 | | Ubuntu | 1.27 | arm64 | | Ubuntu | 1.26 | arm64 | -| Ubuntu | 1.25 | arm64 | | macOS | 1.27 | amd64 | | macOS | 1.26 | amd64 | -| macOS | 1.25 | amd64 | | macOS | 1.27 | arm64 | | macOS | 1.26 | arm64 | -| macOS | 1.25 | arm64 | | Windows | 1.27 | amd64 | | Windows | 1.26 | amd64 | -| Windows | 1.25 | amd64 | | Windows | 1.27 | 386 | | Windows | 1.26 | 386 | -| Windows | 1.25 | 386 | While this project should work for other systems, no compatibility guarantees are made for those systems currently. @@ -120,10 +110,3 @@ All officially supported exporters for the OpenTelemetry project are contained i ## Contributing See the [contributing documentation](CONTRIBUTING.md). - -### Emeritus - -- [Alex Kats](https://github.com/akats7), Triager - -For more information about the emeritus role, see the -[community repository](https://github.com/open-telemetry/community/blob/main/guides/contributor/membership.md#emeritus-maintainerapprovertriager). diff --git a/vendor/go.opentelemetry.io/otel/attribute/internal/xxhash/xxhash.go b/vendor/go.opentelemetry.io/otel/attribute/internal/xxhash/xxhash.go index 4fcdd2d..499aa33 100644 --- a/vendor/go.opentelemetry.io/otel/attribute/internal/xxhash/xxhash.go +++ b/vendor/go.opentelemetry.io/otel/attribute/internal/xxhash/xxhash.go @@ -21,6 +21,7 @@ func New() Hash { return Hash{d: xxhash.New()} } +// Uint64 hashes val into h, returning the updated Hash. func (h Hash) Uint64(val uint64) Hash { var buf [8]byte binary.LittleEndian.PutUint64(buf[:], val) @@ -40,10 +41,12 @@ func (h Hash) Bool(val bool) Hash { // nolint:revive // This is a hashing functi return h.Uint64(0) } +// Float64 hashes val into h, returning the updated Hash. func (h Hash) Float64(val float64) Hash { return h.Uint64(math.Float64bits(val)) } +// Int64 hashes val into h, returning the updated Hash. func (h Hash) Int64(val int64) Hash { return h.Uint64(uint64(val)) // nolint:gosec // Overflow doesn't matter since we are hashing. } diff --git a/vendor/go.opentelemetry.io/otel/attribute/kv.go b/vendor/go.opentelemetry.io/otel/attribute/kv.go index c4f0dd9..60d4973 100644 --- a/vendor/go.opentelemetry.io/otel/attribute/kv.go +++ b/vendor/go.opentelemetry.io/otel/attribute/kv.go @@ -13,6 +13,16 @@ type KeyValue struct { Value Value } +// String returns a string representation of KeyValue using the +// [OpenTelemetry Attribute representation for non-OTLP protocols] rules. +// +// The KeyValue is encoded as a JSON object containing a single key-value pair. +// +// [OpenTelemetry Attribute representation for non-OTLP protocols]: https://opentelemetry.io/docs/specs/otel/common/#attribute-representation-for-non-otlp +func (kv KeyValue) String() string { + return formatMap([]KeyValue{kv}) +} + // Valid reports whether kv is a valid OpenTelemetry attribute. func (kv KeyValue) Valid() bool { return kv.Key.Defined() diff --git a/vendor/go.opentelemetry.io/otel/attribute/set.go b/vendor/go.opentelemetry.io/otel/attribute/set.go index 56a70a9..d3b2e24 100644 --- a/vendor/go.opentelemetry.io/otel/attribute/set.go +++ b/vendor/go.opentelemetry.io/otel/attribute/set.go @@ -409,6 +409,21 @@ func computeDataReflect(kvs []KeyValue) any { return at.Interface() } +// String returns a string representation of the Set using the +// [OpenTelemetry Attribute Collection representation for non-OTLP protocols] +// rules. +// +// The Set is encoded as a JSON object. A nil or empty Set is encoded as an +// empty JSON object. +// +// [OpenTelemetry Attribute Collection representation for non-OTLP protocols]: https://opentelemetry.io/docs/specs/otel/common/#attribute-collection-representation-for-non-otlp +func (l *Set) String() string { + if l == nil || l.hash == 0 { + return "{}" + } + return formatMapValue(l.data) +} + // MarshalJSON returns the JSON encoding of the Set. func (l *Set) MarshalJSON() ([]byte, error) { return json.Marshal(l.data) diff --git a/vendor/go.opentelemetry.io/otel/baggage/baggage.go b/vendor/go.opentelemetry.io/otel/baggage/baggage.go index 25c739d..72a58c1 100644 --- a/vendor/go.opentelemetry.io/otel/baggage/baggage.go +++ b/vendor/go.opentelemetry.io/otel/baggage/baggage.go @@ -247,10 +247,78 @@ func (p properties) String() string { return strings.Join(props, propertyDelimiter) } +// validateMetadata validates non-empty W3C property elements without decoding +// or materializing Property values. Empty elements are accepted to preserve +// existing parsing behavior. +func validateMetadata(raw string) (string, bool) { + start := 0 + for end := 0; end <= len(raw); end++ { + if end != len(raw) && raw[end] != propertyDelimiter[0] { + continue + } + + if start != end { + if _, ok := parsePropertyFields(raw[start:end]); !ok { + return raw[start:end], false + } + } + start = end + 1 + } + return "", true +} + +// normalizeMetadata removes empty property elements while preserving the raw +// representation of all non-empty elements. +func normalizeMetadata(metadata string) string { + if metadata == "" || + (metadata[0] != propertyDelimiter[0] && + metadata[len(metadata)-1] != propertyDelimiter[0] && + !strings.Contains(metadata, propertyDelimiter+propertyDelimiter)) { + return metadata + } + + var normalized strings.Builder + normalized.Grow(len(metadata)) + for property := range strings.SplitSeq(metadata, propertyDelimiter) { + if property == "" { + continue + } + if normalized.Len() > 0 { + _, _ = normalized.WriteString(propertyDelimiter) + } + _, _ = normalized.WriteString(property) + } + return normalized.String() +} + +func propertiesFromMetadata(metadata string) properties { + if metadata == "" { + return nil + } + + props := make(properties, 0, strings.Count(metadata, propertyDelimiter)+1) + for pStr := range strings.SplitSeq(metadata, propertyDelimiter) { + if pStr == "" { + continue + } + p, err := parseProperty(pStr) + if err != nil { + return nil + } + props = append(props, p) + } + return props +} + // Member is a list-member of a baggage-string as defined by the W3C Baggage // specification. type Member struct { key, value string + + // metadata contains the opaque W3C property suffix extracted from the wire + // without the leading semicolon. properties contains API-created + // properties. The fields are mutually exclusive. + metadata string properties properties // hasData indicates whether the created property contains data or not. @@ -307,21 +375,16 @@ func newInvalidMember() Member { return Member{} } -// parseMember attempts to decode a Member from the passed string. It returns -// an error if the input is invalid according to the W3C Baggage -// specification. +// parseMember attempts to decode a Member from the passed string. Property +// metadata grammar is validated without decoding or materializing properties. func parseMember(member string) (Member, error) { - var props properties - keyValue, properties, found := strings.Cut(member, propertyDelimiter) + var metadata string + keyValue, rawMetadata, found := strings.Cut(member, propertyDelimiter) if found { - // Parse the member properties. - for pStr := range strings.SplitSeq(properties, propertyDelimiter) { - p, err := parseProperty(pStr) - if err != nil { - return newInvalidMember(), err - } - props = append(props, p) + if invalid, ok := validateMetadata(rawMetadata); !ok { + return newInvalidMember(), fmt.Errorf("%w: %q", errInvalidProperty, invalid) } + metadata = normalizeMetadata(rawMetadata) } // Parse the member key/value pair. @@ -349,7 +412,7 @@ func parseMember(member string) (Member, error) { } value := replaceInvalidUTF8Sequences(len(rawVal), unescapeVal) - return Member{key: key, value: value, properties: props, hasData: true}, nil + return Member{key: key, value: value, metadata: metadata, hasData: true}, nil } // replaceInvalidUTF8Sequences replaces invalid UTF-8 sequences with '�'. @@ -399,10 +462,14 @@ func (m Member) Key() string { return m.key } func (m Member) Value() string { return m.value } // Properties returns a copy of the Member properties. -func (m Member) Properties() []Property { return m.properties.Copy() } +func (m Member) Properties() []Property { + if m.metadata != "" { + return propertiesFromMetadata(m.metadata) + } + return m.properties.Copy() +} -// String encodes Member into a header string compliant with the W3C Baggage -// specification. +// String encodes Member into a baggage header string. // It would return empty string if the key is invalid with the W3C Baggage // specification. This could happen for a UTF-8 key, as it may contain // invalid characters. @@ -413,12 +480,31 @@ func (m Member) String() string { } s := m.key + keyValueDelimiter + valueEscape(m.value) - if len(m.properties) > 0 { + if m.metadata != "" { + s += propertyDelimiter + m.metadata + } else if len(m.properties) > 0 { s += propertyDelimiter + m.properties.String() } return s } +func memberFromItem(key string, item baggage.Item) Member { + return Member{ + key: key, + value: item.Value(), + metadata: item.Metadata(), + properties: fromInternalProperties(item.Properties()), + hasData: true, + } +} + +func itemFromMember(member Member) baggage.Item { + if member.metadata != "" { + return baggage.NewItemWithMetadata(member.value, member.metadata) + } + return baggage.NewItemWithProperties(member.value, member.properties.asInternal()) +} + // Baggage is a list of baggage members representing the baggage-string as // defined by the W3C Baggage specification. type Baggage struct { //nolint:golint @@ -444,10 +530,7 @@ func New(members ...Member) (Baggage, error) { return Baggage{}, errInvalidMember } // OpenTelemetry resolves duplicates by last-one-wins. - b[m.key] = baggage.Item{ - Value: m.value, - Properties: m.properties.asInternal(), - } + b[m.key] = itemFromMember(m) } var truncateErr error @@ -467,11 +550,7 @@ func New(members ...Member) (Baggage, error) { totalBytes := 0 first := true for k := range b { - m := Member{ - key: k, - value: b[k].Value, - properties: fromInternalProperties(b[k].Properties), - } + m := memberFromItem(k, b[k]) memberSize := len(m.String()) if !first { memberSize++ // comma separator @@ -563,10 +642,7 @@ func Parse(bStr string) (Baggage, error) { } // OpenTelemetry resolves duplicates by last-one-wins. - b[m.key] = baggage.Item{ - Value: m.value, - Properties: m.properties.asInternal(), - } + b[m.key] = itemFromMember(m) sizes[m.key] = memberBytes totalBytes = newTotalBytes } @@ -597,12 +673,7 @@ func (b Baggage) Member(key string) Member { return newInvalidMember() } - return Member{ - key: key, - value: v.Value, - properties: fromInternalProperties(v.Properties), - hasData: true, - } + return memberFromItem(key, v) } // Members returns all the baggage list-members. @@ -617,12 +688,7 @@ func (b Baggage) Members() []Member { members := make([]Member, 0, len(b.list)) for k, v := range b.list { - members = append(members, Member{ - key: k, - value: v.Value, - properties: fromInternalProperties(v.Properties), - hasData: true, - }) + members = append(members, memberFromItem(k, v)) } return members } @@ -652,10 +718,7 @@ func (b Baggage) SetMember(member Member) (Baggage, error) { list[k] = v } - list[member.key] = baggage.Item{ - Value: member.value, - Properties: member.properties.asInternal(), - } + list[member.key] = itemFromMember(member) return Baggage{list: list}, nil } @@ -692,11 +755,7 @@ func (b Baggage) Len() int { func (b Baggage) String() string { members := make([]string, 0, len(b.list)) for k, v := range b.list { - s := Member{ - key: k, - value: v.Value, - properties: fromInternalProperties(v.Properties), - }.String() + s := memberFromItem(k, v).String() // Ignored empty members. if s != "" { @@ -706,9 +765,14 @@ func (b Baggage) String() string { return strings.Join(members, listDelimiter) } -// parsePropertyInternal attempts to decode a Property from the passed string. -// It follows the spec at https://www.w3.org/TR/baggage/#definition. -func parsePropertyInternal(s string) (p Property, ok bool) { +type propertyFields struct { + key, rawValue string + hasValue bool +} + +// parsePropertyFields validates and locates a property's fields without +// decoding or allocating them. +func parsePropertyFields(s string) (fields propertyFields, ok bool) { // For the entire function we will use " key = value " as an example. // Attempting to parse the key. // First skip spaces at the beginning "< >key = value " (they could be empty). @@ -727,7 +791,7 @@ func parsePropertyInternal(s string) (p Property, ok bool) { // If we couldn't find any valid key character, // it means the key is either empty or invalid. if keyStart == keyEnd { - return p, ok + return fields, ok } // Skip spaces after the key: " key< >= value ". @@ -735,15 +799,14 @@ func parsePropertyInternal(s string) (p Property, ok bool) { if index == len(s) { // A key can have no value, like: " key ". - ok = true - p.key = s[keyStart:keyEnd] - return p, ok + fields.key = s[keyStart:keyEnd] + return fields, true } // If we have not reached the end and we can't find the '=' delimiter, // it means the property is invalid. if s[index] != keyValueDelimiter[0] { - return p, ok + return fields, ok } // Attempting to parse the value. @@ -769,23 +832,59 @@ func parsePropertyInternal(s string) (p Property, ok bool) { // we have not reached the end, it means the property is // invalid, something like: " key = value value1". if index != len(s) { - return p, ok + return fields, ok + } + rawVal := s[valueStart:valueEnd] + if !validPercentEncoding(rawVal) { + return fields, ok + } + + fields.key = s[keyStart:keyEnd] + fields.rawValue = rawVal + fields.hasValue = true + return fields, true +} + +func validPercentEncoding(s string) bool { + for i := 0; i < len(s); i++ { + if s[i] != '%' { + continue + } + if i+2 >= len(s) || !isHex(s[i+1]) || !isHex(s[i+2]) { + return false + } + i += 2 + } + return true +} + +func isHex(c byte) bool { + return '0' <= c && c <= '9' || 'a' <= c && c <= 'f' || 'A' <= c && c <= 'F' +} + +// parsePropertyInternal attempts to decode a Property from the passed string. +// It follows the spec at https://www.w3.org/TR/baggage/#definition. +func parsePropertyInternal(s string) (p Property, ok bool) { + fields, ok := parsePropertyFields(s) + if !ok { + return p, false + } + if !fields.hasValue { + p.key = fields.key + return p, true } // Decode a percent-encoded value. - rawVal := s[valueStart:valueEnd] - unescapeVal, err := url.PathUnescape(rawVal) + unescapeVal, err := url.PathUnescape(fields.rawValue) if err != nil { - return p, ok + return p, false } - value := replaceInvalidUTF8Sequences(len(rawVal), unescapeVal) + value := replaceInvalidUTF8Sequences(len(fields.rawValue), unescapeVal) - ok = true - p.key = s[keyStart:keyEnd] + p.key = fields.key p.hasValue = true - p.value = value - return p, ok + return p, true } func skipSpace(s string, offset int) int { diff --git a/vendor/go.opentelemetry.io/otel/codes/codes.go b/vendor/go.opentelemetry.io/otel/codes/codes.go index 9355545..1502de3 100644 --- a/vendor/go.opentelemetry.io/otel/codes/codes.go +++ b/vendor/go.opentelemetry.io/otel/codes/codes.go @@ -32,7 +32,7 @@ const ( maxCode = 3 ) -// Code is an 32-bit representation of a status state. +// Code is a 32-bit representation of a status state. type Code uint32 var codeToStr = map[Code]string{ diff --git a/vendor/go.opentelemetry.io/otel/dependencies.Dockerfile b/vendor/go.opentelemetry.io/otel/dependencies.Dockerfile index 20eecba..82653bc 100644 --- a/vendor/go.opentelemetry.io/otel/dependencies.Dockerfile +++ b/vendor/go.opentelemetry.io/otel/dependencies.Dockerfile @@ -1,4 +1,4 @@ # This is a renovate-friendly source of Docker images. FROM python:3.13.6-slim-bullseye@sha256:e98b521460ee75bca92175c16247bdf7275637a8faaeb2bcfa19d879ae5c4b9a AS python -FROM otel/weaver:v0.25.1@sha256:9ad46ca9cd4fa5974b121f886aa3e9946a8ef8ea905001a96c018d21f9db87ca AS weaver +FROM otel/weaver:v0.26.1@sha256:9094862c0ab261bdbcb079bb981f9a573b3659b130a6d2ab8616eca6ba37aaec AS weaver FROM avtodev/markdown-lint:v1@sha256:6aeedc2f49138ce7a1cd0adffc1b1c0321b841dc2102408967d9301c031949ee AS markdown diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform/instrumentation.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform/instrumentation.go index 078a9db..1754a7f 100644 --- a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform/instrumentation.go +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform/instrumentation.go @@ -9,6 +9,8 @@ import ( "go.opentelemetry.io/otel/sdk/instrumentation" ) +// InstrumentationScope transforms il into an OTLP InstrumentationScope, +// returning nil if il is the zero value. func InstrumentationScope(il instrumentation.Scope) *commonpb.InstrumentationScope { if il == (instrumentation.Scope{}) { return nil diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/client.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/client.go index 00b4572..698a757 100644 --- a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/client.go +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/client.go @@ -36,13 +36,6 @@ const ( contentTypeJSON = "application/json" ) -// maxResponseBodySize is the maximum number of bytes to read from a response -// body. It is set to 4 MiB per the OTLP specification recommendation to -// mitigate excessive memory usage caused by a misconfigured or malicious -// server. If exceeded, the response is treated as a not-retryable error. -// This is a variable to allow tests to override it. -var maxResponseBodySize int64 = 4 * 1024 * 1024 - var gzPool = sync.Pool{ New: func() any { w := gzip.NewWriter(io.Discard) @@ -217,11 +210,7 @@ func (c *client) UploadTraces(ctx context.Context, protoSpans []*tracepb.Resourc // Success, do not retry. // Read the partial success message, if any. var respData bytes.Buffer - if _, err := io.Copy(&respData, http.MaxBytesReader(nil, resp.Body, maxResponseBodySize)); err != nil { - var maxBytesErr *http.MaxBytesError - if errors.As(err, &maxBytesErr) { - return fmt.Errorf("response body too large: exceeded %d bytes", maxBytesErr.Limit) - } + if err := internal.CopyResponseBody(&respData, resp.Body, c.cfg.MaxResponseSize); err != nil { return err } if respData.Len() == 0 { @@ -259,11 +248,7 @@ func (c *client) UploadTraces(ctx context.Context, protoSpans []*tracepb.Resourc // message to be returned. It will help in // debugging the actual issue. var respData bytes.Buffer - if _, err := io.Copy(&respData, http.MaxBytesReader(nil, resp.Body, maxResponseBodySize)); err != nil { - var maxBytesErr *http.MaxBytesError - if errors.As(err, &maxBytesErr) { - return fmt.Errorf("response body too large: exceeded %d bytes", maxBytesErr.Limit) - } + if err := internal.CopyResponseBody(&respData, resp.Body, c.cfg.MaxResponseSize); err != nil { return err } respStr := strings.TrimSpace(respData.String()) diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/internal/gen.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/internal/gen.go index 9064f65..c4d2df3 100644 --- a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/internal/gen.go +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/internal/gen.go @@ -6,6 +6,8 @@ package internal //go:generate gotmpl --body=../../../../../internal/shared/otlp/partialsuccess.go.tmpl "--data={}" --out=partialsuccess.go //go:generate gotmpl --body=../../../../../internal/shared/otlp/partialsuccess_test.go.tmpl "--data={}" --out=partialsuccess_test.go +//go:generate gotmpl --body=../../../../../internal/shared/otlp/response.go.tmpl "--data={}" --out=response.go +//go:generate gotmpl --body=../../../../../internal/shared/otlp/response_test.go.tmpl "--data={}" --out=response_test.go //go:generate gotmpl --body=../../../../../internal/shared/otlp/retry/retry.go.tmpl "--data={}" --out=retry/retry.go //go:generate gotmpl --body=../../../../../internal/shared/otlp/retry/retry_test.go.tmpl "--data={}" --out=retry/retry_test.go @@ -14,8 +16,8 @@ package internal //go:generate gotmpl --body=../../../../../internal/shared/otlp/envconfig/envconfig_test.go.tmpl "--data={}" --out=envconfig/envconfig_test.go //go:generate gotmpl --body=../../../../../internal/shared/otlp/otlptrace/otlpconfig/envconfig.go.tmpl "--data={\"envconfigImportPath\": \"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/internal/envconfig\"}" --out=otlpconfig/envconfig.go -//go:generate gotmpl --body=../../../../../internal/shared/otlp/otlptrace/otlpconfig/options.go.tmpl "--data={\"retryImportPath\": \"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/internal/retry\"}" --out=otlpconfig/options.go -//go:generate gotmpl --body=../../../../../internal/shared/otlp/otlptrace/otlpconfig/options_test.go.tmpl "--data={\"envconfigImportPath\": \"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/internal/envconfig\"}" --out=otlpconfig/options_test.go +//go:generate gotmpl --body=../../../../../internal/shared/otlp/otlptrace/otlpconfig/options.go.tmpl "--data={\"isHTTP\": true, \"retryImportPath\": \"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/internal/retry\"}" --out=otlpconfig/options.go +//go:generate gotmpl --body=../../../../../internal/shared/otlp/otlptrace/otlpconfig/options_test.go.tmpl "--data={\"isHTTP\": true, \"envconfigImportPath\": \"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/internal/envconfig\"}" --out=otlpconfig/options_test.go //go:generate gotmpl --body=../../../../../internal/shared/otlp/otlptrace/otlpconfig/optiontypes.go.tmpl "--data={}" --out=otlpconfig/optiontypes.go //go:generate gotmpl --body=../../../../../internal/shared/otlp/otlptrace/otlpconfig/tls.go.tmpl "--data={}" --out=otlpconfig/tls.go diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/internal/otlpconfig/envconfig.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/internal/otlpconfig/envconfig.go index 96f857f..e129bd7 100644 --- a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/internal/otlpconfig/envconfig.go +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/internal/otlpconfig/envconfig.go @@ -119,10 +119,20 @@ func withEndpointScheme(u *url.URL) GenericOption { } func withEndpointForGRPC(u *url.URL) func(cfg Config) Config { + target := u.String() + switch strings.ToLower(u.Scheme) { + case "http", "https": + target = u.Host + case "": + if u.Host != "" { + target = path.Join(u.Host, u.Path) + } + } + return func(cfg Config) Config { // For OTLP/gRPC endpoints, this is the target to which the // exporter is going to send telemetry. - cfg.Traces.Endpoint = path.Join(u.Host, u.Path) + cfg.Traces.Endpoint = target return cfg } } diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/internal/otlpconfig/options.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/internal/otlpconfig/options.go index f1c1d27..090bc66 100644 --- a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/internal/otlpconfig/options.go +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/internal/otlpconfig/options.go @@ -34,6 +34,9 @@ const ( // DefaultMaxRequestSize is the default maximum size of a serialized export // request, before compression. DefaultMaxRequestSize int = 64 * 1024 * 1024 + // DefaultMaxResponseSize is the default maximum size of an OTLP/HTTP + // response body, after decompression. + DefaultMaxResponseSize int64 = 4 * 1024 * 1024 // DefaultTimeout is a default max waiting time for the backend to process // each span batch. DefaultTimeout time.Duration = 10 * time.Second @@ -44,16 +47,18 @@ type ( // This type is compatible with `http.Transport.Proxy` and can be used to set a custom proxy function to the OTLP HTTP client. HTTPTransportProxyFunc func(*http.Request) (*url.URL, error) + // SignalConfig holds the configuration for exporting a single signal. SignalConfig struct { - Endpoint string - Insecure bool - TLSCfg *tls.Config - Headers map[string]string - Compression Compression - Protocol Protocol - MaxRequestSize int - Timeout time.Duration - URLPath string + Endpoint string + Insecure bool + TLSCfg *tls.Config + Headers map[string]string + Compression Compression + Protocol Protocol + MaxRequestSize int + MaxResponseSize int64 + Timeout time.Duration + URLPath string // gRPC configurations GRPCCredentials credentials.TransportCredentials @@ -63,6 +68,7 @@ type ( HTTPClient *http.Client } + // Config holds the configuration for an otlptrace exporter. Config struct { // Signal specific configurations Traces SignalConfig @@ -82,12 +88,13 @@ type ( func NewHTTPConfig(opts ...HTTPOption) Config { cfg := Config{ Traces: SignalConfig{ - Endpoint: fmt.Sprintf("%s:%d", DefaultCollectorHost, DefaultCollectorHTTPPort), - URLPath: DefaultTracesPath, - Compression: NoCompression, - Protocol: ProtocolHTTPProtobuf, - MaxRequestSize: DefaultMaxRequestSize, - Timeout: DefaultTimeout, + Endpoint: fmt.Sprintf("%s:%d", DefaultCollectorHost, DefaultCollectorHTTPPort), + URLPath: DefaultTracesPath, + Compression: NoCompression, + Protocol: ProtocolHTTPProtobuf, + MaxRequestSize: DefaultMaxRequestSize, + MaxResponseSize: DefaultMaxResponseSize, + Timeout: DefaultTimeout, }, RetryConfig: retry.DefaultConfig, } @@ -126,37 +133,42 @@ func NewGRPCConfig(opts ...GRPCOption) Config { Timeout: DefaultTimeout, }, RetryConfig: retry.DefaultConfig, - DialOptions: []grpc.DialOption{grpc.WithUserAgent(userAgent)}, } cfg = ApplyGRPCEnvConfigs(cfg) for _, opt := range opts { cfg = opt.ApplyGRPCOption(cfg) } + // dialOptsPrefix holds the internally computed defaults. It is prepended + // to cfg.DialOptions so that a raw grpc.DialOption supplied via WithDialOption + // always takes precedence: grpc.DialOption values are opaque closures, so this code has no way to + // detect a conflicting user-supplied option and defer to it instead. + dialOptsPrefix := []grpc.DialOption{grpc.WithUserAgent(userAgent)} if cfg.ServiceConfig != "" { - cfg.DialOptions = append(cfg.DialOptions, grpc.WithDefaultServiceConfig(cfg.ServiceConfig)) + dialOptsPrefix = append(dialOptsPrefix, grpc.WithDefaultServiceConfig(cfg.ServiceConfig)) } // Prioritize GRPCCredentials over Insecure (passing both is an error). if cfg.Traces.GRPCCredentials != nil { //nolint:gocritic // if-else is clearer than switch - cfg.DialOptions = append(cfg.DialOptions, grpc.WithTransportCredentials(cfg.Traces.GRPCCredentials)) + dialOptsPrefix = append(dialOptsPrefix, grpc.WithTransportCredentials(cfg.Traces.GRPCCredentials)) } else if cfg.Traces.Insecure { - cfg.DialOptions = append(cfg.DialOptions, grpc.WithTransportCredentials(insecure.NewCredentials())) + dialOptsPrefix = append(dialOptsPrefix, grpc.WithTransportCredentials(insecure.NewCredentials())) } else { // Default to using the host's root CA. creds := credentials.NewTLS(nil) cfg.Traces.GRPCCredentials = creds - cfg.DialOptions = append(cfg.DialOptions, grpc.WithTransportCredentials(creds)) + dialOptsPrefix = append(dialOptsPrefix, grpc.WithTransportCredentials(creds)) } if cfg.Traces.Compression == GzipCompression { - cfg.DialOptions = append(cfg.DialOptions, grpc.WithDefaultCallOptions(grpc.UseCompressor(gzip.Name))) + dialOptsPrefix = append(dialOptsPrefix, grpc.WithDefaultCallOptions(grpc.UseCompressor(gzip.Name))) } if cfg.ReconnectionPeriod != 0 { p := grpc.ConnectParams{ Backoff: backoff.DefaultConfig, MinConnectTimeout: cfg.ReconnectionPeriod, } - cfg.DialOptions = append(cfg.DialOptions, grpc.WithConnectParams(p)) + dialOptsPrefix = append(dialOptsPrefix, grpc.WithConnectParams(p)) } + cfg.DialOptions = append(dialOptsPrefix, cfg.DialOptions...) return cfg } @@ -246,6 +258,7 @@ func (h *httpOption) ApplyHTTPOption(cfg Config) Config { func (httpOption) private() {} +// NewHTTPOption creates an option that is only applied to the HTTP driver. func NewHTTPOption(fn func(cfg Config) Config) HTTPOption { return &httpOption{fn: fn} } @@ -261,6 +274,7 @@ func (h *grpcOption) ApplyGRPCOption(cfg Config) Config { func (grpcOption) private() {} +// NewGRPCOption creates an option that is only applied to the gRPC driver. func NewGRPCOption(fn func(cfg Config) Config) GRPCOption { return &grpcOption{fn: fn} } @@ -300,6 +314,7 @@ func WithEndpointURL(v string) GenericOption { }) } +// WithCompression configures the compression used for exports. func WithCompression(compression Compression) GenericOption { return newGenericOption(func(cfg Config) Config { cfg.Traces.Compression = compression @@ -307,6 +322,7 @@ func WithCompression(compression Compression) GenericOption { }) } +// WithURLPath configures the URL path the exporter sends requests to. func WithURLPath(urlPath string) GenericOption { return newGenericOption(func(cfg Config) Config { cfg.Traces.URLPath = urlPath @@ -314,6 +330,7 @@ func WithURLPath(urlPath string) GenericOption { }) } +// WithRetry configures the retry policy used on failed exports. func WithRetry(rc retry.Config) GenericOption { return newGenericOption(func(cfg Config) Config { cfg.RetryConfig = rc @@ -321,6 +338,8 @@ func WithRetry(rc retry.Config) GenericOption { }) } +// WithTLSClientConfig configures the TLS configuration used by the +// exporter's client. func WithTLSClientConfig(tlsCfg *tls.Config) GenericOption { return newSplitOption(func(cfg Config) Config { cfg.Traces.TLSCfg = tlsCfg.Clone() @@ -331,6 +350,8 @@ func WithTLSClientConfig(tlsCfg *tls.Config) GenericOption { }) } +// WithInsecure disables client transport security for the exporter's +// connection. func WithInsecure() GenericOption { return newGenericOption(func(cfg Config) Config { cfg.Traces.Insecure = true @@ -338,6 +359,8 @@ func WithInsecure() GenericOption { }) } +// WithSecure enables client transport security for the exporter's +// connection. func WithSecure() GenericOption { return newGenericOption(func(cfg Config) Config { cfg.Traces.Insecure = false @@ -345,6 +368,7 @@ func WithSecure() GenericOption { }) } +// WithHeaders configures headers sent with every export request. func WithHeaders(headers map[string]string) GenericOption { return newGenericOption(func(cfg Config) Config { cfg.Traces.Headers = headers @@ -352,6 +376,8 @@ func WithHeaders(headers map[string]string) GenericOption { }) } +// WithTimeout configures the max waiting time for the backend to process +// each export batch. func WithTimeout(duration time.Duration) GenericOption { return newGenericOption(func(cfg Config) Config { cfg.Traces.Timeout = duration @@ -359,6 +385,8 @@ func WithTimeout(duration time.Duration) GenericOption { }) } +// WithMaxRequestSize configures the maximum size, in bytes, of a serialized +// export request, before compression. func WithMaxRequestSize(size int) GenericOption { return newGenericOption(func(cfg Config) Config { cfg.Traces.MaxRequestSize = size @@ -366,6 +394,19 @@ func WithMaxRequestSize(size int) GenericOption { }) } +// WithMaxResponseSize configures the maximum size, in bytes, of an OTLP/HTTP +// response body, after decompression. +func WithMaxResponseSize(size int64) HTTPOption { + return NewHTTPOption(func(cfg Config) Config { + if size > 0 { + cfg.Traces.MaxResponseSize = size + } + return cfg + }) +} + +// WithProxy configures the proxy function used by the exporter's HTTP +// client. func WithProxy(pf HTTPTransportProxyFunc) GenericOption { return newGenericOption(func(cfg Config) Config { cfg.Traces.Proxy = pf @@ -373,6 +414,7 @@ func WithProxy(pf HTTPTransportProxyFunc) GenericOption { }) } +// WithHTTPClient configures the HTTP client used to make requests. func WithHTTPClient(c *http.Client) GenericOption { return newGenericOption(func(cfg Config) Config { cfg.Traces.HTTPClient = c @@ -380,6 +422,7 @@ func WithHTTPClient(c *http.Client) GenericOption { }) } +// WithProtocol configures the protocol used to encode and send telemetry. func WithProtocol(protocol Protocol) GenericOption { return newSplitOption( // For OTLP/HTTP endpoints, this is the encoding format of the payloads sent to the collector. diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/internal/otlpjson/export_trace_service_request.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/internal/otlpjson/export_trace_service_request.go index 9e7756f..02dddf8 100644 --- a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/internal/otlpjson/export_trace_service_request.go +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/internal/otlpjson/export_trace_service_request.go @@ -486,6 +486,7 @@ func decodeAnyValue(jav *AnyValue) *commonpb.AnyValue { // Float64 encodes non-finite values as strings per ProtoJSON specs. type Float64 float64 +// MarshalJSON implements the [json.Marshaler] interface. func (f Float64) MarshalJSON() ([]byte, error) { switch value := float64(f); { case math.IsNaN(value): @@ -499,6 +500,7 @@ func (f Float64) MarshalJSON() ([]byte, error) { } } +// UnmarshalJSON implements the [json.Unmarshaler] interface. func (f *Float64) UnmarshalJSON(data []byte) error { var str string if err := json.Unmarshal(data, &str); err == nil { @@ -530,10 +532,12 @@ func (f *Float64) UnmarshalJSON(data []byte) error { // Int64 encodes int64 as a quoted decimal string per ProtoJSON specs. type Int64 int64 +// MarshalJSON implements the [json.Marshaler] interface. func (i Int64) MarshalJSON() ([]byte, error) { return []byte(`"` + strconv.FormatInt(int64(i), 10) + `"`), nil } +// UnmarshalJSON implements the [json.Unmarshaler] interface. func (i *Int64) UnmarshalJSON(data []byte) error { // expects either a string representation or a number var s string @@ -556,10 +560,12 @@ func (i *Int64) UnmarshalJSON(data []byte) error { // Uint64 encodes uint64 as a quoted decimal string per ProtoJSON specs. type Uint64 uint64 +// MarshalJSON implements the [json.Marshaler] interface. func (i Uint64) MarshalJSON() ([]byte, error) { return []byte(`"` + strconv.FormatUint(uint64(i), 10) + `"`), nil } +// UnmarshalJSON implements the [json.Unmarshaler] interface. func (i *Uint64) UnmarshalJSON(data []byte) error { // expects either a string representation or a number var s string @@ -584,6 +590,7 @@ const base16Alphabets = "0123456789ABCDEF" // TraceID encodes a 16-byte trace ID as a case-insensitive hex-encoded string. type TraceID [16]byte +// MarshalJSON implements the [json.Marshaler] interface. func (t TraceID) MarshalJSON() ([]byte, error) { var b [34]byte b[0] = '"' @@ -595,6 +602,7 @@ func (t TraceID) MarshalJSON() ([]byte, error) { return b[:], nil } +// UnmarshalJSON implements the [json.Unmarshaler] interface. func (t *TraceID) UnmarshalJSON(data []byte) error { var str string if err := json.Unmarshal(data, &str); err != nil { @@ -614,6 +622,7 @@ func (t *TraceID) UnmarshalJSON(data []byte) error { // SpanID encodes an 8-byte span ID as a case-insensitive hex-encoded string. type SpanID [8]byte +// MarshalJSON implements the [json.Marshaler] interface. func (s SpanID) MarshalJSON() ([]byte, error) { var b [18]byte b[0] = '"' @@ -625,6 +634,7 @@ func (s SpanID) MarshalJSON() ([]byte, error) { return b[:], nil } +// UnmarshalJSON implements the [json.Unmarshaler] interface. func (s *SpanID) UnmarshalJSON(data []byte) error { var str string if err := json.Unmarshal(data, &str); err != nil { diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/internal/response.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/internal/response.go new file mode 100644 index 0000000..0b48bf1 --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/internal/response.go @@ -0,0 +1,31 @@ +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +// DO NOT MODIFY. Generated by gotmpl. +// source: internal/shared/otlp/response.go.tmpl + +package internal + +import ( + "errors" + "fmt" + "io" +) + +// CopyResponseBody copies at most maxSize bytes from src to dst. It returns +// an error if src contains more than maxSize bytes. +func CopyResponseBody(dst io.Writer, src io.Reader, maxSize int64) error { + if _, err := io.Copy(dst, io.LimitReader(src, maxSize)); err != nil { + return err + } + + var extra [1]byte + _, err := io.ReadFull(src, extra[:]) + if err == nil { + return fmt.Errorf("response body too large: exceeded %d bytes", maxSize) + } + if errors.Is(err, io.EOF) { + return nil + } + return err +} diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/internal/version.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/internal/version.go index 87fcc4c..0149ae7 100644 --- a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/internal/version.go +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/internal/version.go @@ -5,4 +5,4 @@ package internal // Version is the current release version of the OpenTelemetry OTLP HTTP trace // exporter in use. -const Version = "1.46.0" +const Version = "1.47.0" diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/options.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/options.go index b17ac12..5b0d7a2 100644 --- a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/options.go +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/options.go @@ -172,6 +172,15 @@ func WithMaxRequestSize(size int) Option { return wrappedOption{otlpconfig.WithMaxRequestSize(size)} } +// WithMaxResponseSize sets the maximum size, in bytes, of an OTLP/HTTP +// response body, after decompression, that the exporter will read. +// +// By default, a limit of 4 MiB is used. Values less than or equal to zero are +// ignored. The response-size limit cannot be disabled. +func WithMaxResponseSize(size int64) Option { + return wrappedOption{otlpconfig.WithMaxResponseSize(size)} +} + // WithRetry configures the retry policy for transient errors that may occurs // when exporting traces. An exponential back-off algorithm is used to ensure // endpoints are not overwhelmed with retries. If unset, the default retry diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/version.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/version.go index fd8ee81..78e4f8e 100644 --- a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/version.go +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/version.go @@ -5,5 +5,5 @@ package otlptrace // Version is the current release version of the OpenTelemetry OTLP trace exporter in use. func Version() string { - return "1.46.0" + return "1.47.0" } diff --git a/vendor/go.opentelemetry.io/otel/internal/baggage/baggage.go b/vendor/go.opentelemetry.io/otel/internal/baggage/baggage.go index cbeb14f..d682f8c 100644 --- a/vendor/go.opentelemetry.io/otel/internal/baggage/baggage.go +++ b/vendor/go.opentelemetry.io/otel/internal/baggage/baggage.go @@ -16,12 +16,35 @@ package baggage // but OpenTelemetry does not, therefore, this is represented as a map. type List map[string]Item -// Item is the value and metadata properties part of a list-member. +// Item is the value and metadata or properties part of a list-member. +// Metadata and properties are mutually exclusive representations. type Item struct { - Value string - Properties []Property + value string + metadata string + properties []Property } +// NewItemWithMetadata returns an Item with opaque W3C metadata. +func NewItemWithMetadata(value, metadata string) Item { + return Item{value: value, metadata: metadata} +} + +// NewItemWithProperties returns an Item with materialized properties. +func NewItemWithProperties(value string, properties []Property) Item { + return Item{value: value, properties: properties} +} + +// Value returns the value of i. +func (i Item) Value() string { return i.value } + +// Metadata returns the opaque W3C metadata of i. It is empty for an Item +// created with properties. +func (i Item) Metadata() string { return i.metadata } + +// Properties returns the materialized properties of i. It is nil for an Item +// created with metadata. +func (i Item) Properties() []Property { return i.properties } + // Property is a metadata entry for a list-member. type Property struct { Key, Value string diff --git a/vendor/go.opentelemetry.io/otel/internal/errorhandler/errorhandler.go b/vendor/go.opentelemetry.io/otel/internal/errorhandler/errorhandler.go index de29446..1234ead 100644 --- a/vendor/go.opentelemetry.io/otel/internal/errorhandler/errorhandler.go +++ b/vendor/go.opentelemetry.io/otel/internal/errorhandler/errorhandler.go @@ -21,6 +21,9 @@ type ErrorHandler interface { Handle(error) } +// ErrDelegator is an ErrorHandler that forwards errors to a delegate +// ErrorHandler set with setDelegate. Before a delegate is set, it logs +// errors to STDERR. type ErrDelegator struct { delegate atomic.Pointer[ErrorHandler] } @@ -28,6 +31,8 @@ type ErrDelegator struct { // Compile-time check that delegator implements ErrorHandler. var _ ErrorHandler = (*ErrDelegator)(nil) +// Handle handles err by forwarding it to the configured delegate, or +// logging it to STDERR if no delegate is set. func (d *ErrDelegator) Handle(err error) { if eh := d.delegate.Load(); eh != nil { (*eh).Handle(err) diff --git a/vendor/go.opentelemetry.io/otel/internal/global/logger.go b/vendor/go.opentelemetry.io/otel/internal/global/logger.go new file mode 100644 index 0000000..e4328da --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/internal/global/logger.go @@ -0,0 +1,96 @@ +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +package global + +import ( + "context" + "sync" + "sync/atomic" + + "go.opentelemetry.io/otel/log" + "go.opentelemetry.io/otel/log/embedded" +) + +type loggerProvider struct { + embedded.LoggerProvider + + mu sync.Mutex + loggers map[il]*logger + delegate log.LoggerProvider +} + +// This is a compile-time guarantee that loggerProvider implements LoggerProvider. +var _ log.LoggerProvider = (*loggerProvider)(nil) + +func (p *loggerProvider) Logger(name string, options ...log.LoggerOption) log.Logger { + p.mu.Lock() + defer p.mu.Unlock() + + if p.delegate != nil { + return p.delegate.Logger(name, options...) + } + + cfg := log.NewLoggerConfig(options...) + key := il{ + name: name, + version: cfg.InstrumentationVersion(), + schema: cfg.SchemaURL(), + attrs: cfg.InstrumentationAttributes(), + } + + if p.loggers == nil { + l := &logger{name: name, options: options} + p.loggers = map[il]*logger{key: l} + return l + } + + if l, ok := p.loggers[key]; ok { + return l + } + + l := &logger{name: name, options: options} + p.loggers[key] = l + return l +} + +func (p *loggerProvider) setDelegate(provider log.LoggerProvider) { + p.mu.Lock() + defer p.mu.Unlock() + + p.delegate = provider + for _, l := range p.loggers { + l.setDelegate(provider) + } + p.loggers = nil // Only set logger delegates once. +} + +type logger struct { + embedded.Logger + + name string + options []log.LoggerOption + + delegate atomic.Value // log.Logger +} + +// This is a compile-time guarantee that logger implements Logger. +var _ log.Logger = (*logger)(nil) + +func (l *logger) Emit(ctx context.Context, r log.Record) { + if del, ok := l.delegate.Load().(log.Logger); ok { + del.Emit(ctx, r) + } +} + +func (l *logger) Enabled(ctx context.Context, param log.EnabledParameters) bool { + var enabled bool + if del, ok := l.delegate.Load().(log.Logger); ok { + enabled = del.Enabled(ctx, param) + } + return enabled +} + +func (l *logger) setDelegate(provider log.LoggerProvider) { + l.delegate.Store(provider.Logger(l.name, l.options...)) +} diff --git a/vendor/go.opentelemetry.io/otel/internal/global/state.go b/vendor/go.opentelemetry.io/otel/internal/global/state.go index f8fcb82..bd388d8 100644 --- a/vendor/go.opentelemetry.io/otel/internal/global/state.go +++ b/vendor/go.opentelemetry.io/otel/internal/global/state.go @@ -9,6 +9,7 @@ import ( "sync/atomic" "go.opentelemetry.io/otel/internal/errorhandler" + "go.opentelemetry.io/otel/log" "go.opentelemetry.io/otel/metric" "go.opentelemetry.io/otel/propagation" "go.opentelemetry.io/otel/trace" @@ -26,16 +27,22 @@ type ( meterProviderHolder struct { mp metric.MeterProvider } + + loggerProviderHolder struct { + provider log.LoggerProvider + } ) var ( - globalTracer = defaultTracerValue() - globalPropagators = defaultPropagatorsValue() - globalMeterProvider = defaultMeterProvider() + globalTracer = defaultTracerValue() + globalPropagators = defaultPropagatorsValue() + globalMeterProvider = defaultMeterProvider() + globalLoggerProvider = defaultLoggerProvider() delegateTraceOnce sync.Once delegateTextMapPropagatorOnce sync.Once delegateMeterOnce sync.Once + delegateLoggerOnce sync.Once ) // GetErrorHandler returns the global ErrorHandler instance. @@ -150,6 +157,32 @@ func SetMeterProvider(mp metric.MeterProvider) { globalMeterProvider.Store(meterProviderHolder{mp: mp}) } +// LoggerProvider is the internal implementation for global.LoggerProvider. +func LoggerProvider() log.LoggerProvider { + return globalLoggerProvider.Load().(loggerProviderHolder).provider +} + +// SetLoggerProvider is the internal implementation for global.SetLoggerProvider. +func SetLoggerProvider(provider log.LoggerProvider) { + current := LoggerProvider() + if _, cOk := current.(*loggerProvider); cOk { + if _, lpOk := provider.(*loggerProvider); lpOk && current == provider { + Error( + errors.New("no delegate configured in logger provider"), + "Setting logger provider to its current value. No delegate will be configured", + ) + return + } + } + + delegateLoggerOnce.Do(func() { + if def, ok := current.(*loggerProvider); ok { + def.setDelegate(provider) + } + }) + globalLoggerProvider.Store(loggerProviderHolder{provider: provider}) +} + func defaultTracerValue() *atomic.Value { v := &atomic.Value{} v.Store(tracerProviderHolder{tp: &tracerProvider{}}) @@ -167,3 +200,9 @@ func defaultMeterProvider() *atomic.Value { v.Store(meterProviderHolder{mp: &meterProvider{}}) return v } + +func defaultLoggerProvider() *atomic.Value { + v := &atomic.Value{} + v.Store(loggerProviderHolder{provider: &loggerProvider{}}) + return v +} diff --git a/vendor/go.opentelemetry.io/otel/log.go b/vendor/go.opentelemetry.io/otel/log.go new file mode 100644 index 0000000..1758913 --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/log.go @@ -0,0 +1,41 @@ +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +package otel + +import ( + "go.opentelemetry.io/otel/internal/global" + "go.opentelemetry.io/otel/log" +) + +// Logger returns a [log.Logger] configured with the provided name and options +// from the globally configured [log.LoggerProvider]. +// +// If this is called before a global LoggerProvider is configured, the returned +// Logger will be a No-Op implementation of a Logger. When a global +// LoggerProvider is registered for the first time, the returned Logger is +// updated in place to report to this new LoggerProvider. There is no need to +// call this function again for an updated instance. +// +// This is a convenience function. It is equivalent to: +// +// GetLoggerProvider().Logger(name, options...) +func Logger(name string, options ...log.LoggerOption) log.Logger { + return GetLoggerProvider().Logger(name, options...) +} + +// GetLoggerProvider returns the globally configured [log.LoggerProvider]. +// +// If a global LoggerProvider has not been configured with [SetLoggerProvider], +// the returned LoggerProvider will be a No-Op implementation. When +// a global LoggerProvider is registered for the first time, the returned +// LoggerProvider and all Loggers it has created are updated in place. There is +// no need to call this function again for an updated instance. +func GetLoggerProvider() log.LoggerProvider { + return global.LoggerProvider() +} + +// SetLoggerProvider configures provider as the global [log.LoggerProvider]. +func SetLoggerProvider(provider log.LoggerProvider) { + global.SetLoggerProvider(provider) +} diff --git a/vendor/go.opentelemetry.io/otel/log/DESIGN.md b/vendor/go.opentelemetry.io/otel/log/DESIGN.md new file mode 100644 index 0000000..d36c967 --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/log/DESIGN.md @@ -0,0 +1,566 @@ +# Logs API + +## Abstract + +`go.opentelemetry.io/otel/log` provides +[Logs API](https://opentelemetry.io/docs/specs/otel/logs/api/). + +The prototype was created in +[#4725](https://github.com/open-telemetry/opentelemetry-go/pull/4725). + +## Background + +The key challenge is to create a performant API compliant with the [specification](https://opentelemetry.io/docs/specs/otel/logs/api/) +with an intuitive and user friendly design. +Performance is seen as one of the most important characteristics of logging libraries in Go. + +## Design + +This proposed design aims to: + +- be specification compliant, +- be similar to Trace and Metrics API, +- take advantage of both OpenTelemetry and `slog` experience to achieve acceptable performance. + +### Module structure + +The API is published as a single `go.opentelemetry.io/otel/log` Go module. + +The package structure is similar to Trace API and Metrics API. +The Go module consists of the following packages: + +- `go.opentelemetry.io/otel/log` +- `go.opentelemetry.io/otel/log/embedded` +- `go.opentelemetry.io/otel/log/logtest` +- `go.opentelemetry.io/otel/log/noop` + +Rejected alternative: + +- [Reuse slog](#reuse-slog) + +### LoggerProvider + +The [`LoggerProvider` abstraction](https://opentelemetry.io/docs/specs/otel/logs/api/#loggerprovider) +is defined as `LoggerProvider` interface in [provider.go](provider.go). + +The specification may add new operations to `LoggerProvider`. +The interface may have methods added without a package major version bump. +This embeds `embedded.LoggerProvider` to help inform an API implementation +author about this non-standard API evolution. +This approach is already used in Trace API and Metrics API. + +#### LoggerProvider.Logger + +The `Logger` method implements the [`Get a Logger` operation](https://opentelemetry.io/docs/specs/otel/logs/api/#get-a-logger). + +The required `name` parameter is accepted as a `string` method argument. + +The `LoggerOption` options are defined to support optional parameters. + +Implementation requirements: + +- The [specification requires](https://opentelemetry.io/docs/specs/otel/logs/api/#concurrency-requirements) + the method to be safe to be called concurrently. + +- If the passed name is empty, this should be reported as invalid as specified + by the [Logs SDK specification](https://opentelemetry.io/docs/specs/otel/logs/sdk/#logger-creation). + The method should still use it as the instrumentation scope name and return + a working logger. + +`Logger` can be extended by adding new `LoggerOption` options +and adding new exported fields to the `LoggerConfig` struct. +This design is already used in Trace API for getting tracers +and in Metrics API for getting meters. + +Rejected alternative: + +- [Passing struct as parameter to LoggerProvider.Logger](#passing-struct-as-parameter-to-loggerproviderlogger). + +### Logger + +The [`Logger` abstraction](https://opentelemetry.io/docs/specs/otel/logs/api/#logger) +is defined as `Logger` interface in [logger.go](logger.go). + +The specification may add new operations to `Logger`. +The interface may have methods added without a package major version bump. +This embeds `embedded.Logger` to help inform an API implementation +author about this non-standard API evolution. +This approach is already used in Trace API and Metrics API. + +### Logger.Emit + +The `Emit` method implements the [`Emit a LogRecord` operation](https://opentelemetry.io/docs/specs/otel/logs/api/#emit-a-logrecord). + +[`Context` associated with the `LogRecord`](https://opentelemetry.io/docs/specs/otel/context/) +is accepted as a `context.Context` method argument. + +Calls to `Emit` are supposed to be on the hot path. +Therefore, in order to reduce the number of heap allocations, +the [`LogRecord` abstraction](https://opentelemetry.io/docs/specs/otel/logs/api/#emit-a-logrecord), +is defined as `Record` struct in [record.go](record.go). + +[`Timestamp`](https://opentelemetry.io/docs/specs/otel/logs/data-model/#field-timestamp) +is accessed using following methods: + +```go +func (r *Record) Timestamp() time.Time +func (r *Record) SetTimestamp(t time.Time) +``` + +[`ObservedTimestamp`](https://opentelemetry.io/docs/specs/otel/logs/data-model/#field-observedtimestamp) +is accessed using following methods: + +```go +func (r *Record) ObservedTimestamp() time.Time +func (r *Record) SetObservedTimestamp(t time.Time) +``` + +[`EventName`](https://opentelemetry.io/docs/specs/otel/logs/data-model/#field-eventname) +is accessed using following methods: + +```go +func (r *Record) EventName() string +func (r *Record) SetEventName(s string) +``` + +[`SeverityNumber`](https://opentelemetry.io/docs/specs/otel/logs/data-model/#field-severitynumber) +is accessed using following methods: + +```go +func (r *Record) Severity() Severity +func (r *Record) SetSeverity(s Severity) +``` + +`Severity` type is defined in [severity.go](severity.go). +The constants are are based on +[Displaying Severity recommendation](https://opentelemetry.io/docs/specs/otel/logs/data-model/#displaying-severity). +Additionally, `Severity[Level]` constants are defined to make the API more readable and user friendly. + +[`SeverityText`](https://opentelemetry.io/docs/specs/otel/logs/data-model/#field-severitytext) +is accessed using following methods: + +```go +func (r *Record) SeverityText() string +func (r *Record) SetSeverityText(s string) +``` + +[`Body`](https://opentelemetry.io/docs/specs/otel/logs/data-model/#field-body) +is accessed using following methods: + +```go +func (r *Record) Body() attribute.Value +func (r *Record) SetBody(v attribute.Value) +``` + +[Log record attributes](https://opentelemetry.io/docs/specs/otel/logs/data-model/#field-attributes) +are accessed using following methods: + +```go +func (r *Record) WalkAttributes(f func(attribute.KeyValue) bool) +func (r *Record) AddAttributes(attrs ...attribute.KeyValue) +``` + +`Record` has a `AttributesLen` method that returns +the number of attributes to allow slice preallocation +when converting records to a different representation: + +```go +func (r *Record) AttributesLen() int +``` + +The records attributes design and implementation is based on +[`slog.Record`](https://pkg.go.dev/log/slog#Record). +It allows achieving high-performance access and manipulation of the attributes +while keeping the API user friendly. +It relieves the user from making his own improvements +for reducing the number of allocations when passing attributes. + +Log body and attributes use the common +[`attribute.Value`](https://pkg.go.dev/go.opentelemetry.io/otel/attribute#Value) +and +[`attribute.KeyValue`](https://pkg.go.dev/go.opentelemetry.io/otel/attribute#KeyValue) +types. +These types cover the Logs Data Model `any` value shape, including empty +values, byte slices, generic slices, and maps. +Reusing the attribute package keeps the API consistent across signals and +avoids maintaining a second value model with conversion helpers. + +The zero value of `attribute.Value` represents an empty body. +Log maps use `attribute.MAP`, which may contain duplicate keys when callers +construct one that way. Duplicate-key normalization is an SDK policy, not an +API behavior. + +The caller must not subsequently mutate the record passed to `Emit`. +This would allow the implementation to not clone the record, +but simply retain, modify or discard it. +The implementation may still choose to clone the record or copy its attributes +if it needs to retain or modify it, +e.g. in case of asynchronous processing to eliminate the possibility of data races, +because the user can technically reuse the record and add new attributes +after the call (even when the documentation says that the caller must not do it). + +Implementation requirements: + +- The [specification requires](https://opentelemetry.io/docs/specs/otel/logs/api/#concurrency-requirements) + the method to be safe to be called concurrently. + +- The method must not interrupt the record processing if the context is canceled + per ["ignoring context cancellation" guideline](../CONTRIBUTING.md#ignoring-context-cancellation). + +- The [specification requires](https://opentelemetry.io/docs/specs/otel/logs/api/#emit-a-logrecord) + use the current time as observed timestamp if the passed is empty. + +- The method should handle the trace context passed via `ctx` argument in order to meet the + [specification's SDK requirement](https://opentelemetry.io/docs/specs/otel/logs/sdk/#readablelogrecord) + to populate the trace context fields from the resolved context. + +`Emit` can be extended by adding new exported fields to the `Record` struct. + +Rejected alternatives: + +- [Record as interface](#record-as-interface) +- [Options as parameter to Logger.Emit](#options-as-parameter-to-loggeremit) +- [Passing record as pointer to Logger.Emit](#passing-record-as-pointer-to-loggeremit) +- [Logger.WithAttributes](#loggerwithattributes) +- [Record attributes as slice](#record-attributes-as-slice) +- [Use any instead of attribute.Value](#use-any-instead-of-attributevalue) +- [Severity type encapsulating number and text](#severity-type-encapsulating-number-and-text) +- [Define log-specific value types](#define-log-specific-value-types) +- [Mix receiver types for Record](#mix-receiver-types-for-record) +- [Add XYZ method to Logger](#add-xyz-method-to-logger) + +### Logger.Enabled + +The `Enabled` method implements the [`Enabled` operation](https://opentelemetry.io/docs/specs/otel/logs/api/#enabled). + +[`Context` associated with the `LogRecord`](https://opentelemetry.io/docs/specs/otel/context/) +is accepted as a `context.Context` method argument. + +Calls to `Enabled` are supposed to be on the hot path and the list of arguments +can be extendend in future. Therefore, in order to reduce the number of heap +allocations and make it possible to handle new arguments, `Enabled` accepts +a `EnabledParameters` struct, defined in [logger.go](logger.go), as the second +method argument. + +The `EnabledParameters` uses fields, instead of getters and setters, to allow +simpler usage which allows configuring the `EnabledParameters` in the same line +where `Enabled` is called. + +### noop package + +The `go.opentelemetry.io/otel/log/noop` package provides +[Logs API No-Op Implementation](https://opentelemetry.io/docs/specs/otel/logs/noop/). + +### Trace context correlation + +The bridge implementation should do its best to pass +the `ctx` containing the trace context from the caller +so it can later be passed via `Logger.Emit`. + +It is not expected that users (caller or bridge implementation) reconstruct +a `context.Context`. Reconstructing a `context.Context` with +[`trace.ContextWithSpanContext`](https://pkg.go.dev/go.opentelemetry.io/otel/trace#ContextWithSpanContext) +and [`trace.NewSpanContext`](https://pkg.go.dev/go.opentelemetry.io/otel/trace#NewSpanContext) +would usually involve more memory allocations. + +The logging libraries which have recording methods that accepts `context.Context`, +such us [`slog`](https://pkg.go.dev/log/slog), +[`logrus`](https://pkg.go.dev/github.com/sirupsen/logrus), +[`zerolog`](https://pkg.go.dev/github.com/rs/zerolog), +makes passing the trace context trivial. + +However, some libraries do not accept a `context.Context` in their recording methods. +Structured logging libraries, +such as [`logr`](https://pkg.go.dev/github.com/go-logr/logr) +and [`zap`](https://pkg.go.dev/go.uber.org/zap), +offer passing `any` type as a log attribute/field. +Therefore, their bridge implementations can define a "special" log attributes/field +that will be used to capture the trace context. + +[The prototype](https://github.com/open-telemetry/opentelemetry-go/pull/4725) +has bridge implementations that handle trace context correlation efficiently. + +## Benchmarking + +The benchmarks take inspiration from [`slog`](https://pkg.go.dev/log/slog), +because for the Go team it was also critical to create API that would be fast +and interoperable with existing logging packages.[^2][^3] + +The benchmark results can be found in [the prototype](https://github.com/open-telemetry/opentelemetry-go/pull/4725). + +## Rejected alternatives + +### Reuse slog + +The API must not be coupled to [`slog`](https://pkg.go.dev/log/slog), +nor any other logging library. + +The API needs to evolve orthogonally to `slog`. + +`slog` is not compliant with the [Logs API](https://opentelemetry.io/docs/specs/otel/logs/api/). +and we cannot expect the Go team to make `slog` compliant with it. + +The interoperability can be achieved using [a log bridge](https://opentelemetry.io/docs/specs/otel/glossary/#log-appender--bridge). + +You can read more about OpenTelemetry Logs design on [opentelemetry.io](https://opentelemetry.io/docs/concepts/signals/logs/). + +### Record as interface + +`Record` is defined as a `struct` because of the following reasons. + +Log record is a value object without any behavior. +It is used as data input for Logger methods. + +The log record resembles the instrument config structs like [metric.Float64CounterConfig](https://pkg.go.dev/go.opentelemetry.io/otel/metric#Float64CounterConfig). + +Using `struct` instead of `interface` improves the performance as e.g. +indirect calls are less optimized, +usage of interfaces tend to increase heap allocations.[^3] + +### Options as parameter to Logger.Emit + +One of the initial ideas was to have: + +```go +type Logger interface{ + embedded.Logger + Emit(ctx context.Context, options ...RecordOption) +} +``` + +The main reason was that design would be similar +to the [Meter API](https://pkg.go.dev/go.opentelemetry.io/otel/metric#Meter) +for creating instruments. + +However, passing `Record` directly, instead of using options, +is more performant as it reduces heap allocations.[^4] + +Another advantage of passing `Record` is that API would not have functions like `NewRecord(options...)`, +which would be used by the SDK and not by the users. + +Finally, the definition would be similar to [`slog.Handler.Handle`](https://pkg.go.dev/log/slog#Handler) +that was designed to provide optimization opportunities.[^2] + +### Passing record as pointer to Logger.Emit + +So far the benchmarks do not show differences that would +favor passing the record via pointer (and vice versa). + +Passing via value feels safer because of the following reasons. + +The user would not be able to pass `nil`. +Therefore, it reduces the possibility to have a nil pointer dereference. + +It should reduce the possibility of a heap allocation. + +It follows the design of [`slog.Handler`](https://pkg.go.dev/log/slog#Handler). + +If follows one of Google's Go Style Decisions +to prefer [passing values](https://google.github.io/styleguide/go/decisions#pass-values). + +### Passing struct as parameter to LoggerProvider.Logger + +Similarly to `Logger.Emit`, we could have something like: + +```go +type LoggerProvider interface{ + embedded.LoggerProvider + Logger(name string, config LoggerConfig) +} +``` + +The drawback of this idea would be that this would be +a different design from Trace and Metrics API. + +The performance of acquiring a logger is not as critical +as the performance of emitting a log record. While a single +HTTP/RPC handler could write hundreds of logs, it should not +create a new logger for each log entry. +The bridge implementation should reuse loggers whenever possible. + +### Logger.WithAttributes + +We could add `WithAttributes` to the `Logger` interface. +Then `Record` could be a simple struct with only exported fields. +The idea was that the SDK would implement the performance improvements +instead of doing it in the API. +This would allow having different optimization strategies. + +During the analysis[^5], it occurred that the main problem of this proposal +is that the variadic slice passed to an interface method is always heap allocated. + +Moreover, the logger returned by `WithAttribute` was allocated on the heap. + +Lastly, the proposal was not specification compliant. + +### Record attributes as slice + +One of the proposals[^6] was to have `Record` as a simple struct: + +```go +type Record struct { + Timestamp time.Time + ObservedTimestamp time.Time + EventName string + Severity Severity + SeverityText string + Body Value + Attributes []KeyValue +} +``` + +The bridge implementations could use [`sync.Pool`](https://pkg.go.dev/sync#Pool) +for reducing the number of allocations when passing attributes. + +The benchmarks results were better. + +In such a design, most bridges would have a `sync.Pool` +to reduce the number of heap allocations. +However, the `sync.Pool` will not work correctly with API implementations +that would take ownership of the record +(e.g. implementations that do not copy records for asynchronous processing). +The current design, even in case of improper API implementation, +has lower chances of encountering a bug as most bridges would +create a record, pass it, and forget about it. + +For reference, here is the reason why `slog` does not use `sync.Pool`[^3] +as well: + +> We can use a sync pool for records though we decided not to. +You can but it's a bad idea for us. Why? +Because users have control of Records. +Handler writers can get their hands on a record +and we'd have to ask them to free it +or try to free it magically at some some point. +But either way, they could get themselves in trouble by freeing it twice +or holding on to one after they free it. +That's a use after free bug and that's why `zerolog` was problematic for us. +`zerolog` as as part of its speed exposes a pool allocated value to users +if you use `zerolog` the normal way, that you'll see in all the examples, +you will never encounter a problem. +But if you do something a little out of the ordinary you can get +use after free bugs and we just didn't want to put that in the standard library. + +Therefore, we decided to not follow the proposal as it is +less user friendly (users and bridges would use e.g. a `sync.Pool` to reduce +the number of heap allocation), less safe (more prone to use after free bugs +and race conditions), and the benchmark differences were not significant. + +### Use any instead of attribute.Value + +[Logs Data Model](https://opentelemetry.io/docs/specs/otel/logs/data-model/#field-body) +defines Body to be `any`. +One could propose to define `Body` (and attribute values) as `any` +instead of using `attribute.Value`. + +First of all, [`any` type defined in the specification](https://opentelemetry.io/docs/specs/otel/logs/data-model/#type-any) +is not the same as `any` (`interface{}`) in Go. + +Moreover, using `any` as a field would decrease the performance.[^7] + +Using `attribute.Value` preserves a typed, allocation-conscious representation +of the Logs Data Model `any` values while avoiding unconstrained `interface{}` +handling in bridge implementations. + +### Severity type encapsulating number and text + +We could combine severity into a single field defining a type: + +```go +type Severity struct { + Number SeverityNumber + Text string +} +``` + +However, the [Logs Data Model](https://opentelemetry.io/docs/specs/otel/logs/data-model/#log-and-event-record-definition) +define it as independent fields. +It should be more user friendly to have them separated. +Especially when having getter and setter methods, setting one value +when the other is already set would be unpleasant. + +### Define log-specific value types + +The original design defined `Kind`, `Value`, and `KeyValue` in +`go.opentelemetry.io/otel/log`. +That avoided coupling log bodies to the common attribute package while logs were +still exploring structured value support. + +The Logs Data Model and common attribute value model now share the structured +`any` shapes needed by Go: empty, bool, int64, float64, string, byte slice, +homogeneous slices, generic slices, and maps. +The specification direction is to reuse these value shapes across signals. +Keeping log-specific types would duplicate API surface, require conversion +helpers, and make bridge code choose between two equivalent value models. + +Therefore log records now use `attribute.Value` for body values and +`attribute.KeyValue` for attributes and map entries. + +### Mix receiver types for Record + +Methods of [`slog.Record`](https://pkg.go.dev/log/slog#Record) +have different receiver types. + +In `log/slog` GitHub issue we can only find that the reason is:[^8] + +>> some receiver of Record struct is by value +> Passing Records by value means they incur no heap allocation. +> That improves performance overall, even though they are copied. + +However, the benchmarks do not show any noticeable differences.[^9] + +The compiler is smart-enough to not make a heap allocation for any of these methods. +The use of a pointer receiver does not cause any heap allocation. +From Go FAQ:[^10] + +> In the current compilers, if a variable has its address taken, +> that variable is a candidate for allocation on the heap. +> However, a basic escape analysis recognizes some cases +> when such variables will not live past the return from the function +> and can reside on the stack. + +The [Understanding Allocations: the Stack and the Heap](https://www.youtube.com/watch?v=ZMZpH4yT7M0) +presentation by Jacob Walker describes the escape analysis with details. + +Moreover, also from Go FAQ:[^10] + +> Also, if a local variable is very large, +> it might make more sense to store it on the heap rather than the stack. + +Therefore, even if we use a value receiver and the value is very large +it may be heap allocated. + +Both [Go Code Review Comments](https://go.dev/wiki/CodeReviewComments#receiver-type) +and [Google's Go Style Decisions](https://google.github.io/styleguide/go/decisions#receiver-type) +highly recommend making the methods for a type either all pointer methods +or all value methods. Google's Go Style Decisions even goes further and says: + +> There is a lot of misinformation about whether passing a value or a pointer +> to a function can affect performance. +> The compiler can choose to pass pointers to values on the stack +> as well as copying values on the stack, +> but these considerations should not outweigh the readability +> and correctness of the code in most circumstances. +> When the performance does matter, it is important to profile both approaches +> with a realistic benchmark before deciding that one approach outperforms the other. + +Because, the benchmarks[^9] do not proof any performance difference +and the general recommendation is to not mix receiver types, +we decided to use pointer receivers for all `Record` methods. + +### Add XYZ method to Logger + +The `Logger` does not have methods like `SetSeverity`, etc. +as the Logs API needs to follow (be compliant with) +the [specification](https://opentelemetry.io/docs/specs/otel/logs/api/) + +[^1]: [Handle structured body and attributes](https://github.com/pellared/opentelemetry-go/pull/7) +[^2]: Jonathan Amsterdam, [The Go Blog: Structured Logging with slog](https://go.dev/blog/slog) +[^3]: Jonathan Amsterdam, [GopherCon Europe 2023: A Fast Structured Logging Package](https://www.youtube.com/watch?v=tC4Jt3i62ns) +[^4]: [Emit definition discussion with benchmarks](https://github.com/open-telemetry/opentelemetry-go/pull/4725#discussion_r1400869566) +[^5]: [Logger.WithAttributes analysis](https://github.com/pellared/opentelemetry-go/pull/3) +[^6]: [Record attributes as field and use sync.Pool for reducing allocations](https://github.com/pellared/opentelemetry-go/pull/4) and [Record attributes based on slog.Record](https://github.com/pellared/opentelemetry-go/pull/6) +[^7]: [Record.Body as any](https://github.com/pellared/opentelemetry-go/pull/5) +[^8]: [log/slog: structured, leveled logging](https://github.com/golang/go/issues/56345#issuecomment-1302563756) +[^9]: [Record with pointer receivers only](https://github.com/pellared/opentelemetry-go/pull/8) +[^10]: [Go FAQ: Stack or heap](https://go.dev/doc/faq#stack_or_heap) diff --git a/vendor/go.opentelemetry.io/otel/log/LICENSE b/vendor/go.opentelemetry.io/otel/log/LICENSE new file mode 100644 index 0000000..f1aee0f --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/log/LICENSE @@ -0,0 +1,231 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +-------------------------------------------------------------------------------- + +Copyright 2009 The Go Authors. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google LLC nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/vendor/go.opentelemetry.io/otel/log/README.md b/vendor/go.opentelemetry.io/otel/log/README.md new file mode 100644 index 0000000..3f71427 --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/log/README.md @@ -0,0 +1,3 @@ +# Log API + +[![PkgGoDev](https://pkg.go.dev/badge/go.opentelemetry.io/otel/log)](https://pkg.go.dev/go.opentelemetry.io/otel/log) diff --git a/vendor/go.opentelemetry.io/otel/log/doc.go b/vendor/go.opentelemetry.io/otel/log/doc.go new file mode 100644 index 0000000..211de35 --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/log/doc.go @@ -0,0 +1,85 @@ +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +/* +Package log provides the OpenTelemetry Logs API. + +This API is separate from its implementation, so the instrumentation built +from it is reusable. See [go.opentelemetry.io/otel/sdk/log] for the official +OpenTelemetry implementation of this API. + +The log package provides the OpenTelemetry Logs API, which serves as a standard +interface for generating and managing log records within the OpenTelemetry ecosystem. +This package allows users to emit LogRecords, enabling structured, context-rich logging +that can be easily integrated with observability tools. It ensures that log data is captured +in a way that is consistent with OpenTelemetry's data model. + +This package can be used to create bridges between existing logging libraries and OpenTelemetry. +Log bridges allow existing logging setups to be integrated with OpenTelemetry. +Log bridges can be found in the [registry]. + +# API Implementations + +This package does not conform to the standard Go versioning policy; all of its +interfaces may have methods added to them without a package major version bump. +This non-standard API evolution could surprise an uninformed implementation +author. They could unknowingly build their implementation in a way that would +result in a runtime panic for their users who update to the new API. + +The API is designed to help inform an instrumentation author about this +non-standard API evolution. It requires them to choose a default behavior for +unimplemented interface methods. There are three behavior choices they can +make: + + - Compilation failure + - Panic + - Default to another implementation + +All interfaces in this API embed a corresponding interface from +[go.opentelemetry.io/otel/log/embedded]. If an author wants the default +behavior of their implementations to be a compilation failure, signaling to +their users that they need to update to the latest version of that implementation, +they need to embed the corresponding interface from +[go.opentelemetry.io/otel/log/embedded] in their implementation. For example, + + import "go.opentelemetry.io/otel/log/embedded" + + type LoggerProvider struct { + embedded.LoggerProvider + // ... + } + +If an author wants the default behavior of their implementations to panic, +they need to embed the API interface directly. + + import "go.opentelemetry.io/otel/log" + + type LoggerProvider struct { + log.LoggerProvider + // ... + } + +This is not a recommended behavior as it could lead to publishing packages that +contain runtime panics when users update other packages that use newer versions +of [go.opentelemetry.io/otel/log]. + +Finally, an author can embed another implementation in theirs. The embedded +implementation will be used for methods not defined by the author. For example, +an author who wants to default to silently dropping the call can use +[go.opentelemetry.io/otel/log/noop]: + + import "go.opentelemetry.io/otel/log/noop" + + type LoggerProvider struct { + noop.LoggerProvider + // ... + } + +It is strongly recommended that authors only embed +go.opentelemetry.io/otel/log/noop if they choose this default behavior. That +implementation is the only one OpenTelemetry authors can guarantee will fully +implement all the API interfaces when a user updates their API. + +[registry]: https://opentelemetry.io/ecosystem/registry/?language=go&component=log-bridge +*/ +package log diff --git a/vendor/go.opentelemetry.io/otel/log/embedded/README.md b/vendor/go.opentelemetry.io/otel/log/embedded/README.md new file mode 100644 index 0000000..bae4ac6 --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/log/embedded/README.md @@ -0,0 +1,3 @@ +# Log Embedded + +[![PkgGoDev](https://pkg.go.dev/badge/go.opentelemetry.io/otel/log/embedded)](https://pkg.go.dev/go.opentelemetry.io/otel/log/embedded) diff --git a/vendor/go.opentelemetry.io/otel/log/embedded/embedded.go b/vendor/go.opentelemetry.io/otel/log/embedded/embedded.go new file mode 100644 index 0000000..3b97fcd --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/log/embedded/embedded.go @@ -0,0 +1,36 @@ +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +// Package embedded provides interfaces embedded within the [OpenTelemetry Logs +// Bridge API]. +// +// Implementers of the [OpenTelemetry Logs API] can embed the relevant +// type from this package into their implementation directly. Doing so will +// result in a compilation error for users when the [OpenTelemetry Logs Bridge +// API] is extended (which is something that can happen without a major version +// bump of the API package). +// +// [OpenTelemetry Logs API]: https://pkg.go.dev/go.opentelemetry.io/otel/log +package embedded + +// LoggerProvider is embedded in the [Logs API LoggerProvider]. +// +// Embed this interface in your implementation of the [Logs API +// LoggerProvider] if you want users to experience a compilation error when the +// [Logs Bridge API LoggerProvider] interface is extended (which is something +// that can happen without a major version bump of the API package). This error +// signals that they need to update to your latest implementation. +// +// [Logs API LoggerProvider]: https://pkg.go.dev/go.opentelemetry.io/otel/log#LoggerProvider +type LoggerProvider interface{ loggerProvider() } + +// Logger is embedded in the [Logs API Logger]. +// +// Embed this interface in your implementation of the [Logs API Logger] +// if you want users to experience a compilation error when the [Logs API +// Logger] interface is extended (which is something that can happen without a +// major version bump of the API package). This error signals that they need to +// update to your latest implementation. +// +// [Logs API Logger]: https://pkg.go.dev/go.opentelemetry.io/otel/log#Logger +type Logger interface{ logger() } diff --git a/vendor/go.opentelemetry.io/otel/log/logger.go b/vendor/go.opentelemetry.io/otel/log/logger.go new file mode 100644 index 0000000..c0e4ca7 --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/log/logger.go @@ -0,0 +1,197 @@ +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +package log + +import ( + "context" + "slices" + + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/log/embedded" +) + +// Logger emits log records. +// +// Warning: Methods may be added to this interface in minor releases. See +// package documentation on API implementation for information on how to set +// the default behavior for unimplemented methods. +type Logger interface { + // Users of the interface can ignore this. This embedded type is only used + // by implementations of this interface. See the "API Implementations" + // section of the package documentation for more information. + embedded.Logger + + // Emit emits a log record. + // + // The record may be held by the implementation. Callers should not mutate + // the record after it is passed. + // + // Implementations of this method need to be safe for a user to call + // concurrently. + Emit(ctx context.Context, record Record) + + // Enabled reports whether the Logger emits for the given context and + // param. + // + // Calling Enabled is optional. It is not required before calling + // [Logger.Emit]. + // + // Enabled is useful when constructing a [Record] is expensive. A caller can + // call Enabled first and skip record construction when it returns false. + // When constructing the Record is inexpensive, a caller can emit it + // directly. + // + // The returned value is not static and may change over time. A cached value + // can become stale. + // + // The passed param is likely to contain only partial information about a + // record (e.g., a param with only the Severity set). + // If a Logger needs more information than is provided, it + // is said to be in an indeterminate state (see below). + // + // The returned value is true if the Logger emits for the provided context + // and param, and false if the Logger does not emit. The returned value may be + // true or false in an indeterminate state. + // An implementation should default to returning true for an indeterminate + // state, but may return false if there are valid reasons to do so in + // particular circumstances (e.g., performance or correctness). + // + // The param should not be held by the implementation. A copy should be + // made if the param needs to be held after the call returns. + // + // Implementations of this method need to be safe for a user to call + // concurrently. + Enabled(ctx context.Context, param EnabledParameters) bool +} + +// LoggerOption applies configuration options to a [Logger]. +type LoggerOption interface { + // applyLogger applies a LoggerOption to a LoggerConfig. + applyLogger(LoggerConfig) LoggerConfig +} + +// LoggerConfig contains options for a [Logger]. +type LoggerConfig struct { + // Ensure forward compatibility by explicitly making this not comparable. + noCmp [0]func() //nolint: unused // This is indeed used. + + version string + schemaURL string + attrs attribute.Set +} + +type experimentalOption interface { + Experimental() +} + +// NewLoggerConfig returns a new [LoggerConfig] with all the options applied. +func NewLoggerConfig(options ...LoggerOption) LoggerConfig { + var c LoggerConfig + for _, opt := range options { + if _, ok := opt.(experimentalOption); ok { + continue + } + c = opt.applyLogger(c) + } + return c +} + +// InstrumentationVersion returns the version of the library providing +// instrumentation. +func (cfg LoggerConfig) InstrumentationVersion() string { + return cfg.version +} + +// InstrumentationAttributes returns the attributes associated with the library +// providing instrumentation. +func (cfg LoggerConfig) InstrumentationAttributes() attribute.Set { + return cfg.attrs +} + +// SchemaURL returns the schema URL of the library providing instrumentation. +func (cfg LoggerConfig) SchemaURL() string { + return cfg.schemaURL +} + +type loggerOptionFunc func(LoggerConfig) LoggerConfig + +func (fn loggerOptionFunc) applyLogger(cfg LoggerConfig) LoggerConfig { + return fn(cfg) +} + +// WithInstrumentationVersion returns a [LoggerOption] that sets the +// instrumentation version of a [Logger]. +func WithInstrumentationVersion(version string) LoggerOption { + return loggerOptionFunc(func(config LoggerConfig) LoggerConfig { + config.version = version + return config + }) +} + +// mergeSets returns the union of the keys in a and b. For duplicate keys, the +// value associated with b is used. +func mergeSets(a, b attribute.Set) attribute.Set { + // NewMergeIterator uses the first value for any duplicates. + iter := attribute.NewMergeIterator(&b, &a) + merged := make([]attribute.KeyValue, 0, a.Len()+b.Len()) + for iter.Next() { + merged = append(merged, iter.Attribute()) + } + return attribute.NewSet(merged...) +} + +// WithInstrumentationAttributes returns a [LoggerOption] that sets the +// instrumentation attributes of a [Logger]. +// +// This is equivalent to calling WithInstrumentationAttributeSet with an +// [attribute.Set] created from a clone of the passed attributes. +// [WithInstrumentationAttributeSet] is recommended for more control. +// +// If multiple [WithInstrumentationAttributes] or [WithInstrumentationAttributeSet] +// options are passed, the attributes will be merged together in the order +// they are passed. For attributes with duplicate keys, the last value passed +// will be used. +func WithInstrumentationAttributes(attr ...attribute.KeyValue) LoggerOption { + set := attribute.NewSet(slices.Clone(attr)...) + return WithInstrumentationAttributeSet(set) +} + +// WithInstrumentationAttributeSet returns a [LoggerOption] that adds +// instrumentation attributes to a [Logger]. +// +// If multiple [WithInstrumentationAttributes] or [WithInstrumentationAttributeSet] +// options are passed, the attributes will be merged together in the order +// they are passed. For attributes with duplicate keys, the last value passed +// will be used. +func WithInstrumentationAttributeSet(set attribute.Set) LoggerOption { + if set.Len() == 0 { + return loggerOptionFunc(func(config LoggerConfig) LoggerConfig { + return config + }) + } + + return loggerOptionFunc(func(config LoggerConfig) LoggerConfig { + if config.attrs.Len() == 0 { + config.attrs = set + } else { + config.attrs = mergeSets(config.attrs, set) + } + return config + }) +} + +// WithSchemaURL returns a [LoggerOption] that sets the schema URL for a +// [Logger]. +func WithSchemaURL(schemaURL string) LoggerOption { + return loggerOptionFunc(func(config LoggerConfig) LoggerConfig { + config.schemaURL = schemaURL + return config + }) +} + +// EnabledParameters represents the payload for [Logger.Enabled]. +type EnabledParameters struct { + Severity Severity + EventName string +} diff --git a/vendor/go.opentelemetry.io/otel/log/provider.go b/vendor/go.opentelemetry.io/otel/log/provider.go new file mode 100644 index 0000000..10969b4 --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/log/provider.go @@ -0,0 +1,38 @@ +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +package log + +import "go.opentelemetry.io/otel/log/embedded" + +// LoggerProvider provides access to [Logger]. +// +// Warning: Methods may be added to this interface in minor releases. See +// package documentation on API implementation for information on how to set +// the default behavior for unimplemented methods. +type LoggerProvider interface { + // Users of the interface can ignore this. This embedded type is only used + // by implementations of this interface. See the "API Implementations" + // section of the package documentation for more information. + embedded.LoggerProvider + + // Logger returns a new [Logger] with the provided name and configuration. + // + // The name needs to uniquely identify the source of logged code. It is + // recommended that name be the Go package name of the library using a log + // bridge (note: this is not the name of the bridge package). Most + // commonly, this means a bridge will need to accept this value from its + // users. + // + // An empty name is invalid. Implementations should retain the empty value as the + // instrumentation scope name, return a working Logger, and report the invalid value. + // + // The version of the package using a bridge can be critical information + // to include when logging. The bridge should accept this version + // information and use the [WithInstrumentationVersion] option to configure + // the Logger appropriately. + // + // Implementations of this method need to be safe for a user to call + // concurrently. + Logger(name string, options ...LoggerOption) Logger +} diff --git a/vendor/go.opentelemetry.io/otel/log/record.go b/vendor/go.opentelemetry.io/otel/log/record.go new file mode 100644 index 0000000..351657e --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/log/record.go @@ -0,0 +1,168 @@ +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +package log + +import ( + "slices" + "time" + + "go.opentelemetry.io/otel/attribute" +) + +// attributesInlineCount is the number of attributes that are efficiently +// stored in an array within a Record. This value is borrowed from slog, which +// performed a quantitative survey of log library use and found that this value +// covers 95% of all use cases (https://go.dev/blog/slog#performance). +const attributesInlineCount = 5 + +// Record represents a log record. +// A log record with a non-empty event name is interpreted as an event record. +type Record struct { + // Ensure forward compatibility by explicitly making this not comparable. + noCmp [0]func() //nolint: unused // This is indeed used. + + eventName string + timestamp time.Time + observedTimestamp time.Time + severity Severity + severityText string + body attribute.Value + err error + + // The fields below are for optimizing the implementation of Attributes and + // AddAttributes. This design is borrowed from the slog Record type: + // https://cs.opensource.google/go/go/+/refs/tags/go1.22.0:src/log/slog/record.go;l=20 + + // Allocation optimization: an inline array sized to hold + // the majority of log calls (based on examination of open-source + // code). It holds the start of the list of attributes. + front [attributesInlineCount]attribute.KeyValue + + // The number of attributes in front. + nFront int + + // The list of attributes except for those in front. + // Invariants: + // - len(back) > 0 if nFront == len(front) + // - Unused array elements are zeroed to detect mistakes. + back []attribute.KeyValue +} + +// EventName returns the event name. +// A log record with a non-empty event name is interpreted as an event record. +func (r *Record) EventName() string { + return r.eventName +} + +// SetEventName sets the event name. +// A log record with a non-empty event name is interpreted as an event record. +// Event names should uniquely identify the structure of the event's attributes +// and body. +func (r *Record) SetEventName(s string) { + r.eventName = s +} + +// Timestamp returns the time when the log record occurred. +func (r *Record) Timestamp() time.Time { + return r.timestamp +} + +// SetTimestamp sets the time when the log record occurred. +func (r *Record) SetTimestamp(t time.Time) { + r.timestamp = t +} + +// ObservedTimestamp returns the time when the log record was observed. +func (r *Record) ObservedTimestamp() time.Time { + return r.observedTimestamp +} + +// SetObservedTimestamp sets the time when the log record was observed. +func (r *Record) SetObservedTimestamp(t time.Time) { + r.observedTimestamp = t +} + +// Severity returns the [Severity] of the log record. +func (r *Record) Severity() Severity { + return r.severity +} + +// SetSeverity sets the [Severity] level of the log record. +func (r *Record) SetSeverity(level Severity) { + r.severity = level +} + +// SeverityText returns the text of the severity (also known as the log level) +// as originally known at the source. +func (r *Record) SeverityText() string { + return r.severityText +} + +// SetSeverityText sets the text of the severity (also known as the log level) +// as originally known at the source. +func (r *Record) SetSeverityText(text string) { + r.severityText = text +} + +// Body returns the body of the log record. +func (r *Record) Body() attribute.Value { + return r.body +} + +// SetBody sets the body of the log record. +func (r *Record) SetBody(v attribute.Value) { + r.body = v +} + +// Err returns the associated error if one has been set. +func (r *Record) Err() error { + return r.err +} + +// SetErr sets the associated error. Passing nil clears the error. +func (r *Record) SetErr(err error) { + r.err = err +} + +// WalkAttributes walks all attributes in the log record by calling f for each +// [attribute.KeyValue] in the [Record]. Iteration stops if f returns false. +func (r *Record) WalkAttributes(f func(attribute.KeyValue) bool) { + for i := 0; i < r.nFront; i++ { + if !f(r.front[i]) { + return + } + } + for _, a := range r.back { + if !f(a) { + return + } + } +} + +// AddAttributes adds attributes to the log record. +func (r *Record) AddAttributes(attrs ...attribute.KeyValue) { + var i int + for i = 0; i < len(attrs) && r.nFront < len(r.front); i++ { + a := attrs[i] + r.front[r.nFront] = a + r.nFront++ + } + + r.back = slices.Grow(r.back, len(attrs[i:])) + r.back = append(r.back, attrs[i:]...) +} + +// AttributesLen returns the number of attributes in the log record. +func (r *Record) AttributesLen() int { + return r.nFront + len(r.back) +} + +// Clone returns a copy of the record with no shared state. +// The original record and the clone can both be modified without interfering +// with each other. +func (r *Record) Clone() Record { + res := *r + res.back = slices.Clone(r.back) + return res +} diff --git a/vendor/go.opentelemetry.io/otel/log/severity.go b/vendor/go.opentelemetry.io/otel/log/severity.go new file mode 100644 index 0000000..4f305be --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/log/severity.go @@ -0,0 +1,69 @@ +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +//go:generate stringer -type=Severity -linecomment + +package log + +// Severity represents a log record's severity (also known as its log level). +// Smaller numerical values correspond to less severe log records (such as +// debug events); larger numerical values correspond to more severe log records +// (such as errors and critical events). +type Severity int + +// The following Severity values are defined by OpenTelemetry. +const ( + // SeverityUndefined represents an unset Severity. + SeverityUndefined Severity = 0 // UNDEFINED + + // The following are severity values for fine-grained debugging log records. + // They are typically disabled in default configurations. + SeverityTrace1 Severity = 1 // TRACE + SeverityTrace2 Severity = 2 // TRACE2 + SeverityTrace3 Severity = 3 // TRACE3 + SeverityTrace4 Severity = 4 // TRACE4 + + // The following are severity values for debugging log records. + SeverityDebug1 Severity = 5 // DEBUG + SeverityDebug2 Severity = 6 // DEBUG2 + SeverityDebug3 Severity = 7 // DEBUG3 + SeverityDebug4 Severity = 8 // DEBUG4 + + // The following are severity values for informational log records indicating + // that an event happened. + SeverityInfo1 Severity = 9 // INFO + SeverityInfo2 Severity = 10 // INFO2 + SeverityInfo3 Severity = 11 // INFO3 + SeverityInfo4 Severity = 12 // INFO4 + + // The following are severity values for warning log records. These records + // are not errors, but they are likely more important than informational + // events. + SeverityWarn1 Severity = 13 // WARN + SeverityWarn2 Severity = 14 // WARN2 + SeverityWarn3 Severity = 15 // WARN3 + SeverityWarn4 Severity = 16 // WARN4 + + // The following are severity values for error log records indicating that + // something went wrong. + SeverityError1 Severity = 17 // ERROR + SeverityError2 Severity = 18 // ERROR2 + SeverityError3 Severity = 19 // ERROR3 + SeverityError4 Severity = 20 // ERROR4 + + // The following are severity values for fatal log records, such as those + // associated with an application or system crash. + SeverityFatal1 Severity = 21 // FATAL + SeverityFatal2 Severity = 22 // FATAL2 + SeverityFatal3 Severity = 23 // FATAL3 + SeverityFatal4 Severity = 24 // FATAL4 + + // The following are convenience definitions for the base severity of each + // level. + SeverityTrace = SeverityTrace1 + SeverityDebug = SeverityDebug1 + SeverityInfo = SeverityInfo1 + SeverityWarn = SeverityWarn1 + SeverityError = SeverityError1 + SeverityFatal = SeverityFatal1 +) diff --git a/vendor/go.opentelemetry.io/otel/log/severity_string.go b/vendor/go.opentelemetry.io/otel/log/severity_string.go new file mode 100644 index 0000000..fb94cae --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/log/severity_string.go @@ -0,0 +1,48 @@ +// Code generated by "stringer -type=Severity -linecomment"; DO NOT EDIT. + +package log + +import "strconv" + +func _() { + // An "invalid array index" compiler error signifies that the constant values have changed. + // Re-run the stringer command to generate them again. + var x [1]struct{} + _ = x[SeverityUndefined-0] + _ = x[SeverityTrace1-1] + _ = x[SeverityTrace2-2] + _ = x[SeverityTrace3-3] + _ = x[SeverityTrace4-4] + _ = x[SeverityDebug1-5] + _ = x[SeverityDebug2-6] + _ = x[SeverityDebug3-7] + _ = x[SeverityDebug4-8] + _ = x[SeverityInfo1-9] + _ = x[SeverityInfo2-10] + _ = x[SeverityInfo3-11] + _ = x[SeverityInfo4-12] + _ = x[SeverityWarn1-13] + _ = x[SeverityWarn2-14] + _ = x[SeverityWarn3-15] + _ = x[SeverityWarn4-16] + _ = x[SeverityError1-17] + _ = x[SeverityError2-18] + _ = x[SeverityError3-19] + _ = x[SeverityError4-20] + _ = x[SeverityFatal1-21] + _ = x[SeverityFatal2-22] + _ = x[SeverityFatal3-23] + _ = x[SeverityFatal4-24] +} + +const _Severity_name = "UNDEFINEDTRACETRACE2TRACE3TRACE4DEBUGDEBUG2DEBUG3DEBUG4INFOINFO2INFO3INFO4WARNWARN2WARN3WARN4ERRORERROR2ERROR3ERROR4FATALFATAL2FATAL3FATAL4" + +var _Severity_index = [...]uint8{0, 9, 14, 20, 26, 32, 37, 43, 49, 55, 59, 64, 69, 74, 78, 83, 88, 93, 98, 104, 110, 116, 121, 127, 133, 139} + +func (i Severity) String() string { + idx := int(i) - 0 + if i < 0 || idx >= len(_Severity_index)-1 { + return "Severity(" + strconv.FormatInt(int64(i), 10) + ")" + } + return _Severity_name[_Severity_index[idx]:_Severity_index[idx+1]] +} diff --git a/vendor/go.opentelemetry.io/otel/metric/meter.go b/vendor/go.opentelemetry.io/otel/metric/meter.go index 70ff4c7..9712415 100644 --- a/vendor/go.opentelemetry.io/otel/metric/meter.go +++ b/vendor/go.opentelemetry.io/otel/metric/meter.go @@ -320,7 +320,7 @@ type Observer interface { ObserveInt64(obsrv Int64Observable, value int64, opts ...ObserveOption) } -// Registration is an token representing the unique registration of a callback +// Registration is a token representing the unique registration of a callback // for a set of instruments with a Meter. // // Warning: Methods may be added to this interface in minor releases. See diff --git a/vendor/go.opentelemetry.io/otel/propagation/internal/hextable/hextable.go b/vendor/go.opentelemetry.io/otel/propagation/internal/hextable/hextable.go new file mode 100644 index 0000000..3d63244 --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/propagation/internal/hextable/hextable.go @@ -0,0 +1,32 @@ +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +// Package hextable provides a lookup table for decoding lowercase +// hexadecimal. +package hextable + +// Rev is a reverse hex lookup table for lowercase hex digits. Valid +// hexadecimal characters are indexed at their respective values. All other +// characters, including the upper-case A-F disallowed by the W3C trace +// context specification, are represented with '\xff'. +// +// The '\xff' character is used as invalid because no valid character has the +// upper 4 bits set. Meaning, an efficient validation can be performed over +// multiple character parsing by checking these bits remain zero. +const Rev = "" + + "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" + + "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" + + "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" + + "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\xff\xff\xff\xff\xff\xff" + + "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" + + "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" + + "\xff\x0a\x0b\x0c\x0d\x0e\x0f\xff\xff\xff\xff\xff\xff\xff\xff\xff" + + "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" + + "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" + + "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" + + "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" + + "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" + + "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" + + "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" + + "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" + + "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" diff --git a/vendor/go.opentelemetry.io/otel/propagation/trace_context.go b/vendor/go.opentelemetry.io/otel/propagation/trace_context.go index ffaa903..1eb36b8 100644 --- a/vendor/go.opentelemetry.io/otel/propagation/trace_context.go +++ b/vendor/go.opentelemetry.io/otel/propagation/trace_context.go @@ -9,6 +9,7 @@ import ( "fmt" "strings" + "go.opentelemetry.io/otel/propagation/internal/hextable" "go.opentelemetry.io/otel/trace" ) @@ -126,27 +127,23 @@ func (TraceContext) extract(carrier TextMapCarrier) trace.SpanContext { return sc } -// upperHex detect hex is upper case Unicode characters. -func upperHex(v string) bool { - for _, c := range v { - if c >= 'A' && c <= 'F' { - return true - } - } - return false -} - func extractPart(dst []byte, h *string, n int) bool { part, left, _ := strings.Cut(*h, delimiter) *h = left - // hex.Decode decodes unsupported upper-case characters, so exclude explicitly. - if len(part) != n || upperHex(part) { + if len(part) != n { return false } - if p, err := hex.Decode(dst, []byte(part)); err != nil || p != n/2 { - return false + // hextable.Rev maps every invalid character to 0xff, including the + // upper-case A-F the specification disallows. OR-ing every looked-up value + // together lets a single check detect any invalid character, because no + // valid value has the upper 4 bits set. + invalidMark := byte(0) + for i := 0; i < n; i += 2 { + hi, lo := hextable.Rev[part[i]], hextable.Rev[part[i+1]] + dst[i/2] = (hi << 4) | lo + invalidMark |= hi | lo } - return true + return invalidMark&0xf0 == 0 } // Fields returns the keys who's values are set with Inject. diff --git a/vendor/go.opentelemetry.io/otel/sdk/internal/attrnorm/dedup.go b/vendor/go.opentelemetry.io/otel/sdk/internal/attrnorm/dedup.go index fe9ddc9..d72cfb3 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/internal/attrnorm/dedup.go +++ b/vendor/go.opentelemetry.io/otel/sdk/internal/attrnorm/dedup.go @@ -28,40 +28,142 @@ type rawValue struct { slice any } -// Value returns value with all map values deduplicated and whether it changed. +type valueChanges uint8 + +const ( + depthLimitChanged valueChanges = 1 << iota + deduplicationChanged +) + +// ValueDedup returns value with all map values deduplicated and whether +// it changed. // // Duplicate map keys are resolved using last-value-wins semantics. -func Value(value attribute.Value) (attribute.Value, bool) { +func ValueDedup(value attribute.Value) (attribute.Value, bool) { switch value.Type() { case attribute.SLICE: - return deduplicateSliceValue(value) + return sliceValueDedup(value) case attribute.MAP: - return deduplicateMapValue(value) + return mapValueDedup(value) default: return value, false } } -// KeyValue returns kv with all map values deduplicated and whether it changed. -func KeyValue(kv attribute.KeyValue) (attribute.KeyValue, bool) { - value, changed := Value(kv.Value) +// ValueDedupLimitDepth returns value with all map values +// deduplicated and all array and map values limited to depthLimit. The boolean +// results report depth limiting and deduplication changes, respectively. +// +// Duplicate map keys are resolved using last-value-wins semantics. Depth +// starts at one for value and increments when descending into an array element +// or map value. An array or map beyond a non-negative depthLimit is replaced by +// an empty value. A negative depthLimit disables depth limiting. +func ValueDedupLimitDepth( + value attribute.Value, + depthLimit int, +) (attribute.Value, bool, bool) { + if depthLimit < 0 { + value, deduplicated := ValueDedup(value) + return value, false, deduplicated + } + + // Keep the common scalar and primitive-array cases in this wrapper. Routing + // them through the recursive, multi-result transform adds measurable + // overhead to the dominant simple attribute path. + switch value.Type() { + case attribute.BOOLSLICE, + attribute.INT64SLICE, + attribute.FLOAT64SLICE, + attribute.STRINGSLICE, + attribute.BYTESLICE: + if depthLimit == 0 { + return attribute.Value{}, true, false + } + return value, false, false + case attribute.SLICE, attribute.MAP: + default: + return value, false, false + } + + value, changes := valueDedupLimitDepth(value, depthLimit) + return value, changes&depthLimitChanged != 0, changes&deduplicationChanged != 0 +} + +// ValueLimitDepth returns value with all array and map values limited to +// depthLimit. Map keys are not deduplicated. +// +// Depth starts at one for value and increments when descending into an array +// element or map value. An array or map beyond a non-negative depthLimit is +// replaced by an empty value. A negative depthLimit disables depth limiting. +func ValueLimitDepth(value attribute.Value, depthLimit int) (attribute.Value, bool) { + if depthLimit < 0 { + return value, false + } + + switch value.Type() { + case attribute.BOOLSLICE, + attribute.INT64SLICE, + attribute.FLOAT64SLICE, + attribute.STRINGSLICE, + attribute.BYTESLICE: + if depthLimit == 0 { + return attribute.Value{}, true + } + return value, false + case attribute.SLICE, attribute.MAP: + default: + return value, false + } + + return valueLimitDepth(value, depthLimit) +} + +// KeyValueDedup returns kv with all map values deduplicated and whether +// it changed. +func KeyValueDedup(kv attribute.KeyValue) (attribute.KeyValue, bool) { + value, changed := ValueDedup(kv.Value) if changed { kv.Value = value } return kv, changed } -// KeyValues returns kvs with all map values deduplicated and whether they changed. +// KeyValueDedupLimitDepth returns kv with all map values +// deduplicated and all array and map values limited to depthLimit. The boolean +// results report depth limiting and deduplication changes, respectively. +func KeyValueDedupLimitDepth( + kv attribute.KeyValue, + depthLimit int, +) (attribute.KeyValue, bool, bool) { + value, depthLimited, deduplicated := ValueDedupLimitDepth(kv.Value, depthLimit) + if depthLimited || deduplicated { + kv.Value = value + } + return kv, depthLimited, deduplicated +} + +// KeyValueLimitDepth returns kv with all array and map values limited to +// depthLimit. Map keys are not deduplicated. +func KeyValueLimitDepth(kv attribute.KeyValue, depthLimit int) (attribute.KeyValue, bool) { + value, changed := ValueLimitDepth(kv.Value, depthLimit) + if changed { + kv.Value = value + } + return kv, changed +} + +// KeyValuesDedup returns kvs with all map values deduplicated and whether +// they changed. // // The returned slice is the original kvs slice if no value needs // deduplication. Top-level keys in kvs are not deduplicated. -func KeyValues(kvs []attribute.KeyValue) ([]attribute.KeyValue, bool) { +func KeyValuesDedup(kvs []attribute.KeyValue) ([]attribute.KeyValue, bool) { // Preserve the caller's slice on the common no-op path. Once a changed // value is found, copy the prior values exactly once and fill the rest in // place as the scan continues. var normalized []attribute.KeyValue for i, kv := range kvs { - kv, changed := KeyValue(kv) + kv, changed := KeyValueDedup(kv) if normalized != nil { normalized[i] = kv continue @@ -80,22 +182,67 @@ func KeyValues(kvs []attribute.KeyValue) ([]attribute.KeyValue, bool) { return normalized, true } -// Set returns set with all map values deduplicated and whether it changed. +// KeyValuesDedupLimitDepth returns kvs with all map values +// deduplicated and all array and map values limited to depthLimit. The boolean +// results report depth limiting and deduplication changes, respectively. +// +// The returned slice is the original kvs slice if no value needs +// normalization. Top-level keys in kvs are not deduplicated. +func KeyValuesDedupLimitDepth( + kvs []attribute.KeyValue, + depthLimit int, +) ([]attribute.KeyValue, bool, bool) { + if depthLimit < 0 { + kvs, deduplicated := KeyValuesDedup(kvs) + return kvs, false, deduplicated + } + + var normalized []attribute.KeyValue + var allChanges valueChanges + for i, kv := range kvs { + value, changes := valueDedupLimitDepth(kv.Value, depthLimit) + allChanges |= changes + if changes != 0 { + kv.Value = value + } + if normalized != nil { + normalized[i] = kv + continue + } + if changes == 0 { + continue + } + + normalized = make([]attribute.KeyValue, len(kvs)) + copy(normalized, kvs[:i]) + normalized[i] = kv + } + if normalized == nil { + return kvs, false, false + } + return normalized, + allChanges&depthLimitChanged != 0, + allChanges&deduplicationChanged != 0 +} + +// SetDedup returns set with all map values deduplicated and whether it +// changed. // // The returned Set is the original set if no value needs deduplication. // Top-level key uniqueness remains attribute.Set's responsibility; this only // normalizes map attribute values. -func Set(set attribute.Set) (attribute.Set, bool) { - if set.Len() == 0 { +func SetDedup(set attribute.Set) (attribute.Set, bool) { + length := set.Len() + if length == 0 { return set, false } // Most attribute sets contain no duplicate map keys. Delay allocation until // the first changed value so the no-op path returns the original Set. var normalized []attribute.KeyValue - for i := range set.Len() { + for i := range length { kv, _ := set.Get(i) - kv, changed := KeyValue(kv) + kv, changed := KeyValueDedup(kv) if normalized != nil { normalized = append(normalized, kv) continue @@ -104,7 +251,7 @@ func Set(set attribute.Set) (attribute.Set, bool) { continue } - normalized = make([]attribute.KeyValue, 0, set.Len()) + normalized = make([]attribute.KeyValue, 0, length) for j := range i { prior, _ := set.Get(j) normalized = append(normalized, prior) @@ -118,7 +265,359 @@ func Set(set attribute.Set) (attribute.Set, bool) { return attribute.NewSet(normalized...), true } -func deduplicateSliceValue(value attribute.Value) (attribute.Value, bool) { +// SetDedupLimitDepth returns set with all map values deduplicated and +// all array and map values limited to depthLimit. The boolean results report +// depth limiting and deduplication changes, respectively. +// +// The returned Set is the original set if no value needs normalization. +// Top-level key uniqueness remains attribute.Set's responsibility; this only +// normalizes attribute values. +func SetDedupLimitDepth( + set attribute.Set, + depthLimit int, +) (attribute.Set, bool, bool) { + if depthLimit < 0 { + set, deduplicated := SetDedup(set) + return set, false, deduplicated + } + length := set.Len() + if length == 0 { + return set, false, false + } + + var normalized []attribute.KeyValue + var allChanges valueChanges + for i := range length { + kv, _ := set.Get(i) + value, changes := valueDedupLimitDepth(kv.Value, depthLimit) + allChanges |= changes + if changes != 0 { + kv.Value = value + } + if normalized != nil { + normalized = append(normalized, kv) + continue + } + if changes == 0 { + continue + } + + normalized = make([]attribute.KeyValue, 0, length) + for j := range i { + prior, _ := set.Get(j) + normalized = append(normalized, prior) + } + normalized = append(normalized, kv) + } + if normalized == nil { + return set, false, false + } + return attribute.NewSet(normalized...), + allChanges&depthLimitChanged != 0, + allChanges&deduplicationChanged != 0 +} + +// SetLimitDepth returns set with all array and map values limited to +// depthLimit. Map keys are not deduplicated. +// +// The returned Set is the original set if no value changes. +func SetLimitDepth(set attribute.Set, depthLimit int) (attribute.Set, bool) { + if depthLimit < 0 { + return set, false + } + length := set.Len() + if length == 0 { + return set, false + } + + var normalized []attribute.KeyValue + for i := range length { + kv, _ := set.Get(i) + value, changed := valueLimitDepth(kv.Value, depthLimit) + if changed { + kv.Value = value + } + if normalized != nil { + normalized = append(normalized, kv) + continue + } + if !changed { + continue + } + + normalized = make([]attribute.KeyValue, 0, length) + for j := range i { + prior, _ := set.Get(j) + normalized = append(normalized, prior) + } + normalized = append(normalized, kv) + } + if normalized == nil { + return set, false + } + return attribute.NewSet(normalized...), true +} + +// valueDedupLimitDepth combines depth limiting with recursive map +// deduplication. remainingDepth is non-negative. It checks the remaining +// budget before reading collection storage and lazily rebuilds only changed +// ancestry. +func valueDedupLimitDepth( + value attribute.Value, + remainingDepth int, +) (attribute.Value, valueChanges) { + switch value.Type() { + case attribute.BOOLSLICE, + attribute.INT64SLICE, + attribute.FLOAT64SLICE, + attribute.STRINGSLICE, + attribute.BYTESLICE: + if remainingDepth == 0 { + return attribute.Value{}, depthLimitChanged + } + case attribute.SLICE: + if remainingDepth == 0 { + return attribute.Value{}, depthLimitChanged + } + return sliceValueDedupLimitDepth(value, remainingDepth) + case attribute.MAP: + if remainingDepth == 0 { + return attribute.Value{}, depthLimitChanged + } + return mapValueDedupLimitDepth(value, remainingDepth) + } + return value, 0 +} + +// valueLimitDepth limits collection depth while preserving duplicate map keys. +func valueLimitDepth( + value attribute.Value, + remainingDepth int, +) (attribute.Value, bool) { + switch value.Type() { + case attribute.BOOLSLICE, + attribute.INT64SLICE, + attribute.FLOAT64SLICE, + attribute.STRINGSLICE, + attribute.BYTESLICE: + if remainingDepth == 0 { + return attribute.Value{}, true + } + case attribute.SLICE: + if remainingDepth == 0 { + return attribute.Value{}, true + } + return sliceValueLimitDepth(value, remainingDepth) + case attribute.MAP: + if remainingDepth == 0 { + return attribute.Value{}, true + } + return mapValueLimitDepth(value, remainingDepth) + } + return value, false +} + +func sliceValueDedupLimitDepth( + value attribute.Value, + remainingDepth int, +) (attribute.Value, valueChanges) { + storage := valueStorage(value) + length := valueLen(storage) + if length <= 1 { + if length == 1 { + elem := valueAt(storage, 0) + newElem, changes := valueDedupLimitDepth( + elem, + remainingDepth-1, + ) + if changes != 0 { + return attribute.SliceValue(newElem), changes + } + } + return value, 0 + } + + var normalized []attribute.Value + var allChanges valueChanges + for i := range length { + elem := valueAt(storage, i) + newElem, changes := valueDedupLimitDepth( + elem, + remainingDepth-1, + ) + allChanges |= changes + if normalized != nil { + normalized[i] = newElem + continue + } + if changes == 0 { + continue + } + + normalized = make([]attribute.Value, length) + for j := range i { + normalized[j] = valueAt(storage, j) + } + normalized[i] = newElem + } + if normalized == nil { + return value, 0 + } + return attribute.SliceValue(normalized...), allChanges +} + +func sliceValueLimitDepth( + value attribute.Value, + remainingDepth int, +) (attribute.Value, bool) { + storage := valueStorage(value) + length := valueLen(storage) + if length <= 1 { + if length == 1 { + elem := valueAt(storage, 0) + newElem, changed := valueLimitDepth(elem, remainingDepth-1) + if changed { + return attribute.SliceValue(newElem), true + } + } + return value, false + } + + var normalized []attribute.Value + for i := range length { + elem := valueAt(storage, i) + newElem, changed := valueLimitDepth(elem, remainingDepth-1) + if normalized != nil { + normalized[i] = newElem + continue + } + if !changed { + continue + } + + normalized = make([]attribute.Value, length) + for j := range i { + normalized[j] = valueAt(storage, j) + } + normalized[i] = newElem + } + if normalized == nil { + return value, false + } + return attribute.SliceValue(normalized...), true +} + +func mapValueDedupLimitDepth( + value attribute.Value, + remainingDepth int, +) (attribute.Value, valueChanges) { + storage := valueStorage(value) + length := keyValueLen(storage) + if length <= 1 { + if length == 1 { + kv := keyValueAt(storage, 0) + newValue, changes := valueDedupLimitDepth( + kv.Value, + remainingDepth-1, + ) + if changes != 0 { + kv.Value = newValue + return attribute.MapValue(kv), changes + } + } + return value, 0 + } + + var normalized []attribute.KeyValue + var allChanges valueChanges + for i := 0; i < length; { + // attribute.MapValue stores key-values sorted by key using a stable + // sort. Only the last entry in an equal-key run survives, so avoid + // traversing values that will be discarded. + first := keyValueAt(storage, i) + j := i + 1 + for j < length && keyValueAt(storage, j).Key == first.Key { + j++ + } + + kv := keyValueAt(storage, j-1) + newValue, changes := valueDedupLimitDepth( + kv.Value, + remainingDepth-1, + ) + if changes != 0 { + kv.Value = newValue + } + if j-i > 1 { + changes |= deduplicationChanged + } + allChanges |= changes + if normalized != nil { + normalized = append(normalized, kv) + } else if changes != 0 { + if i == 0 && j == length { + return attribute.MapValue(kv), allChanges + } + normalized = make([]attribute.KeyValue, 0, length-(j-i-1)) + for k := range i { + normalized = append(normalized, keyValueAt(storage, k)) + } + normalized = append(normalized, kv) + } + i = j + } + if normalized == nil { + return value, 0 + } + return attribute.MapValue(normalized...), allChanges +} + +func mapValueLimitDepth( + value attribute.Value, + remainingDepth int, +) (attribute.Value, bool) { + storage := valueStorage(value) + length := keyValueLen(storage) + if length <= 1 { + if length == 1 { + kv := keyValueAt(storage, 0) + newValue, changed := valueLimitDepth(kv.Value, remainingDepth-1) + if changed { + kv.Value = newValue + return attribute.MapValue(kv), true + } + } + return value, false + } + + var normalized []attribute.KeyValue + for i := range length { + kv := keyValueAt(storage, i) + newValue, changed := valueLimitDepth(kv.Value, remainingDepth-1) + if changed { + kv.Value = newValue + } + if normalized != nil { + normalized[i] = kv + continue + } + if !changed { + continue + } + + normalized = make([]attribute.KeyValue, length) + for j := range i { + normalized[j] = keyValueAt(storage, j) + } + normalized[i] = kv + } + if normalized == nil { + return value, false + } + return attribute.MapValue(normalized...), true +} + +func sliceValueDedup(value attribute.Value) (attribute.Value, bool) { storage := valueStorage(value) length := valueLen(storage) @@ -127,7 +626,7 @@ func deduplicateSliceValue(value attribute.Value) (attribute.Value, bool) { var normalized []attribute.Value for i := range length { elem := valueAt(storage, i) - elem, changed := Value(elem) + elem, changed := ValueDedup(elem) if normalized != nil { normalized[i] = elem continue @@ -148,14 +647,14 @@ func deduplicateSliceValue(value attribute.Value) (attribute.Value, bool) { return attribute.SliceValue(normalized...), true } -func deduplicateMapValue(value attribute.Value) (attribute.Value, bool) { +func mapValueDedup(value attribute.Value) (attribute.Value, bool) { storage := valueStorage(value) length := keyValueLen(storage) if length <= 1 { // A single map entry cannot duplicate its own key, but its value might // contain a map or slice that needs recursive normalization. if length == 1 { - kv, changed := KeyValue(keyValueAt(storage, 0)) + kv, changed := KeyValueDedup(keyValueAt(storage, 0)) if changed { return attribute.MapValue(kv), true } @@ -174,13 +673,16 @@ func deduplicateMapValue(value attribute.Value) (attribute.Value, bool) { j++ } - kv, nestedChanged := KeyValue(keyValueAt(storage, j-1)) + kv, nestedChanged := KeyValueDedup(keyValueAt(storage, j-1)) // j-i > 1 means the current key run contained duplicates. changed := nestedChanged || j-i > 1 if normalized != nil { normalized = append(normalized, kv) } else if changed { - normalized = make([]attribute.KeyValue, 0, length) + if i == 0 && j == length { + return attribute.MapValue(kv), true + } + normalized = make([]attribute.KeyValue, 0, length-(j-i-1)) for k := range i { normalized = append(normalized, keyValueAt(storage, k)) } diff --git a/vendor/go.opentelemetry.io/otel/sdk/internal/attrnorm/truncate.go b/vendor/go.opentelemetry.io/otel/sdk/internal/attrnorm/truncate.go index c834159..db7c538 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/internal/attrnorm/truncate.go +++ b/vendor/go.opentelemetry.io/otel/sdk/internal/attrnorm/truncate.go @@ -7,7 +7,7 @@ package attrnorm import ( - "slices" + "reflect" "strings" "unicode/utf8" @@ -26,43 +26,24 @@ func Truncate(limit int, attr attribute.KeyValue) attribute.KeyValue { if limit < 0 { return attr } + + // Keep scalar cases in this wrapper. Routing them through the recursive, + // multi-result transform adds measurable overhead to the dominant simple + // attribute path. switch attr.Value.Type() { case attribute.STRING: - v := attr.Value.AsString() - return attr.Key.String(truncate(limit, v)) - case attribute.STRINGSLICE: - v := attr.Value.AsStringSlice() - for i := range v { - v[i] = truncate(limit, v[i]) - } - return attr.Key.StringSlice(v) + attr.Value = attribute.StringValue(truncate(limit, attr.Value.AsString())) case attribute.BYTESLICE: - v := attr.Value.AsString() - if len(v) > limit { - return attr.Key.ByteSlice([]byte(v[:limit])) + s := attr.Value.AsString() + if len(s) > limit { + attr.Value = attribute.ByteSliceValue([]byte(s[:limit])) } - return attr + case attribute.STRINGSLICE: + attr.Value, _ = truncateStringSliceValue(limit, attr.Value) case attribute.SLICE: - v := attr.Value.AsSlice() - if !slices.ContainsFunc(v, func(e attribute.Value) bool { return needsTruncation(limit, e) }) { - return attr - } - newV := make([]attribute.Value, len(v)) - for i, elem := range v { - newV[i] = TruncateValue(limit, elem) - } - return attr.Key.Slice(newV...) + attr.Value, _ = truncateSliceValue(limit, attr.Value) case attribute.MAP: - v := attr.Value.AsMap() - if !slices.ContainsFunc(v, func(kv attribute.KeyValue) bool { return needsTruncation(limit, kv.Value) }) { - return attr - } - newV := make([]attribute.KeyValue, len(v)) - for i, elem := range v { - elem.Value = TruncateValue(limit, elem.Value) - newV[i] = elem - } - return attr.Key.Map(newV...) + attr.Value, _ = truncateMapValue(limit, attr.Value) } return attr } @@ -76,85 +57,275 @@ func TruncateValue(limit int, v attribute.Value) attribute.Value { return v } + // Match Truncate's direct scalar path to avoid paying for the recursive, + // multi-result transform when no composite traversal is needed. switch v.Type() { case attribute.STRING: return attribute.StringValue(truncate(limit, v.AsString())) - case attribute.STRINGSLICE: - ss := v.AsStringSlice() - for i := range ss { - ss[i] = truncate(limit, ss[i]) - } - return attribute.StringSliceValue(ss) case attribute.BYTESLICE: - // len(v.AsString()) is identical to len(v.AsByteSlice()) but - // avoids allocating the full slice before truncation. s := v.AsString() - if limit >= 0 && len(s) > limit { + if len(s) > limit { return attribute.ByteSliceValue([]byte(s[:limit])) } + case attribute.STRINGSLICE: + v, _ = truncateStringSliceValue(limit, v) case attribute.SLICE: - sl := v.AsSlice() - if !slices.ContainsFunc(sl, func(e attribute.Value) bool { return needsTruncation(limit, e) }) { - return v - } - newSl := make([]attribute.Value, len(sl)) - for i, elem := range sl { - newSl[i] = TruncateValue(limit, elem) - } - return attribute.SliceValue(newSl...) + v, _ = truncateSliceValue(limit, v) case attribute.MAP: - m := v.AsMap() - if !slices.ContainsFunc(m, func(kv attribute.KeyValue) bool { return needsTruncation(limit, kv.Value) }) { - return v - } - newM := make([]attribute.KeyValue, len(m)) - for i, elem := range m { - elem.Value = TruncateValue(limit, elem.Value) - newM[i] = elem - } - return attribute.MapValue(newM...) + v, _ = truncateMapValue(limit, v) } return v } -// stringNeedsTruncation reports whether s would be modified by truncate for the -// given limit. -func stringNeedsTruncation(limit int, s string) bool { - if limit < 0 || len(s) <= limit { - return false - } - return utf8.RuneCountInString(s) > limit || !utf8.ValidString(s) -} - -// needsTruncation reports whether v would be modified by TruncateValue for the -// given limit. -func needsTruncation(limit int, v attribute.Value) bool { +// truncateValue traverses composite values once and rebuilds them lazily on +// the first changed child. Recursion provides O(depth) temporary stack space +// without forcing a heap allocation on the common no-op path. +func truncateValue(limit int, v attribute.Value) (attribute.Value, bool) { switch v.Type() { case attribute.STRING: - return stringNeedsTruncation(limit, v.AsString()) - case attribute.BYTESLICE: - // len(v.AsString()) is identical to len(v.AsByteSlice()) but - // avoids memory allocation. - if limit >= 0 && len(v.AsString()) > limit { - return true + s := v.AsString() + truncated := truncate(limit, s) + if truncated != s { + return attribute.StringValue(truncated), true } case attribute.STRINGSLICE: - for _, s := range v.AsStringSlice() { - if stringNeedsTruncation(limit, s) { - return true - } + return truncateStringSliceValue(limit, v) + case attribute.BYTESLICE: + // len(v.AsString()) is identical to len(v.AsByteSlice()) but + // avoids allocating the full slice before truncation. + s := v.AsString() + if len(s) > limit { + return attribute.ByteSliceValue([]byte(s[:limit])), true } case attribute.SLICE: - return slices.ContainsFunc(v.AsSlice(), func(e attribute.Value) bool { return needsTruncation(limit, e) }) + return truncateSliceValue(limit, v) case attribute.MAP: - return slices.ContainsFunc( - v.AsMap(), - func(kv attribute.KeyValue) bool { return needsTruncation(limit, kv.Value) }, - ) + return truncateMapValue(limit, v) } - return false + return v, false } +func truncateStringSliceValue(limit int, value attribute.Value) (attribute.Value, bool) { + storage := valueStorage(value) + switch values := storage.(type) { + case [0]string: + return value, false + case [1]string: + return truncateStrings(limit, value, values[:]) + case [2]string: + return truncateStrings(limit, value, values[:]) + case [3]string: + return truncateStrings(limit, value, values[:]) + default: + array := reflect.ValueOf(storage) + if array.Kind() != reflect.Array || array.Type().Elem() != stringType { + return value, false + } + return truncateStringArray(limit, value, array) + } +} + +func truncateStrings(limit int, value attribute.Value, values []string) (attribute.Value, bool) { + var truncated []string + for i, s := range values { + newS := truncate(limit, s) + if truncated != nil { + truncated[i] = newS + continue + } + if newS == s { + continue + } + + truncated = make([]string, len(values)) + copy(truncated, values[:i]) + truncated[i] = newS + } + if truncated == nil { + return value, false + } + return attribute.StringSliceValue(truncated), true +} + +func truncateStringArray(limit int, value attribute.Value, values reflect.Value) (attribute.Value, bool) { + var truncated []string + for i := range values.Len() { + s := values.Index(i).String() + newS := truncate(limit, s) + if truncated != nil { + truncated[i] = newS + continue + } + if newS == s { + continue + } + + truncated = make([]string, values.Len()) + for j := range i { + truncated[j] = values.Index(j).String() + } + truncated[i] = newS + } + if truncated == nil { + return value, false + } + return attribute.StringSliceValue(truncated), true +} + +func truncateSliceValue(limit int, value attribute.Value) (attribute.Value, bool) { + storage := valueStorage(value) + switch values := storage.(type) { + case [0]attribute.Value: + return value, false + case [1]attribute.Value: + return truncateValueSlice(limit, value, values[:]) + case [2]attribute.Value: + return truncateValueSlice(limit, value, values[:]) + case [3]attribute.Value: + return truncateValueSlice(limit, value, values[:]) + case [4]attribute.Value: + return truncateValueSlice(limit, value, values[:]) + case [5]attribute.Value: + return truncateValueSlice(limit, value, values[:]) + default: + array := reflect.ValueOf(storage) + if array.Kind() != reflect.Array || array.Type().Elem() != valueType { + return value, false + } + return truncateValueArray(limit, value, array) + } +} + +func truncateValueSlice(limit int, value attribute.Value, values []attribute.Value) (attribute.Value, bool) { + var truncated []attribute.Value + for i, elem := range values { + newElem, changed := truncateValue(limit, elem) + if truncated != nil { + truncated[i] = newElem + continue + } + if !changed { + continue + } + + truncated = make([]attribute.Value, len(values)) + copy(truncated, values[:i]) + truncated[i] = newElem + } + if truncated == nil { + return value, false + } + return attribute.SliceValue(truncated...), true +} + +func truncateValueArray(limit int, value attribute.Value, values reflect.Value) (attribute.Value, bool) { + var truncated []attribute.Value + for i := range values.Len() { + elem := values.Index(i).Interface().(attribute.Value) + newElem, changed := truncateValue(limit, elem) + if truncated != nil { + truncated[i] = newElem + continue + } + if !changed { + continue + } + + truncated = make([]attribute.Value, values.Len()) + for j := range i { + truncated[j] = values.Index(j).Interface().(attribute.Value) + } + truncated[i] = newElem + } + if truncated == nil { + return value, false + } + return attribute.SliceValue(truncated...), true +} + +func truncateMapValue(limit int, value attribute.Value) (attribute.Value, bool) { + storage := valueStorage(value) + switch keyValues := storage.(type) { + case [0]attribute.KeyValue: + return value, false + case [1]attribute.KeyValue: + return truncateKeyValueSlice(limit, value, keyValues[:]) + case [2]attribute.KeyValue: + return truncateKeyValueSlice(limit, value, keyValues[:]) + case [3]attribute.KeyValue: + return truncateKeyValueSlice(limit, value, keyValues[:]) + case [4]attribute.KeyValue: + return truncateKeyValueSlice(limit, value, keyValues[:]) + case [5]attribute.KeyValue: + return truncateKeyValueSlice(limit, value, keyValues[:]) + default: + array := reflect.ValueOf(storage) + if array.Kind() != reflect.Array || array.Type().Elem() != keyValueType { + return value, false + } + return truncateKeyValueArray(limit, value, array) + } +} + +func truncateKeyValueSlice( + limit int, + value attribute.Value, + keyValues []attribute.KeyValue, +) (attribute.Value, bool) { + var truncated []attribute.KeyValue + for i, kv := range keyValues { + newValue, changed := truncateValue(limit, kv.Value) + if changed { + kv.Value = newValue + } + if truncated != nil { + truncated[i] = kv + continue + } + if !changed { + continue + } + + truncated = make([]attribute.KeyValue, len(keyValues)) + copy(truncated, keyValues[:i]) + truncated[i] = kv + } + if truncated == nil { + return value, false + } + return attribute.MapValue(truncated...), true +} + +func truncateKeyValueArray(limit int, value attribute.Value, keyValues reflect.Value) (attribute.Value, bool) { + var truncated []attribute.KeyValue + for i := range keyValues.Len() { + kv := keyValues.Index(i).Interface().(attribute.KeyValue) + newValue, changed := truncateValue(limit, kv.Value) + if changed { + kv.Value = newValue + } + if truncated != nil { + truncated[i] = kv + continue + } + if !changed { + continue + } + + truncated = make([]attribute.KeyValue, keyValues.Len()) + for j := range i { + truncated[j] = keyValues.Index(j).Interface().(attribute.KeyValue) + } + truncated[i] = kv + } + if truncated == nil { + return value, false + } + return attribute.MapValue(truncated...), true +} + +var stringType = reflect.TypeFor[string]() + // truncate returns a version of s truncated according to limit. // // If limit is negative, it returns the original string. @@ -168,7 +339,7 @@ func truncate(limit int, s string) string { // This prioritizes performance in the following order based on the most // common expected use cases. // - // - Values shorter than the default limit (128). + // - Values whose byte length does not exceed the limit. // - Strings with valid encodings that exceed the limit. // - No limit. // - Strings with invalid encodings that exceed the limit. @@ -188,14 +359,27 @@ func truncate(limit int, s string) string { continue } + // A zero limit also truncates a leading invalid byte or U+FFFD. + if limit == 0 { + return "" + } + // Range reports RuneError for both an invalid byte and a valid U+FFFD. + // Only a size-1 decoding indicates invalid UTF-8. _, size := utf8.DecodeRuneInString(s[i:]) if size == 1 { - // Invalid encoding. + // Removing this byte makes len(s)-1 an upper bound for a rebuilt + // result. Keep the valid prefix before rescanning s[i:]. b.Grow(len(s) - 1) _, _ = b.WriteString(s[:i]) s = s[i:] break } + + // A valid U+FFFD still consumes one character of the limit. + count++ + if count > limit { + return s[:i] + } } // Fast-path, no invalid input. @@ -203,7 +387,9 @@ func truncate(limit int, s string) string { return s } - // Truncate while validating UTF-8. + // The builder holds the valid prefix before the first invalid byte, and + // count includes its runes. Skip malformed bytes without counting them + // while copying the remaining valid runes up to the limit. for i := 0; i < len(s) && count < limit; { c := s[i] if c < utf8.RuneSelf { diff --git a/vendor/go.opentelemetry.io/otel/sdk/resource/resource.go b/vendor/go.opentelemetry.io/otel/sdk/resource/resource.go index dcd7280..1ab929a 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/resource/resource.go +++ b/vendor/go.opentelemetry.io/otel/sdk/resource/resource.go @@ -90,7 +90,7 @@ func NewSchemaless(attrs ...attribute.KeyValue) *Resource { return &Resource{} } - attrs, _ = attrnorm.KeyValues(attrs) + attrs, _ = attrnorm.KeyValuesDedup(attrs) // Ensure attributes comply with the specification: // https://github.com/open-telemetry/opentelemetry-specification/blob/v1.20.0/specification/common/README.md#attribute diff --git a/vendor/go.opentelemetry.io/otel/sdk/trace/internal/observ/batch_span_processor.go b/vendor/go.opentelemetry.io/otel/sdk/trace/internal/observ/batch_span_processor.go index 896ed51..b55750a 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/trace/internal/observ/batch_span_processor.go +++ b/vendor/go.opentelemetry.io/otel/sdk/trace/internal/observ/batch_span_processor.go @@ -47,6 +47,8 @@ type BSP struct { processedQueueFullOpts []metric.AddOption } +// NewBSP creates new instrumentation for a BatchSpanProcessor. +// It returns nil if observability is not enabled. func NewBSP(id int64, qLen func() int64, qMax int64) (*BSP, error) { if !x.Observability.Enabled() { return nil, nil @@ -108,12 +110,16 @@ func NewBSP(id int64, qLen func() int64, qMax int64) (*BSP, error) { }, err } +// Shutdown unregisters the callbacks registered by NewBSP. func (b *BSP) Shutdown() error { return b.reg.Unregister() } +// Processed records n spans as having finished processing successfully. func (b *BSP) Processed(ctx context.Context, n int64) { b.processed.Add(ctx, n, b.processedOpts...) } +// ProcessedQueueFull records n spans as having finished processing with a +// queue-full error. func (b *BSP) ProcessedQueueFull(ctx context.Context, n int64) { b.processed.Add(ctx, n, b.processedQueueFullOpts...) } diff --git a/vendor/go.opentelemetry.io/otel/sdk/trace/internal/observ/tracer.go b/vendor/go.opentelemetry.io/otel/sdk/trace/internal/observ/tracer.go index 3428aa8..16fad3c 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/trace/internal/observ/tracer.go +++ b/vendor/go.opentelemetry.io/otel/sdk/trace/internal/observ/tracer.go @@ -30,6 +30,8 @@ type Tracer struct { started metric.Int64Counter } +// NewTracer creates new instrumentation for a Tracer. +// It returns an empty, disabled Tracer if observability is not enabled. func NewTracer() (Tracer, error) { if !x.Observability.Enabled() { return Tracer{}, nil @@ -52,8 +54,11 @@ func NewTracer() (Tracer, error) { return Tracer{enabled: true, live: l.Inst(), started: s.Inst()}, err } +// Enabled returns whether observability is enabled for t. func (t Tracer) Enabled() bool { return t.enabled } +// SpanStarted records the start of span, which was created with psc as its +// parent span context. func (t Tracer) SpanStarted(ctx context.Context, psc trace.SpanContext, span trace.Span) { if !t.started.Enabled(ctx) { return @@ -84,10 +89,12 @@ func (t Tracer) SpanStarted(ctx context.Context, psc trace.SpanContext, span tra t.started.Add(ctx, 1, opts...) } +// SpanLive records span as a live span. func (t Tracer) SpanLive(ctx context.Context, span trace.Span) { t.spanLive(ctx, 1, span) } +// SpanEnded records span as no longer being live. func (t Tracer) SpanEnded(ctx context.Context, span trace.Span) { t.spanLive(ctx, -1, span) } diff --git a/vendor/go.opentelemetry.io/otel/sdk/trace/provider.go b/vendor/go.opentelemetry.io/otel/sdk/trace/provider.go index 6b23684..ce615a1 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/trace/provider.go +++ b/vendor/go.opentelemetry.io/otel/sdk/trace/provider.go @@ -150,7 +150,10 @@ func (p *TracerProvider) Tracer(name string, opts ...trace.TracerOption) trace.T return noop.NewTracerProvider().Tracer(name, opts...) } c := trace.NewTracerConfig(opts...) - attrs, _ := attrnorm.Set(c.InstrumentationAttributes()) + attrs, _, _ := attrnorm.SetDedupLimitDepth( + c.InstrumentationAttributes(), + p.spanLimits.AttributeValueDepthLimit, + ) if name == "" { name = defaultTracerName } @@ -255,13 +258,14 @@ func (p *TracerProvider) UnregisterSpanProcessor(sp SpanProcessor) { idx = i } } - if stopOnce != nil { - stopOnce.state.Do(func() { - if err := sp.Shutdown(context.Background()); err != nil { - otel.Handle(err) - } - }) + if stopOnce == nil { + return } + stopOnce.state.Do(func() { + if err := sp.Shutdown(context.Background()); err != nil { + otel.Handle(err) + } + }) if len(spss) > 1 { copy(spss[idx:], spss[idx+1:]) } @@ -429,6 +433,29 @@ func WithSampler(s Sampler) TracerProviderOption { }) } +// WithAttributeValueDepthLimit sets the maximum allowed depth for attribute +// values. Depth starts at one for the top-level value and increments when +// descending into an array element or map value. An array or map beyond this +// depth is replaced by an empty value. +// +// This limit applies to span, event, link, and instrumentation scope +// attributes processed by this TracerProvider. It does not apply to Resource +// attributes. +// +// Setting this to zero means the default limit of 64 is used. Setting this to +// a negative value means no limit is applied. +// +// There is no environment variable for this limit. +func WithAttributeValueDepthLimit(limit int) TracerProviderOption { + if limit == 0 { + limit = DefaultAttributeValueDepthLimit + } + return traceProviderOptionFunc(func(cfg tracerProviderConfig) tracerProviderConfig { + cfg.spanLimits.AttributeValueDepthLimit = limit + return cfg + }) +} + // WithSpanLimits returns a TracerProviderOption that configures a // TracerProvider to use the SpanLimits sl. These SpanLimits bound any Span // created by a Tracer from the TracerProvider. @@ -448,6 +475,9 @@ func WithSpanLimits(sl SpanLimits) TracerProviderOption { if sl.AttributeValueLengthLimit <= 0 { sl.AttributeValueLengthLimit = DefaultAttributeValueLengthLimit } + if sl.AttributeValueDepthLimit <= 0 { + sl.AttributeValueDepthLimit = DefaultAttributeValueDepthLimit + } if sl.AttributeCountLimit <= 0 { sl.AttributeCountLimit = DefaultAttributeCountLimit } @@ -473,13 +503,14 @@ func WithSpanLimits(sl SpanLimits) TracerProviderOption { // TracerProvider to use these limits. These limits bound any Span created by // a Tracer from the TracerProvider. // -// The limits will be used as-is. Zero or negative values will not be changed -// to the default value like WithSpanLimits does. Setting a limit to zero will -// effectively disable the related resource it limits and setting to a -// negative value will mean that resource is unlimited. Consequentially, this -// means that the zero-value SpanLimits will disable all span resources. -// Because of this, limits should be constructed using NewSpanLimits and -// updated accordingly. +// The limits will be used as-is, except that an AttributeValueDepthLimit of +// zero means the default limit is used. Other zero or negative values will not +// be changed to the default value like WithSpanLimits does. Setting a limit to +// zero will effectively disable the related resource it limits and setting to +// a negative value will mean that resource is unlimited. Consequentially, the +// zero-value SpanLimits will disable all span resources except the attribute +// value depth limit. Because of this, limits should be constructed using +// NewSpanLimits and updated accordingly. // // If this or WithSpanLimits are not provided, the TracerProvider will use the // limits defined by environment variables, or the defaults if unset. Refer to @@ -525,5 +556,8 @@ func ensureValidTracerProviderConfig(cfg tracerProviderConfig) tracerProviderCon if cfg.resource == nil { cfg.resource = resource.Default() } + if cfg.spanLimits.AttributeValueDepthLimit == 0 { + cfg.spanLimits.AttributeValueDepthLimit = DefaultAttributeValueDepthLimit + } return cfg } diff --git a/vendor/go.opentelemetry.io/otel/sdk/trace/sampler_env.go b/vendor/go.opentelemetry.io/otel/sdk/trace/sampler_env.go index b0fa94e..76cca5c 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/trace/sampler_env.go +++ b/vendor/go.opentelemetry.io/otel/sdk/trace/sampler_env.go @@ -46,14 +46,13 @@ func (e samplerArgParseError) Unwrap() error { } func samplerFromEnv() (Sampler, error) { - sampler, ok := os.LookupEnv(tracesSamplerKey) - if !ok { + sampler := strings.ToLower(strings.TrimSpace(os.Getenv(tracesSamplerKey))) + if sampler == "" { return nil, nil } - sampler = strings.ToLower(strings.TrimSpace(sampler)) - samplerArg, hasSamplerArg := os.LookupEnv(tracesSamplerArgKey) - samplerArg = strings.TrimSpace(samplerArg) + samplerArg := strings.TrimSpace(os.Getenv(tracesSamplerArgKey)) + hasSamplerArg := samplerArg != "" switch sampler { case samplerAlwaysOn: diff --git a/vendor/go.opentelemetry.io/otel/sdk/trace/simple_span_processor.go b/vendor/go.opentelemetry.io/otel/sdk/trace/simple_span_processor.go index 97985c4..1e6be12 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/trace/simple_span_processor.go +++ b/vendor/go.opentelemetry.io/otel/sdk/trace/simple_span_processor.go @@ -104,10 +104,15 @@ func (ssp *simpleSpanProcessor) Shutdown(ctx context.Context) error { // span would need to be exported. Meaning, OnEnd would be called and // try acquiring the lock that is held here. ssp.exporterMu.Lock() - done, shutdown := stopFunc(ssp.exporter) + exp := ssp.exporter ssp.exporter = nil ssp.exporterMu.Unlock() + if exp == nil { + return + } + + done, shutdown := stopFunc(exp) go shutdown() // Wait for the exporter to shut down or the deadline to expire. diff --git a/vendor/go.opentelemetry.io/otel/sdk/trace/snapshot.go b/vendor/go.opentelemetry.io/otel/sdk/trace/snapshot.go index 8893dc3..6e0c06b 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/trace/snapshot.go +++ b/vendor/go.opentelemetry.io/otel/sdk/trace/snapshot.go @@ -12,7 +12,7 @@ import ( "go.opentelemetry.io/otel/trace" ) -// snapshot is an record of a spans state at a particular checkpointed time. +// snapshot is a record of a span's state at a particular checkpointed time. // It is used as a read-only representation of that state. type snapshot struct { name string diff --git a/vendor/go.opentelemetry.io/otel/sdk/trace/span.go b/vendor/go.opentelemetry.io/otel/sdk/trace/span.go index aae9773..05920ab 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/trace/span.go +++ b/vendor/go.opentelemetry.io/otel/sdk/trace/span.go @@ -278,8 +278,11 @@ func (s *recordingSpan) SetAttributes(attributes ...attribute.KeyValue) { s.addDroppedAttr(1) continue } - a = dedupAttr(a) - a = attrnorm.Truncate(s.tracer.provider.spanLimits.AttributeValueLengthLimit, a) + a = normAttr( + a, + s.tracer.provider.spanLimits.AttributeValueDepthLimit, + s.tracer.provider.spanLimits.AttributeValueLengthLimit, + ) s.attributes = append(s.attributes, a) s.attributesDirty = true } @@ -353,8 +356,11 @@ func (s *recordingSpan) addOverCapAttrs(limit int, attrs []attribute.KeyValue) { if idx, ok := exists[a.Key]; ok { // Perform all updates before dropping, even when at capacity. - a = dedupAttr(a) - a = attrnorm.Truncate(s.tracer.provider.spanLimits.AttributeValueLengthLimit, a) + a = normAttr( + a, + s.tracer.provider.spanLimits.AttributeValueDepthLimit, + s.tracer.provider.spanLimits.AttributeValueLengthLimit, + ) s.attributes[idx] = a continue } @@ -364,22 +370,27 @@ func (s *recordingSpan) addOverCapAttrs(limit int, attrs []attribute.KeyValue) { // updates are checked and performed. s.addDroppedAttr(1) } else { - a = dedupAttr(a) - a = attrnorm.Truncate(s.tracer.provider.spanLimits.AttributeValueLengthLimit, a) + a = normAttr( + a, + s.tracer.provider.spanLimits.AttributeValueDepthLimit, + s.tracer.provider.spanLimits.AttributeValueLengthLimit, + ) s.attributes = append(s.attributes, a) exists[a.Key] = len(s.attributes) - 1 } } } -func dedupAttr(attr attribute.KeyValue) attribute.KeyValue { +func normAttr(attr attribute.KeyValue, depthLimit, lengthLimit int) attribute.KeyValue { switch attr.Value.Type() { case attribute.SLICE, attribute.MAP: - attr, _ = attrnorm.KeyValue(attr) - return attr - default: - return attr + if depthLimit < 0 { + attr, _ = attrnorm.KeyValueDedup(attr) + } else { + attr, _, _ = attrnorm.KeyValueDedupLimitDepth(attr, depthLimit) + } } + return attrnorm.Truncate(lengthLimit, attr) } // End ends the span. This method does nothing if the span is already ended or @@ -483,9 +494,7 @@ func (s *recordingSpan) RecordError(err error, opts ...trace.EventOption) { return } - s.mu.Lock() - defer s.mu.Unlock() - if !s.isRecording() { + if !s.IsRecording() { return } @@ -501,7 +510,7 @@ func (s *recordingSpan) RecordError(err error, opts ...trace.EventOption) { )) } - s.addEvent(semconv.ExceptionEventName, opts...) + s.AddEvent(semconv.ExceptionEventName, opts...) } func typeStr(i any) string { @@ -540,7 +549,10 @@ func (s *recordingSpan) AddEvent(name string, o ...trace.EventOption) { // This method assumes s.mu.Lock is held by the caller. func (s *recordingSpan) addEvent(name string, o ...trace.EventOption) { c := trace.NewEventConfig(o...) - attrs, _ := attrnorm.KeyValues(c.Attributes()) + attrs, _, _ := attrnorm.KeyValuesDedupLimitDepth( + c.Attributes(), + s.tracer.provider.spanLimits.AttributeValueDepthLimit, + ) e := Event{Name: name, Attributes: attrs, Time: c.Timestamp()} // Discard attributes over limit. @@ -580,7 +592,7 @@ func (s *recordingSpan) Name() string { return s.name } -// Name returns the SpanContext of this span's parent span. +// Parent returns the SpanContext of this span's parent span. func (s *recordingSpan) Parent() trace.SpanContext { s.mu.Lock() defer s.mu.Unlock() @@ -720,7 +732,10 @@ func (s *recordingSpan) AddLink(link trace.Link) { return } - attrs, _ := attrnorm.KeyValues(link.Attributes) + attrs, _, _ := attrnorm.KeyValuesDedupLimitDepth( + link.Attributes, + s.tracer.provider.spanLimits.AttributeValueDepthLimit, + ) l := Link{SpanContext: link.SpanContext, Attributes: attrs} // Discard attributes over limit. diff --git a/vendor/go.opentelemetry.io/otel/sdk/trace/span_limits.go b/vendor/go.opentelemetry.io/otel/sdk/trace/span_limits.go index 5ee15a8..3069e22 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/trace/span_limits.go +++ b/vendor/go.opentelemetry.io/otel/sdk/trace/span_limits.go @@ -10,6 +10,10 @@ const ( // attribute value length, unlimited. DefaultAttributeValueLengthLimit = -1 + // DefaultAttributeValueDepthLimit is the default maximum allowed depth for + // nested attribute values. + DefaultAttributeValueDepthLimit = 64 + // DefaultAttributeCountLimit is the default maximum number of attributes // a span can have. DefaultAttributeCountLimit = 128 @@ -43,6 +47,20 @@ type SpanLimits struct { // Setting this to a negative value means no limit is applied. AttributeValueLengthLimit int + // AttributeValueDepthLimit is the maximum allowed depth for an attribute + // value. Depth starts at one for the top-level value and increments when + // descending into an array element or map value. An array or map beyond this + // depth is replaced by an empty value. + // + // This limit applies to span, event, link, and instrumentation scope + // attributes processed by a TracerProvider. It does not apply to Resource + // attributes. + // + // Setting this to zero means the default limit is used. + // + // Setting this to a negative value means no limit is applied. + AttributeValueDepthLimit int + // AttributeCountLimit is the maximum allowed span attribute count. Any // attribute added to a span once this limit is reached will be dropped. // @@ -88,12 +106,15 @@ type SpanLimits struct { AttributePerLinkCountLimit int } -// NewSpanLimits returns a SpanLimits with all limits set to the value their -// corresponding environment variable holds, or the default if unset. +// NewSpanLimits returns a SpanLimits with all limits set to their default. +// Limits with a corresponding environment variable are set from the +// environment when the variable is defined. // // • AttributeValueLengthLimit: OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT // (default: unlimited) // +// • AttributeValueDepthLimit: default 64 (no environment variable) +// // • AttributeCountLimit: OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT (default: 128) // // • EventCountLimit: OTEL_SPAN_EVENT_COUNT_LIMIT (default: 128) @@ -107,6 +128,7 @@ type SpanLimits struct { func NewSpanLimits() SpanLimits { return SpanLimits{ AttributeValueLengthLimit: env.SpanAttributeValueLength(DefaultAttributeValueLengthLimit), + AttributeValueDepthLimit: DefaultAttributeValueDepthLimit, AttributeCountLimit: env.SpanAttributeCount(DefaultAttributeCountLimit), EventCountLimit: env.SpanEventCount(DefaultEventCountLimit), LinkCountLimit: env.SpanLinkCount(DefaultLinkCountLimit), diff --git a/vendor/go.opentelemetry.io/otel/sdk/version.go b/vendor/go.opentelemetry.io/otel/sdk/version.go index 621d6d7..2335ebd 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/version.go +++ b/vendor/go.opentelemetry.io/otel/sdk/version.go @@ -6,5 +6,5 @@ package sdk // Version is the current release version of the OpenTelemetry SDK in use. func Version() string { - return "1.46.0" + return "1.47.0" } diff --git a/vendor/go.opentelemetry.io/otel/trace/auto.go b/vendor/go.opentelemetry.io/otel/trace/auto.go index 17cf898..be4a964 100644 --- a/vendor/go.opentelemetry.io/otel/trace/auto.go +++ b/vendor/go.opentelemetry.io/otel/trace/auto.go @@ -372,7 +372,7 @@ func convAttrValue(value attribute.Value) telemetry.Value { return telemetry.Value{} } -// truncate returns a truncated version of s such that it contains less than +// truncate returns a truncated version of s such that it contains at most // the limit number of characters. Truncation is applied by returning the limit // number of valid characters contained in s. // @@ -381,7 +381,7 @@ func convAttrValue(value attribute.Value) telemetry.Value { // UTF-8 is supported. When truncating, all invalid characters are dropped // before applying truncation. // -// If s already contains less than the limit number of bytes, it is returned +// If s already contains at most the limit number of bytes, it is returned // unchanged. No invalid characters are removed. func truncate(limit int, s string) string { // This prioritize performance in the following order based on the most @@ -407,6 +407,10 @@ func truncate(limit int, s string) string { continue } + // A zero limit also truncates a leading invalid byte or U+FFFD. + if limit == 0 { + return "" + } _, size := utf8.DecodeRuneInString(s[i:]) if size == 1 { // Invalid encoding. @@ -415,6 +419,12 @@ func truncate(limit int, s string) string { s = s[i:] break } + + // A valid U+FFFD still consumes one character of the limit. + count++ + if count > limit { + return s[:i] + } } // Fast-path, no invalid input. diff --git a/vendor/go.opentelemetry.io/otel/trace/internal/telemetry/number.go b/vendor/go.opentelemetry.io/otel/trace/internal/telemetry/number.go index 29e629d..5bb3b16 100644 --- a/vendor/go.opentelemetry.io/otel/trace/internal/telemetry/number.go +++ b/vendor/go.opentelemetry.io/otel/trace/internal/telemetry/number.go @@ -41,7 +41,7 @@ func (i *protoInt64) UnmarshalJSON(data []byte) error { // strings or integers. type protoUint64 uint64 -// Int64 returns the protoUint64 as a uint64. +// Uint64 returns the protoUint64 as a uint64. func (i *protoUint64) Uint64() uint64 { return uint64(*i) } // UnmarshalJSON decodes both strings and integers. diff --git a/vendor/go.opentelemetry.io/otel/trace/internal/telemetry/value.go b/vendor/go.opentelemetry.io/otel/trace/internal/telemetry/value.go index 9d2d680..b7b0e8b 100644 --- a/vendor/go.opentelemetry.io/otel/trace/internal/telemetry/value.go +++ b/vendor/go.opentelemetry.io/otel/trace/internal/telemetry/value.go @@ -327,7 +327,7 @@ func (v Value) String() string { // Try to handle this as gracefully as possible. // // Don't panic here. The goal here is to have developers find this - // first if a slog.Kind is is not handled. It is + // first if a slog.Kind is not handled. It is // preferable to have user's open issue asking why their attributes // have a "unhandled: " prefix than say that their code is panicking. return fmt.Sprintf("", v.Kind()) diff --git a/vendor/go.opentelemetry.io/otel/trace/trace.go b/vendor/go.opentelemetry.io/otel/trace/trace.go index c4c3838..66b967e 100644 --- a/vendor/go.opentelemetry.io/otel/trace/trace.go +++ b/vendor/go.opentelemetry.io/otel/trace/trace.go @@ -134,13 +134,49 @@ func TraceIDFromHex(h string) (TraceID, error) { if len(h) != 32 { return [16]byte{}, errInvalidTraceIDLength } - var b [16]byte - invalidMark := byte(0) - for i := 0; i < len(h); i += 4 { - b[i/2] = (hexRev[h[i]] << 4) | hexRev[h[i+1]] - b[i/2+1] = (hexRev[h[i+2]] << 4) | hexRev[h[i+3]] - invalidMark |= hexRev[h[i]] | hexRev[h[i+1]] | hexRev[h[i+2]] | hexRev[h[i+3]] + // Decoding every character at a constant index allows the compiler to + // eliminate the bounds checks a loop over h would retain. + n0, n1 := hexRev[h[0]], hexRev[h[1]] + n2, n3 := hexRev[h[2]], hexRev[h[3]] + n4, n5 := hexRev[h[4]], hexRev[h[5]] + n6, n7 := hexRev[h[6]], hexRev[h[7]] + n8, n9 := hexRev[h[8]], hexRev[h[9]] + n10, n11 := hexRev[h[10]], hexRev[h[11]] + n12, n13 := hexRev[h[12]], hexRev[h[13]] + n14, n15 := hexRev[h[14]], hexRev[h[15]] + n16, n17 := hexRev[h[16]], hexRev[h[17]] + n18, n19 := hexRev[h[18]], hexRev[h[19]] + n20, n21 := hexRev[h[20]], hexRev[h[21]] + n22, n23 := hexRev[h[22]], hexRev[h[23]] + n24, n25 := hexRev[h[24]], hexRev[h[25]] + n26, n27 := hexRev[h[26]], hexRev[h[27]] + n28, n29 := hexRev[h[28]], hexRev[h[29]] + n30, n31 := hexRev[h[30]], hexRev[h[31]] + + b := [16]byte{ + (n0 << 4) | n1, + (n2 << 4) | n3, + (n4 << 4) | n5, + (n6 << 4) | n7, + (n8 << 4) | n9, + (n10 << 4) | n11, + (n12 << 4) | n13, + (n14 << 4) | n15, + (n16 << 4) | n17, + (n18 << 4) | n19, + (n20 << 4) | n21, + (n22 << 4) | n23, + (n24 << 4) | n25, + (n26 << 4) | n27, + (n28 << 4) | n29, + (n30 << 4) | n31, } + + invalidMark := n0 | n1 | n2 | n3 | n4 | n5 | n6 | n7 | + n8 | n9 | n10 | n11 | n12 | n13 | n14 | n15 | + n16 | n17 | n18 | n19 | n20 | n21 | n22 | n23 | + n24 | n25 | n26 | n27 | n28 | n29 | n30 | n31 + // If the upper 4 bits of any byte are not zero, there was an invalid hex // character since invalid hex characters are 0xff in hexRev. if invalidMark&0xf0 != 0 { @@ -160,13 +196,31 @@ func SpanIDFromHex(h string) (SpanID, error) { if len(h) != 16 { return [8]byte{}, errInvalidSpanIDLength } - var b [8]byte - invalidMark := byte(0) - for i := 0; i < len(h); i += 4 { - b[i/2] = (hexRev[h[i]] << 4) | hexRev[h[i+1]] - b[i/2+1] = (hexRev[h[i+2]] << 4) | hexRev[h[i+3]] - invalidMark |= hexRev[h[i]] | hexRev[h[i+1]] | hexRev[h[i+2]] | hexRev[h[i+3]] + // Decoding every character at a constant index allows the compiler to + // eliminate the bounds checks a loop over h would retain. + n0, n1 := hexRev[h[0]], hexRev[h[1]] + n2, n3 := hexRev[h[2]], hexRev[h[3]] + n4, n5 := hexRev[h[4]], hexRev[h[5]] + n6, n7 := hexRev[h[6]], hexRev[h[7]] + n8, n9 := hexRev[h[8]], hexRev[h[9]] + n10, n11 := hexRev[h[10]], hexRev[h[11]] + n12, n13 := hexRev[h[12]], hexRev[h[13]] + n14, n15 := hexRev[h[14]], hexRev[h[15]] + + b := [8]byte{ + (n0 << 4) | n1, + (n2 << 4) | n3, + (n4 << 4) | n5, + (n6 << 4) | n7, + (n8 << 4) | n9, + (n10 << 4) | n11, + (n12 << 4) | n13, + (n14 << 4) | n15, } + + invalidMark := n0 | n1 | n2 | n3 | n4 | n5 | n6 | n7 | + n8 | n9 | n10 | n11 | n12 | n13 | n14 | n15 + // If the upper 4 bits of any byte are not zero, there was an invalid hex // character since invalid hex characters are 0xff in hexRev. if invalidMark&0xf0 != 0 { diff --git a/vendor/go.opentelemetry.io/otel/trace/tracestate.go b/vendor/go.opentelemetry.io/otel/trace/tracestate.go index 9ac78fa..062ceb2 100644 --- a/vendor/go.opentelemetry.io/otel/trace/tracestate.go +++ b/vendor/go.opentelemetry.io/otel/trace/tracestate.go @@ -283,7 +283,7 @@ func (ts TraceState) Walk(f func(key, value string) bool) { // specification an error is returned with the original TraceState. // // If adding a new list-member means the TraceState would have more members -// then is allowed, the new list-member will be inserted and the right-most +// than is allowed, the new list-member will be inserted and the right-most // list-member will be dropped in the returned TraceState. func (ts TraceState) Insert(key, value string) (TraceState, error) { m, err := newMember(key, value) diff --git a/vendor/go.opentelemetry.io/otel/version.go b/vendor/go.opentelemetry.io/otel/version.go index f599bf2..29ff180 100644 --- a/vendor/go.opentelemetry.io/otel/version.go +++ b/vendor/go.opentelemetry.io/otel/version.go @@ -5,5 +5,5 @@ package otel // Version is the current release version of OpenTelemetry in use. func Version() string { - return "1.46.0" + return "1.47.0" } diff --git a/vendor/go.opentelemetry.io/otel/versions.yaml b/vendor/go.opentelemetry.io/otel/versions.yaml index f329d17..a0cb35f 100644 --- a/vendor/go.opentelemetry.io/otel/versions.yaml +++ b/vendor/go.opentelemetry.io/otel/versions.yaml @@ -3,7 +3,7 @@ module-sets: stable-v1: - version: v1.46.0 + version: v1.47.0 modules: - go.opentelemetry.io/otel - go.opentelemetry.io/otel/bridge/opencensus @@ -17,25 +17,29 @@ module-sets: - go.opentelemetry.io/otel/exporters/stdout/stdoutmetric - go.opentelemetry.io/otel/exporters/stdout/stdouttrace - go.opentelemetry.io/otel/exporters/zipkin + - go.opentelemetry.io/otel/log - go.opentelemetry.io/otel/metric - go.opentelemetry.io/otel/sdk + - go.opentelemetry.io/otel/sdk/log - go.opentelemetry.io/otel/sdk/metric - go.opentelemetry.io/otel/trace experimental-metrics: - version: v0.68.0 + version: v0.69.0 modules: - go.opentelemetry.io/otel/exporters/prometheus - go.opentelemetry.io/otel/metric/x experimental-logs: - version: v0.22.0 + version: v0.23.0 modules: - - go.opentelemetry.io/otel/log - go.opentelemetry.io/otel/log/logtest - - go.opentelemetry.io/otel/sdk/log - go.opentelemetry.io/otel/sdk/log/logtest - go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc - go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp - go.opentelemetry.io/otel/exporters/stdout/stdoutlog + experimental-traces: + version: v0.1.0 + modules: + - go.opentelemetry.io/otel/sdk/trace/x experimental-schema: version: v0.0.19 modules: diff --git a/vendor/go.opentelemetry.io/proto/otlp/collector/trace/v1/trace_service.pb.go b/vendor/go.opentelemetry.io/proto/otlp/collector/trace/v1/trace_service.pb.go index c1af04e..2234be2 100644 --- a/vendor/go.opentelemetry.io/proto/otlp/collector/trace/v1/trace_service.pb.go +++ b/vendor/go.opentelemetry.io/proto/otlp/collector/trace/v1/trace_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.6 +// protoc-gen-go v1.36.11 +// protoc v7.35.0 // source: opentelemetry/proto/collector/trace/v1/trace_service.proto package v1 @@ -26,6 +26,7 @@ import ( protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" + unsafe "unsafe" ) const ( @@ -36,25 +37,22 @@ const ( ) type ExportTraceServiceRequest struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // An array of ResourceSpans. // For data coming from a single resource this array will typically contain one // element. Intermediary nodes (such as OpenTelemetry Collector) that receive // data from multiple origins typically batch the data before forwarding further and // in that case this array will contain multiple elements. ResourceSpans []*v1.ResourceSpans `protobuf:"bytes,1,rep,name=resource_spans,json=resourceSpans,proto3" json:"resource_spans,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *ExportTraceServiceRequest) Reset() { *x = ExportTraceServiceRequest{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_collector_trace_v1_trace_service_proto_msgTypes[0] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_collector_trace_v1_trace_service_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *ExportTraceServiceRequest) String() string { @@ -65,7 +63,7 @@ func (*ExportTraceServiceRequest) ProtoMessage() {} func (x *ExportTraceServiceRequest) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_collector_trace_v1_trace_service_proto_msgTypes[0] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -88,10 +86,7 @@ func (x *ExportTraceServiceRequest) GetResourceSpans() []*v1.ResourceSpans { } type ExportTraceServiceResponse struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // The details of a partially successful export request. // // If the request is only partially accepted @@ -108,15 +103,15 @@ type ExportTraceServiceResponse struct { // `error_message` = "") is equivalent to it not being set/present. Senders // SHOULD interpret it the same way as in the full success case. PartialSuccess *ExportTracePartialSuccess `protobuf:"bytes,1,opt,name=partial_success,json=partialSuccess,proto3" json:"partial_success,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *ExportTraceServiceResponse) Reset() { *x = ExportTraceServiceResponse{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_collector_trace_v1_trace_service_proto_msgTypes[1] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_collector_trace_v1_trace_service_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *ExportTraceServiceResponse) String() string { @@ -127,7 +122,7 @@ func (*ExportTraceServiceResponse) ProtoMessage() {} func (x *ExportTraceServiceResponse) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_collector_trace_v1_trace_service_proto_msgTypes[1] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -150,10 +145,7 @@ func (x *ExportTraceServiceResponse) GetPartialSuccess() *ExportTracePartialSucc } type ExportTracePartialSuccess struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // The number of rejected spans. // // A `rejected_` field holding a `0` value indicates that the @@ -166,16 +158,16 @@ type ExportTracePartialSuccess struct { // // error_message is an optional field. An error_message with an empty value // is equivalent to it not being set. - ErrorMessage string `protobuf:"bytes,2,opt,name=error_message,json=errorMessage,proto3" json:"error_message,omitempty"` + ErrorMessage string `protobuf:"bytes,2,opt,name=error_message,json=errorMessage,proto3" json:"error_message,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *ExportTracePartialSuccess) Reset() { *x = ExportTracePartialSuccess{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_collector_trace_v1_trace_service_proto_msgTypes[2] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_collector_trace_v1_trace_service_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *ExportTracePartialSuccess) String() string { @@ -186,7 +178,7 @@ func (*ExportTracePartialSuccess) ProtoMessage() {} func (x *ExportTracePartialSuccess) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_collector_trace_v1_trace_service_proto_msgTypes[2] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -217,75 +209,34 @@ func (x *ExportTracePartialSuccess) GetErrorMessage() string { var File_opentelemetry_proto_collector_trace_v1_trace_service_proto protoreflect.FileDescriptor -var file_opentelemetry_proto_collector_trace_v1_trace_service_proto_rawDesc = []byte{ - 0x0a, 0x3a, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2f, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x63, 0x6f, 0x6c, 0x6c, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x2f, - 0x74, 0x72, 0x61, 0x63, 0x65, 0x2f, 0x76, 0x31, 0x2f, 0x74, 0x72, 0x61, 0x63, 0x65, 0x5f, 0x73, - 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x26, 0x6f, 0x70, - 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, - 0x6f, 0x2e, 0x63, 0x6f, 0x6c, 0x6c, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x2e, 0x74, 0x72, 0x61, 0x63, - 0x65, 0x2e, 0x76, 0x31, 0x1a, 0x28, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, - 0x74, 0x72, 0x79, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x74, 0x72, 0x61, 0x63, 0x65, 0x2f, - 0x76, 0x31, 0x2f, 0x74, 0x72, 0x61, 0x63, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x6f, - 0x0a, 0x19, 0x45, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x54, 0x72, 0x61, 0x63, 0x65, 0x53, 0x65, 0x72, - 0x76, 0x69, 0x63, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x52, 0x0a, 0x0e, 0x72, - 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x5f, 0x73, 0x70, 0x61, 0x6e, 0x73, 0x18, 0x01, 0x20, - 0x03, 0x28, 0x0b, 0x32, 0x2b, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, - 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, 0x2e, - 0x76, 0x31, 0x2e, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x53, 0x70, 0x61, 0x6e, 0x73, - 0x52, 0x0d, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x53, 0x70, 0x61, 0x6e, 0x73, 0x22, - 0x88, 0x01, 0x0a, 0x1a, 0x45, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x54, 0x72, 0x61, 0x63, 0x65, 0x53, - 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x6a, - 0x0a, 0x0f, 0x70, 0x61, 0x72, 0x74, 0x69, 0x61, 0x6c, 0x5f, 0x73, 0x75, 0x63, 0x63, 0x65, 0x73, - 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x41, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, - 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x63, 0x6f, - 0x6c, 0x6c, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, 0x2e, 0x76, 0x31, - 0x2e, 0x45, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x54, 0x72, 0x61, 0x63, 0x65, 0x50, 0x61, 0x72, 0x74, - 0x69, 0x61, 0x6c, 0x53, 0x75, 0x63, 0x63, 0x65, 0x73, 0x73, 0x52, 0x0e, 0x70, 0x61, 0x72, 0x74, - 0x69, 0x61, 0x6c, 0x53, 0x75, 0x63, 0x63, 0x65, 0x73, 0x73, 0x22, 0x67, 0x0a, 0x19, 0x45, 0x78, - 0x70, 0x6f, 0x72, 0x74, 0x54, 0x72, 0x61, 0x63, 0x65, 0x50, 0x61, 0x72, 0x74, 0x69, 0x61, 0x6c, - 0x53, 0x75, 0x63, 0x63, 0x65, 0x73, 0x73, 0x12, 0x25, 0x0a, 0x0e, 0x72, 0x65, 0x6a, 0x65, 0x63, - 0x74, 0x65, 0x64, 0x5f, 0x73, 0x70, 0x61, 0x6e, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, - 0x0d, 0x72, 0x65, 0x6a, 0x65, 0x63, 0x74, 0x65, 0x64, 0x53, 0x70, 0x61, 0x6e, 0x73, 0x12, 0x23, - 0x0a, 0x0d, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x5f, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, - 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0c, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x4d, 0x65, 0x73, 0x73, - 0x61, 0x67, 0x65, 0x32, 0xa2, 0x01, 0x0a, 0x0c, 0x54, 0x72, 0x61, 0x63, 0x65, 0x53, 0x65, 0x72, - 0x76, 0x69, 0x63, 0x65, 0x12, 0x91, 0x01, 0x0a, 0x06, 0x45, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x12, - 0x41, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x63, 0x6f, 0x6c, 0x6c, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x2e, - 0x74, 0x72, 0x61, 0x63, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x45, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x54, - 0x72, 0x61, 0x63, 0x65, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, - 0x73, 0x74, 0x1a, 0x42, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, - 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x63, 0x6f, 0x6c, 0x6c, 0x65, 0x63, 0x74, - 0x6f, 0x72, 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x45, 0x78, 0x70, 0x6f, - 0x72, 0x74, 0x54, 0x72, 0x61, 0x63, 0x65, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x52, 0x65, - 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x42, 0x9c, 0x01, 0x0a, 0x29, 0x69, 0x6f, 0x2e, - 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, - 0x6f, 0x74, 0x6f, 0x2e, 0x63, 0x6f, 0x6c, 0x6c, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x2e, 0x74, 0x72, - 0x61, 0x63, 0x65, 0x2e, 0x76, 0x31, 0x42, 0x11, 0x54, 0x72, 0x61, 0x63, 0x65, 0x53, 0x65, 0x72, - 0x76, 0x69, 0x63, 0x65, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x31, 0x67, 0x6f, 0x2e, - 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x69, 0x6f, - 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x6f, 0x74, 0x6c, 0x70, 0x2f, 0x63, 0x6f, 0x6c, 0x6c, - 0x65, 0x63, 0x74, 0x6f, 0x72, 0x2f, 0x74, 0x72, 0x61, 0x63, 0x65, 0x2f, 0x76, 0x31, 0xaa, 0x02, - 0x26, 0x4f, 0x70, 0x65, 0x6e, 0x54, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x50, - 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x43, 0x6f, 0x6c, 0x6c, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x2e, 0x54, - 0x72, 0x61, 0x63, 0x65, 0x2e, 0x56, 0x31, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, -} +const file_opentelemetry_proto_collector_trace_v1_trace_service_proto_rawDesc = "" + + "\n" + + ":opentelemetry/proto/collector/trace/v1/trace_service.proto\x12&opentelemetry.proto.collector.trace.v1\x1a(opentelemetry/proto/trace/v1/trace.proto\"o\n" + + "\x19ExportTraceServiceRequest\x12R\n" + + "\x0eresource_spans\x18\x01 \x03(\v2+.opentelemetry.proto.trace.v1.ResourceSpansR\rresourceSpans\"\x88\x01\n" + + "\x1aExportTraceServiceResponse\x12j\n" + + "\x0fpartial_success\x18\x01 \x01(\v2A.opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccessR\x0epartialSuccess\"g\n" + + "\x19ExportTracePartialSuccess\x12%\n" + + "\x0erejected_spans\x18\x01 \x01(\x03R\rrejectedSpans\x12#\n" + + "\rerror_message\x18\x02 \x01(\tR\ferrorMessage2\xa2\x01\n" + + "\fTraceService\x12\x91\x01\n" + + "\x06Export\x12A.opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest\x1aB.opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse\"\x00B\x9c\x01\n" + + ")io.opentelemetry.proto.collector.trace.v1B\x11TraceServiceProtoP\x01Z1go.opentelemetry.io/proto/otlp/collector/trace/v1\xaa\x02&OpenTelemetry.Proto.Collector.Trace.V1b\x06proto3" var ( file_opentelemetry_proto_collector_trace_v1_trace_service_proto_rawDescOnce sync.Once - file_opentelemetry_proto_collector_trace_v1_trace_service_proto_rawDescData = file_opentelemetry_proto_collector_trace_v1_trace_service_proto_rawDesc + file_opentelemetry_proto_collector_trace_v1_trace_service_proto_rawDescData []byte ) func file_opentelemetry_proto_collector_trace_v1_trace_service_proto_rawDescGZIP() []byte { file_opentelemetry_proto_collector_trace_v1_trace_service_proto_rawDescOnce.Do(func() { - file_opentelemetry_proto_collector_trace_v1_trace_service_proto_rawDescData = protoimpl.X.CompressGZIP(file_opentelemetry_proto_collector_trace_v1_trace_service_proto_rawDescData) + file_opentelemetry_proto_collector_trace_v1_trace_service_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_opentelemetry_proto_collector_trace_v1_trace_service_proto_rawDesc), len(file_opentelemetry_proto_collector_trace_v1_trace_service_proto_rawDesc))) }) return file_opentelemetry_proto_collector_trace_v1_trace_service_proto_rawDescData } var file_opentelemetry_proto_collector_trace_v1_trace_service_proto_msgTypes = make([]protoimpl.MessageInfo, 3) -var file_opentelemetry_proto_collector_trace_v1_trace_service_proto_goTypes = []interface{}{ +var file_opentelemetry_proto_collector_trace_v1_trace_service_proto_goTypes = []any{ (*ExportTraceServiceRequest)(nil), // 0: opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest (*ExportTraceServiceResponse)(nil), // 1: opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse (*ExportTracePartialSuccess)(nil), // 2: opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess @@ -308,49 +259,11 @@ func file_opentelemetry_proto_collector_trace_v1_trace_service_proto_init() { if File_opentelemetry_proto_collector_trace_v1_trace_service_proto != nil { return } - if !protoimpl.UnsafeEnabled { - file_opentelemetry_proto_collector_trace_v1_trace_service_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ExportTraceServiceRequest); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_opentelemetry_proto_collector_trace_v1_trace_service_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ExportTraceServiceResponse); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_opentelemetry_proto_collector_trace_v1_trace_service_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ExportTracePartialSuccess); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), - RawDescriptor: file_opentelemetry_proto_collector_trace_v1_trace_service_proto_rawDesc, + RawDescriptor: unsafe.Slice(unsafe.StringData(file_opentelemetry_proto_collector_trace_v1_trace_service_proto_rawDesc), len(file_opentelemetry_proto_collector_trace_v1_trace_service_proto_rawDesc)), NumEnums: 0, NumMessages: 3, NumExtensions: 0, @@ -361,7 +274,6 @@ func file_opentelemetry_proto_collector_trace_v1_trace_service_proto_init() { MessageInfos: file_opentelemetry_proto_collector_trace_v1_trace_service_proto_msgTypes, }.Build() File_opentelemetry_proto_collector_trace_v1_trace_service_proto = out.File - file_opentelemetry_proto_collector_trace_v1_trace_service_proto_rawDesc = nil file_opentelemetry_proto_collector_trace_v1_trace_service_proto_goTypes = nil file_opentelemetry_proto_collector_trace_v1_trace_service_proto_depIdxs = nil } diff --git a/vendor/go.opentelemetry.io/proto/otlp/collector/trace/v1/trace_service.pb.gw.go b/vendor/go.opentelemetry.io/proto/otlp/collector/trace/v1/trace_service.pb.gw.go index bb1bd26..b2cf91e 100644 --- a/vendor/go.opentelemetry.io/proto/otlp/collector/trace/v1/trace_service.pb.gw.go +++ b/vendor/go.opentelemetry.io/proto/otlp/collector/trace/v1/trace_service.pb.gw.go @@ -10,6 +10,7 @@ package v1 import ( "context" + "errors" "io" "net/http" @@ -24,62 +25,56 @@ import ( ) // Suppress "imported and not used" errors -var _ codes.Code -var _ io.Reader -var _ status.Status -var _ = runtime.String -var _ = utilities.NewDoubleArray -var _ = metadata.Join +var ( + _ codes.Code + _ io.Reader + _ status.Status + _ = errors.New + _ = runtime.String + _ = utilities.NewDoubleArray + _ = metadata.Join +) func request_TraceService_Export_0(ctx context.Context, marshaler runtime.Marshaler, client TraceServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq ExportTraceServiceRequest - var metadata runtime.ServerMetadata - - newReader, berr := utilities.IOReaderFactory(req.Body) - if berr != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) - } - if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { + var ( + protoReq ExportTraceServiceRequest + metadata runtime.ServerMetadata + ) + if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } - + if req.Body != nil { + _, _ = io.Copy(io.Discard, req.Body) + } msg, err := client.Export(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err - } func local_request_TraceService_Export_0(ctx context.Context, marshaler runtime.Marshaler, server TraceServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq ExportTraceServiceRequest - var metadata runtime.ServerMetadata - - newReader, berr := utilities.IOReaderFactory(req.Body) - if berr != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) - } - if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { + var ( + protoReq ExportTraceServiceRequest + metadata runtime.ServerMetadata + ) + if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } - msg, err := server.Export(ctx, &protoReq) return msg, metadata, err - } // RegisterTraceServiceHandlerServer registers the http handlers for service TraceService to "mux". // UnaryRPC :call TraceServiceServer directly. // StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. // Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterTraceServiceHandlerFromEndpoint instead. +// GRPC interceptors will not work for this type of registration. To use interceptors, you must use the "runtime.WithMiddlewares" option in the "runtime.NewServeMux" call. func RegisterTraceServiceHandlerServer(ctx context.Context, mux *runtime.ServeMux, server TraceServiceServer) error { - - mux.Handle("POST", pattern_TraceService_Export_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle(http.MethodPost, pattern_TraceService_Export_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateIncomingContext(ctx, mux, req, "/opentelemetry.proto.collector.trace.v1.TraceService/Export", runtime.WithHTTPPathPattern("/v1/traces")) + annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/opentelemetry.proto.collector.trace.v1.TraceService/Export", runtime.WithHTTPPathPattern("/v1/traces")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return @@ -91,9 +86,7 @@ func RegisterTraceServiceHandlerServer(ctx context.Context, mux *runtime.ServeMu runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } - forward_TraceService_Export_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) return nil @@ -102,25 +95,24 @@ func RegisterTraceServiceHandlerServer(ctx context.Context, mux *runtime.ServeMu // RegisterTraceServiceHandlerFromEndpoint is same as RegisterTraceServiceHandler but // automatically dials to "endpoint" and closes the connection when "ctx" gets done. func RegisterTraceServiceHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { - conn, err := grpc.Dial(endpoint, opts...) + conn, err := grpc.NewClient(endpoint, opts...) if err != nil { return err } defer func() { if err != nil { if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) + grpclog.Errorf("Failed to close conn to %s: %v", endpoint, cerr) } return } go func() { <-ctx.Done() if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) + grpclog.Errorf("Failed to close conn to %s: %v", endpoint, cerr) } }() }() - return RegisterTraceServiceHandler(ctx, mux, conn) } @@ -134,16 +126,13 @@ func RegisterTraceServiceHandler(ctx context.Context, mux *runtime.ServeMux, con // to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "TraceServiceClient". // Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "TraceServiceClient" // doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in -// "TraceServiceClient" to call the correct interceptors. +// "TraceServiceClient" to call the correct interceptors. This client ignores the HTTP middlewares. func RegisterTraceServiceHandlerClient(ctx context.Context, mux *runtime.ServeMux, client TraceServiceClient) error { - - mux.Handle("POST", pattern_TraceService_Export_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle(http.MethodPost, pattern_TraceService_Export_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateContext(ctx, mux, req, "/opentelemetry.proto.collector.trace.v1.TraceService/Export", runtime.WithHTTPPathPattern("/v1/traces")) + annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/opentelemetry.proto.collector.trace.v1.TraceService/Export", runtime.WithHTTPPathPattern("/v1/traces")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return @@ -154,11 +143,8 @@ func RegisterTraceServiceHandlerClient(ctx context.Context, mux *runtime.ServeMu runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } - forward_TraceService_Export_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - return nil } diff --git a/vendor/go.opentelemetry.io/proto/otlp/collector/trace/v1/trace_service_grpc.pb.go b/vendor/go.opentelemetry.io/proto/otlp/collector/trace/v1/trace_service_grpc.pb.go index 892864e..0c93f2d 100644 --- a/vendor/go.opentelemetry.io/proto/otlp/collector/trace/v1/trace_service_grpc.pb.go +++ b/vendor/go.opentelemetry.io/proto/otlp/collector/trace/v1/trace_service_grpc.pb.go @@ -1,7 +1,21 @@ +// Copyright 2019, OpenTelemetry Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + // Code generated by protoc-gen-go-grpc. DO NOT EDIT. // versions: -// - protoc-gen-go-grpc v1.1.0 -// - protoc v3.21.6 +// - protoc-gen-go-grpc v1.5.1 +// - protoc v7.35.0 // source: opentelemetry/proto/collector/trace/v1/trace_service.proto package v1 @@ -15,12 +29,20 @@ import ( // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. -// Requires gRPC-Go v1.32.0 or later. -const _ = grpc.SupportPackageIsVersion7 +// Requires gRPC-Go v1.64.0 or later. +const _ = grpc.SupportPackageIsVersion9 + +const ( + TraceService_Export_FullMethodName = "/opentelemetry.proto.collector.trace.v1.TraceService/Export" +) // TraceServiceClient is the client API for TraceService service. // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. +// +// Service that can be used to push spans between one Application instrumented with +// OpenTelemetry and a collector, or between a collector and a central collector (in this +// case spans are sent/received to/from multiple Applications). type TraceServiceClient interface { Export(ctx context.Context, in *ExportTraceServiceRequest, opts ...grpc.CallOption) (*ExportTraceServiceResponse, error) } @@ -34,8 +56,9 @@ func NewTraceServiceClient(cc grpc.ClientConnInterface) TraceServiceClient { } func (c *traceServiceClient) Export(ctx context.Context, in *ExportTraceServiceRequest, opts ...grpc.CallOption) (*ExportTraceServiceResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(ExportTraceServiceResponse) - err := c.cc.Invoke(ctx, "/opentelemetry.proto.collector.trace.v1.TraceService/Export", in, out, opts...) + err := c.cc.Invoke(ctx, TraceService_Export_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } @@ -44,20 +67,28 @@ func (c *traceServiceClient) Export(ctx context.Context, in *ExportTraceServiceR // TraceServiceServer is the server API for TraceService service. // All implementations must embed UnimplementedTraceServiceServer -// for forward compatibility +// for forward compatibility. +// +// Service that can be used to push spans between one Application instrumented with +// OpenTelemetry and a collector, or between a collector and a central collector (in this +// case spans are sent/received to/from multiple Applications). type TraceServiceServer interface { Export(context.Context, *ExportTraceServiceRequest) (*ExportTraceServiceResponse, error) mustEmbedUnimplementedTraceServiceServer() } -// UnimplementedTraceServiceServer must be embedded to have forward compatible implementations. -type UnimplementedTraceServiceServer struct { -} +// UnimplementedTraceServiceServer must be embedded to have +// forward compatible implementations. +// +// NOTE: this should be embedded by value instead of pointer to avoid a nil +// pointer dereference when methods are called. +type UnimplementedTraceServiceServer struct{} func (UnimplementedTraceServiceServer) Export(context.Context, *ExportTraceServiceRequest) (*ExportTraceServiceResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method Export not implemented") } func (UnimplementedTraceServiceServer) mustEmbedUnimplementedTraceServiceServer() {} +func (UnimplementedTraceServiceServer) testEmbeddedByValue() {} // UnsafeTraceServiceServer may be embedded to opt out of forward compatibility for this service. // Use of this interface is not recommended, as added methods to TraceServiceServer will @@ -67,6 +98,13 @@ type UnsafeTraceServiceServer interface { } func RegisterTraceServiceServer(s grpc.ServiceRegistrar, srv TraceServiceServer) { + // If the following call pancis, it indicates UnimplementedTraceServiceServer was + // embedded by pointer and is nil. This will cause panics if an + // unimplemented method is ever invoked, so we test this at initialization + // time to prevent it from happening at runtime later due to I/O. + if t, ok := srv.(interface{ testEmbeddedByValue() }); ok { + t.testEmbeddedByValue() + } s.RegisterService(&TraceService_ServiceDesc, srv) } @@ -80,7 +118,7 @@ func _TraceService_Export_Handler(srv interface{}, ctx context.Context, dec func } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: "/opentelemetry.proto.collector.trace.v1.TraceService/Export", + FullMethod: TraceService_Export_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(TraceServiceServer).Export(ctx, req.(*ExportTraceServiceRequest)) diff --git a/vendor/go.opentelemetry.io/proto/otlp/common/v1/common.pb.go b/vendor/go.opentelemetry.io/proto/otlp/common/v1/common.pb.go index cef3580..626d8c6 100644 --- a/vendor/go.opentelemetry.io/proto/otlp/common/v1/common.pb.go +++ b/vendor/go.opentelemetry.io/proto/otlp/common/v1/common.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.6 +// protoc-gen-go v1.36.11 +// protoc v7.35.0 // source: opentelemetry/proto/common/v1/common.proto package v1 @@ -25,6 +25,7 @@ import ( protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" + unsafe "unsafe" ) const ( @@ -38,14 +39,12 @@ const ( // primitive value such as a string or integer or it may contain an arbitrary nested // object containing arrays, key-value lists and primitives. type AnyValue struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // The value is one of the listed fields. It is valid for all values to be unspecified // in which case this AnyValue is considered to be "empty". // - // Types that are assignable to Value: + // Types that are valid to be assigned to Value: + // // *AnyValue_StringValue // *AnyValue_BoolValue // *AnyValue_IntValue @@ -54,16 +53,16 @@ type AnyValue struct { // *AnyValue_KvlistValue // *AnyValue_BytesValue // *AnyValue_StringValueStrindex - Value isAnyValue_Value `protobuf_oneof:"value"` + Value isAnyValue_Value `protobuf_oneof:"value"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *AnyValue) Reset() { *x = AnyValue{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_common_v1_common_proto_msgTypes[0] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_common_v1_common_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *AnyValue) String() string { @@ -74,7 +73,7 @@ func (*AnyValue) ProtoMessage() {} func (x *AnyValue) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_common_v1_common_proto_msgTypes[0] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -89,65 +88,81 @@ func (*AnyValue) Descriptor() ([]byte, []int) { return file_opentelemetry_proto_common_v1_common_proto_rawDescGZIP(), []int{0} } -func (m *AnyValue) GetValue() isAnyValue_Value { - if m != nil { - return m.Value +func (x *AnyValue) GetValue() isAnyValue_Value { + if x != nil { + return x.Value } return nil } func (x *AnyValue) GetStringValue() string { - if x, ok := x.GetValue().(*AnyValue_StringValue); ok { - return x.StringValue + if x != nil { + if x, ok := x.Value.(*AnyValue_StringValue); ok { + return x.StringValue + } } return "" } func (x *AnyValue) GetBoolValue() bool { - if x, ok := x.GetValue().(*AnyValue_BoolValue); ok { - return x.BoolValue + if x != nil { + if x, ok := x.Value.(*AnyValue_BoolValue); ok { + return x.BoolValue + } } return false } func (x *AnyValue) GetIntValue() int64 { - if x, ok := x.GetValue().(*AnyValue_IntValue); ok { - return x.IntValue + if x != nil { + if x, ok := x.Value.(*AnyValue_IntValue); ok { + return x.IntValue + } } return 0 } func (x *AnyValue) GetDoubleValue() float64 { - if x, ok := x.GetValue().(*AnyValue_DoubleValue); ok { - return x.DoubleValue + if x != nil { + if x, ok := x.Value.(*AnyValue_DoubleValue); ok { + return x.DoubleValue + } } return 0 } func (x *AnyValue) GetArrayValue() *ArrayValue { - if x, ok := x.GetValue().(*AnyValue_ArrayValue); ok { - return x.ArrayValue + if x != nil { + if x, ok := x.Value.(*AnyValue_ArrayValue); ok { + return x.ArrayValue + } } return nil } func (x *AnyValue) GetKvlistValue() *KeyValueList { - if x, ok := x.GetValue().(*AnyValue_KvlistValue); ok { - return x.KvlistValue + if x != nil { + if x, ok := x.Value.(*AnyValue_KvlistValue); ok { + return x.KvlistValue + } } return nil } func (x *AnyValue) GetBytesValue() []byte { - if x, ok := x.GetValue().(*AnyValue_BytesValue); ok { - return x.BytesValue + if x != nil { + if x, ok := x.Value.(*AnyValue_BytesValue); ok { + return x.BytesValue + } } return nil } func (x *AnyValue) GetStringValueStrindex() int32 { - if x, ok := x.GetValue().(*AnyValue_StringValueStrindex); ok { - return x.StringValueStrindex + if x != nil { + if x, ok := x.Value.(*AnyValue_StringValueStrindex); ok { + return x.StringValueStrindex + } } return 0 } @@ -195,6 +210,8 @@ type AnyValue_StringValueStrindex struct { // empty, ignoring its semantic content for the non-Profiling signal. // // Status: [Alpha] + // + // [Since v1.10.0] StringValueStrindex int32 `protobuf:"varint,8,opt,name=string_value_strindex,json=stringValueStrindex,proto3,oneof"` } @@ -217,21 +234,18 @@ func (*AnyValue_StringValueStrindex) isAnyValue_Value() {} // ArrayValue is a list of AnyValue messages. We need ArrayValue as a message // since oneof in AnyValue does not allow repeated fields. type ArrayValue struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // Array of values. The array may be empty (contain 0 elements). - Values []*AnyValue `protobuf:"bytes,1,rep,name=values,proto3" json:"values,omitempty"` + Values []*AnyValue `protobuf:"bytes,1,rep,name=values,proto3" json:"values,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *ArrayValue) Reset() { *x = ArrayValue{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_common_v1_common_proto_msgTypes[1] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_common_v1_common_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *ArrayValue) String() string { @@ -242,7 +256,7 @@ func (*ArrayValue) ProtoMessage() {} func (x *ArrayValue) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_common_v1_common_proto_msgTypes[1] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -270,26 +284,23 @@ func (x *ArrayValue) GetValues() []*AnyValue { // avoid unnecessary extra wrapping (which slows down the protocol). The 2 approaches // are semantically equivalent. type KeyValueList struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // A collection of key/value pairs of key-value pairs. The list may be empty (may // contain 0 elements). // // The keys MUST be unique (it is not allowed to have more than one // value with the same key). // The behavior of software that receives duplicated keys can be unpredictable. - Values []*KeyValue `protobuf:"bytes,1,rep,name=values,proto3" json:"values,omitempty"` + Values []*KeyValue `protobuf:"bytes,1,rep,name=values,proto3" json:"values,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *KeyValueList) Reset() { *x = KeyValueList{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_common_v1_common_proto_msgTypes[2] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_common_v1_common_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *KeyValueList) String() string { @@ -300,7 +311,7 @@ func (*KeyValueList) ProtoMessage() {} func (x *KeyValueList) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_common_v1_common_proto_msgTypes[2] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -325,10 +336,7 @@ func (x *KeyValueList) GetValues() []*KeyValue { // Represents a key-value pair that is used to store Span attributes, Link // attributes, etc. type KeyValue struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // The key name of the pair. // key_strindex MUST NOT be set if key is used. Key string `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"` @@ -345,16 +353,18 @@ type KeyValue struct { // empty, ignoring its semantic content for the non-Profiling signal. // // Status: [Alpha] - KeyStrindex int32 `protobuf:"varint,3,opt,name=key_strindex,json=keyStrindex,proto3" json:"key_strindex,omitempty"` + // + // [Since v1.10.0] + KeyStrindex int32 `protobuf:"varint,3,opt,name=key_strindex,json=keyStrindex,proto3" json:"key_strindex,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *KeyValue) Reset() { *x = KeyValue{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_common_v1_common_proto_msgTypes[3] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_common_v1_common_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *KeyValue) String() string { @@ -365,7 +375,7 @@ func (*KeyValue) ProtoMessage() {} func (x *KeyValue) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_common_v1_common_proto_msgTypes[3] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -404,10 +414,7 @@ func (x *KeyValue) GetKeyStrindex() int32 { // InstrumentationScope is a message representing the instrumentation scope information // such as the fully qualified name and version. type InstrumentationScope struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // A name denoting the Instrumentation scope. // An empty instrumentation scope name means the name is unknown. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` @@ -423,15 +430,15 @@ type InstrumentationScope struct { // can be discarded because their keys are too long or because there are too many // attributes. If this value is 0, then no attributes were dropped. DroppedAttributesCount uint32 `protobuf:"varint,4,opt,name=dropped_attributes_count,json=droppedAttributesCount,proto3" json:"dropped_attributes_count,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *InstrumentationScope) Reset() { *x = InstrumentationScope{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_common_v1_common_proto_msgTypes[4] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_common_v1_common_proto_msgTypes[4] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *InstrumentationScope) String() string { @@ -442,7 +449,7 @@ func (*InstrumentationScope) ProtoMessage() {} func (x *InstrumentationScope) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_common_v1_common_proto_msgTypes[4] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -489,11 +496,10 @@ func (x *InstrumentationScope) GetDroppedAttributesCount() uint32 { // Entity represents an object of interest associated with produced telemetry: e.g spans, metrics, profiles, or logs. // // Status: [Development] +// +// [Since v1.6.0] type EntityRef struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // The Schema URL, if known. This is the identifier of the Schema that the entity data // is recorded in. To learn more about Schema URL see // https://opentelemetry.io/docs/specs/otel/schemas/#schema-url @@ -518,15 +524,15 @@ type EntityRef struct { // These attribute keys are not part of entity's identity. // These keys MUST exist in the containing {message}.attributes. DescriptionKeys []string `protobuf:"bytes,4,rep,name=description_keys,json=descriptionKeys,proto3" json:"description_keys,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *EntityRef) Reset() { *x = EntityRef{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_common_v1_common_proto_msgTypes[5] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_common_v1_common_proto_msgTypes[5] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *EntityRef) String() string { @@ -537,7 +543,7 @@ func (*EntityRef) ProtoMessage() {} func (x *EntityRef) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_common_v1_common_proto_msgTypes[5] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -582,101 +588,60 @@ func (x *EntityRef) GetDescriptionKeys() []string { var File_opentelemetry_proto_common_v1_common_proto protoreflect.FileDescriptor -var file_opentelemetry_proto_common_v1_common_proto_rawDesc = []byte{ - 0x0a, 0x2a, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2f, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2f, 0x76, 0x31, 0x2f, - 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x1d, 0x6f, 0x70, - 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, - 0x6f, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x76, 0x31, 0x22, 0x96, 0x03, 0x0a, 0x08, - 0x41, 0x6e, 0x79, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x23, 0x0a, 0x0c, 0x73, 0x74, 0x72, 0x69, - 0x6e, 0x67, 0x5f, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x48, 0x00, - 0x52, 0x0b, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x1f, 0x0a, - 0x0a, 0x62, 0x6f, 0x6f, 0x6c, 0x5f, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, - 0x08, 0x48, 0x00, 0x52, 0x09, 0x62, 0x6f, 0x6f, 0x6c, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x1d, - 0x0a, 0x09, 0x69, 0x6e, 0x74, 0x5f, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, - 0x03, 0x48, 0x00, 0x52, 0x08, 0x69, 0x6e, 0x74, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x23, 0x0a, - 0x0c, 0x64, 0x6f, 0x75, 0x62, 0x6c, 0x65, 0x5f, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x04, 0x20, - 0x01, 0x28, 0x01, 0x48, 0x00, 0x52, 0x0b, 0x64, 0x6f, 0x75, 0x62, 0x6c, 0x65, 0x56, 0x61, 0x6c, - 0x75, 0x65, 0x12, 0x4c, 0x0a, 0x0b, 0x61, 0x72, 0x72, 0x61, 0x79, 0x5f, 0x76, 0x61, 0x6c, 0x75, - 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x29, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, - 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x63, 0x6f, - 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x76, 0x31, 0x2e, 0x41, 0x72, 0x72, 0x61, 0x79, 0x56, 0x61, 0x6c, - 0x75, 0x65, 0x48, 0x00, 0x52, 0x0a, 0x61, 0x72, 0x72, 0x61, 0x79, 0x56, 0x61, 0x6c, 0x75, 0x65, - 0x12, 0x50, 0x0a, 0x0c, 0x6b, 0x76, 0x6c, 0x69, 0x73, 0x74, 0x5f, 0x76, 0x61, 0x6c, 0x75, 0x65, - 0x18, 0x06, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2b, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, - 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x63, 0x6f, 0x6d, - 0x6d, 0x6f, 0x6e, 0x2e, 0x76, 0x31, 0x2e, 0x4b, 0x65, 0x79, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x4c, - 0x69, 0x73, 0x74, 0x48, 0x00, 0x52, 0x0b, 0x6b, 0x76, 0x6c, 0x69, 0x73, 0x74, 0x56, 0x61, 0x6c, - 0x75, 0x65, 0x12, 0x21, 0x0a, 0x0b, 0x62, 0x79, 0x74, 0x65, 0x73, 0x5f, 0x76, 0x61, 0x6c, 0x75, - 0x65, 0x18, 0x07, 0x20, 0x01, 0x28, 0x0c, 0x48, 0x00, 0x52, 0x0a, 0x62, 0x79, 0x74, 0x65, 0x73, - 0x56, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x34, 0x0a, 0x15, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x5f, - 0x76, 0x61, 0x6c, 0x75, 0x65, 0x5f, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x64, 0x65, 0x78, 0x18, 0x08, - 0x20, 0x01, 0x28, 0x05, 0x48, 0x00, 0x52, 0x13, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, - 0x6c, 0x75, 0x65, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x64, 0x65, 0x78, 0x42, 0x07, 0x0a, 0x05, 0x76, - 0x61, 0x6c, 0x75, 0x65, 0x22, 0x4d, 0x0a, 0x0a, 0x41, 0x72, 0x72, 0x61, 0x79, 0x56, 0x61, 0x6c, - 0x75, 0x65, 0x12, 0x3f, 0x0a, 0x06, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, - 0x28, 0x0b, 0x32, 0x27, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, - 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, - 0x76, 0x31, 0x2e, 0x41, 0x6e, 0x79, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x06, 0x76, 0x61, 0x6c, - 0x75, 0x65, 0x73, 0x22, 0x4f, 0x0a, 0x0c, 0x4b, 0x65, 0x79, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x4c, - 0x69, 0x73, 0x74, 0x12, 0x3f, 0x0a, 0x06, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x73, 0x18, 0x01, 0x20, - 0x03, 0x28, 0x0b, 0x32, 0x27, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, - 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, - 0x2e, 0x76, 0x31, 0x2e, 0x4b, 0x65, 0x79, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x06, 0x76, 0x61, - 0x6c, 0x75, 0x65, 0x73, 0x22, 0x7e, 0x0a, 0x08, 0x4b, 0x65, 0x79, 0x56, 0x61, 0x6c, 0x75, 0x65, - 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, - 0x65, 0x79, 0x12, 0x3d, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, - 0x0b, 0x32, 0x27, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, - 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x76, - 0x31, 0x2e, 0x41, 0x6e, 0x79, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, - 0x65, 0x12, 0x21, 0x0a, 0x0c, 0x6b, 0x65, 0x79, 0x5f, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x64, 0x65, - 0x78, 0x18, 0x03, 0x20, 0x01, 0x28, 0x05, 0x52, 0x0b, 0x6b, 0x65, 0x79, 0x53, 0x74, 0x72, 0x69, - 0x6e, 0x64, 0x65, 0x78, 0x22, 0xc7, 0x01, 0x0a, 0x14, 0x49, 0x6e, 0x73, 0x74, 0x72, 0x75, 0x6d, - 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x12, 0x12, 0x0a, - 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, - 0x65, 0x12, 0x18, 0x0a, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x02, 0x20, 0x01, - 0x28, 0x09, 0x52, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x47, 0x0a, 0x0a, 0x61, - 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0b, 0x32, - 0x27, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x76, 0x31, 0x2e, - 0x4b, 0x65, 0x79, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x0a, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, - 0x75, 0x74, 0x65, 0x73, 0x12, 0x38, 0x0a, 0x18, 0x64, 0x72, 0x6f, 0x70, 0x70, 0x65, 0x64, 0x5f, - 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x5f, 0x63, 0x6f, 0x75, 0x6e, 0x74, - 0x18, 0x04, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x16, 0x64, 0x72, 0x6f, 0x70, 0x70, 0x65, 0x64, 0x41, - 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x22, 0x82, - 0x01, 0x0a, 0x09, 0x45, 0x6e, 0x74, 0x69, 0x74, 0x79, 0x52, 0x65, 0x66, 0x12, 0x1d, 0x0a, 0x0a, - 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x5f, 0x75, 0x72, 0x6c, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, - 0x52, 0x09, 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x55, 0x72, 0x6c, 0x12, 0x12, 0x0a, 0x04, 0x74, - 0x79, 0x70, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x74, 0x79, 0x70, 0x65, 0x12, - 0x17, 0x0a, 0x07, 0x69, 0x64, 0x5f, 0x6b, 0x65, 0x79, 0x73, 0x18, 0x03, 0x20, 0x03, 0x28, 0x09, - 0x52, 0x06, 0x69, 0x64, 0x4b, 0x65, 0x79, 0x73, 0x12, 0x29, 0x0a, 0x10, 0x64, 0x65, 0x73, 0x63, - 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x6b, 0x65, 0x79, 0x73, 0x18, 0x04, 0x20, 0x03, - 0x28, 0x09, 0x52, 0x0f, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x4b, - 0x65, 0x79, 0x73, 0x42, 0x7b, 0x0a, 0x20, 0x69, 0x6f, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, - 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x63, 0x6f, - 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x76, 0x31, 0x42, 0x0b, 0x43, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x50, - 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x28, 0x67, 0x6f, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, - 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x69, 0x6f, 0x2f, 0x70, 0x72, 0x6f, 0x74, - 0x6f, 0x2f, 0x6f, 0x74, 0x6c, 0x70, 0x2f, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2f, 0x76, 0x31, - 0xaa, 0x02, 0x1d, 0x4f, 0x70, 0x65, 0x6e, 0x54, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, - 0x2e, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x43, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x56, 0x31, - 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, -} +const file_opentelemetry_proto_common_v1_common_proto_rawDesc = "" + + "\n" + + "*opentelemetry/proto/common/v1/common.proto\x12\x1dopentelemetry.proto.common.v1\"\x96\x03\n" + + "\bAnyValue\x12#\n" + + "\fstring_value\x18\x01 \x01(\tH\x00R\vstringValue\x12\x1f\n" + + "\n" + + "bool_value\x18\x02 \x01(\bH\x00R\tboolValue\x12\x1d\n" + + "\tint_value\x18\x03 \x01(\x03H\x00R\bintValue\x12#\n" + + "\fdouble_value\x18\x04 \x01(\x01H\x00R\vdoubleValue\x12L\n" + + "\varray_value\x18\x05 \x01(\v2).opentelemetry.proto.common.v1.ArrayValueH\x00R\n" + + "arrayValue\x12P\n" + + "\fkvlist_value\x18\x06 \x01(\v2+.opentelemetry.proto.common.v1.KeyValueListH\x00R\vkvlistValue\x12!\n" + + "\vbytes_value\x18\a \x01(\fH\x00R\n" + + "bytesValue\x124\n" + + "\x15string_value_strindex\x18\b \x01(\x05H\x00R\x13stringValueStrindexB\a\n" + + "\x05value\"M\n" + + "\n" + + "ArrayValue\x12?\n" + + "\x06values\x18\x01 \x03(\v2'.opentelemetry.proto.common.v1.AnyValueR\x06values\"O\n" + + "\fKeyValueList\x12?\n" + + "\x06values\x18\x01 \x03(\v2'.opentelemetry.proto.common.v1.KeyValueR\x06values\"~\n" + + "\bKeyValue\x12\x10\n" + + "\x03key\x18\x01 \x01(\tR\x03key\x12=\n" + + "\x05value\x18\x02 \x01(\v2'.opentelemetry.proto.common.v1.AnyValueR\x05value\x12!\n" + + "\fkey_strindex\x18\x03 \x01(\x05R\vkeyStrindex\"\xc7\x01\n" + + "\x14InstrumentationScope\x12\x12\n" + + "\x04name\x18\x01 \x01(\tR\x04name\x12\x18\n" + + "\aversion\x18\x02 \x01(\tR\aversion\x12G\n" + + "\n" + + "attributes\x18\x03 \x03(\v2'.opentelemetry.proto.common.v1.KeyValueR\n" + + "attributes\x128\n" + + "\x18dropped_attributes_count\x18\x04 \x01(\rR\x16droppedAttributesCount\"\x82\x01\n" + + "\tEntityRef\x12\x1d\n" + + "\n" + + "schema_url\x18\x01 \x01(\tR\tschemaUrl\x12\x12\n" + + "\x04type\x18\x02 \x01(\tR\x04type\x12\x17\n" + + "\aid_keys\x18\x03 \x03(\tR\x06idKeys\x12)\n" + + "\x10description_keys\x18\x04 \x03(\tR\x0fdescriptionKeysB{\n" + + " io.opentelemetry.proto.common.v1B\vCommonProtoP\x01Z(go.opentelemetry.io/proto/otlp/common/v1\xaa\x02\x1dOpenTelemetry.Proto.Common.V1b\x06proto3" var ( file_opentelemetry_proto_common_v1_common_proto_rawDescOnce sync.Once - file_opentelemetry_proto_common_v1_common_proto_rawDescData = file_opentelemetry_proto_common_v1_common_proto_rawDesc + file_opentelemetry_proto_common_v1_common_proto_rawDescData []byte ) func file_opentelemetry_proto_common_v1_common_proto_rawDescGZIP() []byte { file_opentelemetry_proto_common_v1_common_proto_rawDescOnce.Do(func() { - file_opentelemetry_proto_common_v1_common_proto_rawDescData = protoimpl.X.CompressGZIP(file_opentelemetry_proto_common_v1_common_proto_rawDescData) + file_opentelemetry_proto_common_v1_common_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_opentelemetry_proto_common_v1_common_proto_rawDesc), len(file_opentelemetry_proto_common_v1_common_proto_rawDesc))) }) return file_opentelemetry_proto_common_v1_common_proto_rawDescData } var file_opentelemetry_proto_common_v1_common_proto_msgTypes = make([]protoimpl.MessageInfo, 6) -var file_opentelemetry_proto_common_v1_common_proto_goTypes = []interface{}{ +var file_opentelemetry_proto_common_v1_common_proto_goTypes = []any{ (*AnyValue)(nil), // 0: opentelemetry.proto.common.v1.AnyValue (*ArrayValue)(nil), // 1: opentelemetry.proto.common.v1.ArrayValue (*KeyValueList)(nil), // 2: opentelemetry.proto.common.v1.KeyValueList @@ -703,81 +668,7 @@ func file_opentelemetry_proto_common_v1_common_proto_init() { if File_opentelemetry_proto_common_v1_common_proto != nil { return } - if !protoimpl.UnsafeEnabled { - file_opentelemetry_proto_common_v1_common_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*AnyValue); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_opentelemetry_proto_common_v1_common_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ArrayValue); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_opentelemetry_proto_common_v1_common_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*KeyValueList); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_opentelemetry_proto_common_v1_common_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*KeyValue); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_opentelemetry_proto_common_v1_common_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*InstrumentationScope); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_opentelemetry_proto_common_v1_common_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*EntityRef); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - } - file_opentelemetry_proto_common_v1_common_proto_msgTypes[0].OneofWrappers = []interface{}{ + file_opentelemetry_proto_common_v1_common_proto_msgTypes[0].OneofWrappers = []any{ (*AnyValue_StringValue)(nil), (*AnyValue_BoolValue)(nil), (*AnyValue_IntValue)(nil), @@ -791,7 +682,7 @@ func file_opentelemetry_proto_common_v1_common_proto_init() { out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), - RawDescriptor: file_opentelemetry_proto_common_v1_common_proto_rawDesc, + RawDescriptor: unsafe.Slice(unsafe.StringData(file_opentelemetry_proto_common_v1_common_proto_rawDesc), len(file_opentelemetry_proto_common_v1_common_proto_rawDesc)), NumEnums: 0, NumMessages: 6, NumExtensions: 0, @@ -802,7 +693,6 @@ func file_opentelemetry_proto_common_v1_common_proto_init() { MessageInfos: file_opentelemetry_proto_common_v1_common_proto_msgTypes, }.Build() File_opentelemetry_proto_common_v1_common_proto = out.File - file_opentelemetry_proto_common_v1_common_proto_rawDesc = nil file_opentelemetry_proto_common_v1_common_proto_goTypes = nil file_opentelemetry_proto_common_v1_common_proto_depIdxs = nil } diff --git a/vendor/go.opentelemetry.io/proto/otlp/resource/v1/resource.pb.go b/vendor/go.opentelemetry.io/proto/otlp/resource/v1/resource.pb.go index 301247d..de95b8f 100644 --- a/vendor/go.opentelemetry.io/proto/otlp/resource/v1/resource.pb.go +++ b/vendor/go.opentelemetry.io/proto/otlp/resource/v1/resource.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.6 +// protoc-gen-go v1.36.11 +// protoc v7.35.0 // source: opentelemetry/proto/resource/v1/resource.proto package v1 @@ -26,6 +26,7 @@ import ( protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" + unsafe "unsafe" ) const ( @@ -37,10 +38,7 @@ const ( // Resource information. type Resource struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // Set of attributes that describe the resource. // Attribute keys MUST be unique (it is not allowed to have more than one // attribute with the same key). @@ -54,16 +52,18 @@ type Resource struct { // Note: keys in the references MUST exist in attributes of this message. // // Status: [Development] - EntityRefs []*v1.EntityRef `protobuf:"bytes,3,rep,name=entity_refs,json=entityRefs,proto3" json:"entity_refs,omitempty"` + // + // [Since v1.6.0] + EntityRefs []*v1.EntityRef `protobuf:"bytes,3,rep,name=entity_refs,json=entityRefs,proto3" json:"entity_refs,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *Resource) Reset() { *x = Resource{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_resource_v1_resource_proto_msgTypes[0] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_resource_v1_resource_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *Resource) String() string { @@ -74,7 +74,7 @@ func (*Resource) ProtoMessage() {} func (x *Resource) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_resource_v1_resource_proto_msgTypes[0] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -112,54 +112,32 @@ func (x *Resource) GetEntityRefs() []*v1.EntityRef { var File_opentelemetry_proto_resource_v1_resource_proto protoreflect.FileDescriptor -var file_opentelemetry_proto_resource_v1_resource_proto_rawDesc = []byte{ - 0x0a, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2f, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x2f, 0x76, - 0x31, 0x2f, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, - 0x12, 0x1f, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x2e, 0x76, - 0x31, 0x1a, 0x2a, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, - 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2f, 0x76, 0x31, - 0x2f, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xd8, 0x01, - 0x0a, 0x08, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x12, 0x47, 0x0a, 0x0a, 0x61, 0x74, - 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x27, - 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, - 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x76, 0x31, 0x2e, 0x4b, - 0x65, 0x79, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x0a, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, - 0x74, 0x65, 0x73, 0x12, 0x38, 0x0a, 0x18, 0x64, 0x72, 0x6f, 0x70, 0x70, 0x65, 0x64, 0x5f, 0x61, - 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x5f, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x18, - 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x16, 0x64, 0x72, 0x6f, 0x70, 0x70, 0x65, 0x64, 0x41, 0x74, - 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x49, 0x0a, - 0x0b, 0x65, 0x6e, 0x74, 0x69, 0x74, 0x79, 0x5f, 0x72, 0x65, 0x66, 0x73, 0x18, 0x03, 0x20, 0x03, - 0x28, 0x0b, 0x32, 0x28, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, - 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, - 0x76, 0x31, 0x2e, 0x45, 0x6e, 0x74, 0x69, 0x74, 0x79, 0x52, 0x65, 0x66, 0x52, 0x0a, 0x65, 0x6e, - 0x74, 0x69, 0x74, 0x79, 0x52, 0x65, 0x66, 0x73, 0x42, 0x83, 0x01, 0x0a, 0x22, 0x69, 0x6f, 0x2e, - 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, - 0x6f, 0x74, 0x6f, 0x2e, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x2e, 0x76, 0x31, 0x42, - 0x0d, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, - 0x5a, 0x2a, 0x67, 0x6f, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, - 0x72, 0x79, 0x2e, 0x69, 0x6f, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x6f, 0x74, 0x6c, 0x70, - 0x2f, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x2f, 0x76, 0x31, 0xaa, 0x02, 0x1f, 0x4f, - 0x70, 0x65, 0x6e, 0x54, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x50, 0x72, 0x6f, - 0x74, 0x6f, 0x2e, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x2e, 0x56, 0x31, 0x62, 0x06, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, -} +const file_opentelemetry_proto_resource_v1_resource_proto_rawDesc = "" + + "\n" + + ".opentelemetry/proto/resource/v1/resource.proto\x12\x1fopentelemetry.proto.resource.v1\x1a*opentelemetry/proto/common/v1/common.proto\"\xd8\x01\n" + + "\bResource\x12G\n" + + "\n" + + "attributes\x18\x01 \x03(\v2'.opentelemetry.proto.common.v1.KeyValueR\n" + + "attributes\x128\n" + + "\x18dropped_attributes_count\x18\x02 \x01(\rR\x16droppedAttributesCount\x12I\n" + + "\ventity_refs\x18\x03 \x03(\v2(.opentelemetry.proto.common.v1.EntityRefR\n" + + "entityRefsB\x83\x01\n" + + "\"io.opentelemetry.proto.resource.v1B\rResourceProtoP\x01Z*go.opentelemetry.io/proto/otlp/resource/v1\xaa\x02\x1fOpenTelemetry.Proto.Resource.V1b\x06proto3" var ( file_opentelemetry_proto_resource_v1_resource_proto_rawDescOnce sync.Once - file_opentelemetry_proto_resource_v1_resource_proto_rawDescData = file_opentelemetry_proto_resource_v1_resource_proto_rawDesc + file_opentelemetry_proto_resource_v1_resource_proto_rawDescData []byte ) func file_opentelemetry_proto_resource_v1_resource_proto_rawDescGZIP() []byte { file_opentelemetry_proto_resource_v1_resource_proto_rawDescOnce.Do(func() { - file_opentelemetry_proto_resource_v1_resource_proto_rawDescData = protoimpl.X.CompressGZIP(file_opentelemetry_proto_resource_v1_resource_proto_rawDescData) + file_opentelemetry_proto_resource_v1_resource_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_opentelemetry_proto_resource_v1_resource_proto_rawDesc), len(file_opentelemetry_proto_resource_v1_resource_proto_rawDesc))) }) return file_opentelemetry_proto_resource_v1_resource_proto_rawDescData } var file_opentelemetry_proto_resource_v1_resource_proto_msgTypes = make([]protoimpl.MessageInfo, 1) -var file_opentelemetry_proto_resource_v1_resource_proto_goTypes = []interface{}{ +var file_opentelemetry_proto_resource_v1_resource_proto_goTypes = []any{ (*Resource)(nil), // 0: opentelemetry.proto.resource.v1.Resource (*v1.KeyValue)(nil), // 1: opentelemetry.proto.common.v1.KeyValue (*v1.EntityRef)(nil), // 2: opentelemetry.proto.common.v1.EntityRef @@ -179,25 +157,11 @@ func file_opentelemetry_proto_resource_v1_resource_proto_init() { if File_opentelemetry_proto_resource_v1_resource_proto != nil { return } - if !protoimpl.UnsafeEnabled { - file_opentelemetry_proto_resource_v1_resource_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*Resource); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), - RawDescriptor: file_opentelemetry_proto_resource_v1_resource_proto_rawDesc, + RawDescriptor: unsafe.Slice(unsafe.StringData(file_opentelemetry_proto_resource_v1_resource_proto_rawDesc), len(file_opentelemetry_proto_resource_v1_resource_proto_rawDesc)), NumEnums: 0, NumMessages: 1, NumExtensions: 0, @@ -208,7 +172,6 @@ func file_opentelemetry_proto_resource_v1_resource_proto_init() { MessageInfos: file_opentelemetry_proto_resource_v1_resource_proto_msgTypes, }.Build() File_opentelemetry_proto_resource_v1_resource_proto = out.File - file_opentelemetry_proto_resource_v1_resource_proto_rawDesc = nil file_opentelemetry_proto_resource_v1_resource_proto_goTypes = nil file_opentelemetry_proto_resource_v1_resource_proto_depIdxs = nil } diff --git a/vendor/go.opentelemetry.io/proto/otlp/trace/v1/trace.pb.go b/vendor/go.opentelemetry.io/proto/otlp/trace/v1/trace.pb.go index d7bfca9..9a9daf4 100644 --- a/vendor/go.opentelemetry.io/proto/otlp/trace/v1/trace.pb.go +++ b/vendor/go.opentelemetry.io/proto/otlp/trace/v1/trace.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.6 +// protoc-gen-go v1.36.11 +// protoc v7.35.0 // source: opentelemetry/proto/trace/v1/trace.proto package v1 @@ -27,6 +27,7 @@ import ( protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" + unsafe "unsafe" ) const ( @@ -42,7 +43,7 @@ const ( // a bit-mask. To extract the bit-field, for example, use an // expression like: // -// (span.flags & SPAN_FLAGS_TRACE_FLAGS_MASK) +// (span.flags & SPAN_FLAGS_TRACE_FLAGS_MASK) // // See https://www.w3.org/TR/trace-context-2/#trace-flags for the flag definitions. // @@ -50,6 +51,8 @@ const ( // OpenTelemetry protocol. Older Span producers do not set this // field, consequently consumers should not rely on the absence of a // particular flag bit to indicate the presence of a particular feature. +// +// [Since v1.1.0] type SpanFlags int32 const ( @@ -61,8 +64,11 @@ const ( // Bits 8 and 9 are used to indicate that the parent span or link span is remote. // Bit 8 (`HAS_IS_REMOTE`) indicates whether the value is known. // Bit 9 (`IS_REMOTE`) indicates whether the span or link is remote. + // + // [Since v1.2.0] SpanFlags_SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE_MASK SpanFlags = 256 - SpanFlags_SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK SpanFlags = 512 + // [Since v1.2.0] + SpanFlags_SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK SpanFlags = 512 ) // Enum value maps for SpanFlags. @@ -248,25 +254,22 @@ func (Status_StatusCode) EnumDescriptor() ([]byte, []int) { // When new fields are added into this message, the OTLP request MUST be updated // as well. type TracesData struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // An array of ResourceSpans. // For data coming from a single resource this array will typically contain // one element. Intermediary nodes that receive data from multiple origins // typically batch the data before forwarding further and in that case this // array will contain multiple elements. ResourceSpans []*ResourceSpans `protobuf:"bytes,1,rep,name=resource_spans,json=resourceSpans,proto3" json:"resource_spans,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *TracesData) Reset() { *x = TracesData{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_trace_v1_trace_proto_msgTypes[0] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_trace_v1_trace_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *TracesData) String() string { @@ -277,7 +280,7 @@ func (*TracesData) ProtoMessage() {} func (x *TracesData) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_trace_v1_trace_proto_msgTypes[0] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -301,10 +304,7 @@ func (x *TracesData) GetResourceSpans() []*ResourceSpans { // A collection of ScopeSpans from a Resource. type ResourceSpans struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // The resource for the spans in this message. // If this field is not set then no resource info is known. Resource *v1.Resource `protobuf:"bytes,1,opt,name=resource,proto3" json:"resource,omitempty"` @@ -316,16 +316,16 @@ type ResourceSpans struct { // https://opentelemetry.io/docs/specs/otel/schemas/#schema-url // This schema_url applies to the data in the "resource" field. It does not apply // to the data in the "scope_spans" field which have their own schema_url field. - SchemaUrl string `protobuf:"bytes,3,opt,name=schema_url,json=schemaUrl,proto3" json:"schema_url,omitempty"` + SchemaUrl string `protobuf:"bytes,3,opt,name=schema_url,json=schemaUrl,proto3" json:"schema_url,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *ResourceSpans) Reset() { *x = ResourceSpans{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_trace_v1_trace_proto_msgTypes[1] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_trace_v1_trace_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *ResourceSpans) String() string { @@ -336,7 +336,7 @@ func (*ResourceSpans) ProtoMessage() {} func (x *ResourceSpans) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_trace_v1_trace_proto_msgTypes[1] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -374,10 +374,7 @@ func (x *ResourceSpans) GetSchemaUrl() string { // A collection of Spans produced by an InstrumentationScope. type ScopeSpans struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // The instrumentation scope information for the spans in this message. // Semantically when InstrumentationScope isn't set, it is equivalent with // an empty instrumentation scope name (unknown). @@ -390,16 +387,16 @@ type ScopeSpans struct { // https://opentelemetry.io/docs/specs/otel/schemas/#schema-url // This schema_url applies to the data in the "scope" field and all spans and span // events in the "spans" field. - SchemaUrl string `protobuf:"bytes,3,opt,name=schema_url,json=schemaUrl,proto3" json:"schema_url,omitempty"` + SchemaUrl string `protobuf:"bytes,3,opt,name=schema_url,json=schemaUrl,proto3" json:"schema_url,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *ScopeSpans) Reset() { *x = ScopeSpans{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_trace_v1_trace_proto_msgTypes[2] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_trace_v1_trace_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *ScopeSpans) String() string { @@ -410,7 +407,7 @@ func (*ScopeSpans) ProtoMessage() {} func (x *ScopeSpans) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_trace_v1_trace_proto_msgTypes[2] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -450,10 +447,7 @@ func (x *ScopeSpans) GetSchemaUrl() string { // // The next available field id is 17. type Span struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // A unique identifier for a trace. All spans from the same trace share // the same `trace_id`. The ID is a 16-byte array. An ID with all zeroes OR // of length other than 16 bytes is considered invalid (empty string in OTLP/JSON @@ -496,6 +490,8 @@ type Span struct { // Readers MUST NOT assume that bits 10-31 (22 most significant bits) will be zero. // // [Optional]. + // + // [Since v1.1.0] Flags uint32 `protobuf:"fixed32,16,opt,name=flags,proto3" json:"flags,omitempty"` // A description of the span's operation. // @@ -528,12 +524,12 @@ type Span struct { // This field is semantically required and it is expected that end_time >= start_time. EndTimeUnixNano uint64 `protobuf:"fixed64,8,opt,name=end_time_unix_nano,json=endTimeUnixNano,proto3" json:"end_time_unix_nano,omitempty"` // A collection of key/value pairs. Note, global attributes - // like server name can be set using the resource API. Examples of attributes: + // like service name can be set using the resource API. Examples of attributes: // - // "/http/user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36" - // "/http/server_latency": 300 - // "example.com/myattribute": true - // "example.com/score": 10.239 + // "user_agent.original": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36" + // "http.response.status_code": 200 + // "com.example.myattribute": true + // "com.example.score": 10.239 // // Attribute keys MUST be unique (it is not allowed to have more than one // attribute with the same key). @@ -556,16 +552,16 @@ type Span struct { DroppedLinksCount uint32 `protobuf:"varint,14,opt,name=dropped_links_count,json=droppedLinksCount,proto3" json:"dropped_links_count,omitempty"` // An optional final status for this span. Semantically when Status isn't set, it means // span's status code is unset, i.e. assume STATUS_CODE_UNSET (code = 0). - Status *Status `protobuf:"bytes,15,opt,name=status,proto3" json:"status,omitempty"` + Status *Status `protobuf:"bytes,15,opt,name=status,proto3" json:"status,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *Span) Reset() { *x = Span{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_trace_v1_trace_proto_msgTypes[3] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_trace_v1_trace_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *Span) String() string { @@ -576,7 +572,7 @@ func (*Span) ProtoMessage() {} func (x *Span) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_trace_v1_trace_proto_msgTypes[3] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -706,23 +702,20 @@ func (x *Span) GetStatus() *Status { // The Status type defines a logical error model that is suitable for different // programming environments, including REST APIs and RPC APIs. type Status struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // A developer-facing human readable error message. Message string `protobuf:"bytes,2,opt,name=message,proto3" json:"message,omitempty"` // The status code. - Code Status_StatusCode `protobuf:"varint,3,opt,name=code,proto3,enum=opentelemetry.proto.trace.v1.Status_StatusCode" json:"code,omitempty"` + Code Status_StatusCode `protobuf:"varint,3,opt,name=code,proto3,enum=opentelemetry.proto.trace.v1.Status_StatusCode" json:"code,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *Status) Reset() { *x = Status{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_trace_v1_trace_proto_msgTypes[4] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_trace_v1_trace_proto_msgTypes[4] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *Status) String() string { @@ -733,7 +726,7 @@ func (*Status) ProtoMessage() {} func (x *Status) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_trace_v1_trace_proto_msgTypes[4] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -765,10 +758,7 @@ func (x *Status) GetCode() Status_StatusCode { // Event is a time-stamped annotation of the span, consisting of user-supplied // text description and key-value pairs. type Span_Event struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // The time the event occurred. TimeUnixNano uint64 `protobuf:"fixed64,1,opt,name=time_unix_nano,json=timeUnixNano,proto3" json:"time_unix_nano,omitempty"` // The name of the event. @@ -782,15 +772,15 @@ type Span_Event struct { // The number of dropped attributes. If the value is 0, // then no attributes were dropped. DroppedAttributesCount uint32 `protobuf:"varint,4,opt,name=dropped_attributes_count,json=droppedAttributesCount,proto3" json:"dropped_attributes_count,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *Span_Event) Reset() { *x = Span_Event{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_trace_v1_trace_proto_msgTypes[5] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_trace_v1_trace_proto_msgTypes[5] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *Span_Event) String() string { @@ -801,7 +791,7 @@ func (*Span_Event) ProtoMessage() {} func (x *Span_Event) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_trace_v1_trace_proto_msgTypes[5] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -849,10 +839,7 @@ func (x *Span_Event) GetDroppedAttributesCount() uint32 { // where a single batch handler processes multiple requests from different // traces or when the handler receives a request from a different project. type Span_Link struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - + state protoimpl.MessageState `protogen:"open.v1"` // A unique identifier of a trace that this linked span is part of. The ID is a // 16-byte array. TraceId []byte `protobuf:"bytes,1,opt,name=trace_id,json=traceId,proto3" json:"trace_id,omitempty"` @@ -885,16 +872,18 @@ type Span_Link struct { // When creating new spans, bits 10-31 (most-significant 22-bits) MUST be zero. // // [Optional]. - Flags uint32 `protobuf:"fixed32,6,opt,name=flags,proto3" json:"flags,omitempty"` + // + // [Since v1.1.0] + Flags uint32 `protobuf:"fixed32,6,opt,name=flags,proto3" json:"flags,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *Span_Link) Reset() { *x = Span_Link{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_trace_v1_trace_proto_msgTypes[6] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + mi := &file_opentelemetry_proto_trace_v1_trace_proto_msgTypes[6] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } func (x *Span_Link) String() string { @@ -905,7 +894,7 @@ func (*Span_Link) ProtoMessage() {} func (x *Span_Link) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_trace_v1_trace_proto_msgTypes[6] - if protoimpl.UnsafeEnabled && x != nil { + if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) @@ -964,179 +953,101 @@ func (x *Span_Link) GetFlags() uint32 { var File_opentelemetry_proto_trace_v1_trace_proto protoreflect.FileDescriptor -var file_opentelemetry_proto_trace_v1_trace_proto_rawDesc = []byte{ - 0x0a, 0x28, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2f, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x74, 0x72, 0x61, 0x63, 0x65, 0x2f, 0x76, 0x31, 0x2f, 0x74, - 0x72, 0x61, 0x63, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x1c, 0x6f, 0x70, 0x65, 0x6e, - 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, - 0x74, 0x72, 0x61, 0x63, 0x65, 0x2e, 0x76, 0x31, 0x1a, 0x2a, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, - 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x63, 0x6f, - 0x6d, 0x6d, 0x6f, 0x6e, 0x2f, 0x76, 0x31, 0x2f, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x70, - 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, - 0x74, 0x72, 0x79, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, - 0x63, 0x65, 0x2f, 0x76, 0x31, 0x2f, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x2e, 0x70, - 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x60, 0x0a, 0x0a, 0x54, 0x72, 0x61, 0x63, 0x65, 0x73, 0x44, 0x61, - 0x74, 0x61, 0x12, 0x52, 0x0a, 0x0e, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x5f, 0x73, - 0x70, 0x61, 0x6e, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2b, 0x2e, 0x6f, 0x70, 0x65, - 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, - 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, - 0x63, 0x65, 0x53, 0x70, 0x61, 0x6e, 0x73, 0x52, 0x0d, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, - 0x65, 0x53, 0x70, 0x61, 0x6e, 0x73, 0x22, 0xc8, 0x01, 0x0a, 0x0d, 0x52, 0x65, 0x73, 0x6f, 0x75, - 0x72, 0x63, 0x65, 0x53, 0x70, 0x61, 0x6e, 0x73, 0x12, 0x45, 0x0a, 0x08, 0x72, 0x65, 0x73, 0x6f, - 0x75, 0x72, 0x63, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x29, 0x2e, 0x6f, 0x70, 0x65, - 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, - 0x2e, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x52, 0x65, 0x73, - 0x6f, 0x75, 0x72, 0x63, 0x65, 0x52, 0x08, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x12, - 0x49, 0x0a, 0x0b, 0x73, 0x63, 0x6f, 0x70, 0x65, 0x5f, 0x73, 0x70, 0x61, 0x6e, 0x73, 0x18, 0x02, - 0x20, 0x03, 0x28, 0x0b, 0x32, 0x28, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, - 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, - 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x53, 0x70, 0x61, 0x6e, 0x73, 0x52, 0x0a, - 0x73, 0x63, 0x6f, 0x70, 0x65, 0x53, 0x70, 0x61, 0x6e, 0x73, 0x12, 0x1d, 0x0a, 0x0a, 0x73, 0x63, - 0x68, 0x65, 0x6d, 0x61, 0x5f, 0x75, 0x72, 0x6c, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, - 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x55, 0x72, 0x6c, 0x4a, 0x06, 0x08, 0xe8, 0x07, 0x10, 0xe9, - 0x07, 0x22, 0xb0, 0x01, 0x0a, 0x0a, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x53, 0x70, 0x61, 0x6e, 0x73, - 0x12, 0x49, 0x0a, 0x05, 0x73, 0x63, 0x6f, 0x70, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, - 0x33, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x76, 0x31, 0x2e, - 0x49, 0x6e, 0x73, 0x74, 0x72, 0x75, 0x6d, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x53, - 0x63, 0x6f, 0x70, 0x65, 0x52, 0x05, 0x73, 0x63, 0x6f, 0x70, 0x65, 0x12, 0x38, 0x0a, 0x05, 0x73, - 0x70, 0x61, 0x6e, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x22, 0x2e, 0x6f, 0x70, 0x65, - 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, - 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x70, 0x61, 0x6e, 0x52, 0x05, - 0x73, 0x70, 0x61, 0x6e, 0x73, 0x12, 0x1d, 0x0a, 0x0a, 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x5f, - 0x75, 0x72, 0x6c, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x73, 0x63, 0x68, 0x65, 0x6d, - 0x61, 0x55, 0x72, 0x6c, 0x22, 0xc8, 0x0a, 0x0a, 0x04, 0x53, 0x70, 0x61, 0x6e, 0x12, 0x19, 0x0a, - 0x08, 0x74, 0x72, 0x61, 0x63, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, - 0x07, 0x74, 0x72, 0x61, 0x63, 0x65, 0x49, 0x64, 0x12, 0x17, 0x0a, 0x07, 0x73, 0x70, 0x61, 0x6e, - 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x06, 0x73, 0x70, 0x61, 0x6e, 0x49, - 0x64, 0x12, 0x1f, 0x0a, 0x0b, 0x74, 0x72, 0x61, 0x63, 0x65, 0x5f, 0x73, 0x74, 0x61, 0x74, 0x65, - 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, 0x74, 0x72, 0x61, 0x63, 0x65, 0x53, 0x74, 0x61, - 0x74, 0x65, 0x12, 0x24, 0x0a, 0x0e, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x5f, 0x73, 0x70, 0x61, - 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0c, 0x70, 0x61, 0x72, 0x65, - 0x6e, 0x74, 0x53, 0x70, 0x61, 0x6e, 0x49, 0x64, 0x12, 0x14, 0x0a, 0x05, 0x66, 0x6c, 0x61, 0x67, - 0x73, 0x18, 0x10, 0x20, 0x01, 0x28, 0x07, 0x52, 0x05, 0x66, 0x6c, 0x61, 0x67, 0x73, 0x12, 0x12, - 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, - 0x6d, 0x65, 0x12, 0x3f, 0x0a, 0x04, 0x6b, 0x69, 0x6e, 0x64, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0e, - 0x32, 0x2b, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, - 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, 0x2e, 0x76, 0x31, 0x2e, - 0x53, 0x70, 0x61, 0x6e, 0x2e, 0x53, 0x70, 0x61, 0x6e, 0x4b, 0x69, 0x6e, 0x64, 0x52, 0x04, 0x6b, - 0x69, 0x6e, 0x64, 0x12, 0x2f, 0x0a, 0x14, 0x73, 0x74, 0x61, 0x72, 0x74, 0x5f, 0x74, 0x69, 0x6d, - 0x65, 0x5f, 0x75, 0x6e, 0x69, 0x78, 0x5f, 0x6e, 0x61, 0x6e, 0x6f, 0x18, 0x07, 0x20, 0x01, 0x28, - 0x06, 0x52, 0x11, 0x73, 0x74, 0x61, 0x72, 0x74, 0x54, 0x69, 0x6d, 0x65, 0x55, 0x6e, 0x69, 0x78, - 0x4e, 0x61, 0x6e, 0x6f, 0x12, 0x2b, 0x0a, 0x12, 0x65, 0x6e, 0x64, 0x5f, 0x74, 0x69, 0x6d, 0x65, - 0x5f, 0x75, 0x6e, 0x69, 0x78, 0x5f, 0x6e, 0x61, 0x6e, 0x6f, 0x18, 0x08, 0x20, 0x01, 0x28, 0x06, - 0x52, 0x0f, 0x65, 0x6e, 0x64, 0x54, 0x69, 0x6d, 0x65, 0x55, 0x6e, 0x69, 0x78, 0x4e, 0x61, 0x6e, - 0x6f, 0x12, 0x47, 0x0a, 0x0a, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x18, - 0x09, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x27, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, - 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, - 0x6f, 0x6e, 0x2e, 0x76, 0x31, 0x2e, 0x4b, 0x65, 0x79, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x0a, - 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x12, 0x38, 0x0a, 0x18, 0x64, 0x72, - 0x6f, 0x70, 0x70, 0x65, 0x64, 0x5f, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, - 0x5f, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x16, 0x64, 0x72, - 0x6f, 0x70, 0x70, 0x65, 0x64, 0x41, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x43, - 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x40, 0x0a, 0x06, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x73, 0x18, 0x0b, - 0x20, 0x03, 0x28, 0x0b, 0x32, 0x28, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, - 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, - 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x70, 0x61, 0x6e, 0x2e, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x52, 0x06, - 0x65, 0x76, 0x65, 0x6e, 0x74, 0x73, 0x12, 0x30, 0x0a, 0x14, 0x64, 0x72, 0x6f, 0x70, 0x70, 0x65, - 0x64, 0x5f, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x73, 0x5f, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x0c, - 0x20, 0x01, 0x28, 0x0d, 0x52, 0x12, 0x64, 0x72, 0x6f, 0x70, 0x70, 0x65, 0x64, 0x45, 0x76, 0x65, - 0x6e, 0x74, 0x73, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x3d, 0x0a, 0x05, 0x6c, 0x69, 0x6e, 0x6b, - 0x73, 0x18, 0x0d, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x27, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, - 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x74, 0x72, - 0x61, 0x63, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x70, 0x61, 0x6e, 0x2e, 0x4c, 0x69, 0x6e, 0x6b, - 0x52, 0x05, 0x6c, 0x69, 0x6e, 0x6b, 0x73, 0x12, 0x2e, 0x0a, 0x13, 0x64, 0x72, 0x6f, 0x70, 0x70, - 0x65, 0x64, 0x5f, 0x6c, 0x69, 0x6e, 0x6b, 0x73, 0x5f, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x0e, - 0x20, 0x01, 0x28, 0x0d, 0x52, 0x11, 0x64, 0x72, 0x6f, 0x70, 0x70, 0x65, 0x64, 0x4c, 0x69, 0x6e, - 0x6b, 0x73, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x3c, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, - 0x73, 0x18, 0x0f, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x24, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, - 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x74, 0x72, - 0x61, 0x63, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x06, 0x73, - 0x74, 0x61, 0x74, 0x75, 0x73, 0x1a, 0xc4, 0x01, 0x0a, 0x05, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x12, - 0x24, 0x0a, 0x0e, 0x74, 0x69, 0x6d, 0x65, 0x5f, 0x75, 0x6e, 0x69, 0x78, 0x5f, 0x6e, 0x61, 0x6e, - 0x6f, 0x18, 0x01, 0x20, 0x01, 0x28, 0x06, 0x52, 0x0c, 0x74, 0x69, 0x6d, 0x65, 0x55, 0x6e, 0x69, - 0x78, 0x4e, 0x61, 0x6e, 0x6f, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x02, 0x20, - 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x47, 0x0a, 0x0a, 0x61, 0x74, 0x74, - 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x27, 0x2e, - 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, - 0x6f, 0x74, 0x6f, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x76, 0x31, 0x2e, 0x4b, 0x65, - 0x79, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x0a, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, - 0x65, 0x73, 0x12, 0x38, 0x0a, 0x18, 0x64, 0x72, 0x6f, 0x70, 0x70, 0x65, 0x64, 0x5f, 0x61, 0x74, - 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x5f, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x04, - 0x20, 0x01, 0x28, 0x0d, 0x52, 0x16, 0x64, 0x72, 0x6f, 0x70, 0x70, 0x65, 0x64, 0x41, 0x74, 0x74, - 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x1a, 0xf4, 0x01, 0x0a, - 0x04, 0x4c, 0x69, 0x6e, 0x6b, 0x12, 0x19, 0x0a, 0x08, 0x74, 0x72, 0x61, 0x63, 0x65, 0x5f, 0x69, - 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x74, 0x72, 0x61, 0x63, 0x65, 0x49, 0x64, - 0x12, 0x17, 0x0a, 0x07, 0x73, 0x70, 0x61, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, - 0x0c, 0x52, 0x06, 0x73, 0x70, 0x61, 0x6e, 0x49, 0x64, 0x12, 0x1f, 0x0a, 0x0b, 0x74, 0x72, 0x61, - 0x63, 0x65, 0x5f, 0x73, 0x74, 0x61, 0x74, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, - 0x74, 0x72, 0x61, 0x63, 0x65, 0x53, 0x74, 0x61, 0x74, 0x65, 0x12, 0x47, 0x0a, 0x0a, 0x61, 0x74, - 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x18, 0x04, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x27, - 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, - 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x76, 0x31, 0x2e, 0x4b, - 0x65, 0x79, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x0a, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, - 0x74, 0x65, 0x73, 0x12, 0x38, 0x0a, 0x18, 0x64, 0x72, 0x6f, 0x70, 0x70, 0x65, 0x64, 0x5f, 0x61, - 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x5f, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x18, - 0x05, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x16, 0x64, 0x72, 0x6f, 0x70, 0x70, 0x65, 0x64, 0x41, 0x74, - 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x14, 0x0a, - 0x05, 0x66, 0x6c, 0x61, 0x67, 0x73, 0x18, 0x06, 0x20, 0x01, 0x28, 0x07, 0x52, 0x05, 0x66, 0x6c, - 0x61, 0x67, 0x73, 0x22, 0x99, 0x01, 0x0a, 0x08, 0x53, 0x70, 0x61, 0x6e, 0x4b, 0x69, 0x6e, 0x64, - 0x12, 0x19, 0x0a, 0x15, 0x53, 0x50, 0x41, 0x4e, 0x5f, 0x4b, 0x49, 0x4e, 0x44, 0x5f, 0x55, 0x4e, - 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x16, 0x0a, 0x12, 0x53, - 0x50, 0x41, 0x4e, 0x5f, 0x4b, 0x49, 0x4e, 0x44, 0x5f, 0x49, 0x4e, 0x54, 0x45, 0x52, 0x4e, 0x41, - 0x4c, 0x10, 0x01, 0x12, 0x14, 0x0a, 0x10, 0x53, 0x50, 0x41, 0x4e, 0x5f, 0x4b, 0x49, 0x4e, 0x44, - 0x5f, 0x53, 0x45, 0x52, 0x56, 0x45, 0x52, 0x10, 0x02, 0x12, 0x14, 0x0a, 0x10, 0x53, 0x50, 0x41, - 0x4e, 0x5f, 0x4b, 0x49, 0x4e, 0x44, 0x5f, 0x43, 0x4c, 0x49, 0x45, 0x4e, 0x54, 0x10, 0x03, 0x12, - 0x16, 0x0a, 0x12, 0x53, 0x50, 0x41, 0x4e, 0x5f, 0x4b, 0x49, 0x4e, 0x44, 0x5f, 0x50, 0x52, 0x4f, - 0x44, 0x55, 0x43, 0x45, 0x52, 0x10, 0x04, 0x12, 0x16, 0x0a, 0x12, 0x53, 0x50, 0x41, 0x4e, 0x5f, - 0x4b, 0x49, 0x4e, 0x44, 0x5f, 0x43, 0x4f, 0x4e, 0x53, 0x55, 0x4d, 0x45, 0x52, 0x10, 0x05, 0x22, - 0xbd, 0x01, 0x0a, 0x06, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x18, 0x0a, 0x07, 0x6d, 0x65, - 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x6d, 0x65, 0x73, - 0x73, 0x61, 0x67, 0x65, 0x12, 0x43, 0x0a, 0x04, 0x63, 0x6f, 0x64, 0x65, 0x18, 0x03, 0x20, 0x01, - 0x28, 0x0e, 0x32, 0x2f, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, - 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, 0x2e, 0x76, - 0x31, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x43, - 0x6f, 0x64, 0x65, 0x52, 0x04, 0x63, 0x6f, 0x64, 0x65, 0x22, 0x4e, 0x0a, 0x0a, 0x53, 0x74, 0x61, - 0x74, 0x75, 0x73, 0x43, 0x6f, 0x64, 0x65, 0x12, 0x15, 0x0a, 0x11, 0x53, 0x54, 0x41, 0x54, 0x55, - 0x53, 0x5f, 0x43, 0x4f, 0x44, 0x45, 0x5f, 0x55, 0x4e, 0x53, 0x45, 0x54, 0x10, 0x00, 0x12, 0x12, - 0x0a, 0x0e, 0x53, 0x54, 0x41, 0x54, 0x55, 0x53, 0x5f, 0x43, 0x4f, 0x44, 0x45, 0x5f, 0x4f, 0x4b, - 0x10, 0x01, 0x12, 0x15, 0x0a, 0x11, 0x53, 0x54, 0x41, 0x54, 0x55, 0x53, 0x5f, 0x43, 0x4f, 0x44, - 0x45, 0x5f, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x10, 0x02, 0x4a, 0x04, 0x08, 0x01, 0x10, 0x02, 0x2a, - 0x9c, 0x01, 0x0a, 0x09, 0x53, 0x70, 0x61, 0x6e, 0x46, 0x6c, 0x61, 0x67, 0x73, 0x12, 0x19, 0x0a, - 0x15, 0x53, 0x50, 0x41, 0x4e, 0x5f, 0x46, 0x4c, 0x41, 0x47, 0x53, 0x5f, 0x44, 0x4f, 0x5f, 0x4e, - 0x4f, 0x54, 0x5f, 0x55, 0x53, 0x45, 0x10, 0x00, 0x12, 0x20, 0x0a, 0x1b, 0x53, 0x50, 0x41, 0x4e, - 0x5f, 0x46, 0x4c, 0x41, 0x47, 0x53, 0x5f, 0x54, 0x52, 0x41, 0x43, 0x45, 0x5f, 0x46, 0x4c, 0x41, - 0x47, 0x53, 0x5f, 0x4d, 0x41, 0x53, 0x4b, 0x10, 0xff, 0x01, 0x12, 0x2a, 0x0a, 0x25, 0x53, 0x50, - 0x41, 0x4e, 0x5f, 0x46, 0x4c, 0x41, 0x47, 0x53, 0x5f, 0x43, 0x4f, 0x4e, 0x54, 0x45, 0x58, 0x54, - 0x5f, 0x48, 0x41, 0x53, 0x5f, 0x49, 0x53, 0x5f, 0x52, 0x45, 0x4d, 0x4f, 0x54, 0x45, 0x5f, 0x4d, - 0x41, 0x53, 0x4b, 0x10, 0x80, 0x02, 0x12, 0x26, 0x0a, 0x21, 0x53, 0x50, 0x41, 0x4e, 0x5f, 0x46, - 0x4c, 0x41, 0x47, 0x53, 0x5f, 0x43, 0x4f, 0x4e, 0x54, 0x45, 0x58, 0x54, 0x5f, 0x49, 0x53, 0x5f, - 0x52, 0x45, 0x4d, 0x4f, 0x54, 0x45, 0x5f, 0x4d, 0x41, 0x53, 0x4b, 0x10, 0x80, 0x04, 0x42, 0x77, - 0x0a, 0x1f, 0x69, 0x6f, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, - 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, 0x2e, 0x76, - 0x31, 0x42, 0x0a, 0x54, 0x72, 0x61, 0x63, 0x65, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, - 0x27, 0x67, 0x6f, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, - 0x79, 0x2e, 0x69, 0x6f, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x6f, 0x74, 0x6c, 0x70, 0x2f, - 0x74, 0x72, 0x61, 0x63, 0x65, 0x2f, 0x76, 0x31, 0xaa, 0x02, 0x1c, 0x4f, 0x70, 0x65, 0x6e, 0x54, - 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x54, - 0x72, 0x61, 0x63, 0x65, 0x2e, 0x56, 0x31, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, -} +const file_opentelemetry_proto_trace_v1_trace_proto_rawDesc = "" + + "\n" + + "(opentelemetry/proto/trace/v1/trace.proto\x12\x1copentelemetry.proto.trace.v1\x1a*opentelemetry/proto/common/v1/common.proto\x1a.opentelemetry/proto/resource/v1/resource.proto\"`\n" + + "\n" + + "TracesData\x12R\n" + + "\x0eresource_spans\x18\x01 \x03(\v2+.opentelemetry.proto.trace.v1.ResourceSpansR\rresourceSpans\"\xc8\x01\n" + + "\rResourceSpans\x12E\n" + + "\bresource\x18\x01 \x01(\v2).opentelemetry.proto.resource.v1.ResourceR\bresource\x12I\n" + + "\vscope_spans\x18\x02 \x03(\v2(.opentelemetry.proto.trace.v1.ScopeSpansR\n" + + "scopeSpans\x12\x1d\n" + + "\n" + + "schema_url\x18\x03 \x01(\tR\tschemaUrlJ\x06\b\xe8\a\x10\xe9\a\"\xb0\x01\n" + + "\n" + + "ScopeSpans\x12I\n" + + "\x05scope\x18\x01 \x01(\v23.opentelemetry.proto.common.v1.InstrumentationScopeR\x05scope\x128\n" + + "\x05spans\x18\x02 \x03(\v2\".opentelemetry.proto.trace.v1.SpanR\x05spans\x12\x1d\n" + + "\n" + + "schema_url\x18\x03 \x01(\tR\tschemaUrl\"\xc8\n" + + "\n" + + "\x04Span\x12\x19\n" + + "\btrace_id\x18\x01 \x01(\fR\atraceId\x12\x17\n" + + "\aspan_id\x18\x02 \x01(\fR\x06spanId\x12\x1f\n" + + "\vtrace_state\x18\x03 \x01(\tR\n" + + "traceState\x12$\n" + + "\x0eparent_span_id\x18\x04 \x01(\fR\fparentSpanId\x12\x14\n" + + "\x05flags\x18\x10 \x01(\aR\x05flags\x12\x12\n" + + "\x04name\x18\x05 \x01(\tR\x04name\x12?\n" + + "\x04kind\x18\x06 \x01(\x0e2+.opentelemetry.proto.trace.v1.Span.SpanKindR\x04kind\x12/\n" + + "\x14start_time_unix_nano\x18\a \x01(\x06R\x11startTimeUnixNano\x12+\n" + + "\x12end_time_unix_nano\x18\b \x01(\x06R\x0fendTimeUnixNano\x12G\n" + + "\n" + + "attributes\x18\t \x03(\v2'.opentelemetry.proto.common.v1.KeyValueR\n" + + "attributes\x128\n" + + "\x18dropped_attributes_count\x18\n" + + " \x01(\rR\x16droppedAttributesCount\x12@\n" + + "\x06events\x18\v \x03(\v2(.opentelemetry.proto.trace.v1.Span.EventR\x06events\x120\n" + + "\x14dropped_events_count\x18\f \x01(\rR\x12droppedEventsCount\x12=\n" + + "\x05links\x18\r \x03(\v2'.opentelemetry.proto.trace.v1.Span.LinkR\x05links\x12.\n" + + "\x13dropped_links_count\x18\x0e \x01(\rR\x11droppedLinksCount\x12<\n" + + "\x06status\x18\x0f \x01(\v2$.opentelemetry.proto.trace.v1.StatusR\x06status\x1a\xc4\x01\n" + + "\x05Event\x12$\n" + + "\x0etime_unix_nano\x18\x01 \x01(\x06R\ftimeUnixNano\x12\x12\n" + + "\x04name\x18\x02 \x01(\tR\x04name\x12G\n" + + "\n" + + "attributes\x18\x03 \x03(\v2'.opentelemetry.proto.common.v1.KeyValueR\n" + + "attributes\x128\n" + + "\x18dropped_attributes_count\x18\x04 \x01(\rR\x16droppedAttributesCount\x1a\xf4\x01\n" + + "\x04Link\x12\x19\n" + + "\btrace_id\x18\x01 \x01(\fR\atraceId\x12\x17\n" + + "\aspan_id\x18\x02 \x01(\fR\x06spanId\x12\x1f\n" + + "\vtrace_state\x18\x03 \x01(\tR\n" + + "traceState\x12G\n" + + "\n" + + "attributes\x18\x04 \x03(\v2'.opentelemetry.proto.common.v1.KeyValueR\n" + + "attributes\x128\n" + + "\x18dropped_attributes_count\x18\x05 \x01(\rR\x16droppedAttributesCount\x12\x14\n" + + "\x05flags\x18\x06 \x01(\aR\x05flags\"\x99\x01\n" + + "\bSpanKind\x12\x19\n" + + "\x15SPAN_KIND_UNSPECIFIED\x10\x00\x12\x16\n" + + "\x12SPAN_KIND_INTERNAL\x10\x01\x12\x14\n" + + "\x10SPAN_KIND_SERVER\x10\x02\x12\x14\n" + + "\x10SPAN_KIND_CLIENT\x10\x03\x12\x16\n" + + "\x12SPAN_KIND_PRODUCER\x10\x04\x12\x16\n" + + "\x12SPAN_KIND_CONSUMER\x10\x05\"\xbd\x01\n" + + "\x06Status\x12\x18\n" + + "\amessage\x18\x02 \x01(\tR\amessage\x12C\n" + + "\x04code\x18\x03 \x01(\x0e2/.opentelemetry.proto.trace.v1.Status.StatusCodeR\x04code\"N\n" + + "\n" + + "StatusCode\x12\x15\n" + + "\x11STATUS_CODE_UNSET\x10\x00\x12\x12\n" + + "\x0eSTATUS_CODE_OK\x10\x01\x12\x15\n" + + "\x11STATUS_CODE_ERROR\x10\x02J\x04\b\x01\x10\x02*\x9c\x01\n" + + "\tSpanFlags\x12\x19\n" + + "\x15SPAN_FLAGS_DO_NOT_USE\x10\x00\x12 \n" + + "\x1bSPAN_FLAGS_TRACE_FLAGS_MASK\x10\xff\x01\x12*\n" + + "%SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE_MASK\x10\x80\x02\x12&\n" + + "!SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK\x10\x80\x04Bw\n" + + "\x1fio.opentelemetry.proto.trace.v1B\n" + + "TraceProtoP\x01Z'go.opentelemetry.io/proto/otlp/trace/v1\xaa\x02\x1cOpenTelemetry.Proto.Trace.V1b\x06proto3" var ( file_opentelemetry_proto_trace_v1_trace_proto_rawDescOnce sync.Once - file_opentelemetry_proto_trace_v1_trace_proto_rawDescData = file_opentelemetry_proto_trace_v1_trace_proto_rawDesc + file_opentelemetry_proto_trace_v1_trace_proto_rawDescData []byte ) func file_opentelemetry_proto_trace_v1_trace_proto_rawDescGZIP() []byte { file_opentelemetry_proto_trace_v1_trace_proto_rawDescOnce.Do(func() { - file_opentelemetry_proto_trace_v1_trace_proto_rawDescData = protoimpl.X.CompressGZIP(file_opentelemetry_proto_trace_v1_trace_proto_rawDescData) + file_opentelemetry_proto_trace_v1_trace_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_opentelemetry_proto_trace_v1_trace_proto_rawDesc), len(file_opentelemetry_proto_trace_v1_trace_proto_rawDesc))) }) return file_opentelemetry_proto_trace_v1_trace_proto_rawDescData } var file_opentelemetry_proto_trace_v1_trace_proto_enumTypes = make([]protoimpl.EnumInfo, 3) var file_opentelemetry_proto_trace_v1_trace_proto_msgTypes = make([]protoimpl.MessageInfo, 7) -var file_opentelemetry_proto_trace_v1_trace_proto_goTypes = []interface{}{ +var file_opentelemetry_proto_trace_v1_trace_proto_goTypes = []any{ (SpanFlags)(0), // 0: opentelemetry.proto.trace.v1.SpanFlags (Span_SpanKind)(0), // 1: opentelemetry.proto.trace.v1.Span.SpanKind (Status_StatusCode)(0), // 2: opentelemetry.proto.trace.v1.Status.StatusCode @@ -1177,97 +1088,11 @@ func file_opentelemetry_proto_trace_v1_trace_proto_init() { if File_opentelemetry_proto_trace_v1_trace_proto != nil { return } - if !protoimpl.UnsafeEnabled { - file_opentelemetry_proto_trace_v1_trace_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*TracesData); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_opentelemetry_proto_trace_v1_trace_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ResourceSpans); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_opentelemetry_proto_trace_v1_trace_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ScopeSpans); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_opentelemetry_proto_trace_v1_trace_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*Span); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_opentelemetry_proto_trace_v1_trace_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*Status); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_opentelemetry_proto_trace_v1_trace_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*Span_Event); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_opentelemetry_proto_trace_v1_trace_proto_msgTypes[6].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*Span_Link); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), - RawDescriptor: file_opentelemetry_proto_trace_v1_trace_proto_rawDesc, + RawDescriptor: unsafe.Slice(unsafe.StringData(file_opentelemetry_proto_trace_v1_trace_proto_rawDesc), len(file_opentelemetry_proto_trace_v1_trace_proto_rawDesc)), NumEnums: 3, NumMessages: 7, NumExtensions: 0, @@ -1279,7 +1104,6 @@ func file_opentelemetry_proto_trace_v1_trace_proto_init() { MessageInfos: file_opentelemetry_proto_trace_v1_trace_proto_msgTypes, }.Build() File_opentelemetry_proto_trace_v1_trace_proto = out.File - file_opentelemetry_proto_trace_v1_trace_proto_rawDesc = nil file_opentelemetry_proto_trace_v1_trace_proto_goTypes = nil file_opentelemetry_proto_trace_v1_trace_proto_depIdxs = nil } diff --git a/vendor/go.yaml.in/yaml/v3/resolve.go b/vendor/go.yaml.in/yaml/v3/resolve.go index 64ae888..d47f50e 100644 --- a/vendor/go.yaml.in/yaml/v3/resolve.go +++ b/vendor/go.yaml.in/yaml/v3/resolve.go @@ -42,6 +42,7 @@ func init() { for _, c := range "yYnNtTfFoO~" { t[int(c)] = 'M' // In map } + t[int('<')] = 'M' // In map (merge key "<<") t[int('.')] = '.' // Float (potentially in map) var resolveMapList = []struct { diff --git a/vendor/golang.org/x/net/http2/ascii.go b/vendor/golang.org/x/net/http2/ascii.go index 17caa20..3a7aed1 100644 --- a/vendor/golang.org/x/net/http2/ascii.go +++ b/vendor/golang.org/x/net/http2/ascii.go @@ -4,7 +4,9 @@ package http2 -import "strings" +import ( + "strings" +) // The HTTP protocols are defined in terms of ASCII, not Unicode. This file // contains helper functions which may use Unicode-aware functions which would @@ -43,6 +45,16 @@ func isASCIIPrint(s string) bool { return true } +// isASCII returns whether s is ASCII. +func isASCII(s string) bool { + for i := 0; i < len(s); i++ { + if s[i] > 0x7f { + return false + } + } + return true +} + // asciiToLower returns the lowercase version of s if s is ASCII and printable, // and whether or not it was. func asciiToLower(s string) (lower string, ok bool) { diff --git a/vendor/golang.org/x/net/http2/databuffer.go b/vendor/golang.org/x/net/http2/databuffer.go index e6f55cb..9763ab1 100644 --- a/vendor/golang.org/x/net/http2/databuffer.go +++ b/vendor/golang.org/x/net/http2/databuffer.go @@ -121,10 +121,7 @@ func (b *dataBuffer) Write(p []byte) (int, error) { // If the last chunk is empty, allocate a new chunk. Try to allocate // enough to fully copy p plus any additional bytes we expect to // receive. However, this may allocate less than len(p). - want := int64(len(p)) - if b.expected > want { - want = b.expected - } + want := max(int64(len(p)), b.expected) chunk := b.lastChunkOrAlloc(want) n := copy(chunk[b.w:], p) p = p[n:] diff --git a/vendor/golang.org/x/net/http2/flow.go b/vendor/golang.org/x/net/http2/flow.go index b7dbd18..5066a39 100644 --- a/vendor/golang.org/x/net/http2/flow.go +++ b/vendor/golang.org/x/net/http2/flow.go @@ -10,6 +10,9 @@ package http2 // flow control window update. const inflowMinRefresh = 4 << 10 +// maxFlowWindow is the maximum size of a flow control window. +const maxFlowWindow = (1 << 31) - 1 + // inflow accounts for an inbound flow control window. // It tracks both the latest window sent to the peer (used for enforcement) // and the accumulated unsent window. @@ -74,47 +77,99 @@ func takeInflows(f1, f2 *inflow, n uint32) bool { return true } -// outflow is the outbound flow control window's size. +// connOutflow is connection-level outbound flow control. +type connOutflow struct { + initial int32 // SETTINGS_INITIAL_WINDOW_SIZE, changes with settings updates + n int32 // connection-level flow control window + flowErr bool // set when a flow control error is encountered +} + +func (f *connOutflow) init() { + f.initial = initialWindowSize // initial stream window size + f.n = initialWindowSize // current connection window size +} + +func (f *connOutflow) changeInitialWindowSize(size int64) bool { + if size > maxFlowWindow { + f.flowErr = true + return false + } + f.initial = int32(size) + return true +} + +func (f *connOutflow) add(n int32) bool { + sum := int64(f.n) + int64(n) + if sum > maxFlowWindow { + f.flowErr = true + return false + } + f.n += n + return true +} + +// outflow is the stream-level outbound flow control window's size. type outflow struct { _ incomparable - // n is the number of DATA bytes we're allowed to send. - // An outflow is kept both on a conn and a per-stream. - n int32 + // delta is the difference between the stream's flow control window and + // the connection's initial window size (conn.initial). + // + // Another view is that delta is the number of flow control bytes provided to this + // stream in WINDOW_UPDATE frames, less the number of bytes sent on the stream. + delta int32 // conn points to the shared connection-level outflow that is - // shared by all streams on that conn. It is nil for the outflow - // that's on the conn directly. - conn *outflow + // shared by all streams on that conn. + conn *connOutflow } -func (f *outflow) setConnFlow(cf *outflow) { f.conn = cf } - -func (f *outflow) available() int32 { - n := f.n - if f.conn != nil && f.conn.n < n { - n = f.conn.n +func (f *outflow) available() (int32, bool) { + if f.conn == nil { + return maxFlowWindow, true // only happens in tests } - return n + if f.conn.flowErr { + // Block all sending once any stream observes a flow control error. + return 0, false + } + n := int64(f.conn.initial) + int64(f.delta) + if n > maxFlowWindow { + f.conn.flowErr = true + return 0, false + } + return min(int32(n), f.conn.n), true } func (f *outflow) take(n int32) { - if n > f.available() { + if f.conn == nil { + return // only happens in tests + } + avail, _ := f.available() + if n > avail { panic("internal error: took too much") } - f.n -= n - if f.conn != nil { - f.conn.n -= n - } + f.delta -= n + f.conn.n -= n } // add adds n bytes (positive or negative) to the flow control window. // It returns false if the sum would exceed 2^31-1. func (f *outflow) add(n int32) bool { - sum := f.n + n - if (sum > n) == (f.n > 0) { - f.n = sum - return true + if f.conn == nil { + return true // only happens in tests } - return false + avail := int64(f.conn.initial) + int64(f.delta) + if avail > maxFlowWindow { + // An earlier change to the initial window pushed this stream over the limit. + // This is a connection-level flow control error. + f.conn.flowErr = true + return false + } + if avail+int64(n) > maxFlowWindow { + // This update would push the stream over the limit. + // This is a stream-level flow control error. + return false + } + f.delta += n + return true } diff --git a/vendor/golang.org/x/net/http2/frame.go b/vendor/golang.org/x/net/http2/frame.go index be75bad..3363bba 100644 --- a/vendor/golang.org/x/net/http2/frame.go +++ b/vendor/golang.org/x/net/http2/frame.go @@ -1711,7 +1711,8 @@ func (fr *Framer) readMetaFrame(hf *HeadersFrame) (Frame, error) { mh := &MetaHeadersFrame{ HeadersFrame: hf, } - var remainSize = fr.maxHeaderListSize() + var headersRemainSize = fr.maxHeaderListSize() + var trailersRemainSize = fr.maxHeaderListSize() var sawRegular bool var invalid error // pseudo header field errors @@ -1743,14 +1744,29 @@ func (fr *Framer) readMetaFrame(hf *HeadersFrame) (Frame, error) { return } - size := hf.Size() - if size > remainSize { + var remainSize *uint32 + var size uint32 + if hf.Name == "trailer" { + remainSize = &trailersRemainSize + fieldCount := strings.Count(hf.Value, ",") + 1 + // Rather than actually constructing hpack.HeaderField for each + // trailer field and cumulatively adding its Size, just do the math + // manually to avoid unnecessary work. This does make it so + // whitespaces after comma are counted against the budget, but that + // should be innocuous. + size = uint32(len(hf.Value)-fieldCount+1) + uint32(fieldCount)*hpack.HeaderField{}.Size() + } else { + remainSize = &headersRemainSize + size = hf.Size() + } + if size > *remainSize { hdec.SetEmitEnabled(false) mh.Truncated = true - remainSize = 0 + headersRemainSize = 0 + trailersRemainSize = 0 return } - remainSize -= size + *remainSize -= size mh.Fields = append(mh.Fields, hf) }) @@ -1766,10 +1782,10 @@ func (fr *Framer) readMetaFrame(hf *HeadersFrame) (Frame, error) { // skip parsing the fragment and close the connection. // // "Too much" is either any CONTINUATION frame after we've already - // exceeded the max header list size (in which case remainSize is 0), - // or a frame whose encoded size is more than twice the remaining - // header list bytes we're willing to accept. - if int64(len(frag)) > int64(2*remainSize) { + // exceeded the max header list size (if so, both budgets are 0), or a + // frame whose encoded size is more than twice the remaining header + // list bytes we're willing to accept. + if int64(len(frag)) > 2*int64(headersRemainSize+trailersRemainSize) { if VerboseLogs { log.Printf("http2: header list too large") } diff --git a/vendor/golang.org/x/net/http2/server.go b/vendor/golang.org/x/net/http2/server.go index a7d2053..a6cd662 100644 --- a/vendor/golang.org/x/net/http2/server.go +++ b/vendor/golang.org/x/net/http2/server.go @@ -280,7 +280,6 @@ func (s *Server) serveConn(c net.Conn, opts *ServeConnOpts, newf func(*serverCon doneServing: make(chan struct{}), clientMaxStreams: math.MaxUint32, // Section 6.5.2: "Initially, there is no limit to this value" advMaxStreams: conf.MaxConcurrentStreams, - initialStreamSendWindowSize: initialWindowSize, initialStreamRecvWindowSize: conf.MaxUploadBufferPerStream, maxFrameSize: initialMaxFrameSize, pingTimeout: conf.PingTimeout, @@ -320,7 +319,7 @@ func (s *Server) serveConn(c net.Conn, opts *ServeConnOpts, newf func(*serverCon // These start at the RFC-specified defaults. If there is a higher // configured value for inflow, that will be updated when we send a // WINDOW_UPDATE shortly after sending SETTINGS. - sc.flow.add(initialWindowSize) + sc.flow.init() sc.inflow.init(initialWindowSize) sc.hpackEncoder = hpack.NewEncoder(&sc.headerWriteBuf) sc.hpackEncoder.SetMaxDynamicTableSizeLimit(conf.MaxEncoderHeaderTableSize) @@ -427,7 +426,7 @@ type serverConn struct { wroteFrameCh chan frameWriteResult // from writeFrameAsync -> serve, tickles more frame writes bodyReadCh chan bodyReadMsg // from handlers -> serve serveMsgCh chan interface{} // misc messages & code to send to / run on the serve loop - flow outflow // conn-wide (not stream-specific) outbound flow control + flow connOutflow // conn-wide (not stream-specific) outbound flow control inflow inflow // conn-wide inbound flow control tlsState *tls.ConnectionState // shared by all handlers, like net/http remoteAddrStr string @@ -441,6 +440,9 @@ type serverConn struct { sawFirstSettings bool // got the initial SETTINGS frame after the preface needToSendSettingsAck bool unackedSettings int // how many SETTINGS have we sent without ACKs? + pendingEncoderTableSize bool // peer changed SETTINGS_HEADER_TABLE_SIZE; apply to hpackEncoder before the next frame write + encoderTableSizeMin uint32 // smallest SETTINGS_HEADER_TABLE_SIZE since the last apply + encoderTableSize uint32 // latest SETTINGS_HEADER_TABLE_SIZE queuedControlFrames int // control frames in the writeSched queue clientMaxStreams uint32 // SETTINGS_MAX_CONCURRENT_STREAMS from client (our PUSH_PROMISE limit) advMaxStreams uint32 // our SETTINGS_MAX_CONCURRENT_STREAMS advertised the client @@ -451,7 +453,6 @@ type serverConn struct { maxPushPromiseID uint32 // ID of the last push promise (even), or 0 if there have been no pushes streams map[uint32]*stream unstartedHandlers []unstartedHandler - initialStreamSendWindowSize int32 initialStreamRecvWindowSize int32 maxFrameSize int32 peerMaxHeaderListSize uint32 // zero means unknown (default) @@ -521,7 +522,8 @@ type stream struct { // immutable: sc *serverConn id uint32 - body *pipe // non-nil if expecting DATA frames + body *pipe // non-nil if expecting DATA frames + reqBody *requestBody cw closeWaiter // closed wait stream transitions to closed state ctx context.Context cancelCtx func() @@ -1172,6 +1174,16 @@ func (sc *serverConn) startFrameWrite(wr FrameWriteRequest) { sc.writingFrame = true sc.needsFrameFlush = true + if sc.pendingEncoderTableSize { + // hpackEncoder may be in use by writeFrameAsync, so SETTINGS + // changes to it are deferred until no frame is being written. + // Replaying the smallest size before the latest one keeps the + // encoder's view identical to having applied every change + // (RFC 7541, Section 4.2). + sc.pendingEncoderTableSize = false + sc.hpackEncoder.SetMaxDynamicTableSize(sc.encoderTableSizeMin) + sc.hpackEncoder.SetMaxDynamicTableSize(sc.encoderTableSize) + } if wr.write.staysWithinBuffer(sc.bw.Available()) { sc.writingFrameAsync = false err := wr.write.writeFrame(sc) @@ -1271,6 +1283,11 @@ func (sc *serverConn) scheduleFrameWrite() { } sc.inFrameScheduleLoop = true for !sc.writingFrameAsync { + if sc.flow.flowErr && (!sc.inGoAway || sc.goAwayCode == ErrCodeNo) { + sc.inGoAway = true + sc.needToSendGoAway = true + sc.goAwayCode = ErrCodeFlowControl + } if sc.needToSendGoAway { sc.needToSendGoAway = false sc.startFrameWrite(FrameWriteRequest{ @@ -1294,6 +1311,9 @@ func (sc *serverConn) scheduleFrameWrite() { sc.startFrameWrite(wr) continue } + if sc.flow.flowErr { + continue + } } if sc.needsFrameFlush { sc.startFrameWrite(FrameWriteRequest{write: flushFrameWriter{}}) @@ -1526,6 +1546,10 @@ func (sc *serverConn) processWindowUpdate(f *WindowUpdateFrame) error { return nil } if !st.flow.add(int32(f.Increment)) { + if st.flow.conn.flowErr { + // This is a lazily-detected connection-level flow control error. + return sc.countError("bad_flow", ConnectionError(ErrCodeFlowControl)) + } return sc.countError("bad_flow", streamError(f.StreamID, ErrCodeFlowControl)) } default: // connection-level flow control @@ -1584,10 +1608,6 @@ func (sc *serverConn) closeStream(st *stream, err error) { } } if p := st.body; p != nil { - // Return any buffered unread bytes worth of conn-level flow control. - // See golang.org/issue/16481 - sc.sendWindowUpdate(nil, p.Len()) - p.CloseWithError(err) } if e, ok := err.(StreamError); ok { @@ -1641,7 +1661,12 @@ func (sc *serverConn) processSetting(s Setting) error { } switch s.ID { case SettingHeaderTableSize: - sc.hpackEncoder.SetMaxDynamicTableSize(s.Val) + // Applied by startFrameWrite; see comment there. + if !sc.pendingEncoderTableSize || s.Val < sc.encoderTableSizeMin { + sc.encoderTableSizeMin = s.Val + } + sc.encoderTableSize = s.Val + sc.pendingEncoderTableSize = true case SettingEnablePush: sc.pushEnabled = s.Val != 0 case SettingMaxConcurrentStreams: @@ -1672,28 +1697,14 @@ func (sc *serverConn) processSetting(s Setting) error { func (sc *serverConn) processSettingInitialWindowSize(val uint32) error { sc.serveG.check() - // Note: val already validated to be within range by - // processSetting's Valid call. - - // "A SETTINGS frame can alter the initial flow control window - // size for all current streams. When the value of - // SETTINGS_INITIAL_WINDOW_SIZE changes, a receiver MUST - // adjust the size of all stream flow control windows that it - // maintains by the difference between the new value and the - // old value." - old := sc.initialStreamSendWindowSize - sc.initialStreamSendWindowSize = int32(val) - growth := int32(val) - old // may be negative - for _, st := range sc.streams { - if !st.flow.add(growth) { - // 6.9.2 Initial Flow Control Window Size - // "An endpoint MUST treat a change to - // SETTINGS_INITIAL_WINDOW_SIZE that causes any flow - // control window to exceed the maximum size as a - // connection error (Section 5.4.1) of type - // FLOW_CONTROL_ERROR." - return sc.countError("setting_win_size", ConnectionError(ErrCodeFlowControl)) - } + if !sc.flow.changeInitialWindowSize(int64(val)) { + // 6.9.2 Initial Flow Control Window Size + // "An endpoint MUST treat a change to + // SETTINGS_INITIAL_WINDOW_SIZE that causes any flow + // control window to exceed the maximum size as a + // connection error (Section 5.4.1) of type + // FLOW_CONTROL_ERROR." + return sc.countError("setting_win_size", ConnectionError(ErrCodeFlowControl)) } return nil } @@ -1966,7 +1977,7 @@ func (sc *serverConn) processHeaders(f *MetaHeadersFrame) error { if st.reqTrailer != nil { st.trailer = make(http.Header) } - st.body = req.Body.(*requestBody).pipe // may be nil + st.body = st.reqBody.pipe // may be nil st.declBodyBytes = req.ContentLength handler := sc.handler.ServeHTTP @@ -1989,7 +2000,7 @@ func (sc *serverConn) processHeaders(f *MetaHeadersFrame) error { st.readDeadline = time.AfterFunc(sc.hs.ReadTimeout, st.onReadTimeout) } - return sc.scheduleHandler(id, rw, req, handler) + return sc.scheduleHandler(st, rw, req, handler) } func (sc *serverConn) upgradeRequest(req *http.Request) { @@ -2102,7 +2113,6 @@ func (sc *serverConn) newStream(id, pusherID uint32, state streamState, priority } st.cw.Init() st.flow.conn = &sc.flow // link to conn-level counter - st.flow.add(sc.initialStreamSendWindowSize) st.inflow.init(sc.initialStreamRecvWindowSize) if sc.hs.WriteTimeout > 0 { st.writeDeadline = time.AfterFunc(sc.hs.WriteTimeout, st.onWriteTimeout) @@ -2184,7 +2194,7 @@ func (sc *serverConn) newWriterAndRequest(st *stream, f *MetaHeadersFrame) (*res } else { req.ContentLength = -1 } - req.Body.(*requestBody).pipe = &pipe{ + st.reqBody.pipe = &pipe{ b: &dataBuffer{expected: req.ContentLength}, } } @@ -2204,7 +2214,7 @@ func (sc *serverConn) newWriterAndRequestNoBody(st *stream, rp httpcommon.Server return nil, nil, sc.countError(res.InvalidReason, streamError(st.id, ErrCodeProtocol)) } - body := &requestBody{ + st.reqBody = &requestBody{ conn: sc, stream: st, needsContinue: res.NeedsContinue, @@ -2220,7 +2230,7 @@ func (sc *serverConn) newWriterAndRequestNoBody(st *stream, rp httpcommon.Server ProtoMinor: 0, TLS: tlsState, Host: rp.Authority, - Body: body, + Body: st.reqBody, Trailer: res.Trailer, }).WithContext(st.ctx) rw := sc.newResponseWriter(st, req) @@ -2244,11 +2254,12 @@ type unstartedHandler struct { rw *responseWriter req *http.Request handler func(http.ResponseWriter, *http.Request) + body *pipe } // scheduleHandler starts a handler goroutine, // or schedules one to start as soon as an existing handler finishes. -func (sc *serverConn) scheduleHandler(streamID uint32, rw *responseWriter, req *http.Request, handler func(http.ResponseWriter, *http.Request)) error { +func (sc *serverConn) scheduleHandler(st *stream, rw *responseWriter, req *http.Request, handler func(http.ResponseWriter, *http.Request)) error { sc.serveG.check() maxHandlers := sc.advMaxStreams if sc.curHandlers < maxHandlers { @@ -2260,10 +2271,11 @@ func (sc *serverConn) scheduleHandler(streamID uint32, rw *responseWriter, req * return sc.countError("too_many_early_resets", ConnectionError(ErrCodeEnhanceYourCalm)) } sc.unstartedHandlers = append(sc.unstartedHandlers, unstartedHandler{ - streamID: streamID, + streamID: st.id, rw: rw, req: req, handler: handler, + body: st.body, }) return nil } @@ -2277,6 +2289,10 @@ func (sc *serverConn) handlerDone() { u := sc.unstartedHandlers[i] if sc.streams[u.streamID] == nil { // This stream was reset before its goroutine had a chance to start. + if u.body != nil { + u.body.BreakWithError(errClosedBody) + sc.sendWindowUpdate(nil, u.body.Len()) + } continue } if sc.curHandlers >= maxHandlers { @@ -2298,6 +2314,12 @@ func (sc *serverConn) runHandler(rw *responseWriter, req *http.Request, handler didPanic := true defer func() { rw.rws.stream.cancelCtx() + if b := rw.rws.stream.reqBody; b != nil { + // Closing the body refunds flow control credit for any unconsumed data. + // (reqBody is nil for Upgrade: h2c requests, but those do not use flow + // control for the request body.) + b.Close() + } if req.MultipartForm != nil { req.MultipartForm.RemoveAll() } @@ -2396,7 +2418,7 @@ func (sc *serverConn) noteBodyReadFromHandler(st *stream, n int, err error) { func (sc *serverConn) noteBodyRead(st *stream, n int) { sc.serveG.check() sc.sendWindowUpdate(nil, n) // conn-level - if st.state != stateHalfClosedRemote && st.state != stateClosed { + if st != nil && st.state != stateHalfClosedRemote && st.state != stateClosed { // Don't send this WINDOW_UPDATE if the stream is closed // remotely. sc.sendWindowUpdate(st, n) @@ -2444,6 +2466,9 @@ func (b *requestBody) Close() error { b.closeOnce.Do(func() { if b.pipe != nil { b.pipe.BreakWithError(errClosedBody) + if unread := b.pipe.Len(); unread > 0 { + b.conn.noteBodyReadFromHandler(nil, unread, errClosedBody) + } } }) return nil @@ -2461,9 +2486,6 @@ func (b *requestBody) Read(p []byte) (n int, err error) { if err == io.EOF { b.sawEOF = true } - if b.conn == nil { - return - } b.conn.noteBodyReadFromHandler(b.stream, n, err) return } diff --git a/vendor/golang.org/x/net/http2/server_common.go b/vendor/golang.org/x/net/http2/server_common.go index 449538c..fec3690 100644 --- a/vendor/golang.org/x/net/http2/server_common.go +++ b/vendor/golang.org/x/net/http2/server_common.go @@ -25,6 +25,8 @@ import ( // // https://golang.org/pkg/net/http/#ResponseWriter // https://golang.org/pkg/net/http/#example_ResponseWriter_trailers +// +// Deprecated: Use [http.TrailerPrefix] instead. const TrailerPrefix = "Trailer:" // Push errors. @@ -38,16 +40,22 @@ var ( // The configuration conf may be nil. // // ConfigureServer must be called before s begins serving. +// +// Deprecated: Set [http.Server.Protocols] instead. func ConfigureServer(s *http.Server, conf *Server) error { return configureServer(s, conf) } // Server is an HTTP/2 server. +// +// Deprecated: Use [http.Server] instead. type Server struct { // MaxHandlers limits the number of http.Handler ServeHTTP goroutines // which may run at a time over all connections. // Negative or zero no limit. // TODO: implement + // + // Deprecated: This field has never had any effect. MaxHandlers int // MaxConcurrentStreams optionally specifies the number of @@ -56,6 +64,9 @@ type Server struct { // which may be active globally, which is MaxHandlers. // If zero, MaxConcurrentStreams defaults to at least 100, per // the HTTP/2 spec's recommendations. + // + // Deprecated: Use [http.Server.HTTP2] and + // [http.HTTP2Config.MaxConcurrentStreams] instead. MaxConcurrentStreams uint32 // MaxDecoderHeaderTableSize optionally specifies the http2 @@ -63,44 +74,67 @@ type Server struct { // informs the remote endpoint of the maximum size of the header compression // table used to decode header blocks, in octets. If zero, the default value // of 4096 is used. + // + // Deprecated: Use [http.Server.HTTP2] and + // [http.HTTP2Config.MaxDecoderHeaderTableSize] instead. MaxDecoderHeaderTableSize uint32 // MaxEncoderHeaderTableSize optionally specifies an upper limit for the // header compression table used for encoding request headers. Received // SETTINGS_HEADER_TABLE_SIZE settings are capped at this limit. If zero, // the default value of 4096 is used. + // + // Deprecated: Use [http.Server.HTTP2] and + // [http.HTTP2Config.MaxEncoderHeaderTableSize] instead. MaxEncoderHeaderTableSize uint32 // MaxReadFrameSize optionally specifies the largest frame // this server is willing to read. A valid value is between // 16k and 16M, inclusive. If zero or otherwise invalid, a // default value is used. + // + // Deprecated: Use [http.Server.HTTP2] and + // [http.HTTP2Config.MaxReadFrameSize] instead. MaxReadFrameSize uint32 // PermitProhibitedCipherSuites, if true, permits the use of // cipher suites prohibited by the HTTP/2 spec. + // + // Deprecated: Use [http.Server.HTTP2] and + // [http.HTTP2Config.PermitProhibitedCipherSuites] instead. PermitProhibitedCipherSuites bool // IdleTimeout specifies how long until idle clients should be // closed with a GOAWAY frame. PING frames are not considered // activity for the purposes of IdleTimeout. // If zero or negative, there is no timeout. + // + // Deprecated: Use [http.Server.IdleTimeout] instead. IdleTimeout time.Duration // ReadIdleTimeout is the timeout after which a health check using a ping // frame will be carried out if no frame is received on the connection. // If zero, no health check is performed. + // + // Deprecated: Use [http.Server.HTTP2] and + // [http.HTTP2Config.SendPingTimeout] instead. ReadIdleTimeout time.Duration // PingTimeout is the timeout after which the connection will be closed // if a response to a ping is not received. // If zero, a default of 15 seconds is used. + // + // Deprecated: Use [http.Server.HTTP2] and + // [http.HTTP2Config.PingTimeout] instead. PingTimeout time.Duration // WriteByteTimeout is the timeout after which a connection will be // closed if no data can be written to it. The timeout begins when data is // available to write, and is extended whenever any bytes are written. // If zero or negative, there is no timeout. + // + // Deprecated: Use [http.Server.HTTP2] and + // [http.HTTP2Config.WriteByteTimeout] instead. WriteByteTimeout time.Duration // MaxUploadBufferPerConnection is the size of the initial flow @@ -108,12 +142,18 @@ type Server struct { // allow this to be smaller than 65535 or larger than 2^32-1. // If the value is outside this range, a default value will be // used instead. + // + // Deprecated: Use [http.Server.HTTP2] and + // [http.HTTP2Config.MaxReceiveBufferPerConnection] instead. MaxUploadBufferPerConnection int32 // MaxUploadBufferPerStream is the size of the initial flow control // window for each stream. The HTTP/2 spec does not allow this to // be larger than 2^32-1. If the value is zero or larger than the // maximum, a default value will be used instead. + // + // Deprecated: Use [http.Server.HTTP2] and + // [http.HTTP2Config.MaxReceiveBufferPerStream] instead. MaxUploadBufferPerStream int32 // NewWriteScheduler constructs a write scheduler for a connection. @@ -126,6 +166,9 @@ type Server struct { // It's intended to increment a metric for monitoring, such // as an expvar or Prometheus metric. // The errType consists of only ASCII word characters. + // + // Deprecated: Use [http.Server.HTTP2] and + // [http.HTTP2Config.CountError] instead. CountError func(errType string) // Internal state. This is a pointer (rather than embedded directly) @@ -135,6 +178,8 @@ type Server struct { } // ServeConnOpts are options for the Server.ServeConn method. +// +// Deprecated: ServeConnOpts is deprecated. type ServeConnOpts struct { // Context is the base context to use. // If nil, context.Background is used. @@ -178,6 +223,8 @@ type ServeConnOpts struct { // implemented in terms of providing a suitably-behaving net.Conn. // // The opts parameter is optional. If nil, default values are used. +// +// Deprecated: Use [http.Server.Serve] or [http.Server.ServeTLS] instead. func (s *Server) ServeConn(c net.Conn, opts *ServeConnOpts) { if opts == nil { opts = &ServeConnOpts{} diff --git a/vendor/golang.org/x/net/http2/transport.go b/vendor/golang.org/x/net/http2/transport.go index 08ac409..d894c60 100644 --- a/vendor/golang.org/x/net/http2/transport.go +++ b/vendor/golang.org/x/net/http2/transport.go @@ -27,6 +27,7 @@ import ( "net/http" "net/http/httptrace" "net/textproto" + "slices" "strconv" "sync" "sync/atomic" @@ -184,6 +185,8 @@ func (t *Transport) initConnPool() { // ClientConn is the state of a single HTTP/2 client connection to an // HTTP/2 server. +// +// Deprecated: Use [http.ClientConn] instead. type ClientConn struct { t *Transport tconn net.Conn // usually *tls.Conn, except specialized impls @@ -201,7 +204,7 @@ type ClientConn struct { mu sync.Mutex // guards following cond *sync.Cond // hold mu; broadcast on flow/closed changes - flow outflow // our conn-level flow control quota (cs.outflow is per stream) + flow connOutflow // our conn-level flow control quota (cs.outflow is per stream) inflow inflow // peer's conn-level flow control doNotReuse bool // whether conn is marked to not be reused for any future requests closing bool @@ -225,7 +228,6 @@ type ClientConn struct { maxConcurrentStreams uint32 peerMaxHeaderListSize uint64 peerMaxHeaderTableSize uint32 - initialWindowSize uint32 initialStreamRecvWindowSize int32 readIdleTimeout time.Duration pingTimeout time.Duration @@ -470,7 +472,6 @@ func (t *Transport) newClientConn(c net.Conn, singleUse bool, internalStateHook readerDone: make(chan struct{}), nextStreamID: 1, maxFrameSize: 16 << 10, // spec default - initialWindowSize: 65535, // spec default initialStreamRecvWindowSize: conf.MaxUploadBufferPerStream, maxConcurrentStreams: initialMaxConcurrentStreams, // "infinite", per spec. Use a smaller value until we have received server settings. strictMaxConcurrentStreams: conf.StrictMaxConcurrentRequests, @@ -495,7 +496,7 @@ func (t *Transport) newClientConn(c net.Conn, singleUse bool, internalStateHook } cc.cond = sync.NewCond(&cc.mu) - cc.flow.add(int32(initialWindowSize)) + cc.flow.init() // TODO: adjust this writer size to account for frame size + // MTU + crypto/tls record padding. @@ -874,6 +875,33 @@ func (cc *ClientConn) sendGoAway() error { return nil } +func (cc *ClientConn) goAwayAndClose(code ErrCode) { + cc.mu.Lock() + closed := cc.closed + cc.closing = true + cc.closed = true + cc.mu.Unlock() + if closed { + return + } + if f := cc.fr.countError; f != nil { + f(fmt.Sprintf("conn_close_error_%s", code.stringToken())) + } + done := make(chan struct{}) + go func() { + defer close(done) + cc.wmu.Lock() + cc.fr.WriteGoAway(0, code, nil) + cc.bw.Flush() + cc.wmu.Unlock() + }() + select { + case <-done: + case <-time.After(250 * time.Millisecond): + } + cc.closeForError(fmt.Errorf("http2: closing connection with %v", code)) +} + // closes the client connection immediately. In-flight requests are interrupted. // err is sent to streams. func (cc *ClientConn) closeForError(err error) { @@ -1317,7 +1345,9 @@ func (cs *clientStream) cleanupWriteRequest(err error) { } if err != nil { cs.abortStream(err) // possibly redundant, but harmless - if cs.sentHeaders { + if ce, ok := err.(ConnectionError); ok { + cc.goAwayAndClose(ErrCode(ce)) + } else if cs.sentHeaders { if se, ok := err.(StreamError); ok { if se.Cause != errFromPeer { cc.writeStreamReset(cs.ID, se.Code, false, err) @@ -1646,8 +1676,12 @@ func (cs *clientStream) awaitFlowControl(maxBytes int) (taken int32, err error) return 0, errRequestCanceled default: } - if a := cs.flow.available(); a > 0 { - take := a + avail, ok := cs.flow.available() + if !ok { + return 0, ConnectionError(ErrCodeFlowControl) + } + if avail > 0 { + take := avail if int(take) > maxBytes { take = int32(maxBytes) // can't truncate int; take is int32 @@ -1708,8 +1742,7 @@ type resAndError struct { // requires cc.mu be held. func (cc *ClientConn) addStreamLocked(cs *clientStream) { - cs.flow.add(int32(cc.initialWindowSize)) - cs.flow.setConnFlow(&cc.flow) + cs.flow.conn = &cc.flow cs.inflow.init(cc.initialStreamRecvWindowSize) cs.ID = cc.nextStreamID cc.nextStreamID += 2 @@ -2093,18 +2126,42 @@ func (rl *clientConnReadLoop) handleResponse(cs *clientStream, f *MetaHeadersFra return nil, nil } + // Delete various headers that might mess up framing for HTTP/1. This is + // not a problem for HTTP/2, but someone might use HTTP/2 transport as a + // reverse proxy which forwards the response to an HTTP/1 client. Our + // HTTP/1 client transport will properly reject improper headers such as + // multiple conflicting Content-Length headers, but other implementations + // might not. + // TODO: just reject such responses? We deleted them for compatibility + // since this was done in a security fix (go.dev/issue/81115). However, + // rejecting them seems entirely reasonable and relatively safe. + + // Connection-specific header fields must not appear in an HTTP/2 message, + // and any message containing them is malformed. RFC 9113, Section 8.2.2. + for _, k := range connHeaders { + delete(res.Header, k) + } res.ContentLength = -1 - if clens := res.Header["Content-Length"]; len(clens) == 1 { - if cl, err := strconv.ParseUint(clens[0], 10, 63); err == nil { - res.ContentLength = int64(cl) + if clens, ok := res.Header["Content-Length"]; ok { + // Repeated Content-Length values may be collapsed into one only if + // they are identical per RFC 9110 Section 8.6. + // No need to trim whitespace, HTTP/2 header values must not have + // extraneous whitespace per RFC 9113 Section 8.2.1. + // Non-canonical headers are already rejected by our framer at this + // point. + conflicting := slices.ContainsFunc(clens[1:], func(clen string) bool { + return clen != clens[0] + }) + cl, err := strconv.ParseUint(clens[0], 10, 63) + if conflicting || err != nil { + delete(res.Header, "Content-Length") } else { - // TODO: care? unlike http/1, it won't mess up our framing, so it's - // more safe smuggling-wise to ignore. + res.Header["Content-Length"] = clens[:1] + res.ContentLength = int64(cl) } - } else if len(clens) > 1 { - // TODO: care? unlike http/1, it won't mess up our framing, so it's - // more safe smuggling-wise to ignore. - } else if f.StreamEnded() && !cs.isHead { + } + + if res.ContentLength < 0 && f.StreamEnded() && !cs.isHead { res.ContentLength = 0 } @@ -2415,6 +2472,10 @@ const ( func (rl *clientConnReadLoop) streamByID(id uint32, headerOrData bool) *clientStream { rl.cc.mu.Lock() defer rl.cc.mu.Unlock() + return rl.streamByIDLocked(id, headerOrData) +} + +func (rl *clientConnReadLoop) streamByIDLocked(id uint32, headerOrData bool) *clientStream { if headerOrData { // Work around an unfortunate gRPC behavior. // See comment on ClientConn.rstStreamPingsBlocked for details. @@ -2497,24 +2558,10 @@ func (rl *clientConnReadLoop) processSettingsNoWrite(f *SettingsFrame) error { case SettingMaxHeaderListSize: cc.peerMaxHeaderListSize = uint64(s.Val) case SettingInitialWindowSize: - // Values above the maximum flow-control - // window size of 2^31-1 MUST be treated as a - // connection error (Section 5.4.1) of type - // FLOW_CONTROL_ERROR. - if s.Val > math.MaxInt32 { + if !cc.flow.changeInitialWindowSize(int64(s.Val)) { return ConnectionError(ErrCodeFlowControl) } - - // Adjust flow control of currently-open - // frames by the difference of the old initial - // window size and this one. - delta := int32(s.Val) - int32(cc.initialWindowSize) - for _, cs := range cc.streams { - cs.flow.add(delta) - } cc.cond.Broadcast() - - cc.initialWindowSize = s.Val case SettingHeaderTableSize: cc.henc.SetMaxDynamicTableSize(s.Val) cc.peerMaxHeaderTableSize = s.Val @@ -2556,29 +2603,30 @@ func (rl *clientConnReadLoop) processSettingsNoWrite(f *SettingsFrame) error { func (rl *clientConnReadLoop) processWindowUpdate(f *WindowUpdateFrame) error { cc := rl.cc - cs := rl.streamByID(f.StreamID, notHeaderOrDataFrame) - if f.StreamID != 0 && cs == nil { - return nil - } - cc.mu.Lock() defer cc.mu.Unlock() - - fl := &cc.flow - if cs != nil { - fl = &cs.flow - } - if !fl.add(int32(f.Increment)) { - // For stream, the sender sends RST_STREAM with an error code of FLOW_CONTROL_ERROR - if cs != nil { + if f.StreamID == 0 { + if !cc.flow.add(int32(f.Increment)) { + return ConnectionError(ErrCodeFlowControl) + } + } else { + cs := rl.streamByIDLocked(f.StreamID, notHeaderOrDataFrame) + if cs == nil { + return nil + } + if !cs.flow.add(int32(f.Increment)) { + if cs.flow.conn.flowErr { + // This is a lazily-detected connection-level flow control error. + return ConnectionError(ErrCodeFlowControl) + } + // For stream, the sender sends RST_STREAM with + // an error code of FLOW_CONTROL_ERROR. rl.endStreamErrorLocked(cs, StreamError{ StreamID: f.StreamID, Code: ErrCodeFlowControl, }) return nil } - - return ConnectionError(ErrCodeFlowControl) } cc.cond.Broadcast() return nil diff --git a/vendor/golang.org/x/net/http2/transport_common.go b/vendor/golang.org/x/net/http2/transport_common.go index b9f5293..4f0333a 100644 --- a/vendor/golang.org/x/net/http2/transport_common.go +++ b/vendor/golang.org/x/net/http2/transport_common.go @@ -24,6 +24,8 @@ import ( // It returns an error if t1 has already been HTTP/2-enabled. // // Use ConfigureTransports instead to configure the HTTP/2 Transport. +// +// Deprecated: Set [http.Transport.Protocols] instead. func ConfigureTransport(t1 *http.Transport) error { return configureTransport(t1) } @@ -31,6 +33,8 @@ func ConfigureTransport(t1 *http.Transport) error { // ConfigureTransports configures a net/http HTTP/1 Transport to use HTTP/2. // It returns a new HTTP/2 Transport for further configuration. // It returns an error if t1 has already been HTTP/2-enabled. +// +// Deprecated: Set [http.Transport.Protocols] instead. func ConfigureTransports(t1 *http.Transport) (*Transport, error) { return configureTransports(t1) } @@ -39,6 +43,8 @@ func ConfigureTransports(t1 *http.Transport) (*Transport, error) { // // A Transport internally caches connections to servers. It is safe // for concurrent use by multiple goroutines. +// +// Deprecated: Use [http.Transport] instead. type Transport struct { // DialTLSContext specifies an optional dial function with context for // creating TLS connections for requests. @@ -47,6 +53,8 @@ type Transport struct { // // If the returned net.Conn has a ConnectionState method like tls.Conn, // it will be used to set http.Response.TLS. + // + // Deprecated: Use [http.Transport.DialTLSContext] instead. DialTLSContext func(ctx context.Context, network, addr string, cfg *tls.Config) (net.Conn, error) // DialTLS specifies an optional dial function for creating @@ -54,17 +62,21 @@ type Transport struct { // // If DialTLSContext and DialTLS is nil, tls.Dial is used. // - // Deprecated: Use DialTLSContext instead, which allows the transport - // to cancel dials as soon as they are no longer needed. - // If both are set, DialTLSContext takes priority. + // Deprecated: Use [http.Transport.DialTLSContext] instead. DialTLS func(network, addr string, cfg *tls.Config) (net.Conn, error) // TLSClientConfig specifies the TLS configuration to use with // tls.Client. If nil, the default configuration is used. + // + // Deprecated: Use [http.Transport.TLSClientConfig] instead. TLSClientConfig *tls.Config // ConnPool optionally specifies an alternate connection pool to use. // If nil, the default is used. + // + // Deprecated: To create a custom connection pool, implement + // [http.RoundTripper]. Use [http.Transport.NewClientConn] + // to create connections for the pool. ConnPool ClientConnPool // DisableCompression, if true, prevents the Transport from @@ -75,10 +87,14 @@ type Transport struct { // decoded in the Response.Body. However, if the user // explicitly requested gzip it is not automatically // uncompressed. + // + // Deprecated: Use [http.Transport.DisableCompression] instead. DisableCompression bool // AllowHTTP, if true, permits HTTP/2 requests using the insecure, // plain-text "http" scheme. Note that this does not enable h2c support. + // + // Deprecated: Use [http.Transport.Protocols] instead. AllowHTTP bool // MaxHeaderListSize is the http2 SETTINGS_MAX_HEADER_LIST_SIZE to @@ -88,6 +104,8 @@ type Transport struct { // want to advertise an unlimited value to the peer, Transport // interprets the highest possible value here (0xffffffff or 1<<32-1) // to mean no limit. + // + // Deprecated: Use [http.Transport.MaxResponseHeaderBytes] instead. MaxHeaderListSize uint32 // MaxReadFrameSize is the http2 SETTINGS_MAX_FRAME_SIZE to send in the @@ -97,6 +115,9 @@ type Transport struct { // according to the spec: // https://datatracker.ietf.org/doc/html/rfc7540#section-6.5.2. // Values are bounded in the range 16k to 16M. + // + // Deprecated: Use [http.Transport.HTTP2] and + // [http.HTTP2Config.MaxReadFrameSize] instead. MaxReadFrameSize uint32 // MaxDecoderHeaderTableSize optionally specifies the http2 @@ -104,12 +125,18 @@ type Transport struct { // informs the remote endpoint of the maximum size of the header compression // table used to decode header blocks, in octets. If zero, the default value // of 4096 is used. + // + // Deprecated: Use [http.Transport.HTTP2] and + // [http.HTTP2Config.MaxDecoderHeaderTableSize] instead. MaxDecoderHeaderTableSize uint32 // MaxEncoderHeaderTableSize optionally specifies an upper limit for the // header compression table used for encoding request headers. Received // SETTINGS_HEADER_TABLE_SIZE settings are capped at this limit. If zero, // the default value of 4096 is used. + // + // Deprecated: Use [http.Transport.HTTP2] and + // [http.HTTP2Config.MaxEncoderHeaderTableSize] instead. MaxEncoderHeaderTableSize uint32 // StrictMaxConcurrentStreams controls whether the server's @@ -120,12 +147,17 @@ type Transport struct { // server's SETTINGS_MAX_CONCURRENT_STREAMS is interpreted as // a global limit and callers of RoundTrip block when needed, // waiting for their turn. + // + // Deprecated: Use [http.Transport.HTTP2] and + // [http.HTTP2Config.StrictMaxConcurrentRequests] instead. StrictMaxConcurrentStreams bool // IdleConnTimeout is the maximum amount of time an idle // (keep-alive) connection will remain idle before closing // itself. // Zero means no limit. + // + // Deprecated: Use [http.Transport.IdleConnTimeout] instead. IdleConnTimeout time.Duration // ReadIdleTimeout is the timeout after which a health check using ping @@ -134,22 +166,34 @@ type Transport struct { // there is no other traffic on the connection, the health check will // be performed every ReadIdleTimeout interval. // If zero, no health check is performed. + // + // Deprecated: Use [http.Transport.HTTP2] and + // [http.HTTP2Config.SendPingTimeout] instead. ReadIdleTimeout time.Duration // PingTimeout is the timeout after which the connection will be closed // if a response to Ping is not received. // Defaults to 15s. + // + // Deprecated: Use [http.Transport.HTTP2] and + // [http.HTTP2Config.PingTimeout] instead. PingTimeout time.Duration // WriteByteTimeout is the timeout after which the connection will be // closed no data can be written to it. The timeout begins when data is // available to write, and is extended whenever any bytes are written. + // + // Deprecated: Use [http.Transport.HTTP2] and + // [http.HTTP2Config.WriteByteTimeout] instead. WriteByteTimeout time.Duration // CountError, if non-nil, is called on HTTP/2 transport errors. // It's intended to increment a metric for monitoring, such // as an expvar or Prometheus metric. // The errType consists of only ASCII word characters. + // + // Deprecated: Use [http.Transport.HTTP2] and + // [http.HTTP2Config.CountError] instead. CountError func(errType string) // Internal state, differs between wrapped and non-wrapped implementations. @@ -165,6 +209,10 @@ var ( ) // ClientConnPool manages a pool of HTTP/2 client connections. +// +// Deprecated: To create a custom connection pool, implement +// [http.RoundTripper]. Use [http.Transport.NewClientConn] +// to create connections for the pool. type ClientConnPool interface { // GetClientConn returns a specific HTTP/2 connection (usually // a TLS-TCP connection) to an HTTP/2 server. On success, the @@ -177,6 +225,8 @@ type ClientConnPool interface { } // ClientConnState describes the state of a ClientConn. +// +// Deprecated: Use [http.ClientConn] instead. type ClientConnState struct { // Closed is whether the connection is closed. Closed bool @@ -210,6 +260,8 @@ type ClientConnState struct { } // RoundTripOpt are options for the Transport.RoundTripOpt method. +// +// Deprecated: There are no options to set. type RoundTripOpt struct { // OnlyCachedConn controls whether RoundTripOpt may // create a new TCP connection. If set true and @@ -222,11 +274,14 @@ type RoundTripOpt struct { allowHTTP bool // allow http:// URLs } +// Deprecated: Use [http.Transport.RoundTrip] instead. func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) { return t.RoundTripOpt(req, RoundTripOpt{}) } // RoundTripOpt is like RoundTrip, but takes options. +// +// Deprecated: Use [http.Transport.RoundTrip] instead. func (t *Transport) RoundTripOpt(req *http.Request, opt RoundTripOpt) (*http.Response, error) { return t.roundTripOpt(req, opt) } @@ -234,10 +289,15 @@ func (t *Transport) RoundTripOpt(req *http.Request, opt RoundTripOpt) (*http.Res // CloseIdleConnections closes any connections which were previously // connected from previous requests but are now sitting idle. // It does not interrupt any connections currently in use. +// +// Deprecated: Use [http.Transport.CloseIdleConnections] instead. func (t *Transport) CloseIdleConnections() { t.closeIdleConnections() } +// NewClientConn is deprecated. +// +// Deprecated: Use [http.Transport.NewClientConn] instead. func (t *Transport) NewClientConn(c net.Conn) (*ClientConn, error) { return t.newUserClientConn(c) } @@ -256,8 +316,15 @@ func authorityAddr(scheme string, authority string) (addr string) { port = "80" } } - if a, err := idna.ToASCII(host); err == nil { - host = a + // Skip IDNA processing on hosts which are already ASCII. + // This is consistent with net/http and the WHATWG URL Specification. + // (We currently don't follow all of WHATWG, but we're aligned on + // permitting all-ASCII hostnames which fail IDNA validation. + // There are existing, valid domain names which TR #46 processing rejects.) + if !isASCII(host) { + if a, err := idna.Lookup.ToASCII(host); err == nil && a != "" { + host = a + } } // IPv6 address literal, without a port: if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") { @@ -414,6 +481,8 @@ func (t *Transport) dialTLSWithContext(ctx context.Context, network, addr string // GoAwayError is returned by the Transport when the server closes the // TCP connection after sending a GOAWAY frame. +// +// Deprecated: GoAwayError is deprecated. type GoAwayError struct { LastStreamID uint32 ErrCode ErrCode diff --git a/vendor/golang.org/x/net/http2/transport_wrap.go b/vendor/golang.org/x/net/http2/transport_wrap.go index 741fb97..002cb50 100644 --- a/vendor/golang.org/x/net/http2/transport_wrap.go +++ b/vendor/golang.org/x/net/http2/transport_wrap.go @@ -58,6 +58,12 @@ func (t transportConfig) Registered(t1 *http.Transport) { t.t.lazyt1 = t1 } +// GetClientConnStateFunc is called to provide us with a function +// which may be used to fetch additional state from a ClientConn. +func (t transportConfig) GetClientConnStateFunc(f func(*http.ClientConn) any) { + t.t.getCCState = f +} + func (t transportConfig) DisableCompression() bool { return t.t.DisableCompression } @@ -119,33 +125,28 @@ type http2TransportContextKey struct{} // DialFromContext dials a new connection using the http2.Transport's DialTLS/DialTLSContext. func (t transportConfig) DialFromContext(ctx context.Context, network, address string) (net.Conn, error) { - if ctx.Value(http2TransportContextKey{}) == nil { + dial, _ := ctx.Value(http2TransportContextKey{}).(*transportRoundTripState) + if dial == nil { // We're being called from a RoundTrip that did not start with an http2.Transport. // Use the http.Transport's dialer. return nil, errors.ErrUnsupported } - - tlsConf := t.t.TLSClientConfig - if tlsConf == nil { - tlsConf = &tls.Config{} - } else { - tlsConf = tlsConf.Clone() - } - if !slices.Contains(tlsConf.NextProtos, "h2") { - tlsConf.NextProtos = append([]string{"h2"}, tlsConf.NextProtos...) - } - if tlsConf.ServerName == "" { - host, _, err := net.SplitHostPort(address) - if err == nil { - tlsConf.ServerName = host - } - } - return t.t.dialTLS(ctx, network, address, tlsConf) + return t.t.dialForRoundTrip(ctx, dial, network, address) } type transportInternal struct { - initOnce sync.Once - lazyt1 *http.Transport + initOnce sync.Once + lazyt1 *http.Transport + getCCState func(*http.ClientConn) any + + dialMu sync.Mutex + dials map[string]*transportDialState +} + +type transportDialState struct { + dialc chan struct{} // close when dial returns + dialErr error // dial result, set before dialc is closed + rtdonec chan struct{} // closed when RoundTrip initiating the dial returns } func (t *Transport) init() *http.Transport { @@ -167,6 +168,52 @@ func (t *Transport) configure(t1 *http.Transport) { } } +// transportRoundTripState is the state of the dial for an http2.Transport.RoundTrip. +type transportRoundTripState struct { + mu sync.Mutex + rtdone bool // set when RoundTrip returns + rtdonec chan struct{} // closed when RoundTrip returns + gotconnc chan struct{} // closed when GotConn hook is called +} + +// startDial is called when a dial starts. +// +// It returns done=true if the RoundTrip has already returned, +// in which case we should skip dialing. +func (dial *transportRoundTripState) startDial() (gotconnc chan struct{}, done bool) { + dial.mu.Lock() + defer dial.mu.Unlock() + if dial.rtdone { + return nil, true + } + if dial.rtdonec == nil { + dial.rtdonec = make(chan struct{}) + } + dial.gotconnc = make(chan struct{}) + return dial.gotconnc, false +} + +// gotConn is called when RoundTrip gets a connection. +// This may happen multiple times per RoundTrip, if a request is retried. +func (dial *transportRoundTripState) gotConn() { + dial.mu.Lock() + defer dial.mu.Unlock() + if dial.gotconnc != nil { + close(dial.gotconnc) + dial.gotconnc = nil + } +} + +// roundTripDone is called when RoundTrip returns. +func (dial *transportRoundTripState) roundTripDone() { + dial.mu.Lock() + defer dial.mu.Unlock() + dial.rtdone = true + if dial.rtdonec != nil { + close(dial.rtdonec) + } +} + func (t *Transport) roundTripOpt(req *http.Request, opt RoundTripOpt) (*http.Response, error) { t1 := t.init() @@ -186,12 +233,146 @@ func (t *Transport) roundTripOpt(req *http.Request, opt RoundTripOpt) (*http.Res // Both http.Transport and http2.Transport allow the user to provide a custom // dial function, and historically you only get the dial function from the // Transport you're calling RoundTrip on. - ctx := context.WithValue(req.Context(), http2TransportContextKey{}, t) + // + // In addition, http2.Transport coalesces dials, which http.Transport historically + // has not. + dial := &transportRoundTripState{} + defer dial.roundTripDone() + ctx := context.WithValue(req.Context(), http2TransportContextKey{}, dial) + ctx = httptrace.WithClientTrace(ctx, &httptrace.ClientTrace{ + GotConn: func(httptrace.GotConnInfo) { + // Tell dialForRoundTrip that we have received a connection. + dial.gotConn() + }, + }) req = req.WithContext(ctx) - return t1.RoundTrip(req) } +var errCoalescedDialAbandoned = errors.New("http2: abandoned coalesced dial") + +const coalescedDialRetryTimeout = 50 * time.Millisecond + +// dialForRoundTrip is called (indirectly) by net/http when dialing a new connection +// for a request call which originated as an http2.Transport.RoundTrip call. +// +// It uses the http2.Transport's Dial hooks and coalesces dials. +func (t *Transport) dialForRoundTrip(ctx context.Context, dial *transportRoundTripState, network, address string) (net.Conn, error) { + gotconnc, rtdone := dial.startDial() + if rtdone { + // RoundTrip returned, no need for this dial to proceed. + return nil, errCoalescedDialAbandoned + } + + var state *transportDialState + for { + // The first dial to an address registers itself with t.dials. + // When the dial finishes, it records the outcome and removes itself from t.dials + // so future dials will start a new round of coalescing. + // + // Subsequent dials observe that a dial is in progress, and skip dialing. + t.dialMu.Lock() + if t.dials == nil { + t.dials = make(map[string]*transportDialState) + } + leader := t.dials[address] + if leader == nil { + // No entry in t.dials to coalesce with. Add ourselves as leader. + state = &transportDialState{ + dialc: make(chan struct{}), + rtdonec: dial.rtdonec, + } + t.dials[address] = state + } + t.dialMu.Unlock() + if leader == nil { + // We are the leader, so we should dial for real. + break + } + + // Coalesce with a previous dial. + var ( + done = false + leaderdialc = leader.dialc + leaderrtdonec = leader.rtdonec + timerc <-chan time.Time + ) + for !done { + if leaderdialc == nil && leaderrtdonec == nil && timerc == nil { + // The leader finished dialing, and its RoundTrip finished. + // + // There are several possibilities, which reduce to: + // - The RoundTrip we are dialing for is about to receive + // a connection (possibly the one the leader just dialed), + // but we haven't observed it yet. + // - There's something wrong with the leader's connection, + // such as a TLS handshake failure. + // + // We have no good way to distinguish between these cases. + // + // Wait a short time for the leader's connection (or some + // other usable connection) to be delivered to our RoundTrip. + // If it is not, start a dial of our own. + timerc = time.After(coalescedDialRetryTimeout) + } + select { + case <-leaderdialc: + // The leader's dial completed. + if leader.dialErr != nil { + return nil, leader.dialErr + } + leaderdialc = nil + case <-leaderrtdonec: + // The leader's RoundTrip completed. + leaderrtdonec = nil + case <-timerc: + // The leader's dial and RoundTrip completed, and some time + // has passed. Assume we're not getting a connection and + // restart the dial process. + done = true + case <-dial.rtdonec: + // Our RoundTrip returned. + return nil, errCoalescedDialAbandoned + case <-gotconnc: + // Our RoundTrip got a connection. + return nil, errCoalescedDialAbandoned + case <-ctx.Done(): + // net/http abandoned the dial. + return nil, ctx.Err() + } + } + } + + // Dial for real. + tlsConf := t.TLSClientConfig + if tlsConf == nil { + tlsConf = &tls.Config{} + } else { + tlsConf = tlsConf.Clone() + } + if !slices.Contains(tlsConf.NextProtos, "h2") { + tlsConf.NextProtos = append([]string{"h2"}, tlsConf.NextProtos...) + } + if tlsConf.ServerName == "" { + host, _, err := net.SplitHostPort(address) + if err == nil { + tlsConf.ServerName = host + } + } + nc, err := t.dialTLS(ctx, network, address, tlsConf) + + // Remove this dial from t.dials, so future dial attempts will not coalesce with it. + t.dialMu.Lock() + delete(t.dials, address) + t.dialMu.Unlock() + + // Notify any dial coalesced with this one that we are done. + state.dialErr = err + close(state.dialc) + + return nc, err +} + func (t *Transport) closeIdleConnections() { t1 := t.init() t1.CloseIdleConnections() @@ -216,6 +397,8 @@ func (t *Transport) newUserClientConn(c net.Conn) (*ClientConn, error) { // ClientConn is the state of a single HTTP/2 client connection to an // HTTP/2 server. +// +// Deprecated: Use [http.ClientConn] instead. type ClientConn struct { cc *http.ClientConn tconn net.Conn @@ -349,10 +532,32 @@ func (cc *ClientConn) state() ClientConnState { cc.mu.Lock() defer cc.mu.Unlock() cc.updateStateLocked() + var gotStats bool + var streamsActive int + if cc.tr.getCCState != nil { + stats, ok := cc.tr.getCCState(cc.cc).(interface { + StreamsActive() int + MaxConcurrentStreams() int + }) + if ok { + gotStats = true + streamsActive = stats.StreamsActive() + cc.maxConcurrent = stats.MaxConcurrentStreams() + } + } + if !gotStats { + streamsActive = cc.cc.InFlight() - cc.reserved + if !cc.closed { + // This is slightly racy (a request could start or finish in between + // the Available and InFlight calls), but the best we can do given that + // the net/http ClientConn API doesn't expose the conn's max concurrency. + cc.maxConcurrent = cc.cc.Available() + cc.cc.InFlight() + } + } return ClientConnState{ Closed: cc.closed, Closing: cc.closing, - StreamsActive: cc.cc.InFlight() - cc.reserved, + StreamsActive: streamsActive, StreamsReserved: cc.reserved, StreamsPending: cc.pending, MaxConcurrentStreams: uint32(min(int64(cc.maxConcurrent), math.MaxUint32)), @@ -380,12 +585,6 @@ func (cc *ClientConn) updateStateLocked() { if cc.cc.InFlight() == 0 && cc.roundTrips > 0 && cc.starting == 0 { cc.lastIdle = time.Now() } - if !cc.closed { - // This is slightly racy (a request could start or finish in between - // the Available and InFlight calls), but the best we can do given that - // the net/http ClientConn API doesn't expose the conn's max concurrency. - cc.maxConcurrent = cc.cc.Available() + cc.cc.InFlight() - } if cc.shutdownc != nil && cc.cc.InFlight()+cc.starting == 0 { close(cc.shutdownc) cc.shutdownc = nil diff --git a/vendor/golang.org/x/net/http2/writesched.go b/vendor/golang.org/x/net/http2/writesched.go index 36ad5e3..f1903a8 100644 --- a/vendor/golang.org/x/net/http2/writesched.go +++ b/vendor/golang.org/x/net/http2/writesched.go @@ -79,10 +79,11 @@ func (wr FrameWriteRequest) Consume(n int32) (FrameWriteRequest, FrameWriteReque } // Might need to split after applying limits. - allowed := wr.stream.flow.available() - if n < allowed { - allowed = n + avail, ok := wr.stream.flow.available() + if !ok { + return empty, empty, 0 } + allowed := min(n, avail) if wr.stream.sc.maxFrameSize < allowed { allowed = wr.stream.sc.maxFrameSize } diff --git a/vendor/golang.org/x/net/internal/httpcommon/README.md b/vendor/golang.org/x/net/internal/httpcommon/README.md new file mode 100644 index 0000000..951c346 --- /dev/null +++ b/vendor/golang.org/x/net/internal/httpcommon/README.md @@ -0,0 +1,7 @@ +These two packages are identical: + +- net/http/internal/httpcommon +- golang.org/x/net/internal/httpcommon + +The two are kept in sync manually. +Any change to one should be made in the other. diff --git a/vendor/golang.org/x/net/internal/httpcommon/gzip.go b/vendor/golang.org/x/net/internal/httpcommon/gzip.go new file mode 100644 index 0000000..819dd65 --- /dev/null +++ b/vendor/golang.org/x/net/internal/httpcommon/gzip.go @@ -0,0 +1,132 @@ +// Copyright 2026 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package httpcommon + +import ( + "compress/flate" + "compress/gzip" + "errors" + "io" + "io/fs" + "sync" +) + +var errConcurrentRead = errors.New("http: concurrent read on response body") + +// incomparable is a zero-width, non-comparable type. Adding it to a struct +// makes that struct also non-comparable, and generally doesn't add +// any size (as long as it's first). +type incomparable [0]func() + +// GzipReader wraps a response body so it can lazily +// get gzip.Reader from the pool on the first call to Read. +// After Close is called it puts gzip.Reader to the pool immediately +// if there is no Read in progress or later when Read completes. +type GzipReader struct { + _ incomparable + Body io.ReadCloser // underlying Response.Body + mu sync.Mutex // guards zr and zerr + zr *gzip.Reader // stores gzip reader from the pool between reads + zerr error // sticky gzip reader init error or sentinel value to detect concurrent read and read after close +} + +type eofReader struct{} + +func (eofReader) Read([]byte) (int, error) { return 0, io.EOF } +func (eofReader) ReadByte() (byte, error) { return 0, io.EOF } + +var gzipPool = sync.Pool{New: func() any { return new(gzip.Reader) }} + +// gzipPoolGet gets a gzip.Reader from the pool and resets it to read from r. +func gzipPoolGet(r io.Reader) (*gzip.Reader, error) { + zr := gzipPool.Get().(*gzip.Reader) + if err := zr.Reset(r); err != nil { + gzipPoolPut(zr) + return nil, err + } + return zr, nil +} + +// gzipPoolPut puts a gzip.Reader back into the pool. +func gzipPoolPut(zr *gzip.Reader) { + // Reset will allocate bufio.Reader if we pass it anything + // other than a flate.Reader, so ensure that it's getting one. + var r flate.Reader = eofReader{} + zr.Reset(r) + gzipPool.Put(zr) +} + +// acquire returns a gzip.Reader for reading response body. +// The reader must be released after use. +func (gz *GzipReader) acquire() (*gzip.Reader, error) { + gz.mu.Lock() + defer gz.mu.Unlock() + if gz.zerr != nil { + return nil, gz.zerr + } + if gz.zr == nil { + // gzipPoolGet might block indefinitely since it reads the gzip header. + // Therefore, drop mu temporarily when using gzipPoolGet. + // We set zerr to errConcurrentRead to prevent concurrent read + // even when mu is temporarily dropped. + gz.zerr = errConcurrentRead + gz.mu.Unlock() + zr, err := gzipPoolGet(gz.Body) + gz.mu.Lock() + // Guard against Close being called while gzipPoolGet is running. + if gz.zerr != errConcurrentRead { + if zr != nil { + gzipPoolPut(zr) + } + return nil, gz.zerr + } + gz.zr, gz.zerr = zr, err + if gz.zerr != nil { + return nil, gz.zerr + } + } + ret := gz.zr + gz.zr, gz.zerr = nil, errConcurrentRead + return ret, nil +} + +// release returns the gzip.Reader to the pool if Close was called during Read. +func (gz *GzipReader) release(zr *gzip.Reader) { + gz.mu.Lock() + defer gz.mu.Unlock() + if gz.zerr == errConcurrentRead { + gz.zr, gz.zerr = zr, nil + } else { // fs.ErrClosed + gzipPoolPut(zr) + } +} + +// close returns the gzip.Reader to the pool immediately or +// signals release to do so after Read completes. +func (gz *GzipReader) close() { + gz.mu.Lock() + defer gz.mu.Unlock() + if gz.zerr == nil && gz.zr != nil { + gzipPoolPut(gz.zr) + gz.zr = nil + } + gz.zerr = fs.ErrClosed +} + +func (gz *GzipReader) Read(p []byte) (n int, err error) { + zr, err := gz.acquire() + if err != nil { + return 0, err + } + defer gz.release(zr) + + return zr.Read(p) +} + +func (gz *GzipReader) Close() error { + gz.close() + + return gz.Body.Close() +} diff --git a/vendor/golang.org/x/net/internal/httpcommon/request.go b/vendor/golang.org/x/net/internal/httpcommon/request.go index d94c874..5aaca59 100644 --- a/vendor/golang.org/x/net/internal/httpcommon/request.go +++ b/vendor/golang.org/x/net/internal/httpcommon/request.go @@ -391,6 +391,7 @@ type ServerRequestParam struct { // ServerRequestResult is the result of NewServerRequest. type ServerRequestResult struct { // Various http.Request fields. + Host string URL *url.URL RequestURI string Trailer map[string][]string @@ -433,20 +434,46 @@ func NewServerRequest(rp ServerRequestParam) ServerRequestResult { } delete(rp.Header, "Trailer") + authority := rp.Authority + if host := rp.Header["Host"]; len(host) == 1 { + // HTTP/2 and HTTP/3 permit the Host header to be present, + // but it must match the :authority pseudo-header. + if authority == "" { + authority = host[0] + } else if host[0] != authority { + return ServerRequestResult{ + InvalidReason: "authority_host_mismatch", + } + } + delete(rp.Header, "Host") + } else if len(host) > 1 { + // HTTP/1.1 rejects any request containing more than one Host header. + // HTTP/2 and HTTP/3 don't use the Host header, but reject multiple anyway. + return ServerRequestResult{ + InvalidReason: "multiple_host_headers", + } + } + // "':authority' MUST NOT include the deprecated userinfo subcomponent // for "http" or "https" schemed URIs." // https://www.rfc-editor.org/rfc/rfc9113.html#section-8.3.1-2.3.8 - if strings.IndexByte(rp.Authority, '@') != -1 && (rp.Scheme == "http" || rp.Scheme == "https") { + if strings.IndexByte(authority, '@') != -1 && (rp.Scheme == "http" || rp.Scheme == "https") { return ServerRequestResult{ InvalidReason: "userinfo_in_authority", } } + if authority != "" && !httpguts.ValidHostHeader(authority) { + return ServerRequestResult{ + InvalidReason: "invalid_authority", + } + } + var url_ *url.URL var requestURI string if rp.Method == "CONNECT" && rp.Protocol == "" { - url_ = &url.URL{Host: rp.Authority} - requestURI = rp.Authority // mimic HTTP/1 server behavior + url_ = &url.URL{Host: authority} + requestURI = authority // mimic HTTP/1 server behavior } else { // "[The :path] pseudo-header field MUST NOT be empty [...]" // https://www.rfc-editor.org/rfc/rfc9113.html#section-8.3.1-2.4.2 @@ -467,6 +494,7 @@ func NewServerRequest(rp ServerRequestParam) ServerRequestResult { } return ServerRequestResult{ + Host: authority, URL: url_, NeedsContinue: needsContinue, RequestURI: requestURI, diff --git a/vendor/golang.org/x/net/trace/histogram.go b/vendor/golang.org/x/net/trace/histogram.go index d6c7110..2f78683 100644 --- a/vendor/golang.org/x/net/trace/histogram.go +++ b/vendor/golang.org/x/net/trace/histogram.go @@ -70,10 +70,7 @@ func log2(i int64) int { } func getBucket(i int64) (index int) { - index = log2(i) - 1 - if index < 0 { - index = 0 - } + index = max(log2(i)-1, 0) if index >= bucketCount { index = bucketCount - 1 } diff --git a/vendor/golang.org/x/sync/semaphore/semaphore.go b/vendor/golang.org/x/sync/semaphore/semaphore.go index 96a035a..f2a7d3f 100644 --- a/vendor/golang.org/x/sync/semaphore/semaphore.go +++ b/vendor/golang.org/x/sync/semaphore/semaphore.go @@ -17,10 +17,13 @@ type waiter struct { } // NewWeighted creates a new weighted semaphore with the given -// maximum combined weight for concurrent access. +// maximum combined weight for concurrent access. NewWeighted panics if n is +// negative. func NewWeighted(n int64) *Weighted { - w := &Weighted{size: n} - return w + if n < 0 { + panic("semaphore: size < 0") + } + return &Weighted{size: n} } // Weighted provides a way to bound concurrent access to a resource. diff --git a/vendor/golang.org/x/sys/cpu/cpu.go b/vendor/golang.org/x/sys/cpu/cpu.go index f1ce515..422b139 100644 --- a/vendor/golang.org/x/sys/cpu/cpu.go +++ b/vendor/golang.org/x/sys/cpu/cpu.go @@ -61,7 +61,11 @@ var X86 struct { HasBMI2 bool // Bit manipulation instruction set 2 HasCX16 bool // Compare and exchange 16 Bytes HasERMS bool // Enhanced REP for MOVSB and STOSB + HasF16C bool // 16-bit floating-point conversion instructions HasFMA bool // Fused-multiply-add instructions + HasLAHF bool // LAHF/SAHF available in 64-bit mode + HasLZCNT bool // Leading zeros count instruction + HasMOVBE bool // Move data after byte swap HasOSXSAVE bool // OS supports XSAVE/XRESTOR for saving/restoring XMM registers. HasPCLMULQDQ bool // PCLMULQDQ instruction - most often used for AES-GCM HasPOPCNT bool // Hamming weight instruction POPCNT. @@ -75,6 +79,7 @@ var X86 struct { HasAVXIFMA bool // Advanced vector extension Integer Fused Multiply Add HasAVXVNNI bool // Advanced vector extension Vector Neural Network Instructions HasAVXVNNIInt8 bool // Advanced vector extension Vector Neural Network Int8 instructions + HasXSAVE bool // XSAVE/XRSTOR/XSETBV/XGETBV instructions (hardware support; see also HasOSXSAVE) _ CacheLinePad } @@ -182,12 +187,13 @@ var MIPS64X struct { // require kernel support to work (DARN, SCV), so there are feature bits for // those as well. The struct is padded to avoid false sharing. var PPC64 struct { - _ CacheLinePad - HasDARN bool // Hardware random number generator (requires kernel enablement) - HasSCV bool // Syscall vectored (requires kernel enablement) - IsPOWER8 bool // ISA v2.07 (POWER8) - IsPOWER9 bool // ISA v3.00 (POWER9), implies IsPOWER8 - _ CacheLinePad + _ CacheLinePad + HasDARN bool // Hardware random number generator (requires kernel enablement) + HasSCV bool // Syscall vectored (requires kernel enablement) + IsPOWER8 bool // ISA v2.07 (POWER8) + IsPOWER9 bool // ISA v3.00 (POWER9), implies IsPOWER8 + IsPOWER10 bool // ISA v3.1 (POWER10 and POWER11; POWER11 did not add a new architected level), implies IsPOWER9 + _ CacheLinePad } // S390X contains the supported CPU features of the current IBM Z @@ -248,13 +254,21 @@ var RISCV64 struct { HasZvks bool // ShangMi Algorithm Suite HasZvksc bool // ShangMi Algorithm Suite with carryless multiplication HasZvksg bool // ShangMi Algorithm Suite with GCM + VLENB uint // Vector register length in bytes, 0 if undetected _ CacheLinePad } +// doDerived, if non-nil, is called after processing GODEBUG to set "derived" +// feature flags. +var doDerived func() + func init() { archInit() initOptions() processOptions() + if doDerived != nil { + doDerived() + } } // options contains the cpu debug options that can be used in GODEBUG. diff --git a/vendor/golang.org/x/sys/cpu/cpu_gc_riscv64.go b/vendor/golang.org/x/sys/cpu/cpu_gc_riscv64.go new file mode 100644 index 0000000..3d660dd --- /dev/null +++ b/vendor/golang.org/x/sys/cpu/cpu_gc_riscv64.go @@ -0,0 +1,11 @@ +// Copyright 2026 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build gc + +package cpu + +// Can only be called when the vector extension is present. +// Implemented in cpu_riscv64.s. +func readVLENB() uint diff --git a/vendor/golang.org/x/sys/cpu/cpu_linux_ppc64x.go b/vendor/golang.org/x/sys/cpu/cpu_linux_ppc64x.go index 197188e..70b3dc7 100644 --- a/vendor/golang.org/x/sys/cpu/cpu_linux_ppc64x.go +++ b/vendor/golang.org/x/sys/cpu/cpu_linux_ppc64x.go @@ -11,6 +11,7 @@ const ( // ISA Level _PPC_FEATURE2_ARCH_2_07 = 0x80000000 _PPC_FEATURE2_ARCH_3_00 = 0x00800000 + _PPC_FEATURE2_ARCH_3_1 = 0x00040000 // CPU features _PPC_FEATURE2_DARN = 0x00200000 @@ -21,6 +22,9 @@ func doinit() { // HWCAP2 feature bits PPC64.IsPOWER8 = isSet(hwCap2, _PPC_FEATURE2_ARCH_2_07) PPC64.IsPOWER9 = isSet(hwCap2, _PPC_FEATURE2_ARCH_3_00) + // ISA 3.1 covers both POWER10 and POWER11: POWER11 did not introduce a + // new architected HWCAP level, so there is no separate IsPOWER11. + PPC64.IsPOWER10 = isSet(hwCap2, _PPC_FEATURE2_ARCH_3_1) PPC64.HasDARN = isSet(hwCap2, _PPC_FEATURE2_DARN) PPC64.HasSCV = isSet(hwCap2, _PPC_FEATURE2_SCV) } diff --git a/vendor/golang.org/x/sys/cpu/cpu_linux_riscv64.go b/vendor/golang.org/x/sys/cpu/cpu_linux_riscv64.go index f4fb52e..53e9091 100644 --- a/vendor/golang.org/x/sys/cpu/cpu_linux_riscv64.go +++ b/vendor/golang.org/x/sys/cpu/cpu_linux_riscv64.go @@ -130,6 +130,9 @@ func doinit() { RISCV64.HasFastMisaligned = v == riscv_HWPROBE_MISALIGNED_FAST } } + if RISCV64.HasV { + RISCV64.VLENB = readVLENB() + } // Let's double check with HWCAP if the C extension does not appear to be supported. // This may happen if we're running on a kernel older than 6.4. @@ -137,6 +140,14 @@ func doinit() { if !RISCV64.HasC { RISCV64.HasC = isSet(hwCap, hwcap_RISCV_ISA_C) } + + doDerived = func() { + // If the vector extension is disabled by GODEBUG, then the VLENB is zero. + if !RISCV64.HasV { + RISCV64.VLENB = 0 + } + } + } func isSet(hwc uint, value uint) bool { diff --git a/vendor/golang.org/x/sys/cpu/cpu_netbsd_amd64.go b/vendor/golang.org/x/sys/cpu/cpu_netbsd_amd64.go new file mode 100644 index 0000000..4f981b1 --- /dev/null +++ b/vendor/golang.org/x/sys/cpu/cpu_netbsd_amd64.go @@ -0,0 +1,47 @@ +// Copyright 2026 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build netbsd && amd64 && gc + +package cpu + +func doinit() { + // NetBSD corrupts avx registers when receiving signals. + // See issue 80285. + // TODO: when NetBSD fixes the bug, add a version + // check and skip here. + X86.HasAVX = false + X86.HasAVX2 = false + // Set these also, just to be safe + X86.HasAVXVNNI = false + X86.HasAVX512 = false + X86.HasAVX512F = false + X86.HasAVX512CD = false + X86.HasAVX512CD = false + X86.HasAVX512ER = false + X86.HasAVX512PF = false + X86.HasAVX512VL = false + X86.HasAVX512BW = false + X86.HasAVX512DQ = false + X86.HasAVX512IFMA = false + X86.HasAVX512VBMI = false + X86.HasAVX5124VNNIW = false + X86.HasAVX5124FMAPS = false + X86.HasAVX512VPOPCNTDQ = false + X86.HasAVX512VPCLMULQDQ = false + X86.HasAVX512VNNI = false + X86.HasAVX512GFNI = false + X86.HasAVX512VAES = false + X86.HasAVX512VBMI2 = false + X86.HasAVX512BITALG = false + X86.HasAVX512BF16 = false + X86.HasAVXIFMA = false + X86.HasAVXVNNI = false + X86.HasAVXVNNIInt8 = false + +} + +func darwinSupportsAVX512() bool { + panic("only implemented for gc && amd64 && darwin") +} diff --git a/vendor/golang.org/x/sys/cpu/cpu_other_x86.go b/vendor/golang.org/x/sys/cpu/cpu_other_x86.go index a0fd7e2..82b7580 100644 --- a/vendor/golang.org/x/sys/cpu/cpu_other_x86.go +++ b/vendor/golang.org/x/sys/cpu/cpu_other_x86.go @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -//go:build 386 || amd64p32 || (amd64 && (!darwin || !gc)) +//go:build 386 || amd64p32 || (amd64 && ((!darwin && !netbsd) || !gc)) package cpu diff --git a/vendor/golang.org/x/sys/cpu/cpu_riscv64.s b/vendor/golang.org/x/sys/cpu/cpu_riscv64.s new file mode 100644 index 0000000..b092fb2 --- /dev/null +++ b/vendor/golang.org/x/sys/cpu/cpu_riscv64.s @@ -0,0 +1,17 @@ +// Copyright 2026 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build gc + +#include "textflag.h" + +// Read the vector register length in bytes from the vlenb CSR. +// May only be called when the vector extension is present. +// func readVLENB() uint +TEXT ·readVLENB(SB), NOSPLIT|NOFRAME, $0-8 + // Go 1.25's assembler does not recognize VLENB, so use its raw CSRR encoding. + // Replace WORD with CSRR VLENB, X10 once go.mod requires Go 1.27. + WORD $0xc2202573 + MOV X10, ret+0(FP) + RET diff --git a/vendor/golang.org/x/sys/cpu/cpu_sparc64.go b/vendor/golang.org/x/sys/cpu/cpu_sparc64.go new file mode 100644 index 0000000..0199ef1 --- /dev/null +++ b/vendor/golang.org/x/sys/cpu/cpu_sparc64.go @@ -0,0 +1,12 @@ +// Copyright 2026 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build sparc64 + +package cpu + +// The L1 line is 32 bytes; false sharing is governed by the 64-byte L2 line. +const cacheLineSize = 64 + +func initOptions() {} diff --git a/vendor/golang.org/x/sys/cpu/cpu_wasm32.go b/vendor/golang.org/x/sys/cpu/cpu_wasm32.go new file mode 100644 index 0000000..2d093dd --- /dev/null +++ b/vendor/golang.org/x/sys/cpu/cpu_wasm32.go @@ -0,0 +1,17 @@ +// Copyright 2026 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build wasm32 + +package cpu + +// We're compiling the cpu package for an unknown (software-abstracted) CPU. +// Make CacheLinePad an empty struct and hope that the usual struct alignment +// rules are good enough. + +const cacheLineSize = 0 + +func initOptions() {} + +func archInit() {} diff --git a/vendor/golang.org/x/sys/cpu/cpu_x86.go b/vendor/golang.org/x/sys/cpu/cpu_x86.go index f5723d4..7e6cead 100644 --- a/vendor/golang.org/x/sys/cpu/cpu_x86.go +++ b/vendor/golang.org/x/sys/cpu/cpu_x86.go @@ -43,7 +43,11 @@ func initOptions() { {Name: "bmi2", Feature: &X86.HasBMI2}, {Name: "cx16", Feature: &X86.HasCX16}, {Name: "erms", Feature: &X86.HasERMS}, + {Name: "f16c", Feature: &X86.HasF16C}, {Name: "fma", Feature: &X86.HasFMA}, + {Name: "lahf", Feature: &X86.HasLAHF}, + {Name: "lzcnt", Feature: &X86.HasLZCNT}, + {Name: "movbe", Feature: &X86.HasMOVBE}, {Name: "osxsave", Feature: &X86.HasOSXSAVE}, {Name: "pclmulqdq", Feature: &X86.HasPCLMULQDQ}, {Name: "popcnt", Feature: &X86.HasPOPCNT}, @@ -56,6 +60,7 @@ func initOptions() { {Name: "avxifma", Feature: &X86.HasAVXIFMA}, {Name: "avxvnni", Feature: &X86.HasAVXVNNI}, {Name: "avxvnniint8", Feature: &X86.HasAVXVNNIInt8}, + {Name: "xsave", Feature: &X86.HasXSAVE}, // These capabilities should always be enabled on amd64: {Name: "sse2", Feature: &X86.HasSSE2, Required: runtime.GOARCH == "amd64"}, @@ -83,10 +88,13 @@ func archInit() { cpuid_AVX512VPOPCNTDQ = 1 << 14 cpuid_SSE41 = 1 << 19 cpuid_SSE42 = 1 << 20 + cpuid_MOVBE = 1 << 22 cpuid_POPCNT = 1 << 23 cpuid_AES = 1 << 25 + cpuid_XSAVE = 1 << 26 cpuid_OSXSAVE = 1 << 27 cpuid_AVX = 1 << 28 + cpuid_F16C = 1 << 29 // "Extended Feature Flag" bits returned in EBX for CPUID EAX=0x7 ECX=0x0 cpuid_BMI1 = 1 << 3 @@ -110,6 +118,9 @@ func archInit() { // edx bits cpuid_FSRM = 1 << 4 + // ecx bits for CPUID 0x80000001 + cpuid_LAHF = 1 << 0 + cpuid_LZCNT = 1 << 5 // edx bits for CPUID 0x80000001 cpuid_RDTSCP = 1 << 27 ) @@ -158,9 +169,21 @@ func archInit() { X86.HasSSE42 = isSet(ecx1, cpuid_SSE42) X86.HasPOPCNT = isSet(ecx1, cpuid_POPCNT) X86.HasAES = isSet(ecx1, cpuid_AES) + X86.HasXSAVE = isSet(ecx1, cpuid_XSAVE) X86.HasOSXSAVE = isSet(ecx1, cpuid_OSXSAVE) + X86.HasF16C = isSet(ecx1, cpuid_F16C) + X86.HasMOVBE = isSet(ecx1, cpuid_MOVBE) X86.HasRDRAND = isSet(ecx1, cpuid_RDRAND) + // Extended processor info and feature bits, under the separate extended + // (0x8000_0000-prefixed) leaf hierarchy, so maxID (the basic leaf count) + // doesn't gate it. + if maxExtID, _, _, _ := cpuid(0x80000000, 0); maxExtID >= 0x80000001 { + _, _, ecxExt1, _ := cpuid(0x80000001, 0) + X86.HasLAHF = isSet(ecxExt1, cpuid_LAHF) + X86.HasLZCNT = isSet(ecxExt1, cpuid_LZCNT) + } + var osSupportsAVX, osSupportsAVX512 bool // For XGETBV, OSXSAVE bit is required and sufficient. if X86.HasOSXSAVE { diff --git a/vendor/golang.org/x/sys/cpu/endian_little.go b/vendor/golang.org/x/sys/cpu/endian_little.go index 48eccc4..af38b79 100644 --- a/vendor/golang.org/x/sys/cpu/endian_little.go +++ b/vendor/golang.org/x/sys/cpu/endian_little.go @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -//go:build 386 || amd64 || amd64p32 || alpha || arm || arm64 || loong64 || mipsle || mips64le || mips64p32le || nios2 || ppc64le || riscv || riscv64 || sh || wasm +//go:build 386 || amd64 || amd64p32 || alpha || arm || arm64 || loong64 || mipsle || mips64le || mips64p32le || nios2 || ppc64le || riscv || riscv64 || sh || wasm || wasm32 package cpu diff --git a/vendor/golang.org/x/sys/cpu/zcpu_windows.go b/vendor/golang.org/x/sys/cpu/zcpu_windows.go index 6411a7a..949b8f4 100644 --- a/vendor/golang.org/x/sys/cpu/zcpu_windows.go +++ b/vendor/golang.org/x/sys/cpu/zcpu_windows.go @@ -43,6 +43,6 @@ var ( func isProcessorFeaturePresent(ProcessorFeature uint32) (ret bool) { r0, _, _ := syscall.SyscallN(procIsProcessorFeaturePresent.Addr(), uintptr(ProcessorFeature)) - ret = r0 != 0 + ret = uint32(r0) != 0 return } diff --git a/vendor/golang.org/x/sys/unix/asm_linux_ppc64x.s b/vendor/golang.org/x/sys/unix/asm_linux_ppc64x.s index bdfc024..daa8571 100644 --- a/vendor/golang.org/x/sys/unix/asm_linux_ppc64x.s +++ b/vendor/golang.org/x/sys/unix/asm_linux_ppc64x.s @@ -13,6 +13,16 @@ // Just jump to package syscall's implementation for all these functions. // The runtime may know about them. +TEXT ·Syscall(SB),NOSPLIT,$0-56 + MOVD $syscall·Syscall(SB), R12 + MOVD R12, CTR + JMP (CTR) + +TEXT ·Syscall6(SB),NOSPLIT,$0-80 + MOVD $syscall·Syscall6(SB), R12 + MOVD R12, CTR + JMP (CTR) + TEXT ·SyscallNoError(SB),NOSPLIT,$0-48 BL runtime·entersyscall(SB) MOVD a1+8(FP), R3 @@ -28,6 +38,16 @@ TEXT ·SyscallNoError(SB),NOSPLIT,$0-48 BL runtime·exitsyscall(SB) RET +TEXT ·RawSyscall(SB),NOSPLIT,$0-56 + MOVD $syscall·RawSyscall(SB), R12 + MOVD R12, CTR + JMP (CTR) + +TEXT ·RawSyscall6(SB),NOSPLIT,$0-80 + MOVD $syscall·RawSyscall6(SB), R12 + MOVD R12, CTR + JMP (CTR) + TEXT ·RawSyscallNoError(SB),NOSPLIT,$0-48 MOVD a1+8(FP), R3 MOVD a2+16(FP), R4 diff --git a/vendor/golang.org/x/sys/unix/asm_linux_sparc64.s b/vendor/golang.org/x/sys/unix/asm_linux_sparc64.s new file mode 100644 index 0000000..77e1e32 --- /dev/null +++ b/vendor/golang.org/x/sys/unix/asm_linux_sparc64.s @@ -0,0 +1,48 @@ +// Copyright 2026 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build linux && sparc64 && gc + +#include "textflag.h" + +// +// System calls for sparc64, Linux +// + +// Just jump to package syscall's implementation for all these functions. +// The runtime may know about them. + +TEXT ·Syscall(SB), NOSPLIT, $0-56 + JMP syscall·Syscall(SB) + +TEXT ·Syscall6(SB), NOSPLIT, $0-80 + JMP syscall·Syscall6(SB) + +TEXT ·SyscallNoError(SB), NOSPLIT, $0-48 + CALL runtime·entersyscall(SB) + MOVD trap+0(FP), R1 // syscall entry + MOVD a1+8(FP), R8 + MOVD a2+16(FP), R9 + MOVD a3+24(FP), R10 + TA $0x6d + MOVD R8, r1+32(FP) + MOVD R9, r2+40(FP) + CALL runtime·exitsyscall(SB) + RET + +TEXT ·RawSyscall(SB), NOSPLIT, $0-56 + JMP syscall·RawSyscall(SB) + +TEXT ·RawSyscall6(SB), NOSPLIT, $0-80 + JMP syscall·RawSyscall6(SB) + +TEXT ·RawSyscallNoError(SB), NOSPLIT, $0-48 + MOVD trap+0(FP), R1 // syscall entry + MOVD a1+8(FP), R8 + MOVD a2+16(FP), R9 + MOVD a3+24(FP), R10 + TA $0x6d + MOVD R8, r1+32(FP) + MOVD R9, r2+40(FP) + RET diff --git a/vendor/golang.org/x/sys/unix/asm_zos_s390x.s b/vendor/golang.org/x/sys/unix/asm_zos_s390x.s index 813dfad..980f07a 100644 --- a/vendor/golang.org/x/sys/unix/asm_zos_s390x.s +++ b/vendor/golang.org/x/sys/unix/asm_zos_s390x.s @@ -30,21 +30,8 @@ #define SVC_LOAD BYTE $0x0A; BYTE $0x08 // SVC 08 LOAD #define SVC_DELETE BYTE $0x0A; BYTE $0x09 // SVC 09 DELETE -DATA zosLibVec<>(SB)/8, $0 -GLOBL zosLibVec<>(SB), NOPTR, $8 - -TEXT ·initZosLibVec(SB), NOSPLIT|NOFRAME, $0-0 - MOVW PSALAA, R8 - MOVD LCA64(R8), R8 - MOVD CAA(R8), R8 - MOVD EDCHPXV(R8), R8 - MOVD R8, zosLibVec<>(SB) - RET - TEXT ·GetZosLibVec(SB), NOSPLIT|NOFRAME, $0-0 - MOVD zosLibVec<>(SB), R8 - MOVD R8, ret+0(FP) - RET + JMP runtime·GetZosLibVec(SB) TEXT ·clearErrno(SB), NOSPLIT, $0-0 BL addrerrno<>(SB) @@ -160,163 +147,13 @@ TEXT ·gettid(SB), NOSPLIT, $0 // errno and errno2 is retrieved // TEXT ·CallLeFuncWithErr(SB), NOSPLIT, $0 - MOVW PSALAA, R8 - MOVD LCA64(R8), R8 - MOVD CAA(R8), R9 - MOVD g, GOCB(R9) - - // Restore LE stack. - MOVD SAVSTACK_ASYNC(R8), R9 // R9-> LE stack frame saving address - MOVD 0(R9), R4 // R4-> restore previously saved stack frame pointer - - MOVD parms_base+8(FP), R7 // R7 -> argument array - MOVD parms_len+16(FP), R8 // R8 number of arguments - - // arg 1 ---> R1 - CMP R8, $0 - BEQ docall - SUB $1, R8 - MOVD 0(R7), R1 - - // arg 2 ---> R2 - CMP R8, $0 - BEQ docall - SUB $1, R8 - ADD $8, R7 - MOVD 0(R7), R2 - - // arg 3 --> R3 - CMP R8, $0 - BEQ docall - SUB $1, R8 - ADD $8, R7 - MOVD 0(R7), R3 - - CMP R8, $0 - BEQ docall - MOVD $2176+16, R6 // starting LE stack address-8 to store 4th argument - -repeat: - ADD $8, R7 - MOVD 0(R7), R0 // advance arg pointer by 8 byte - ADD $8, R6 // advance LE argument address by 8 byte - MOVD R0, (R4)(R6*1) // copy argument from go-slice to le-frame - SUB $1, R8 - CMP R8, $0 - BNE repeat - -docall: - MOVD funcdesc+0(FP), R8 // R8-> function descriptor - LMG 0(R8), R5, R6 - MOVD $0, 0(R9) // R9 address of SAVSTACK_ASYNC - LE_CALL // balr R7, R6 (return #1) - NOPH - MOVD R3, ret+32(FP) - CMP R3, $-1 // compare result to -1 - BNE done - - // retrieve errno and errno2 - MOVD zosLibVec<>(SB), R8 - ADD $(__errno), R8 - LMG 0(R8), R5, R6 - LE_CALL // balr R7, R6 __errno (return #3) - NOPH - MOVWZ 0(R3), R3 - MOVD R3, err+48(FP) - MOVD zosLibVec<>(SB), R8 - ADD $(__err2ad), R8 - LMG 0(R8), R5, R6 - LE_CALL // balr R7, R6 __err2ad (return #2) - NOPH - MOVW (R3), R2 // retrieve errno2 - MOVD R2, errno2+40(FP) // store in return area - -done: - MOVD R4, 0(R9) // Save stack pointer. - RET - + JMP runtime·CallLeFuncWithErr(SB) // // Call LE function, if the return is 0 // errno and errno2 is retrieved // TEXT ·CallLeFuncWithPtrReturn(SB), NOSPLIT, $0 - MOVW PSALAA, R8 - MOVD LCA64(R8), R8 - MOVD CAA(R8), R9 - MOVD g, GOCB(R9) - - // Restore LE stack. - MOVD SAVSTACK_ASYNC(R8), R9 // R9-> LE stack frame saving address - MOVD 0(R9), R4 // R4-> restore previously saved stack frame pointer - - MOVD parms_base+8(FP), R7 // R7 -> argument array - MOVD parms_len+16(FP), R8 // R8 number of arguments - - // arg 1 ---> R1 - CMP R8, $0 - BEQ docall - SUB $1, R8 - MOVD 0(R7), R1 - - // arg 2 ---> R2 - CMP R8, $0 - BEQ docall - SUB $1, R8 - ADD $8, R7 - MOVD 0(R7), R2 - - // arg 3 --> R3 - CMP R8, $0 - BEQ docall - SUB $1, R8 - ADD $8, R7 - MOVD 0(R7), R3 - - CMP R8, $0 - BEQ docall - MOVD $2176+16, R6 // starting LE stack address-8 to store 4th argument - -repeat: - ADD $8, R7 - MOVD 0(R7), R0 // advance arg pointer by 8 byte - ADD $8, R6 // advance LE argument address by 8 byte - MOVD R0, (R4)(R6*1) // copy argument from go-slice to le-frame - SUB $1, R8 - CMP R8, $0 - BNE repeat - -docall: - MOVD funcdesc+0(FP), R8 // R8-> function descriptor - LMG 0(R8), R5, R6 - MOVD $0, 0(R9) // R9 address of SAVSTACK_ASYNC - LE_CALL // balr R7, R6 (return #1) - NOPH - MOVD R3, ret+32(FP) - CMP R3, $0 // compare result to 0 - BNE done - - // retrieve errno and errno2 - MOVD zosLibVec<>(SB), R8 - ADD $(__errno), R8 - LMG 0(R8), R5, R6 - LE_CALL // balr R7, R6 __errno (return #3) - NOPH - MOVWZ 0(R3), R3 - MOVD R3, err+48(FP) - MOVD zosLibVec<>(SB), R8 - ADD $(__err2ad), R8 - LMG 0(R8), R5, R6 - LE_CALL // balr R7, R6 __err2ad (return #2) - NOPH - MOVW (R3), R2 // retrieve errno2 - MOVD R2, errno2+40(FP) // store in return area - XOR R2, R2 - MOVWZ R2, (R3) // clear errno2 - -done: - MOVD R4, 0(R9) // Save stack pointer. - RET - + JMP runtime·CallLeFuncWithPtrReturn(SB) // // function to test if a pointer can be safely dereferenced (content read) // return 0 for succces @@ -360,23 +197,4 @@ TEXT ·ptrtest(SB), NOSPLIT, $0-16 // // func safeload(ptr uintptr) ( value uintptr, error uintptr) TEXT ·safeload(SB), NOSPLIT, $0-24 - MOVD ptr+0(FP), R10 // test pointer in R10 - MOVD $0x0, R6 - BYTE $0xE3; BYTE $0x20; BYTE $0x04; BYTE $0xB8; BYTE $0x00; BYTE $0x17 // llgt 2,1208 - BYTE $0xB9; BYTE $0x17; BYTE $0x00; BYTE $0x22 // llgtr 2,2 - BYTE $0xA5; BYTE $0x26; BYTE $0x7F; BYTE $0xFF // nilh 2,32767 - BYTE $0xE3; BYTE $0x22; BYTE $0x00; BYTE $0x58; BYTE $0x00; BYTE $0x04 // lg 2,88(2) - BYTE $0xE3; BYTE $0x22; BYTE $0x00; BYTE $0x08; BYTE $0x00; BYTE $0x04 // lg 2,8(2) - BYTE $0x41; BYTE $0x22; BYTE $0x03; BYTE $0x68 // la 2,872(2) - BYTE $0xB9; BYTE $0x82; BYTE $0x00; BYTE $0x33 // xgr 3,3 - BYTE $0xA7; BYTE $0x55; BYTE $0x00; BYTE $0x04 // bras 5,lbl1 - BYTE $0xA7; BYTE $0x39; BYTE $0x00; BYTE $0x01 // lghi 3,1 - BYTE $0xB9; BYTE $0x02; BYTE $0x00; BYTE $0x33 // lbl1 ltgr 3,3 - BYTE $0xA7; BYTE $0x74; BYTE $0x00; BYTE $0x08 // brc b'0111',lbl2 - BYTE $0xE3; BYTE $0x52; BYTE $0x00; BYTE $0x00; BYTE $0x00; BYTE $0x24 // stg 5,0(2) - BYTE $0xE3; BYTE $0x6A; BYTE $0x00; BYTE $0x00; BYTE $0x00; BYTE $0x04 // lg 6,0(10) - BYTE $0xB9; BYTE $0x82; BYTE $0x00; BYTE $0x99 // lbl2 xgr 9,9 - BYTE $0xE3; BYTE $0x92; BYTE $0x00; BYTE $0x00; BYTE $0x00; BYTE $0x24 // stg 9,0(2) - MOVD R6, value+8(FP) // result in R6 - MOVD R3, error+16(FP) // error in R3 - RET + JMP runtime·ZosSafeLoad(SB) diff --git a/vendor/golang.org/x/sys/unix/bpxsvc_zos.s b/vendor/golang.org/x/sys/unix/bpxsvc_zos.s index 4bd4a17..1236e1e 100644 --- a/vendor/golang.org/x/sys/unix/bpxsvc_zos.s +++ b/vendor/golang.org/x/sys/unix/bpxsvc_zos.s @@ -20,15 +20,15 @@ TEXT ·bpxcall(SB), NOSPLIT|NOFRAME, $0 MOVD plist_base+0(FP), R1 // r1 points to plist MOVD bpx_offset+24(FP), R2 // r2 offset to BPX vector table MOVD R14, R7 // save r14 - MOVD R15, R8 // save r15 - MOVWZ 16(R0), R9 - MOVWZ 544(R9), R9 - MOVWZ 24(R9), R9 // call vector in r9 - ADD R2, R9 // add offset to vector table - MOVWZ (R9), R9 // r9 points to entry point - BYTE $0x0D // BL R14,R9 --> basr r14,r9 - BYTE $0xE9 // clobbers 0,1,14,15 - MOVD R8, R15 // restore 15 + MOVD R15, R9 // save r15 + MOVWZ 16(R0), R15 + MOVWZ 544(R15), R15 + MOVWZ 24(R15), R15 // call vector in r15 + ADD R2, R15 // add offset to vector table + MOVWZ (R15), R15 // r15 points to entry point + BYTE $0x0D // BL R14,R15 --> basr r14,r15 + BYTE $0xEF // clobbers 0,1,14,15 + MOVD R9, R15 // restore 15 JMP R7 // return via saved return address // func A2e(arr [] byte) diff --git a/vendor/golang.org/x/sys/unix/dirent.go b/vendor/golang.org/x/sys/unix/dirent.go index 1ebf117..182181e 100644 --- a/vendor/golang.org/x/sys/unix/dirent.go +++ b/vendor/golang.org/x/sys/unix/dirent.go @@ -6,7 +6,10 @@ package unix -import "unsafe" +import ( + "runtime" + "unsafe" +) // readInt returns the size-bytes unsigned integer in native byte order at offset off. func readInt(b []byte, off, size uintptr) (u uint64, ok bool) { @@ -75,7 +78,10 @@ func ParseDirent(buf []byte, max int, names []string) (consumed int, count int, if !ok { break } - if ino == 0 { // File absent in directory. + // Some filesystems on Linux (old XFS, FUSE) can return valid + // files with zero inodes. On other platforms, a zero inode + // indicates a file absent from the directory. + if ino == 0 && runtime.GOOS != "linux" { continue } const namoff = uint64(unsafe.Offsetof(Dirent{}.Name)) diff --git a/vendor/golang.org/x/sys/unix/fcntl_darwin.go b/vendor/golang.org/x/sys/unix/fcntl_darwin.go index a9911c7..78c28a3 100644 --- a/vendor/golang.org/x/sys/unix/fcntl_darwin.go +++ b/vendor/golang.org/x/sys/unix/fcntl_darwin.go @@ -13,12 +13,12 @@ func FcntlInt(fd uintptr, cmd, arg int) (int, error) { // FcntlFlock performs a fcntl syscall for the F_GETLK, F_SETLK or F_SETLKW command. func FcntlFlock(fd uintptr, cmd int, lk *Flock_t) error { - _, err := fcntl(int(fd), cmd, int(uintptr(unsafe.Pointer(lk)))) + _, err := fcntlPtr(int(fd), cmd, unsafe.Pointer(lk)) return err } // FcntlFstore performs a fcntl syscall for the F_PREALLOCATE command. func FcntlFstore(fd uintptr, cmd int, fstore *Fstore_t) error { - _, err := fcntl(int(fd), cmd, int(uintptr(unsafe.Pointer(fstore)))) + _, err := fcntlPtr(int(fd), cmd, unsafe.Pointer(fstore)) return err } diff --git a/vendor/golang.org/x/sys/unix/ifreq_linux.go b/vendor/golang.org/x/sys/unix/ifreq_linux.go index 309f5a2..3f7fa76 100644 --- a/vendor/golang.org/x/sys/unix/ifreq_linux.go +++ b/vendor/golang.org/x/sys/unix/ifreq_linux.go @@ -22,7 +22,13 @@ import ( // fields can be get and set using the following methods: // - Uint16/SetUint16: flags // - Uint32/SetUint32: ifindex, metric, mtu -type Ifreq struct{ raw ifreq } +type Ifreq struct { + // Aligns the union for the accessors below, which cast it in place; + // the generated ifreq is all byte arrays, so its alignment is one. + _ [0]int64 + + raw ifreq +} // NewIfreq creates an Ifreq with the input network interface name after // validating the name does not exceed IFNAMSIZ-1 (trailing NULL required) diff --git a/vendor/golang.org/x/sys/unix/ioctl_linux.go b/vendor/golang.org/x/sys/unix/ioctl_linux.go index 7ca4fa1..b1d769a 100644 --- a/vendor/golang.org/x/sys/unix/ioctl_linux.go +++ b/vendor/golang.org/x/sys/unix/ioctl_linux.go @@ -23,6 +23,12 @@ func IoctlGetUint32(fd int, req uint) (uint32, error) { return value, err } +func IoctlGetUint64(fd int, req uint) (uint64, error) { + var value uint64 + err := ioctlPtr(fd, req, unsafe.Pointer(&value)) + return value, err +} + func IoctlGetRTCTime(fd int) (*RTCTime, error) { var value RTCTime err := ioctlPtr(fd, RTC_RD_TIME, unsafe.Pointer(&value)) @@ -332,3 +338,10 @@ func IoctlLoopSetStatus64(fd int, value *LoopInfo64) error { func IoctlLoopConfigure(fd int, value *LoopConfig) error { return ioctlPtr(fd, LOOP_CONFIGURE, unsafe.Pointer(value)) } + +// IoctlPidfdInfo fetches information about a pidfd. +// The Mask field of the info argument indicates which +// values to fetch. +func IoctlPidfdInfo(fd int, info *PidfdInfo) error { + return ioctlPtr(fd, PIDFD_GET_INFO, unsafe.Pointer(info)) +} diff --git a/vendor/golang.org/x/sys/unix/mkerrors.sh b/vendor/golang.org/x/sys/unix/mkerrors.sh index fa74cfe..e95eecd 100644 --- a/vendor/golang.org/x/sys/unix/mkerrors.sh +++ b/vendor/golang.org/x/sys/unix/mkerrors.sh @@ -290,14 +290,7 @@ struct ltchars { #include #include -#if defined(__sparc__) -// On sparc{,64}, the kernel defines struct termios2 itself which clashes with the -// definition in glibc. As only the error constants are needed here, include the -// generic termibits.h (which is included by termbits.h on sparc). -#include -#else #include -#endif #ifndef PTRACE_GETREGS #define PTRACE_GETREGS 0xc @@ -544,7 +537,7 @@ ccflags="$@" $2 ~ /^LO_(KEY|NAME)_SIZE$/ || $2 ~ /^LOOP_(CLR|CTL|GET|SET)_/ || $2 == "LOOP_CONFIGURE" || - $2 ~ /^(AF|SOCK|SO|SOL|IPPROTO|IP|IPV6|TCP|MCAST|EVFILT|NOTE|SHUT|PROT|MAP|MREMAP|MFD|T?PACKET|MSG|SCM|MCL|DT|MADV|PR|LOCAL|TCPOPT|UDP)_/ || + $2 ~ /^(AF|SOCK|SO|SOL|IPPROTO|IP|IPV6|TCP|MCAST|EVFILT|NOTE|SHUT|PROT|MAP|MREMAP|MFD|MLOCK|T?PACKET|MSG|SCM|MCL|DT|MADV|PR|LOCAL|TCPOPT|UDP)_/ || $2 ~ /^NFC_(GENL|PROTO|COMM|RF|SE|DIRECTION|LLCP|SOCKPROTO)_/ || $2 ~ /^NFC_.*_(MAX)?SIZE$/ || $2 ~ /^PTP_/ || @@ -586,7 +579,7 @@ ccflags="$@" $2 ~ /^DIOC/ || $2 ~ /^RUSAGE_(SELF|CHILDREN|THREAD)/ || $2 ~ /^RLIMIT_(AS|CORE|CPU|DATA|FSIZE|LOCKS|MEMLOCK|MSGQUEUE|NICE|NOFILE|NPROC|RSS|RTPRIO|RTTIME|SIGPENDING|STACK)|RLIM_INFINITY/ || - $2 ~ /^PRIO_(PROCESS|PGRP|USER)/ || + $2 ~ /^PRIO_(PROCESS|PGRP|USER|DARWIN_(THREAD|PROCESS|BG|NONUI))/ || $2 ~ /^CLONE_[A-Z_]+/ || $2 !~ /^(BPF_TIMEVAL|BPF_FIB_LOOKUP_[A-Z]+|BPF_F_LINK)$/ && $2 ~ /^(BPF|DLT)_/ || diff --git a/vendor/golang.org/x/sys/unix/ptrace_zos.go b/vendor/golang.org/x/sys/unix/ptrace_zos.go new file mode 100644 index 0000000..394fbd7 --- /dev/null +++ b/vendor/golang.org/x/sys/unix/ptrace_zos.go @@ -0,0 +1,537 @@ +// Copyright 2026 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build zos + +package unix + +import "unsafe" + +// z/OS ptrace implementation notes: +// +// This file provides ptrace wrappers for z/OS that match the Linux API as closely +// as possible. However, there are fundamental differences in how z/OS implements +// process tracing compared to Linux: +// +// 1. SYSTEM CALL INTERFACE: +// - z/OS uses BPX4PTR (5 parameters) vs Linux ptrace syscall (4 parameters) +// - The 5th parameter (buffer) is used for block operations +// +// 2. MEMORY OPERATIONS: +// - z/OS: PT_READ_BLOCK/PT_WRITE_BLOCK for efficient block transfers +// - Linux: PTRACE_PEEKTEXT/POKETEXT for word-by-word access +// +// 3. REGISTER OPERATIONS: +// - z/OS: PT_READ_GPR/PT_WRITE_GPR with register number for 64-bit values +// - Linux: PTRACE_GETREGSET/SETREGSET with iovec structure +// +// 4. SINGLE-STEPPING: +// - z/OS: No native single-step; requires temporary breakpoints or PER +// - Linux: PTRACE_SINGLESTEP natively supported +// a) Read instruction at current PSW +// b) Calculate next instruction address (handle branches) +// c) Set temporary breakpoint (SVC 144 = 0x0A90) at next address +// d) Continue execution until breakpoint hit +// e) Restore original instruction and adjust PSW +// +// 5. SYSCALL TRACING: +// - z/OS: No PTRACE_SYSCALL equivalent; requires breakpoint-based approach +// - Linux: PTRACE_SYSCALL stops at syscall entry/exit +// a) Identify BPX syscall vector location +// b) Set breakpoints at syscall entry points +// c) Detect BASR instructions calling into syscall vector +// d) Parse arguments from registers before/after syscall +// +// 6. LIMITATIONS: +// - PtraceSetOptions: No equivalent (returns ENOSYS) +// - PtraceGetEventMsg: No equivalent (returns ENOSYS) +// - PtraceSingleStep: Requires complex implementation (returns ENOSYS) +// - PtraceInterrupt: No equivalent (returns ENOSYS) +// - PtracePokeUser: No PT_WRITE_U (returns ENOSYS) +// +// For reference implementations of single-stepping and syscall tracing on z/OS, + +// ptrace is the basic wrapper for BPX4PTR on z/OS. +// Note: z/OS ptrace (BPX4PTR) takes 5 parameters vs 4 on Linux/Darwin. +// The 5th parameter (buffer) is used for operations like PT_READ_BLOCK/PT_WRITE_BLOCK. +// +// data is an integer-valued argument (signal number, register index, byte count, +// or a target-process address). It is not a Go-managed pointer. We must not pass +// it to Bpx4ptr as unsafe.Pointer(data) because the garbage collector would treat +// that integer as a pointer and may crash trying to follow it. +// +// Instead we inline the parms array that Bpx4ptr would construct, placing &data +// at parms[3]. BPX4PTR dereferences parms[3] to obtain the data value, so it +// receives data unchanged while the GC only ever sees a valid stack pointer. +func ptrace(request int, pid int, addr uintptr, data uintptr) (err error) { + req32 := int32(request) + pid32 := int32(pid) + var rv, rc, rn int32 + var buffer unsafe.Pointer + parms := [8]unsafe.Pointer{ + unsafe.Pointer(&req32), + unsafe.Pointer(&pid32), + unsafe.Pointer(&addr), + unsafe.Pointer(&data), // &data, not unsafe.Pointer(data) + unsafe.Pointer(&buffer), + unsafe.Pointer(&rv), + unsafe.Pointer(&rc), + unsafe.Pointer(&rn), + } + bpxcall(parms[:], BPX4PTR) + if rv != 0 { + err = errnoErr2(Errno(rc), uintptr(rn)) + } + return +} + +// ptracePtr is a variant that accepts unsafe.Pointer for the data parameter. +// addr is a target-process address (a raw integer), not a Go-managed pointer. +// We must not pass it to Bpx4ptr as unsafe.Pointer(addr); instead we inline the +// parms array and place &addr at parms[2], exactly as ptrace() does for data. +func ptracePtr(request int, pid int, addr uintptr, data unsafe.Pointer) (err error) { + req32 := int32(request) + pid32 := int32(pid) + var rv, rc, rn int32 + var buffer unsafe.Pointer + parms := [8]unsafe.Pointer{ + unsafe.Pointer(&req32), + unsafe.Pointer(&pid32), + unsafe.Pointer(&addr), // &addr, not unsafe.Pointer(addr) + unsafe.Pointer(&data), + unsafe.Pointer(&buffer), + unsafe.Pointer(&rv), + unsafe.Pointer(&rc), + unsafe.Pointer(&rn), + } + bpxcall(parms[:], BPX4PTR) + if rv != 0 { + err = errnoErr2(Errno(rc), uintptr(rn)) + } + return +} + +// ptracePtrWithBuffer is used for operations that require the buffer parameter. +// addr is a target-process address; same &addr treatment as ptracePtr. +func ptracePtrWithBuffer(request int, pid int, addr uintptr, data unsafe.Pointer, buffer unsafe.Pointer) (err error) { + req32 := int32(request) + pid32 := int32(pid) + var rv, rc, rn int32 + parms := [8]unsafe.Pointer{ + unsafe.Pointer(&req32), + unsafe.Pointer(&pid32), + unsafe.Pointer(&addr), // &addr, not unsafe.Pointer(addr) + unsafe.Pointer(&data), + unsafe.Pointer(&buffer), + unsafe.Pointer(&rv), + unsafe.Pointer(&rc), + unsafe.Pointer(&rn), + } + bpxcall(parms[:], BPX4PTR) + if rv != 0 { + err = errnoErr2(Errno(rc), uintptr(rn)) + } + return +} + +// High-level convenience functions matching the Linux/Darwin API + +func PtraceAttach(pid int) (err error) { + return ptrace(PT_ATTACH, pid, 0, 0) +} + +func PtraceDetach(pid int) (err error) { + return ptrace(PT_DETACH, pid, 0, 0) +} + +func PtraceCont(pid int, signal int) (err error) { + // PT_CONTINUE can be interrupted by signals (EINTR), retry if needed + for { + err = ptrace(PT_CONTINUE, pid, 0, uintptr(signal)) + if err != EINTR { + break + } + } + return err +} + +func PtraceKill(pid int) (err error) { + return ptrace(PT_KILL, pid, 0, 0) +} + +// ptracePeek implements the peek operations using PT_READ_BLOCK. +// On z/OS, PT_READ_BLOCK can read arbitrary-length data efficiently. +// Unlike Linux which reads word-by-word, z/OS can read blocks directly. +func ptracePeek(req int, pid int, addr uintptr, out []byte) (count int, err error) { + if len(out) == 0 { + return 0, nil + } + + // z/OS PT_READ_BLOCK can read blocks directly without word-by-word alignment + // The buffer parameter points to the output buffer + buffer := unsafe.Pointer(&out[0]) + err = ptracePtrWithBuffer(req, pid, addr, unsafe.Pointer(uintptr(len(out))), buffer) + if err != nil { + return 0, err + } + return len(out), nil +} + +// PtracePeekText reads from the traced process's text segment. +func PtracePeekText(pid int, addr uintptr, out []byte) (count int, err error) { + return ptracePeek(PT_READ_BLOCK, pid, addr, out) +} + +// PtracePeekData reads from the traced process's data segment. +func PtracePeekData(pid int, addr uintptr, out []byte) (count int, err error) { + return ptracePeek(PT_READ_BLOCK, pid, addr, out) +} + +// PtracePeekUser reads from the traced process's user area. +// On z/OS, PT_READ_U reads a 32-bit word from the user area at the specified offset. +// To match Linux behavior, we implement word-by-word reading for arbitrary lengths. +func PtracePeekUser(pid int, addr uintptr, out []byte) (count int, err error) { + if len(out) == 0 { + return 0, nil + } + + // PT_READ_U reads 32-bit words from user area + // We need to read word-by-word to handle arbitrary lengths + n := 0 + for n < len(out) { + var data uint32 + err = ptracePtr(PT_READ_U, pid, addr+uintptr(n), unsafe.Pointer(&data)) + if err != nil { + return n, err + } + + // Copy up to 4 bytes to output + remaining := len(out) - n + if remaining >= 4 { + out[n] = byte(data >> 24) + out[n+1] = byte(data >> 16) + out[n+2] = byte(data >> 8) + out[n+3] = byte(data) + n += 4 + } else { + // Handle partial word at the end + for i := 0; i < remaining; i++ { + out[n+i] = byte(data >> (24 - i*8)) + } + n += remaining + } + } + return n, nil +} + +// ptracePoke implements the poke operations using PT_WRITE_BLOCK. +func ptracePoke(pokeReq int, peekReq int, pid int, addr uintptr, data []byte) (count int, err error) { + if len(data) == 0 { + return 0, nil + } + + // z/OS PT_WRITE_BLOCK can write blocks directly + buffer := unsafe.Pointer(&data[0]) + err = ptracePtrWithBuffer(pokeReq, pid, addr, unsafe.Pointer(uintptr(len(data))), buffer) + if err != nil { + return 0, err + } + return len(data), nil +} + +// PtracePokeText writes to the traced process's text segment. +func PtracePokeText(pid int, addr uintptr, data []byte) (count int, err error) { + return ptracePoke(PT_WRITE_BLOCK, PT_READ_BLOCK, pid, addr, data) +} + +// PtracePokeData writes to the traced process's data segment. +func PtracePokeData(pid int, addr uintptr, data []byte) (count int, err error) { + return ptracePoke(PT_WRITE_BLOCK, PT_READ_BLOCK, pid, addr, data) +} + +// PtracePokeUser writes to the traced process's user area. +// Note: z/OS does not have a direct PT_WRITE_U equivalent. +// This function returns ENOSYS to indicate it's not supported. +// DIFFERENCE FROM LINUX: Linux supports PTRACE_POKEUSR, z/OS does not. +func PtracePokeUser(pid int, addr uintptr, data []byte) (count int, err error) { + // z/OS doesn't have PT_WRITE_U + return 0, ENOSYS +} + +// PtraceGetRegs retrieves the general purpose registers from the traced process. +// On z/OS, PT_READ_GPR can read individual registers as 64-bit values when called +// with a register number, or read all registers when called with a buffer. +// This function reads each register individually to ensure full 64-bit values. +// DIFFERENCE FROM LINUX: Linux uses PTRACE_GETREGSET with iovec, z/OS uses PT_READ_GPR. +func PtraceGetRegs(pid int, regsout *PtraceRegs) (err error) { + // Use PT_REGHSET to enable reading high GPRs for AMODE 64 programs + rv, rc, rn := Bpx4ptr(int32(PT_REGHSET), int32(pid), nil, nil, nil) + _ = rv + _ = rc + _ = rn + + // Use PT_BLOCKREQ to read GPRs and PSW in one call + // dbx uses 3 requests: PT_READ_GPR, PT_READ_U, PT_READ_GPRH + // PT_READ_U is required for ptrace to populate PSW in GPR block + // + // IMPORTANT: z/OS ptrace always returns 64-bit ESA/390 format PSW in the Psw field. + // The 128-bit Pswg field is never populated, even with PSWG_Req bit set. + // We convert ESA/390 to z/Architecture format in software (matching DBX behavior). + const ( + numRequests = 3 + reqSize = int(unsafe.Sizeof(PtraceBlkReqReq{})) + gprSize = int(unsafe.Sizeof(PtraceBlkGpr{})) + uareaSize = int(unsafe.Sizeof(PtraceBlkUar{})) + 6*int(unsafe.Sizeof(PtraceBlkUarOcw{})) + totalSize = int(unsafe.Sizeof(PtraceBlkReq{})) + numRequests*reqSize + gprSize*2 + uareaSize + ) + + // Allocate buffer for block request + buf := make([]byte, totalSize) + + // Setup block request header + blkReq := (*PtraceBlkReq)(unsafe.Pointer(&buf[0])) + blkReq.Numreq = numRequests + + // Setup request array + reqOffset := int(unsafe.Sizeof(PtraceBlkReq{})) + reqs := (*[3]PtraceBlkReqReq)(unsafe.Pointer(&buf[reqOffset])) + + // Setup GPR block (lower 32 bits) + gprOffset := reqOffset + numRequests*reqSize + gprBlock := (*PtraceBlkGpr)(unsafe.Pointer(&buf[gprOffset])) + + // Setup user area block (required for PSW) + uareaOffset := gprOffset + gprSize + uareaBlock := (*PtraceBlkUar)(unsafe.Pointer(&buf[uareaOffset])) + uareaBlock.Num = 6 // Number of control info entries + + // Setup user area offset/control words + uareaOcw := (*[6]PtraceBlkUarOcw)(unsafe.Pointer(&buf[uareaOffset+int(unsafe.Sizeof(PtraceBlkUar{}))])) + uareaOcw[0].Ofs = 1025 // program interrupt code + uareaOcw[1].Ofs = 1026 // abend completion code + uareaOcw[2].Ofs = 1027 // abend reason code + uareaOcw[3].Ofs = 1028 // signal code + uareaOcw[4].Ofs = 1029 // instruction length code + uareaOcw[5].Ofs = 1030 // process flags + + // Setup high GPR block (upper 32 bits) + gprHighOffset := uareaOffset + uareaSize + gprHighBlock := (*PtraceBlkGpr)(unsafe.Pointer(&buf[gprHighOffset])) + + // Configure requests (order matters: GPR, U, GPRH) + // reqdata contains OFFSET from buffer start, not absolute address + // dbx: brr[0].reqdata=(unsigned long)brg; where brg is the offset + reqs[0].Reqtype = PT_READ_GPR + reqs[0].Reqdata = uint32(gprOffset) + reqs[1].Reqtype = PT_READ_U + reqs[1].Reqdata = uint32(uareaOffset) + reqs[2].Reqtype = PT_READ_GPRH + reqs[2].Reqdata = uint32(gprHighOffset) + + // Execute block request + rvBlk, rcBlk, rnBlk := Bpx4ptr(int32(PT_BLOCKREQ), int32(pid), + unsafe.Pointer(&buf[0]), unsafe.Pointer(uintptr(totalSize)), nil) + if rvBlk == -1 { + return errnoErr2(Errno(rcBlk), uintptr(rnBlk)) + } + + // Extract GPRs (combine low and high 32 bits) + for i := 0; i < 16; i++ { + low := uint64(gprBlock.Gpr[i]) + high := uint64(gprHighBlock.Gpr[i]) << 32 + regsout.Gprs[i] = high | low + } + + // Extract PSW from GPR block structure + // z/OS ptrace ALWAYS returns 8-byte ESA/390 format PSW at offset 144. + // The 16-byte PSWG field at offset 152 is NEVER populated (always zero). + // We must convert ESA/390 format to z/Architecture format in software (like DBX does). + // + // ESA/390 PSW format (8 bytes): + // Word 1 (bytes 0-3): Mask with bit 12 = 1 (ECMODE31BIT) + // Word 2 (bytes 4-7): Address with bit 0 = AMODE bit (1=31-bit, 0=64-bit) + // + // z/Architecture PSW format (16 bytes): + // Mask (bytes 0-7): Extended mask with bit 12 = 0, bits 31-32 = EA+BA (AMODE) + // Addr (bytes 8-15): Full 64-bit instruction address + + // Read ESA/390 PSW as two 32-bit words + pswWord1 := uint32(gprBlock.Psw[0])<<24 | uint32(gprBlock.Psw[1])<<16 | + uint32(gprBlock.Psw[2])<<8 | uint32(gprBlock.Psw[3]) + pswWord2 := uint32(gprBlock.Psw[4])<<24 | uint32(gprBlock.Psw[5])<<16 | + uint32(gprBlock.Psw[6])<<8 | uint32(gprBlock.Psw[7]) + + // Convert ESA/390 to z/Architecture format (matching DBX psw_ESA390_to_zArchitecture) + const ECMODE31BIT = uint64(0x0000000000080000) + const AMODE31BIT = uint64(0x0000000080000000) + const ADDR_MASK_31 = uint64(0x000000007FFFFFFF) + + // Extract AMODE bit from address word (bit 0 of word 2) + amode31 := uint64(pswWord2) & AMODE31BIT + + // Mask off AMODE bit from address + addr := uint64(pswWord2) & ADDR_MASK_31 + + // Convert mask: clear ECMODE31BIT, shift left 32 bits, add AMODE bit + mask := uint64(pswWord1) & ^ECMODE31BIT + mask = (mask << 32) | amode31 + + regsout.Psw.Mask = mask + regsout.Psw.Addr = addr + + // Note: Access registers (Acrs), floating point registers (Fp_regs), + // PER info (Per_info), and other fields would require additional + // PT_READ_* calls. For now, we focus on GPRs and PSW which are + // the most commonly used registers for debugging. + + return nil +} + +// ptraceWritePSW writes only the PSW address register. +// This is a lower-level function used internally for single-stepping. +// Based on ztrace's write_psw function. +func ptraceWritePSW(pid int, pswAddr uint32) error { + const PTRACE_REG_PSWA = 41 + rv, rc, rn := Bpx4ptr(int32(PT_WRITE_GPR), int32(pid), + unsafe.Pointer(uintptr(PTRACE_REG_PSWA)), + unsafe.Pointer(uintptr(pswAddr)), + nil) + if rv == -1 { + return errnoErr2(Errno(rc), uintptr(rn)) + } + return nil +} + +// PtraceSetRegs sets the general purpose registers in the traced process. +// Uses PT_BLOCKREQ to write GPRs and PSW in a single call, matching dbx implementation. +// DIFFERENCE FROM LINUX: Linux uses PTRACE_SETREGSET with iovec, z/OS uses PT_BLOCKREQ. +// NOTE: The process must be in a stopped state for register writes to succeed. +func PtraceSetRegs(pid int, regs *PtraceRegs) (err error) { + // Use PT_REGHSET to enable writing high GPRs for AMODE 64 programs + rv, rc, rn := Bpx4ptr(int32(PT_REGHSET), int32(pid), nil, nil, nil) + _ = rv + _ = rc + _ = rn + + // Use PT_BLOCKREQ to write GPRs and PSW in one call + const ( + numRequests = 2 + reqSize = int(unsafe.Sizeof(PtraceBlkReqReq{})) + gprSize = int(unsafe.Sizeof(PtraceBlkGpr{})) + totalSize = int(unsafe.Sizeof(PtraceBlkReq{})) + numRequests*reqSize + gprSize*2 + ) + + // Allocate buffer for block request + buf := make([]byte, totalSize) + + // Setup block request header + blkReq := (*PtraceBlkReq)(unsafe.Pointer(&buf[0])) + blkReq.Numreq = numRequests + + // Setup request array + reqOffset := int(unsafe.Sizeof(PtraceBlkReq{})) + reqs := (*[2]PtraceBlkReqReq)(unsafe.Pointer(&buf[reqOffset])) + + // Setup GPR block (lower 32 bits) + gprOffset := reqOffset + numRequests*reqSize + gprBlock := (*PtraceBlkGpr)(unsafe.Pointer(&buf[gprOffset])) + + // Setup high GPR block (upper 32 bits) + gprHighOffset := gprOffset + gprSize + gprHighBlock := (*PtraceBlkGpr)(unsafe.Pointer(&buf[gprHighOffset])) + + // Mark all GPRs as modified (set all 16 bits) + gprBlock.Writebitflags = 0xFFFF + gprHighBlock.Writebitflags = 0xFFFF + + // Split 64-bit GPRs into low and high 32 bits + for i := 0; i < 16; i++ { + gprBlock.Gpr[i] = uint32(regs.Gprs[i] & 0xFFFFFFFF) + gprHighBlock.Gpr[i] = uint32(regs.Gprs[i] >> 32) + } + + // Pack PSW for 31-bit targets (current z/OS) + // Upper 32 bits = mask, lower 32 bits = address + gprBlock.Wpsw = 1 // Mark PSW as modified + // Write PSW in old format (8 bytes at offset 144) + // Word 1 (mask) at bytes 0-3, Word 2 (addr) at bytes 4-7 + pswMask := uint32(regs.Psw.Mask) + pswAddr := uint32(regs.Psw.Addr) + gprBlock.Psw[0] = byte(pswMask >> 24) + gprBlock.Psw[1] = byte(pswMask >> 16) + gprBlock.Psw[2] = byte(pswMask >> 8) + gprBlock.Psw[3] = byte(pswMask) + gprBlock.Psw[4] = byte(pswAddr >> 24) + gprBlock.Psw[5] = byte(pswAddr >> 16) + gprBlock.Psw[6] = byte(pswAddr >> 8) + gprBlock.Psw[7] = byte(pswAddr) + + // Clear extended PSWG (not used for 31-bit targets) + for i := 0; i < 16; i++ { + gprBlock.Pswg[i] = 0 + } + + // Configure requests + // reqdata contains OFFSET from buffer start, not absolute address + reqs[0].Reqtype = PT_WRITE_GPR + reqs[0].Reqdata = uint32(gprOffset) + reqs[1].Reqtype = PT_WRITE_GPRH + reqs[1].Reqdata = uint32(gprHighOffset) + + // Execute block request + rvBlk, rcBlk, rnBlk := Bpx4ptr(int32(PT_BLOCKREQ), int32(pid), + unsafe.Pointer(&buf[0]), unsafe.Pointer(uintptr(totalSize)), nil) + if rvBlk == -1 { + return errnoErr2(Errno(rcBlk), uintptr(rnBlk)) + } + + return nil +} + +// PtraceSetOptions sets ptrace options. +// DIFFERENCE FROM LINUX: z/OS doesn't have PTRACE_SETOPTIONS equivalent. +// Returns ENOSYS to indicate this is not supported on z/OS. +func PtraceSetOptions(pid int, options int) (err error) { + return ENOSYS +} + +// PtraceGetEventMsg retrieves a message about the ptrace event. +// DIFFERENCE FROM LINUX: z/OS doesn't have PTRACE_GETEVENTMSG equivalent. +// Returns ENOSYS to indicate this is not supported on z/OS. +func PtraceGetEventMsg(pid int) (msg uint, err error) { + return 0, ENOSYS +} + +// PtraceSyscall continues execution and stops at the next syscall entry/exit. +// DIFFERENCE FROM LINUX: z/OS doesn't have PTRACE_SYSCALL equivalent. +// This function falls back to PT_CONTINUE and will NOT stop at syscalls. +// +// To trace syscalls on z/OS, applications must: +// 1. Set breakpoints at BPX syscall entry points (requires knowledge of syscall vector) +// 2. Detect BASR instructions that call into the BPX syscall vector +// 3. Use PT_LDINFO to identify loaded modules and their entry points +func PtraceSyscall(pid int, signal int) (err error) { + // z/OS doesn't have a direct PTRACE_SYSCALL equivalent + // Use PT_CONTINUE as a fallback (won't stop at syscalls) + return ptrace(PT_CONTINUE, pid, 0, uintptr(signal)) +} + +// Note: PtraceSingleStep is implemented in ptrace_zos_singlestep.go +// with full two-breakpoint emulation for branch instructions. + +// PtraceInterrupt interrupts the traced process. +// DIFFERENCE FROM LINUX: z/OS doesn't have PTRACE_INTERRUPT equivalent. +// Returns ENOSYS to indicate this is not supported on z/OS. +func PtraceInterrupt(pid int) (err error) { + return ENOSYS +} + +// PtraceSeize attaches to a process without stopping it. +// DIFFERENCE FROM LINUX: z/OS doesn't have PTRACE_SEIZE equivalent. +// Uses PT_ATTACH as a fallback, which will stop the process. +func PtraceSeize(pid int) (err error) { + // z/OS doesn't have PTRACE_SEIZE, use PT_ATTACH + // Note: This WILL stop the process, unlike Linux PTRACE_SEIZE + return ptrace(PT_ATTACH, pid, 0, 0) +} diff --git a/vendor/golang.org/x/sys/unix/ptrace_zos_singlestep.go b/vendor/golang.org/x/sys/unix/ptrace_zos_singlestep.go new file mode 100644 index 0000000..7d7e2c8 --- /dev/null +++ b/vendor/golang.org/x/sys/unix/ptrace_zos_singlestep.go @@ -0,0 +1,425 @@ +// Copyright 2024 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build zos + +package unix + +import ( + "sync" +) + +// Single-stepping emulation for z/OS +// +// z/OS does not have native single-step support like Linux's PTRACE_SINGLESTEP. +// Instead, single-stepping must be emulated using temporary breakpoints. +// +// This file provides a complete implementation of single-step emulation using +// temporary breakpoints at both the sequential next instruction and branch target. + +const ( + // NO_BRANCH_DEST indicates the instruction is not a branch or cannot branch + NO_BRANCH_DEST = 0xFFFFFFFF + + // SVC_144 is the breakpoint instruction (SVC 144 = 0x0A90) + SVC_144 = 0x0A90 + + // Maximum number of temporary breakpoints (one for next PC, one for branch dest) + MAX_TEMP_BREAKPOINTS = 2 + + // S/390 branch instruction opcodes + // RR format (Register-Register) + opBCR = 0x07 // Branch on Condition Register + opBALR = 0x05 // Branch and Link Register + opBASR = 0x0D // Branch and Save Register + opBASSM = 0x0C // Branch and Save and Set Mode + opBSM = 0x0B // Branch and Set Mode + opBCTR = 0x06 // Branch on Count Register + + // RX format (Register-Index-Storage) + opBC = 0x47 // Branch on Condition + opBAL = 0x45 // Branch and Link + opBCT = 0x46 // Branch on Count + opBAS = 0x4D // Branch and Save + + // RS format (Register-Storage) + opBXH = 0x86 // Branch on Index High + opBXLE = 0x87 // Branch on Index Low or Equal + + // Extended branch opcodes + opBA7 = 0xA7 // A7x series (BRC, BRAS, BRCT, BRCTG) + opBC0 = 0xC0 // C0x series (BRASL, BRCL) + opBEC = 0xEC // ECxx series (RIEc format: compare-and-branch) +) + +// tempBreakpoint represents a temporary breakpoint for single-stepping +type tempBreakpoint struct { + address uint64 + originalInsn [8]byte // Save up to 8 bytes (full instruction) + active bool +} + +// singleStepState manages temporary breakpoints for a process +type singleStepState struct { + mu sync.Mutex + breakpoints [MAX_TEMP_BREAKPOINTS]tempBreakpoint +} + +var ( + // Global map of process states (pid -> state) + processStates = make(map[int]*singleStepState) + processStatesMu sync.Mutex +) + +// getProcessState returns or creates the single-step state for a process +func getProcessState(pid int) *singleStepState { + processStatesMu.Lock() + defer processStatesMu.Unlock() + + state, exists := processStates[pid] + if !exists { + state = &singleStepState{} + processStates[pid] = state + } + return state +} + +// cleanupProcessState removes the state for a process (call on detach) +func cleanupProcessState(pid int) { + processStatesMu.Lock() + defer processStatesMu.Unlock() + delete(processStates, pid) +} + +// GetInstructionLength returns the length of an S/390 instruction in bytes. +func GetInstructionLength(firstByte byte) int { + switch (firstByte >> 6) & 0x03 { + case 0x00: + return 2 + case 0x01, 0x02: + return 4 + case 0x03: + return 6 + default: + return 2 + } +} + +// GetNextInstructionAddr returns the address of the next sequential instruction. +func GetNextInstructionAddr(pc uint64, instruction []byte) uint64 { + if len(instruction) < 1 { + return pc + 2 + } + insnLen := GetInstructionLength(instruction[0]) + return pc + uint64(insnLen) +} + +// CalculateBranchDest calculates the destination address for branch instructions. +func CalculateBranchDest(pid int, pc uint64, instruction []byte) uint64 { + if len(instruction) < 6 { + return NO_BRANCH_DEST + } + + inst0_15 := uint16(instruction[0])<<8 | uint16(instruction[1]) + inst16_31 := uint16(instruction[2])<<8 | uint16(instruction[3]) + inst32_47 := uint16(instruction[4])<<8 | uint16(instruction[5]) + opcode := instruction[0] + + var dest uint64 = NO_BRANCH_DEST + + // RR format branches + if opcode == opBCR || opcode == opBALR || opcode == opBASR || + opcode == opBASSM || opcode == opBSM || opcode == opBCTR { + + r2 := int(inst0_15 & 0x0F) + + if opcode == opBCR { + mask := int((inst0_15 >> 4) & 0x0F) + if mask == 0 || r2 == 0 { + return NO_BRANCH_DEST + } + } else { + if r2 == 0 { + return NO_BRANCH_DEST + } + } + + var regs PtraceRegs + if err := PtraceGetRegs(pid, ®s); err == nil { + if r2 >= 0 && r2 < 16 { + regVal := regs.Gprs[r2] + dest = regVal + } + } + } else if opcode == opBC || opcode == opBAL || opcode == opBCT || opcode == opBAS { + // RX format branches + if opcode == opBC { + mask := int((inst0_15 >> 4) & 0x0F) + if mask == 0 { + return NO_BRANCH_DEST + } + } + + index := int(inst0_15 & 0x0F) + base := int((inst16_31 >> 12) & 0x0F) + displacement := uint32(inst16_31 & 0x0FFF) + + var baseVal, indexVal uint64 + var regs PtraceRegs + if err := PtraceGetRegs(pid, ®s); err == nil { + if base != 0 && base < 16 { + baseVal = regs.Gprs[base] + } + if index != 0 && index < 16 { + indexVal = regs.Gprs[index] + } + } + + if base == 0 && index == 0 { + dest = pc + uint64(displacement) + } else { + dest = baseVal + indexVal + uint64(displacement) + } + } else if opcode == opBXH || opcode == opBXLE { + // RS format branches + base := int((inst16_31 >> 12) & 0x0F) + displacement := uint32(inst16_31 & 0x0FFF) + + var baseVal uint64 + var regs PtraceRegs + if err := PtraceGetRegs(pid, ®s); err == nil { + if base != 0 && base < 16 { + baseVal = regs.Gprs[base] + } + } + + dest = baseVal + uint64(displacement) + } else if opcode == opBA7 { + // RI format branches + subOp := int(inst0_15 & 0x0F) + + if subOp < 4 || subOp > 7 { + return NO_BRANCH_DEST + } + + if subOp == 0x04 { + mask := int((inst0_15 >> 4) & 0x0F) + if mask == 0 { + return NO_BRANCH_DEST + } + } + + relDispl := int16(inst16_31) + dest = uint64(int64(pc) + int64(relDispl)*2) + } else if opcode == opBC0 { + // RIL format branches + subOp := int(inst0_15 & 0x0F) + + if subOp == 0x04 || subOp == 0x05 { + if subOp == 0x04 { + mask := int((inst0_15 >> 4) & 0x0F) + if mask == 0 { + return NO_BRANCH_DEST + } + } + + inst16_47 := (uint32(inst16_31) << 16) | uint32(inst32_47) + relDispl4 := int32(inst16_47) + dest = uint64(int64(pc) + int64(relDispl4)*2) + } + } else if opcode == opBEC { + // RIEc format compare-and-branch + subOp := instruction[4] + + isCompareBranch := (subOp >= 0x64 && subOp <= 0x67) || + (subOp >= 0x76 && subOp <= 0x77) || + (subOp >= 0x7C && subOp <= 0x7F) + + if isCompareBranch { + ri4 := int16(inst16_31) + dest = uint64(int64(pc) + int64(ri4)*2) + } + } + + if dest < 0x2000 { + return NO_BRANCH_DEST + } + + return dest +} + +// setTempBreakpoint sets a temporary breakpoint at the specified address +func (s *singleStepState) setTempBreakpoint(pid int, addr uint64) error { + s.mu.Lock() + defer s.mu.Unlock() + + // Find free slot + slot := -1 + for i := 0; i < MAX_TEMP_BREAKPOINTS; i++ { + if !s.breakpoints[i].active { + slot = i + break + } + } + + if slot == -1 { + return ENOMEM // All slots in use + } + + // Read original instruction (up to 8 bytes for safety) + _, err := PtracePeekText(pid, uintptr(addr), s.breakpoints[slot].originalInsn[:]) + if err != nil { + return err + } + + // Write SVC 144 (0x0A90) as breakpoint + svc144 := []byte{0x0A, 0x90} + _, err = PtracePokeText(pid, uintptr(addr), svc144) + if err != nil { + return err + } + + s.breakpoints[slot].address = addr + s.breakpoints[slot].active = true + + return nil +} + +// removeTempBreakpoints removes all active temporary breakpoints +func (s *singleStepState) removeTempBreakpoints(pid int) error { + s.mu.Lock() + defer s.mu.Unlock() + + var lastErr error + for i := 0; i < MAX_TEMP_BREAKPOINTS; i++ { + if !s.breakpoints[i].active { + continue + } + + // Restore original instruction (first 2 bytes are enough for SVC 144) + _, err := PtracePokeText(pid, uintptr(s.breakpoints[i].address), s.breakpoints[i].originalInsn[:2]) + if err != nil { + lastErr = err + } + + s.breakpoints[i].active = false + } + + return lastErr +} + +// isTempBreakpoint checks if an address is a temporary breakpoint +func (s *singleStepState) isTempBreakpoint(addr uint64) bool { + s.mu.Lock() + defer s.mu.Unlock() + + for i := 0; i < MAX_TEMP_BREAKPOINTS; i++ { + if s.breakpoints[i].active && s.breakpoints[i].address == addr { + return true + } + } + return false +} + +// PtraceSingleStep executes a single instruction using temporary breakpoints. +// +// This function: +// 1. Reads the current instruction at PSW +// 2. Calculates the next instruction address (sequential) +// 3. If branch instruction, calculates branch destination +// 4. Sets temporary breakpoints at both addresses +// 5. Continues execution until breakpoint hit +// 6. Restores original instructions and adjusts PSW +// +// Returns nil on success, error on failure. +func PtraceSingleStep(pid int) error { + state := getProcessState(pid) + + // 1. Get current PSW + var regs PtraceRegs + if err := PtraceGetRegs(pid, ®s); err != nil { + return err + } + pc := regs.Psw.Addr + + // 2. Read instruction at PC + insn := make([]byte, 8) + if _, err := PtracePeekText(pid, uintptr(pc), insn); err != nil { + return err + } + + // 3. Calculate next instruction addresses + nextPC := GetNextInstructionAddr(pc, insn) + branchDest := CalculateBranchDest(pid, pc, insn) + + // 4. Set temporary breakpoints + if err := state.setTempBreakpoint(pid, nextPC); err != nil { + return err + } + + // If branch instruction, set breakpoint at branch destination too + if branchDest != NO_BRANCH_DEST && branchDest != nextPC { + if err := state.setTempBreakpoint(pid, branchDest); err != nil { + state.removeTempBreakpoints(pid) // Cleanup first breakpoint + return err + } + } + + // 5. Continue execution + if err := PtraceCont(pid, 0); err != nil { + state.removeTempBreakpoints(pid) + return err + } + + // 6. Wait for breakpoint hit (retry on EINTR) + var status WaitStatus + for { + _, err := Wait4(pid, &status, 0, nil) + if err == EINTR { + continue // Retry on interrupted system call + } + if err != nil { + state.removeTempBreakpoints(pid) + return err + } + break + } + + // Check if process stopped (should be at breakpoint) + if !status.Stopped() { + state.removeTempBreakpoints(pid) + return ECHILD // Process exited or error + } + + // 7. Get current PSW (should be at breakpoint + 2) + if err := PtraceGetRegs(pid, ®s); err != nil { + state.removeTempBreakpoints(pid) + return err + } + + // 8. Remove temporary breakpoints + if err := state.removeTempBreakpoints(pid); err != nil { + return err + } + + // 9. Back up PSW by 2 bytes (to point at original instruction, not SVC 144) + // Use direct PSW write like ztrace does, not full register set + hitAddr := regs.Psw.Addr + if state.isTempBreakpoint(hitAddr - 2) { + if err := ptraceWritePSW(pid, uint32(hitAddr-2)); err != nil { + return err + } + } + + return nil +} + +// PtraceDetachWithCleanup detaches from a process and cleans up single-step state. +// Use this instead of PtraceDetach when using PtraceSingleStep. +func PtraceDetachWithCleanup(pid int) error { + state := getProcessState(pid) + state.removeTempBreakpoints(pid) + cleanupProcessState(pid) + return PtraceDetach(pid) +} diff --git a/vendor/golang.org/x/sys/unix/sockcmsg_linux.go b/vendor/golang.org/x/sys/unix/sockcmsg_linux.go index 5f63147..b09bd17 100644 --- a/vendor/golang.org/x/sys/unix/sockcmsg_linux.go +++ b/vendor/golang.org/x/sys/unix/sockcmsg_linux.go @@ -31,6 +31,9 @@ func ParseUnixCredentials(m *SocketControlMessage) (*Ucred, error) { if m.Header.Type != SCM_CREDENTIALS { return nil, EINVAL } + if len(m.Data) < SizeofUcred { + return nil, EINVAL + } ucred := *(*Ucred)(unsafe.Pointer(&m.Data[0])) return &ucred, nil } diff --git a/vendor/golang.org/x/sys/unix/syscall.go b/vendor/golang.org/x/sys/unix/syscall.go index 5ea74da..8f27e7e 100644 --- a/vendor/golang.org/x/sys/unix/syscall.go +++ b/vendor/golang.org/x/sys/unix/syscall.go @@ -76,7 +76,7 @@ func BytePtrToString(p *byte) string { // Find NUL terminator. n := 0 for ptr := unsafe.Pointer(p); *(*byte)(ptr) != 0; n++ { - ptr = unsafe.Pointer(uintptr(ptr) + 1) + ptr = unsafe.Add(ptr, 1) } return string(unsafe.Slice(p, n)) diff --git a/vendor/golang.org/x/sys/unix/syscall_bsd.go b/vendor/golang.org/x/sys/unix/syscall_bsd.go index a00c3e5..035c2cd 100644 --- a/vendor/golang.org/x/sys/unix/syscall_bsd.go +++ b/vendor/golang.org/x/sys/unix/syscall_bsd.go @@ -188,7 +188,7 @@ func (sa *SockaddrUnix) sockaddr() (unsafe.Pointer, _Socklen, error) { } sa.raw.Len = byte(3 + n) // 2 for Family, Len; 1 for NUL sa.raw.Family = AF_UNIX - for i := 0; i < n; i++ { + for i := range n { sa.raw.Path[i] = int8(name[i]) } return unsafe.Pointer(&sa.raw), _Socklen(sa.raw.Len), nil diff --git a/vendor/golang.org/x/sys/unix/syscall_darwin.go b/vendor/golang.org/x/sys/unix/syscall_darwin.go index 38590ca..cb9d0a1 100644 --- a/vendor/golang.org/x/sys/unix/syscall_darwin.go +++ b/vendor/golang.org/x/sys/unix/syscall_darwin.go @@ -369,6 +369,7 @@ func Flistxattr(fd int, dest []byte) (sz int, err error) { */ //sys fcntl(fd int, cmd int, arg int) (val int, err error) +//sys fcntlPtr(fd int, cmd int, arg unsafe.Pointer) (val int, err error) = SYS_FCNTL //sys kill(pid int, signum int, posix int) (err error) diff --git a/vendor/golang.org/x/sys/unix/syscall_freebsd.go b/vendor/golang.org/x/sys/unix/syscall_freebsd.go index 2b57e0f..4951889 100644 --- a/vendor/golang.org/x/sys/unix/syscall_freebsd.go +++ b/vendor/golang.org/x/sys/unix/syscall_freebsd.go @@ -369,6 +369,15 @@ func Dup3(oldfd, newfd, flags int) error { //sys ExtattrSetLink(link string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) //sys ExtattrDeleteLink(link string, attrnamespace int, attrname string) (err error) //sys ExtattrListLink(link string, attrnamespace int, data uintptr, nbytes int) (ret int, err error) +//sys extattrGetFd(fd int, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) +//sys extattrSetFd(fd int, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) +//sys extattrListFd(fd int, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) +//sys extattrGetFile(file string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) +//sys extattrSetFile(file string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) +//sys extattrListFile(file string, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) +//sys extattrGetLink(link string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) +//sys extattrSetLink(link string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) +//sys extattrListLink(link string, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) //sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_POSIX_FADVISE //sys Faccessat(dirfd int, path string, mode uint32, flags int) (err error) //sys Fchdir(fd int) (err error) diff --git a/vendor/golang.org/x/sys/unix/syscall_freebsd_386.go b/vendor/golang.org/x/sys/unix/syscall_freebsd_386.go index 3967bca..6721ca9 100644 --- a/vendor/golang.org/x/sys/unix/syscall_freebsd_386.go +++ b/vendor/golang.org/x/sys/unix/syscall_freebsd_386.go @@ -49,7 +49,13 @@ func sendfile(outfd int, infd int, offset *int64, count int) (written int, err e var writtenOut uint64 = 0 _, _, e1 := Syscall9(SYS_SENDFILE, uintptr(infd), uintptr(outfd), uintptr(*offset), uintptr((*offset)>>32), uintptr(count), 0, uintptr(unsafe.Pointer(&writtenOut)), 0, 0) - written = int(writtenOut) + // For some reason on the freebsd-386 builder writtenOut + // is modified when the system call returns EINVAL. + // The man page says that the value is only written for + // success, EINTR, or EAGAIN, so only use those cases. + if e1 == 0 || e1 == EINTR || e1 == EAGAIN { + written = int(writtenOut) + } if e1 != 0 { err = e1 diff --git a/vendor/golang.org/x/sys/unix/syscall_linux.go b/vendor/golang.org/x/sys/unix/syscall_linux.go index 21e2bfa..a31e2c7 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux.go @@ -1991,7 +1991,24 @@ func FsconfigReconfigure(fd int) (err error) { return fsconfig(fd, FSCONFIG_CMD_RECONFIGURE, nil, nil, 0) } -//sys Getdents(fd int, buf []byte) (n int, err error) = SYS_GETDENTS64 +//sys getdents(fd int, buf []byte) (n int, err error) = SYS_GETDENTS64 + +// Getdents reads directory entries from fd into buf. +func Getdents(fd int, buf []byte) (n int, err error) { + // getdents64 stores d_ino with a 64-bit write, which faults on + // strict-alignment targets unless buf is 8-aligned. + if len(buf) > 0 { + if off := int(-uintptr(unsafe.Pointer(&buf[0])) & 7); off > 0 && off < len(buf) { + n, err = getdents(fd, buf[off:]) + if n > 0 { + copy(buf, buf[off:off+n]) + } + return n, err + } + } + return getdents(fd, buf) +} + //sysnb Getpgid(pid int) (pgid int, err error) func Getpgrp() (pid int) { @@ -2033,6 +2050,7 @@ func Getrandom(buf []byte, flags int) (n int, err error) { //sysnb Kill(pid int, sig syscall.Signal) (err error) //sys Klogctl(typ int, buf []byte) (n int, err error) = SYS_SYSLOG //sys Lgetxattr(path string, attr string, dest []byte) (sz int, err error) +//sys Listns(req *NsIdReq, nsIds []uint64, flags uint) (n int, err error) //sys Listxattr(path string, dest []byte) (sz int, err error) //sys Llistxattr(path string, dest []byte) (sz int, err error) //sys Lremovexattr(path string, attr string) (err error) @@ -2046,6 +2064,7 @@ func Getrandom(buf []byte, flags int) (n int, err error) { //sys PerfEventOpen(attr *PerfEventAttr, pid int, cpu int, groupFd int, flags int) (fd int, err error) //sys PivotRoot(newroot string, putold string) (err error) = SYS_PIVOT_ROOT //sys Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error) +//sys PrctlArg5Ptr(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 unsafe.Pointer) (err error) = SYS_PRCTL //sys pselect6(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timespec, sigmask *sigset_argpack) (n int, err error) //sys read(fd int, p []byte) (n int, err error) //sys Removexattr(path string, attr string) (err error) @@ -2363,7 +2382,7 @@ func (fh *FileHandle) Bytes() []byte { if n == 0 { return nil } - return unsafe.Slice((*byte)(unsafe.Pointer(uintptr(unsafe.Pointer(&fh.fileHandle.Type))+4)), n) + return unsafe.Slice((*byte)(unsafe.Add(unsafe.Pointer(&fh.fileHandle.Type), 4)), n) } // NameToHandleAt wraps the name_to_handle_at system call; it obtains diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_sparc64.go b/vendor/golang.org/x/sys/unix/syscall_linux_sparc64.go index 4964119..cd50715 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_sparc64.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_sparc64.go @@ -8,7 +8,7 @@ package unix //sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_FADVISE64 //sys Fchown(fd int, uid int, gid int) (err error) -//sys Fstat(fd int, stat *Stat_t) (err error) +//sys Fstat(fd int, stat *Stat_t) (err error) = SYS_FSTAT64 //sys Fstatat(dirfd int, path string, stat *Stat_t, flags int) (err error) = SYS_FSTATAT64 //sys Fstatfs(fd int, buf *Statfs_t) (err error) //sys Ftruncate(fd int, length int64) (err error) @@ -19,7 +19,7 @@ package unix //sysnb Getuid() (uid int) //sys Lchown(path string, uid int, gid int) (err error) //sys Listen(s int, n int) (err error) -//sys Lstat(path string, stat *Stat_t) (err error) +//sys Lstat(path string, stat *Stat_t) (err error) = SYS_LSTAT64 //sys Pause() (err error) //sys pread(fd int, p []byte, offset int64) (n int, err error) = SYS_PREAD64 //sys pwrite(fd int, p []byte, offset int64) (n int, err error) = SYS_PWRITE64 @@ -31,7 +31,7 @@ package unix //sys setfsuid(uid int) (prev 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 Stat(path string, stat *Stat_t) (err error) +//sys Stat(path string, stat *Stat_t) (err error) = SYS_STAT64 //sys Statfs(path string, buf *Statfs_t) (err error) //sys SyncFileRange(fd int, off int64, n int64, flags int) (err error) //sys Truncate(path string, length int64) (err error) diff --git a/vendor/golang.org/x/sys/unix/syscall_netbsd.go b/vendor/golang.org/x/sys/unix/syscall_netbsd.go index 34a4676..c8badc5 100644 --- a/vendor/golang.org/x/sys/unix/syscall_netbsd.go +++ b/vendor/golang.org/x/sys/unix/syscall_netbsd.go @@ -293,6 +293,15 @@ func Getvfsstat(buf []Statvfs_t, flags int) (n int, err error) { //sys ExtattrSetLink(link string, attrnamespace int, attrname string, data uintptr, nbytes int) (ret int, err error) //sys ExtattrDeleteLink(link string, attrnamespace int, attrname string) (err error) //sys ExtattrListLink(link string, attrnamespace int, data uintptr, nbytes int) (ret int, err error) +//sys extattrGetFd(fd int, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) +//sys extattrSetFd(fd int, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) +//sys extattrListFd(fd int, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) +//sys extattrGetFile(file string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) +//sys extattrSetFile(file string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) +//sys extattrListFile(file string, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) +//sys extattrGetLink(link string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) +//sys extattrSetLink(link string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) +//sys extattrListLink(link string, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) //sys Faccessat(dirfd int, path string, mode uint32, flags int) (err error) //sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_POSIX_FADVISE //sys Fchdir(fd int) (err error) diff --git a/vendor/golang.org/x/sys/unix/syscall_unix_gc.go b/vendor/golang.org/x/sys/unix/syscall_unix_gc.go index 05c95bc..60c0d16 100644 --- a/vendor/golang.org/x/sys/unix/syscall_unix_gc.go +++ b/vendor/golang.org/x/sys/unix/syscall_unix_gc.go @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -//go:build (darwin || dragonfly || freebsd || (linux && !ppc64 && !ppc64le) || netbsd || openbsd || solaris) && gc +//go:build (darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris) && gc package unix diff --git a/vendor/golang.org/x/sys/unix/syscall_unix_gc_ppc64x.go b/vendor/golang.org/x/sys/unix/syscall_unix_gc_ppc64x.go deleted file mode 100644 index 23f39b7..0000000 --- a/vendor/golang.org/x/sys/unix/syscall_unix_gc_ppc64x.go +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright 2018 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 linux && (ppc64le || ppc64) && gc - -package unix - -import "syscall" - -func Syscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err syscall.Errno) { - return syscall.Syscall(trap, a1, a2, a3) -} -func Syscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno) { - return syscall.Syscall6(trap, a1, a2, a3, a4, a5, a6) -} -func RawSyscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err syscall.Errno) { - return syscall.RawSyscall(trap, a1, a2, a3) -} -func RawSyscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno) { - return syscall.RawSyscall6(trap, a1, a2, a3, a4, a5, a6) -} diff --git a/vendor/golang.org/x/sys/unix/syscall_zos_s390x.go b/vendor/golang.org/x/sys/unix/syscall_zos_s390x.go index 7bf5c04..edabb68 100644 --- a/vendor/golang.org/x/sys/unix/syscall_zos_s390x.go +++ b/vendor/golang.org/x/sys/unix/syscall_zos_s390x.go @@ -27,14 +27,10 @@ import ( "unsafe" ) -//go:noescape -func initZosLibVec() - //go:noescape func GetZosLibVec() uintptr func init() { - initZosLibVec() r0, _, _ := CallLeFuncWithPtrReturn(GetZosLibVec()+SYS_____GETENV_A<<4, uintptr(unsafe.Pointer(&([]byte("__ZOS_XSYSTRACE\x00"))[0]))) if r0 != 0 { n, _, _ := CallLeFuncWithPtrReturn(GetZosLibVec()+SYS___ATOI_A<<4, r0) diff --git a/vendor/golang.org/x/sys/unix/xattr_bsd.go b/vendor/golang.org/x/sys/unix/xattr_bsd.go index e168793..d3d12c2 100644 --- a/vendor/golang.org/x/sys/unix/xattr_bsd.go +++ b/vendor/golang.org/x/sys/unix/xattr_bsd.go @@ -56,7 +56,7 @@ func Getxattr(file string, attr string, dest []byte) (sz int, err error) { return -1, err } - return ExtattrGetFile(file, nsid, a, uintptr(d), destsize) + return extattrGetFile(file, nsid, a, d, destsize) } func Fgetxattr(fd int, attr string, dest []byte) (sz int, err error) { @@ -68,7 +68,7 @@ func Fgetxattr(fd int, attr string, dest []byte) (sz int, err error) { return -1, err } - return ExtattrGetFd(fd, nsid, a, uintptr(d), destsize) + return extattrGetFd(fd, nsid, a, d, destsize) } func Lgetxattr(link string, attr string, dest []byte) (sz int, err error) { @@ -80,7 +80,7 @@ func Lgetxattr(link string, attr string, dest []byte) (sz int, err error) { return -1, err } - return ExtattrGetLink(link, nsid, a, uintptr(d), destsize) + return extattrGetLink(link, nsid, a, d, destsize) } // flags are unused on FreeBSD @@ -97,7 +97,7 @@ func Fsetxattr(fd int, attr string, data []byte, flags int) (err error) { return } - _, err = ExtattrSetFd(fd, nsid, a, uintptr(d), datasiz) + _, err = extattrSetFd(fd, nsid, a, d, datasiz) return } @@ -113,7 +113,7 @@ func Setxattr(file string, attr string, data []byte, flags int) (err error) { return } - _, err = ExtattrSetFile(file, nsid, a, uintptr(d), datasiz) + _, err = extattrSetFile(file, nsid, a, d, datasiz) return } @@ -129,7 +129,7 @@ func Lsetxattr(link string, attr string, data []byte, flags int) (err error) { return } - _, err = ExtattrSetLink(link, nsid, a, uintptr(d), datasiz) + _, err = extattrSetLink(link, nsid, a, d, datasiz) return } @@ -199,9 +199,9 @@ 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) + s, e := extattrListFile(file, nsid, d, destsiz) if e != nil { - return 0, err + return 0, e } return s, nil @@ -235,9 +235,9 @@ 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) + s, e := extattrListFd(fd, nsid, d, destsiz) if e != nil { - return 0, err + return 0, e } return s, nil @@ -271,9 +271,9 @@ 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) + s, e := extattrListLink(link, nsid, d, destsiz) if e != nil { - return 0, err + return 0, e } return s, nil diff --git a/vendor/golang.org/x/sys/unix/zerrors_darwin_amd64.go b/vendor/golang.org/x/sys/unix/zerrors_darwin_amd64.go index d73c465..01a3953 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_darwin_amd64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_darwin_amd64.go @@ -1128,6 +1128,7 @@ const ( O_DSYNC = 0x400000 O_EVTONLY = 0x8000 O_EXCL = 0x800 + O_EXEC = 0x40000000 O_EXLOCK = 0x20 O_FSYNC = 0x80 O_NDELAY = 0x4 @@ -1138,6 +1139,7 @@ const ( O_POPUP = 0x80000000 O_RDONLY = 0x0 O_RDWR = 0x2 + O_SEARCH = 0x40100000 O_SHLOCK = 0x10 O_SYMLINK = 0x200000 O_SYNC = 0x80 @@ -1147,6 +1149,10 @@ const ( PARMRK = 0x8 PARODD = 0x2000 PENDIN = 0x20000000 + PRIO_DARWIN_BG = 0x1000 + PRIO_DARWIN_NONUI = 0x1001 + PRIO_DARWIN_PROCESS = 0x4 + PRIO_DARWIN_THREAD = 0x3 PRIO_PGRP = 0x1 PRIO_PROCESS = 0x0 PRIO_USER = 0x2 diff --git a/vendor/golang.org/x/sys/unix/zerrors_darwin_arm64.go b/vendor/golang.org/x/sys/unix/zerrors_darwin_arm64.go index 4a55a40..d80b95f 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_darwin_arm64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_darwin_arm64.go @@ -1128,6 +1128,7 @@ const ( O_DSYNC = 0x400000 O_EVTONLY = 0x8000 O_EXCL = 0x800 + O_EXEC = 0x40000000 O_EXLOCK = 0x20 O_FSYNC = 0x80 O_NDELAY = 0x4 @@ -1138,6 +1139,7 @@ const ( O_POPUP = 0x80000000 O_RDONLY = 0x0 O_RDWR = 0x2 + O_SEARCH = 0x40100000 O_SHLOCK = 0x10 O_SYMLINK = 0x200000 O_SYNC = 0x80 @@ -1147,6 +1149,10 @@ const ( PARMRK = 0x8 PARODD = 0x2000 PENDIN = 0x20000000 + PRIO_DARWIN_BG = 0x1000 + PRIO_DARWIN_NONUI = 0x1001 + PRIO_DARWIN_PROCESS = 0x4 + PRIO_DARWIN_THREAD = 0x3 PRIO_PGRP = 0x1 PRIO_PROCESS = 0x0 PRIO_USER = 0x2 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux.go b/vendor/golang.org/x/sys/unix/zerrors_linux.go index 5bb51d7..aa68cb8 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux.go @@ -752,10 +752,12 @@ const ( CLONE_ARGS_SIZE_VER0 = 0x40 CLONE_ARGS_SIZE_VER1 = 0x50 CLONE_ARGS_SIZE_VER2 = 0x58 + CLONE_AUTOREAP = 0x400000000 CLONE_CHILD_CLEARTID = 0x200000 CLONE_CHILD_SETTID = 0x1000000 CLONE_CLEAR_SIGHAND = 0x100000000 CLONE_DETACHED = 0x400000 + CLONE_EMPTY_MNTNS = 0x2000000000 CLONE_FILES = 0x400 CLONE_FS = 0x200 CLONE_INTO_CGROUP = 0x200000000 @@ -768,9 +770,11 @@ const ( CLONE_NEWTIME = 0x80 CLONE_NEWUSER = 0x10000000 CLONE_NEWUTS = 0x4000000 + CLONE_NNP = 0x800000000 CLONE_PARENT = 0x8000 CLONE_PARENT_SETTID = 0x100000 CLONE_PIDFD = 0x1000 + CLONE_PIDFD_AUTOKILL = 0x1000000000 CLONE_PTRACE = 0x2000 CLONE_SETTLS = 0x80000 CLONE_SIGHAND = 0x800 @@ -803,12 +807,15 @@ const ( DEVLINK_GENL_MCGRP_CONFIG_NAME = "config" DEVLINK_GENL_NAME = "devlink" DEVLINK_GENL_VERSION = 0x1 + DEVLINK_INDEX_BUS_NAME = "devlink_index" DEVLINK_PORT_FN_CAP_IPSEC_CRYPTO = 0x4 DEVLINK_PORT_FN_CAP_IPSEC_PACKET = 0x8 DEVLINK_PORT_FN_CAP_MIGRATABLE = 0x2 DEVLINK_PORT_FN_CAP_ROCE = 0x1 DEVLINK_RATE_TCS_MAX = 0x8 DEVLINK_RATE_TC_INDEX_MAX = 0x7 + DEVLINK_RESOURCE_SCOPE_DEV = 0x1 + DEVLINK_RESOURCE_SCOPE_PORT = 0x2 DEVLINK_SB_THRESHOLD_TO_ALPHA_MAX = 0x14 DEVLINK_SUPPORTED_FLASH_OVERWRITE_SECTIONS = 0x3 DEVMEM_MAGIC = 0x454d444d @@ -1127,6 +1134,7 @@ const ( ETHTOOL_SWOL = 0x6 ETHTOOL_TEST = 0x1a ETH_P_1588 = 0x88f7 + ETH_P_8021AC = 0x8870 ETH_P_8021AD = 0x88a8 ETH_P_8021AH = 0x88e7 ETH_P_8021Q = 0x8100 @@ -1170,6 +1178,7 @@ const ( ETH_P_ETHERCAT = 0x88a4 ETH_P_FCOE = 0x8906 ETH_P_FIP = 0x8914 + ETH_P_GRE_OSI = 0xfe ETH_P_HDLC = 0x19 ETH_P_HSR = 0x892f ETH_P_IBOE = 0x8915 @@ -1198,6 +1207,7 @@ const ( ETH_P_MXLGSW = 0x88c3 ETH_P_NCSI = 0x88f8 ETH_P_NSH = 0x894f + ETH_P_NXP_NETC = 0xfd3a ETH_P_PAE = 0x888e ETH_P_PAUSE = 0x8808 ETH_P_PHONET = 0xf5 @@ -1359,6 +1369,7 @@ const ( FAN_UNLIMITED_MARKS = 0x20 FAN_UNLIMITED_QUEUE = 0x10 FD_CLOEXEC = 0x1 + FD_NSFS_ROOT = -0x2713 FD_PIDFS_ROOT = -0x2712 FD_SETSIZE = 0x400 FF0 = 0x0 @@ -1427,6 +1438,8 @@ const ( FS_POLICY_FLAGS_PAD_8 = 0x1 FS_POLICY_FLAGS_PAD_MASK = 0x3 FS_POLICY_FLAGS_VALID = 0x7 + FS_SHUTDOWN_FLAGS_LOGFLUSH = 0x1 + FS_SHUTDOWN_FLAGS_NOLOGFLUSH = 0x2 FS_VERITY_FL = 0x100000 FS_VERITY_HASH_ALG_SHA256 = 0x1 FS_VERITY_HASH_ALG_SHA512 = 0x2 @@ -1441,6 +1454,7 @@ const ( F_DUPFD_CLOEXEC = 0x406 F_DUPFD_QUERY = 0x403 F_EXLCK = 0x4 + F_GETDELEG = 0x40f F_GETFD = 0x1 F_GETFL = 0x3 F_GETLEASE = 0x401 @@ -1462,6 +1476,7 @@ const ( F_SEAL_SEAL = 0x1 F_SEAL_SHRINK = 0x2 F_SEAL_WRITE = 0x8 + F_SETDELEG = 0x410 F_SETFD = 0x2 F_SETFL = 0x4 F_SETLEASE = 0x400 @@ -1632,6 +1647,7 @@ const ( IN_UNMOUNT = 0x2000 IOCTL_MEI_CONNECT_CLIENT = 0xc0104801 IOCTL_MEI_CONNECT_CLIENT_VTAG = 0xc0144804 + IPPROTO_AGGFRAG = 0x90 IPPROTO_AH = 0x33 IPPROTO_BEETPH = 0x5e IPPROTO_COMP = 0x6c @@ -1913,10 +1929,14 @@ const ( LANDLOCK_ACCESS_FS_REFER = 0x2000 LANDLOCK_ACCESS_FS_REMOVE_DIR = 0x10 LANDLOCK_ACCESS_FS_REMOVE_FILE = 0x20 + LANDLOCK_ACCESS_FS_RESOLVE_UNIX = 0x10000 LANDLOCK_ACCESS_FS_TRUNCATE = 0x4000 LANDLOCK_ACCESS_FS_WRITE_FILE = 0x2 LANDLOCK_ACCESS_NET_BIND_TCP = 0x1 + LANDLOCK_ACCESS_NET_BIND_UDP = 0x4 + LANDLOCK_ACCESS_NET_CONNECT_SEND_UDP = 0x8 LANDLOCK_ACCESS_NET_CONNECT_TCP = 0x2 + LANDLOCK_ADD_RULE_QUIET = 0x1 LANDLOCK_CREATE_RULESET_ERRATA = 0x2 LANDLOCK_CREATE_RULESET_VERSION = 0x1 LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON = 0x2 @@ -2048,6 +2068,7 @@ const ( MINIX3_SUPER_MAGIC = 0x4d5a MINIX_SUPER_MAGIC = 0x137f MINIX_SUPER_MAGIC2 = 0x138f + MLOCK_ONFAULT = 0x1 MNT_DETACH = 0x2 MNT_EXPIRE = 0x4 MNT_FORCE = 0x1 @@ -3407,6 +3428,7 @@ const ( SCHED_FLAG_UTIL_CLAMP = 0x60 SCHED_FLAG_UTIL_CLAMP_MAX = 0x40 SCHED_FLAG_UTIL_CLAMP_MIN = 0x20 + SCHED_GETATTR_FLAG_DL_DYNAMIC = 0x1 SCHED_IDLE = 0x5 SCHED_NORMAL = 0x0 SCHED_RESET_ON_FORK = 0x40000000 @@ -3789,6 +3811,14 @@ const ( TCPOPT_TIMESTAMP = 0x8 TCPOPT_TSTAMP_HDR = 0x101080a TCPOPT_WINDOW = 0x3 + TCP_ACCECN_ACE_FAIL_RECV = 0x2 + TCP_ACCECN_ACE_FAIL_SEND = 0x1 + TCP_ACCECN_OPT_COUNTER_SEEN = 0x2 + TCP_ACCECN_OPT_EMPTY_SEEN = 0x1 + TCP_ACCECN_OPT_FAIL_RECV = 0x8 + TCP_ACCECN_OPT_FAIL_SEEN = 0x3 + TCP_ACCECN_OPT_FAIL_SEND = 0x4 + TCP_ACCECN_OPT_NOT_SEEN = 0x0 TCP_AO_KEYF_EXCLUDE_OPT = 0x2 TCP_AO_KEYF_IFINDEX = 0x1 TCP_AO_MAXKEYLEN = 0x50 @@ -3803,6 +3833,7 @@ const ( TCP_COOKIE_TRANSACTIONS = 0xf TCP_CORK = 0x3 TCP_DEFER_ACCEPT = 0x9 + TCP_DELACK_MAX_US = 0x2e TCP_FASTOPEN = 0x17 TCP_FASTOPEN_CONNECT = 0x1e TCP_FASTOPEN_KEY = 0x21 @@ -3835,6 +3866,8 @@ const ( TCP_REPAIR_OPTIONS = 0x16 TCP_REPAIR_QUEUE = 0x14 TCP_REPAIR_WINDOW = 0x1d + TCP_RTO_MAX_MS = 0x2c + TCP_RTO_MIN_US = 0x2d TCP_SAVED_SYN = 0x1c TCP_SAVE_SYN = 0x1b TCP_SYNCNT = 0x7 @@ -3862,6 +3895,7 @@ const ( TIOCPKT_NOSTOP = 0x10 TIOCPKT_START = 0x8 TIOCPKT_STOP = 0x4 + TIOCSER_TEMT = 0x1 TIPC_ADDR_ID = 0x3 TIPC_ADDR_MCAST = 0x1 TIPC_ADDR_NAME = 0x2 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_386.go b/vendor/golang.org/x/sys/unix/zerrors_linux_386.go index c0a8ea1..5aaf4bc 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_386.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_386.go @@ -483,7 +483,6 @@ const ( TIOCSERGWILD = 0x5454 TIOCSERSETMULTI = 0x545b TIOCSERSWILD = 0x5455 - TIOCSER_TEMT = 0x1 TIOCSETD = 0x5423 TIOCSIG = 0x40045436 TIOCSISO7816 = 0xc0285443 @@ -601,6 +600,7 @@ const ( EDQUOT = syscall.Errno(0x7a) EFSBADCRC = syscall.Errno(0x4a) EFSCORRUPTED = syscall.Errno(0x75) + EFTYPE = syscall.Errno(0x86) EHOSTDOWN = syscall.Errno(0x70) EHOSTUNREACH = syscall.Errno(0x71) EHWPOISON = syscall.Errno(0x85) @@ -841,6 +841,7 @@ var errorList = [...]struct { {131, "ENOTRECOVERABLE", "state not recoverable"}, {132, "ERFKILL", "operation not possible due to RF-kill"}, {133, "EHWPOISON", "memory page has hardware error"}, + {134, "EFTYPE", "unknown error 134"}, } // Signal table diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go index ff927c8..b8e6287 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go @@ -484,7 +484,6 @@ const ( TIOCSERGWILD = 0x5454 TIOCSERSETMULTI = 0x545b TIOCSERSWILD = 0x5455 - TIOCSER_TEMT = 0x1 TIOCSETD = 0x5423 TIOCSIG = 0x40045436 TIOCSISO7816 = 0xc0285443 @@ -601,6 +600,7 @@ const ( EDQUOT = syscall.Errno(0x7a) EFSBADCRC = syscall.Errno(0x4a) EFSCORRUPTED = syscall.Errno(0x75) + EFTYPE = syscall.Errno(0x86) EHOSTDOWN = syscall.Errno(0x70) EHOSTUNREACH = syscall.Errno(0x71) EHWPOISON = syscall.Errno(0x85) @@ -841,6 +841,7 @@ var errorList = [...]struct { {131, "ENOTRECOVERABLE", "state not recoverable"}, {132, "ERFKILL", "operation not possible due to RF-kill"}, {133, "EHWPOISON", "memory page has hardware error"}, + {134, "EFTYPE", "unknown error 134"}, } // Signal table diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go b/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go index 55294ed..464f821 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go @@ -489,7 +489,6 @@ const ( TIOCSERGWILD = 0x5454 TIOCSERSETMULTI = 0x545b TIOCSERSWILD = 0x5455 - TIOCSER_TEMT = 0x1 TIOCSETD = 0x5423 TIOCSIG = 0x40045436 TIOCSISO7816 = 0xc0285443 @@ -606,6 +605,7 @@ const ( EDQUOT = syscall.Errno(0x7a) EFSBADCRC = syscall.Errno(0x4a) EFSCORRUPTED = syscall.Errno(0x75) + EFTYPE = syscall.Errno(0x86) EHOSTDOWN = syscall.Errno(0x70) EHOSTUNREACH = syscall.Errno(0x71) EHWPOISON = syscall.Errno(0x85) @@ -846,6 +846,7 @@ var errorList = [...]struct { {131, "ENOTRECOVERABLE", "state not recoverable"}, {132, "ERFKILL", "operation not possible due to RF-kill"}, {133, "EHWPOISON", "memory page has hardware error"}, + {134, "EFTYPE", "unknown error 134"}, } // Signal table diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go index 5dac54c..735265b 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go @@ -483,7 +483,6 @@ const ( TIOCSERGWILD = 0x5454 TIOCSERSETMULTI = 0x545b TIOCSERSWILD = 0x5455 - TIOCSER_TEMT = 0x1 TIOCSETD = 0x5423 TIOCSIG = 0x40045436 TIOCSISO7816 = 0xc0285443 @@ -603,6 +602,7 @@ const ( EDQUOT = syscall.Errno(0x7a) EFSBADCRC = syscall.Errno(0x4a) EFSCORRUPTED = syscall.Errno(0x75) + EFTYPE = syscall.Errno(0x86) EHOSTDOWN = syscall.Errno(0x70) EHOSTUNREACH = syscall.Errno(0x71) EHWPOISON = syscall.Errno(0x85) @@ -843,6 +843,7 @@ var errorList = [...]struct { {131, "ENOTRECOVERABLE", "state not recoverable"}, {132, "ERFKILL", "operation not possible due to RF-kill"}, {133, "EHWPOISON", "memory page has hardware error"}, + {134, "EFTYPE", "unknown error 134"}, } // Signal table diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_loong64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_loong64.go index 46ac1fc..1970ce8 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_loong64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_loong64.go @@ -476,7 +476,6 @@ const ( TIOCSERGWILD = 0x5454 TIOCSERSETMULTI = 0x545b TIOCSERSWILD = 0x5455 - TIOCSER_TEMT = 0x1 TIOCSETD = 0x5423 TIOCSIG = 0x40045436 TIOCSISO7816 = 0xc0285443 @@ -593,6 +592,7 @@ const ( EDQUOT = syscall.Errno(0x7a) EFSBADCRC = syscall.Errno(0x4a) EFSCORRUPTED = syscall.Errno(0x75) + EFTYPE = syscall.Errno(0x86) EHOSTDOWN = syscall.Errno(0x70) EHOSTUNREACH = syscall.Errno(0x71) EHWPOISON = syscall.Errno(0x85) @@ -833,6 +833,7 @@ var errorList = [...]struct { {131, "ENOTRECOVERABLE", "state not recoverable"}, {132, "ERFKILL", "operation not possible due to RF-kill"}, {133, "EHWPOISON", "memory page has hardware error"}, + {134, "EFTYPE", "unknown error 134"}, } // Signal table diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_mips.go b/vendor/golang.org/x/sys/unix/zerrors_linux_mips.go index b55483e..56de9ae 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_mips.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_mips.go @@ -481,7 +481,6 @@ const ( TIOCSERGWILD = 0x5489 TIOCSERSETMULTI = 0x5490 TIOCSERSWILD = 0x548a - TIOCSER_TEMT = 0x1 TIOCSETD = 0x7401 TIOCSETN = 0x740a TIOCSETP = 0x7409 @@ -602,6 +601,7 @@ const ( EDQUOT = syscall.Errno(0x46d) EFSBADCRC = syscall.Errno(0x4d) EFSCORRUPTED = syscall.Errno(0x87) + EFTYPE = syscall.Errno(0xa9) EHOSTDOWN = syscall.Errno(0x93) EHOSTUNREACH = syscall.Errno(0x94) EHWPOISON = syscall.Errno(0xa8) @@ -846,6 +846,7 @@ var errorList = [...]struct { {166, "ENOTRECOVERABLE", "state not recoverable"}, {167, "ERFKILL", "operation not possible due to RF-kill"}, {168, "EHWPOISON", "memory page has hardware error"}, + {169, "EFTYPE", "unknown error 169"}, {1133, "EDQUOT", "disk quota exceeded"}, } diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go index 71890c9..26ca1ca 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go @@ -481,7 +481,6 @@ const ( TIOCSERGWILD = 0x5489 TIOCSERSETMULTI = 0x5490 TIOCSERSWILD = 0x548a - TIOCSER_TEMT = 0x1 TIOCSETD = 0x7401 TIOCSETN = 0x740a TIOCSETP = 0x7409 @@ -602,6 +601,7 @@ const ( EDQUOT = syscall.Errno(0x46d) EFSBADCRC = syscall.Errno(0x4d) EFSCORRUPTED = syscall.Errno(0x87) + EFTYPE = syscall.Errno(0xa9) EHOSTDOWN = syscall.Errno(0x93) EHOSTUNREACH = syscall.Errno(0x94) EHWPOISON = syscall.Errno(0xa8) @@ -846,6 +846,7 @@ var errorList = [...]struct { {166, "ENOTRECOVERABLE", "state not recoverable"}, {167, "ERFKILL", "operation not possible due to RF-kill"}, {168, "EHWPOISON", "memory page has hardware error"}, + {169, "EFTYPE", "unknown error 169"}, {1133, "EDQUOT", "disk quota exceeded"}, } diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go b/vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go index a78b6cc..b19df23 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go @@ -481,7 +481,6 @@ const ( TIOCSERGWILD = 0x5489 TIOCSERSETMULTI = 0x5490 TIOCSERSWILD = 0x548a - TIOCSER_TEMT = 0x1 TIOCSETD = 0x7401 TIOCSETN = 0x740a TIOCSETP = 0x7409 @@ -602,6 +601,7 @@ const ( EDQUOT = syscall.Errno(0x46d) EFSBADCRC = syscall.Errno(0x4d) EFSCORRUPTED = syscall.Errno(0x87) + EFTYPE = syscall.Errno(0xa9) EHOSTDOWN = syscall.Errno(0x93) EHOSTUNREACH = syscall.Errno(0x94) EHWPOISON = syscall.Errno(0xa8) @@ -846,6 +846,7 @@ var errorList = [...]struct { {166, "ENOTRECOVERABLE", "state not recoverable"}, {167, "ERFKILL", "operation not possible due to RF-kill"}, {168, "EHWPOISON", "memory page has hardware error"}, + {169, "EFTYPE", "unknown error 169"}, {1133, "EDQUOT", "disk quota exceeded"}, } diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go b/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go index d0e38ca..9ba3c95 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go @@ -481,7 +481,6 @@ const ( TIOCSERGWILD = 0x5489 TIOCSERSETMULTI = 0x5490 TIOCSERSWILD = 0x548a - TIOCSER_TEMT = 0x1 TIOCSETD = 0x7401 TIOCSETN = 0x740a TIOCSETP = 0x7409 @@ -602,6 +601,7 @@ const ( EDQUOT = syscall.Errno(0x46d) EFSBADCRC = syscall.Errno(0x4d) EFSCORRUPTED = syscall.Errno(0x87) + EFTYPE = syscall.Errno(0xa9) EHOSTDOWN = syscall.Errno(0x93) EHOSTUNREACH = syscall.Errno(0x94) EHWPOISON = syscall.Errno(0xa8) @@ -846,6 +846,7 @@ var errorList = [...]struct { {166, "ENOTRECOVERABLE", "state not recoverable"}, {167, "ERFKILL", "operation not possible due to RF-kill"}, {168, "EHWPOISON", "memory page has hardware error"}, + {169, "EFTYPE", "unknown error 169"}, {1133, "EDQUOT", "disk quota exceeded"}, } diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc.go b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc.go index c883e14..62da59f 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc.go @@ -535,7 +535,6 @@ const ( TIOCSERGWILD = 0x5454 TIOCSERSETMULTI = 0x545b TIOCSERSWILD = 0x5455 - TIOCSER_TEMT = 0x1 TIOCSETC = 0x80067411 TIOCSETD = 0x5423 TIOCSETN = 0x8006740a @@ -658,6 +657,7 @@ const ( EDQUOT = syscall.Errno(0x7a) EFSBADCRC = syscall.Errno(0x4a) EFSCORRUPTED = syscall.Errno(0x75) + EFTYPE = syscall.Errno(0x86) EHOSTDOWN = syscall.Errno(0x70) EHOSTUNREACH = syscall.Errno(0x71) EHWPOISON = syscall.Errno(0x85) @@ -899,6 +899,7 @@ var errorList = [...]struct { {131, "ENOTRECOVERABLE", "state not recoverable"}, {132, "ERFKILL", "operation not possible due to RF-kill"}, {133, "EHWPOISON", "memory page has hardware error"}, + {134, "EFTYPE", "unknown error 134"}, } // Signal table diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go index 1834273..d18d4da 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go @@ -539,7 +539,6 @@ const ( TIOCSERGWILD = 0x5454 TIOCSERSETMULTI = 0x545b TIOCSERSWILD = 0x5455 - TIOCSER_TEMT = 0x1 TIOCSETC = 0x80067411 TIOCSETD = 0x5423 TIOCSETN = 0x8006740a @@ -662,6 +661,7 @@ const ( EDQUOT = syscall.Errno(0x7a) EFSBADCRC = syscall.Errno(0x4a) EFSCORRUPTED = syscall.Errno(0x75) + EFTYPE = syscall.Errno(0x86) EHOSTDOWN = syscall.Errno(0x70) EHOSTUNREACH = syscall.Errno(0x71) EHWPOISON = syscall.Errno(0x85) @@ -903,6 +903,7 @@ var errorList = [...]struct { {131, "ENOTRECOVERABLE", "state not recoverable"}, {132, "ERFKILL", "operation not possible due to RF-kill"}, {133, "EHWPOISON", "memory page has hardware error"}, + {134, "EFTYPE", "unknown error 134"}, } // Signal table diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go index 39945dd..ba7767d 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go @@ -539,7 +539,6 @@ const ( TIOCSERGWILD = 0x5454 TIOCSERSETMULTI = 0x545b TIOCSERSWILD = 0x5455 - TIOCSER_TEMT = 0x1 TIOCSETC = 0x80067411 TIOCSETD = 0x5423 TIOCSETN = 0x8006740a @@ -662,6 +661,7 @@ const ( EDQUOT = syscall.Errno(0x7a) EFSBADCRC = syscall.Errno(0x4a) EFSCORRUPTED = syscall.Errno(0x75) + EFTYPE = syscall.Errno(0x86) EHOSTDOWN = syscall.Errno(0x70) EHOSTUNREACH = syscall.Errno(0x71) EHWPOISON = syscall.Errno(0x85) @@ -903,6 +903,7 @@ var errorList = [...]struct { {131, "ENOTRECOVERABLE", "state not recoverable"}, {132, "ERFKILL", "operation not possible due to RF-kill"}, {133, "EHWPOISON", "memory page has hardware error"}, + {134, "EFTYPE", "unknown error 134"}, } // Signal table diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_riscv64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_riscv64.go index bc0f372..76cb221 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_riscv64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_riscv64.go @@ -486,7 +486,6 @@ const ( TIOCSERGWILD = 0x5454 TIOCSERSETMULTI = 0x545b TIOCSERSWILD = 0x5455 - TIOCSER_TEMT = 0x1 TIOCSETD = 0x5423 TIOCSIG = 0x40045436 TIOCSISO7816 = 0xc0285443 @@ -603,6 +602,7 @@ const ( EDQUOT = syscall.Errno(0x7a) EFSBADCRC = syscall.Errno(0x4a) EFSCORRUPTED = syscall.Errno(0x75) + EFTYPE = syscall.Errno(0x86) EHOSTDOWN = syscall.Errno(0x70) EHOSTUNREACH = syscall.Errno(0x71) EHWPOISON = syscall.Errno(0x85) @@ -843,6 +843,7 @@ var errorList = [...]struct { {131, "ENOTRECOVERABLE", "state not recoverable"}, {132, "ERFKILL", "operation not possible due to RF-kill"}, {133, "EHWPOISON", "memory page has hardware error"}, + {134, "EFTYPE", "unknown error 134"}, } // Signal table diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go b/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go index 6e87bd6..ffd12a9 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go @@ -545,7 +545,6 @@ const ( TIOCSERGWILD = 0x5454 TIOCSERSETMULTI = 0x545b TIOCSERSWILD = 0x5455 - TIOCSER_TEMT = 0x1 TIOCSETD = 0x5423 TIOCSIG = 0x40045436 TIOCSISO7816 = 0xc0285443 @@ -662,6 +661,7 @@ const ( EDQUOT = syscall.Errno(0x7a) EFSBADCRC = syscall.Errno(0x4a) EFSCORRUPTED = syscall.Errno(0x75) + EFTYPE = syscall.Errno(0x86) EHOSTDOWN = syscall.Errno(0x70) EHOSTUNREACH = syscall.Errno(0x71) EHWPOISON = syscall.Errno(0x85) @@ -902,6 +902,7 @@ var errorList = [...]struct { {131, "ENOTRECOVERABLE", "state not recoverable"}, {132, "ERFKILL", "operation not possible due to RF-kill"}, {133, "EHWPOISON", "memory page has hardware error"}, + {134, "EFTYPE", "unknown error 134"}, } // Signal table diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go index 7e2b2e8..f372aed 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go @@ -14,21 +14,21 @@ const ( ASI_LEON_DFLUSH = 0x11 ASI_LEON_IFLUSH = 0x10 ASI_LEON_MMUFLUSH = 0x18 - B1000000 = 0x1008 + B1000000 = 0x100c B115200 = 0x1002 - B1152000 = 0x1009 - B1500000 = 0x100a - B2000000 = 0x100b + B1152000 = 0x100d + B1500000 = 0x100e + B153600 = 0x1006 + B2000000 = 0x100f B230400 = 0x1003 - B2500000 = 0x100c - B3000000 = 0x100d - B3500000 = 0x100e - B4000000 = 0x100f + B307200 = 0x1007 B460800 = 0x1004 - B500000 = 0x1005 + B500000 = 0x100a B57600 = 0x1001 - B576000 = 0x1006 - B921600 = 0x1007 + B576000 = 0x100b + B614400 = 0x1008 + B76800 = 0x1005 + B921600 = 0x1009 BLKALIGNOFF = 0x2000127a BLKBSZGET = 0x40081270 BLKBSZSET = 0x80081271 @@ -91,7 +91,7 @@ const ( FFDLY = 0x8000 FICLONE = 0x80049409 FICLONERANGE = 0x8020940d - FLUSHO = 0x1000 + FLUSHO = 0x2000 FS_IOC_ENABLE_VERITY = 0x80806685 FS_IOC_GETFLAGS = 0x40086601 FS_IOC_GET_ENCRYPTION_NONCE = 0x4010661b @@ -563,6 +563,9 @@ const ( TIOCM_CD = 0x40 TIOCM_CTS = 0x20 TIOCM_DSR = 0x100 + TIOCM_LOOP = 0x8000 + TIOCM_OUT1 = 0x2000 + TIOCM_OUT2 = 0x4000 TIOCM_RI = 0x80 TIOCM_RNG = 0x80 TIOCM_SR = 0x10 @@ -641,10 +644,11 @@ const ( UBI_IOCVOLRMBLK = 0x20004f08 UBI_IOCVOLUP = 0x80084f00 VDISCARD = 0xd + VDSUSP = 0xb VEOF = 0x4 - VEOL = 0xb - VEOL2 = 0x10 - VMIN = 0x6 + VEOL = 0x5 + VEOL2 = 0x6 + VMIN = 0x4 VREPRINT = 0xc VSTART = 0x8 VSTOP = 0x9 @@ -664,6 +668,7 @@ const ( WDIOC_KEEPALIVE = 0x40045705 WDIOC_SETOPTIONS = 0x40045704 WORDSIZE = 0x40 + WRAP = 0x20000 XCASE = 0x4 XTABS = 0x1800 _HIDIOCGRAWNAME = 0x40804804 @@ -699,6 +704,7 @@ const ( EDQUOT = syscall.Errno(0x45) EFSBADCRC = syscall.Errno(0x4c) EFSCORRUPTED = syscall.Errno(0x75) + EFTYPE = syscall.Errno(0x88) EHOSTDOWN = syscall.Errno(0x40) EHOSTUNREACH = syscall.Errno(0x41) EHWPOISON = syscall.Errno(0x87) @@ -945,6 +951,7 @@ var errorList = [...]struct { {133, "ENOTRECOVERABLE", "state not recoverable"}, {134, "ERFKILL", "operation not possible due to RF-kill"}, {135, "EHWPOISON", "memory page has hardware error"}, + {136, "EFTYPE", "unknown error 136"}, } // Signal table diff --git a/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.go b/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.go index 813c05b..7db9bf5 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.go @@ -702,6 +702,17 @@ var libc_fcntl_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func fcntlPtr(fd int, cmd int, arg unsafe.Pointer) (val int, err error) { + r0, _, e1 := syscall_syscall(libc_fcntl_trampoline_addr, uintptr(fd), uintptr(cmd), uintptr(arg)) + val = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func kill(pid int, signum int, posix int) (err error) { _, _, e1 := syscall_syscall(libc_kill_trampoline_addr, uintptr(pid), uintptr(signum), uintptr(posix)) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.go b/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.go index e6f58f3..2a65805 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.go @@ -702,6 +702,17 @@ var libc_fcntl_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func fcntlPtr(fd int, cmd int, arg unsafe.Pointer) (val int, err error) { + r0, _, e1 := syscall_syscall(libc_fcntl_trampoline_addr, uintptr(fd), uintptr(cmd), uintptr(arg)) + val = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func kill(pid int, signum int, posix int) (err error) { _, _, e1 := syscall_syscall(libc_kill_trampoline_addr, uintptr(pid), uintptr(signum), uintptr(posix)) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_386.go b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_386.go index c009639..10b57ff 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_386.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_386.go @@ -825,6 +825,165 @@ func ExtattrListLink(link string, attrnamespace int, data uintptr, nbytes int) ( // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func extattrGetFd(fd int, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrSetFd(fd int, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrListFd(fd int, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) { + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FD, uintptr(fd), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrGetFile(file string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrSetFile(file string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrListFile(file string, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrGetLink(link string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrSetLink(link string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrListLink(link string, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Fadvise(fd int, offset int64, length int64, advice int) (err error) { _, _, e1 := Syscall6(SYS_POSIX_FADVISE, uintptr(fd), uintptr(offset), uintptr(offset>>32), uintptr(length), uintptr(length>>32), uintptr(advice)) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_amd64.go b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_amd64.go index 7664df7..6a6fc3c 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_amd64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_amd64.go @@ -825,6 +825,165 @@ func ExtattrListLink(link string, attrnamespace int, data uintptr, nbytes int) ( // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func extattrGetFd(fd int, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrSetFd(fd int, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrListFd(fd int, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) { + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FD, uintptr(fd), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrGetFile(file string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrSetFile(file string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrListFile(file string, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrGetLink(link string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrSetLink(link string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrListLink(link string, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Fadvise(fd int, offset int64, length int64, advice int) (err error) { _, _, e1 := Syscall6(SYS_POSIX_FADVISE, uintptr(fd), uintptr(offset), uintptr(length), uintptr(advice), 0, 0) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm.go b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm.go index ae09918..4a15b4a 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm.go @@ -825,6 +825,165 @@ func ExtattrListLink(link string, attrnamespace int, data uintptr, nbytes int) ( // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func extattrGetFd(fd int, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrSetFd(fd int, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrListFd(fd int, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) { + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FD, uintptr(fd), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrGetFile(file string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrSetFile(file string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrListFile(file string, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrGetLink(link string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrSetLink(link string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrListLink(link string, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Fadvise(fd int, offset int64, length int64, advice int) (err error) { _, _, e1 := Syscall9(SYS_POSIX_FADVISE, uintptr(fd), 0, uintptr(offset), uintptr(offset>>32), uintptr(length), uintptr(length>>32), uintptr(advice), 0, 0) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm64.go b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm64.go index 11fd5d4..f15331f 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm64.go @@ -825,6 +825,165 @@ func ExtattrListLink(link string, attrnamespace int, data uintptr, nbytes int) ( // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func extattrGetFd(fd int, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrSetFd(fd int, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrListFd(fd int, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) { + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FD, uintptr(fd), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrGetFile(file string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrSetFile(file string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrListFile(file string, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrGetLink(link string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrSetLink(link string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrListLink(link string, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Fadvise(fd int, offset int64, length int64, advice int) (err error) { _, _, e1 := Syscall6(SYS_POSIX_FADVISE, uintptr(fd), uintptr(offset), uintptr(length), uintptr(advice), 0, 0) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_riscv64.go b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_riscv64.go index c3d2d65..faa5626 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_riscv64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_riscv64.go @@ -825,6 +825,165 @@ func ExtattrListLink(link string, attrnamespace int, data uintptr, nbytes int) ( // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func extattrGetFd(fd int, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrSetFd(fd int, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrListFd(fd int, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) { + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FD, uintptr(fd), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrGetFile(file string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrSetFile(file string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrListFile(file string, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrGetLink(link string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrSetLink(link string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrListLink(link string, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Fadvise(fd int, offset int64, length int64, advice int) (err error) { _, _, e1 := Syscall6(SYS_POSIX_FADVISE, uintptr(fd), uintptr(offset), uintptr(length), uintptr(advice), 0, 0) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux.go b/vendor/golang.org/x/sys/unix/zsyscall_linux.go index 5788c2a..4c63b97 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux.go @@ -943,7 +943,7 @@ func fsconfig(fd int, cmd uint, key *byte, value *byte, aux int) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Getdents(fd int, buf []byte) (n int, err error) { +func getdents(fd int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) @@ -1167,6 +1167,23 @@ func Lgetxattr(path string, attr string, dest []byte) (sz int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Listns(req *NsIdReq, nsIds []uint64, flags uint) (n int, err error) { + var _p0 unsafe.Pointer + if len(nsIds) > 0 { + _p0 = unsafe.Pointer(&nsIds[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall6(SYS_LISTNS, uintptr(unsafe.Pointer(req)), uintptr(_p0), uintptr(len(nsIds)), uintptr(flags), 0, 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Listxattr(path string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) @@ -1390,6 +1407,16 @@ func Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) ( // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func PrctlArg5Ptr(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 unsafe.Pointer) (err error) { + _, _, e1 := Syscall6(SYS_PRCTL, uintptr(option), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func pselect6(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timespec, sigmask *sigset_argpack) (n int, err error) { r0, _, e1 := Syscall6(SYS_PSELECT6, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask))) n = int(r0) diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_sparc64.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_sparc64.go index 5276376..b7aca54 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_sparc64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_sparc64.go @@ -66,7 +66,7 @@ func Fchown(fd int, uid int, gid int) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { - _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) + _, _, e1 := Syscall(SYS_FSTAT64, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } @@ -183,7 +183,7 @@ func Lstat(path string, stat *Stat_t) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_LSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + _, _, e1 := Syscall(SYS_LSTAT64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } @@ -338,7 +338,7 @@ func Stat(path string, stat *Stat_t) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + _, _, e1 := Syscall(SYS_STAT64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } diff --git a/vendor/golang.org/x/sys/unix/zsyscall_netbsd_386.go b/vendor/golang.org/x/sys/unix/zsyscall_netbsd_386.go index e91ebc1..1e136d1 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_netbsd_386.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_netbsd_386.go @@ -802,6 +802,165 @@ func ExtattrListLink(link string, attrnamespace int, data uintptr, nbytes int) ( // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func extattrGetFd(fd int, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrSetFd(fd int, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrListFd(fd int, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) { + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FD, uintptr(fd), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrGetFile(file string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrSetFile(file string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrListFile(file string, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrGetLink(link string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrSetLink(link string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrListLink(link string, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) diff --git a/vendor/golang.org/x/sys/unix/zsyscall_netbsd_amd64.go b/vendor/golang.org/x/sys/unix/zsyscall_netbsd_amd64.go index be28bab..440db6e 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_netbsd_amd64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_netbsd_amd64.go @@ -802,6 +802,165 @@ func ExtattrListLink(link string, attrnamespace int, data uintptr, nbytes int) ( // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func extattrGetFd(fd int, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrSetFd(fd int, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrListFd(fd int, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) { + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FD, uintptr(fd), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrGetFile(file string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrSetFile(file string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrListFile(file string, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrGetLink(link string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrSetLink(link string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrListLink(link string, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) diff --git a/vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm.go b/vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm.go index fb587e8..db96300 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm.go @@ -802,6 +802,165 @@ func ExtattrListLink(link string, attrnamespace int, data uintptr, nbytes int) ( // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func extattrGetFd(fd int, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrSetFd(fd int, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrListFd(fd int, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) { + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FD, uintptr(fd), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrGetFile(file string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrSetFile(file string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrListFile(file string, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrGetLink(link string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrSetLink(link string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrListLink(link string, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) diff --git a/vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm64.go b/vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm64.go index d576438..c4bea6c 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm64.go @@ -802,6 +802,165 @@ func ExtattrListLink(link string, attrnamespace int, data uintptr, nbytes int) ( // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func extattrGetFd(fd int, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrSetFd(fd int, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FD, uintptr(fd), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p0)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrListFd(fd int, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) { + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FD, uintptr(fd), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrGetFile(file string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrSetFile(file string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrListFile(file string, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(file) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_FILE, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrGetLink(link string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_GET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrSetLink(link string, attrnamespace int, attrname string, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attrname) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_SET_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(unsafe.Pointer(_p1)), uintptr(data), uintptr(nbytes), 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func extattrListLink(link string, attrnamespace int, data unsafe.Pointer, nbytes int) (ret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(link) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_EXTATTR_LIST_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(attrnamespace), uintptr(data), uintptr(nbytes), 0, 0) + ret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_zos_s390x.go b/vendor/golang.org/x/sys/unix/zsysnum_zos_s390x.go index 5e8c263..f09f844 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_zos_s390x.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_zos_s390x.go @@ -2848,5 +2848,18 @@ const ( SYS_____CHATTRAT64_A = 0xE39 // 3641 SYS_MADVISE = 0xE3A // 3642 SYS___AUTHENTICATE = 0xE3B // 3643 + SYS_GETPWENT_R = 0xE3C // 3644 + SYS___GETPWENT_R_A = 0xE3D // 3645 + SYS_STRNLEN = 0xE3E // 3646 + SYS_STPCPY = 0xE3F // 3647 + SYS_STPNCPY = 0xE40 // 3648 + SYS_STRSIGNAL = 0xE41 // 3649 + SYS_WCPCPY = 0xE42 // 3650 + SYS_WCPNCPY = 0xE43 // 3651 + SYS_WCSNLEN = 0xE44 // 3652 + SYS___STRSIGNAL_A = 0xE45 // 3653 + SYS_FDOPENDIR = 0xE46 // 3654 + SYS_FDCLOSEDIR = 0xE47 // 3655 + SYS_SYSCALL = 0xE48 // 3656 ) diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux.go b/vendor/golang.org/x/sys/unix/ztypes_linux.go index 526a0d5..2b3c00b 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux.go @@ -933,6 +933,29 @@ type OpenHow struct { const SizeofOpenHow = 0x18 +type NsIdReq struct { + Size uint32 + Spare uint32 + Ns_id uint64 + Ns_type uint32 + Spare2 uint32 + User_ns_id uint64 +} + +const ( + NS_ID_REQ_SIZE_VER0 = 0x20 + LISTNS_CURRENT_USER = 0xffffffffffffffff + + TIME_NS = 0x80 + MNT_NS = 0x20000 + CGROUP_NS = 0x2000000 + UTS_NS = 0x4000000 + IPC_NS = 0x8000000 + USER_NS = 0x10000000 + PID_NS = 0x20000000 + NET_NS = 0x40000000 +) + const ( RESOLVE_BENEATH = 0x8 RESOLVE_IN_ROOT = 0x10 @@ -3579,7 +3602,7 @@ const ( DEVLINK_ATTR_LINECARD_SUPPORTED_TYPES = 0xae DEVLINK_ATTR_NESTED_DEVLINK = 0xaf DEVLINK_ATTR_SELFTESTS = 0xb0 - DEVLINK_ATTR_MAX = 0xb7 + DEVLINK_ATTR_MAX = 0xb9 DEVLINK_DPIPE_FIELD_MAPPING_TYPE_NONE = 0x0 DEVLINK_DPIPE_FIELD_MAPPING_TYPE_IFINDEX = 0x1 DEVLINK_DPIPE_MATCH_TYPE_FIELD_EXACT = 0x0 @@ -4101,7 +4124,7 @@ const ( ETHTOOL_A_COALESCE_RATE_SAMPLE_INTERVAL = 0x17 ETHTOOL_A_COALESCE_USE_CQE_MODE_TX = 0x18 ETHTOOL_A_COALESCE_USE_CQE_MODE_RX = 0x19 - ETHTOOL_A_COALESCE_MAX = 0x1e + ETHTOOL_A_COALESCE_MAX = 0x20 ETHTOOL_A_PAUSE_UNSPEC = 0x0 ETHTOOL_A_PAUSE_HEADER = 0x1 ETHTOOL_A_PAUSE_AUTONEG = 0x2 @@ -4113,7 +4136,7 @@ const ( ETHTOOL_A_PAUSE_STAT_PAD = 0x1 ETHTOOL_A_PAUSE_STAT_TX_FRAMES = 0x2 ETHTOOL_A_PAUSE_STAT_RX_FRAMES = 0x3 - ETHTOOL_A_PAUSE_STAT_MAX = 0x3 + ETHTOOL_A_PAUSE_STAT_MAX = 0x4 ETHTOOL_A_EEE_UNSPEC = 0x0 ETHTOOL_A_EEE_HEADER = 0x1 ETHTOOL_A_EEE_MODES_OURS = 0x2 @@ -4264,19 +4287,29 @@ type HwTstampConfig struct { } const ( - HWTSTAMP_FILTER_NONE = 0x0 - HWTSTAMP_FILTER_ALL = 0x1 - HWTSTAMP_FILTER_SOME = 0x2 - HWTSTAMP_FILTER_PTP_V1_L4_EVENT = 0x3 - HWTSTAMP_FILTER_PTP_V2_L4_EVENT = 0x6 - HWTSTAMP_FILTER_PTP_V2_L2_EVENT = 0x9 - HWTSTAMP_FILTER_PTP_V2_EVENT = 0xc + HWTSTAMP_FILTER_NONE = 0x0 + HWTSTAMP_FILTER_ALL = 0x1 + HWTSTAMP_FILTER_SOME = 0x2 + HWTSTAMP_FILTER_PTP_V1_L4_EVENT = 0x3 + HWTSTAMP_FILTER_PTP_V1_L4_SYNC = 0x4 + HWTSTAMP_FILTER_PTP_V1_L4_DELAY_REQ = 0x5 + HWTSTAMP_FILTER_PTP_V2_L4_EVENT = 0x6 + HWTSTAMP_FILTER_PTP_V2_L4_SYNC = 0x7 + HWTSTAMP_FILTER_PTP_V2_L4_DELAY_REQ = 0x8 + HWTSTAMP_FILTER_PTP_V2_L2_EVENT = 0x9 + HWTSTAMP_FILTER_PTP_V2_L2_SYNC = 0xa + HWTSTAMP_FILTER_PTP_V2_L2_DELAY_REQ = 0xb + HWTSTAMP_FILTER_PTP_V2_EVENT = 0xc + HWTSTAMP_FILTER_PTP_V2_SYNC = 0xd + HWTSTAMP_FILTER_PTP_V2_DELAY_REQ = 0xe + HWTSTAMP_FILTER_NTP_ALL = 0xf ) const ( HWTSTAMP_TX_OFF = 0x0 HWTSTAMP_TX_ON = 0x1 HWTSTAMP_TX_ONESTEP_SYNC = 0x2 + HWTSTAMP_TX_ONESTEP_P2P = 0x3 ) type ( @@ -4527,9 +4560,12 @@ const ( ) type LandlockRulesetAttr struct { - Access_fs uint64 - Access_net uint64 - Scoped uint64 + Handled_access_fs uint64 + Handled_access_net uint64 + Scoped uint64 + Quiet_access_fs uint64 + Quiet_access_net uint64 + Quiet_scoped uint64 } type LandlockPathBeneathAttr struct { @@ -4541,6 +4577,51 @@ const ( LANDLOCK_RULE_PATH_BENEATH = 0x1 ) +const ( + PIDFD_SIGNAL_THREAD = 0x1 + PIDFD_SIGNAL_THREAD_GROUP = 0x2 + PIDFD_SIGNAL_PROCESS_GROUP = 0x4 + PIDFD_SELF_THREAD = -0x2710 + PIDFD_SELF_THREAD_GROUP = -0x2711 + PIDFD_SELF = -0x2710 + PIDFD_SELF_PROCESS = -0x2711 + PIDFD_INFO_PID = 0x1 + PIDFD_INFO_CREDS = 0x2 + PIDFD_INFO_CGROUPID = 0x4 + PIDFD_INFO_EXIT = 0x8 + PIDFD_INFO_COREDUMP = 0x10 + PIDFD_COREDUMPED = 0x1 + PIDFD_COREDUMP_SKIP = 0x2 + PIDFD_COREDUMP_USER = 0x4 + PIDFD_COREDUMP_ROOT = 0x8 + PIDFD_INFO_SIZE_VER0 = 0x40 + PIDFD_GET_INFO = 0xc058ff0b +) + +const SizeofPidfdInfo = 0x58 + +type PidfdInfo struct { + Mask uint64 + Cgroupid uint64 + Pid uint32 + Tgid uint32 + Ppid uint32 + Ruid uint32 + Rgid uint32 + Euid uint32 + Egid uint32 + Suid uint32 + Sgid uint32 + Fsuid uint32 + Fsgid uint32 + Exit_code int32 + Coredump_mask uint32 + Coredump_signal uint32 + Coredump_code uint32 + Coredump_pad uint32 + Supported_mask uint64 +} + const ( IPC_CREAT = 0x200 IPC_EXCL = 0x400 @@ -4880,7 +4961,7 @@ const ( NL80211_ATTR_MAC_HINT = 0xc8 NL80211_ATTR_MAC_MASK = 0xd7 NL80211_ATTR_MAX_AP_ASSOC_STA = 0xca - NL80211_ATTR_MAX = 0x15c + NL80211_ATTR_MAX = 0x16e NL80211_ATTR_MAX_CRIT_PROT_DURATION = 0xb4 NL80211_ATTR_MAX_CSA_COUNTERS = 0xce NL80211_ATTR_MAX_HW_TIMESTAMP_PEERS = 0x143 @@ -5095,12 +5176,12 @@ const ( NL80211_ATTR_WOWLAN_TRIGGERS = 0x75 NL80211_ATTR_WOWLAN_TRIGGERS_SUPPORTED = 0x76 NL80211_ATTR_WPA_VERSIONS = 0x4b - NL80211_AUTHTYPE_AUTOMATIC = 0x9 + NL80211_AUTHTYPE_AUTOMATIC = 0xa NL80211_AUTHTYPE_FILS_PK = 0x7 NL80211_AUTHTYPE_FILS_SK = 0x5 NL80211_AUTHTYPE_FILS_SK_PFS = 0x6 NL80211_AUTHTYPE_FT = 0x2 - NL80211_AUTHTYPE_MAX = 0x8 + NL80211_AUTHTYPE_MAX = 0x9 NL80211_AUTHTYPE_NETWORK_EAP = 0x3 NL80211_AUTHTYPE_OPEN_SYSTEM = 0x0 NL80211_AUTHTYPE_SAE = 0x4 @@ -5268,7 +5349,7 @@ const ( NL80211_CMD_LEAVE_MESH = 0x45 NL80211_CMD_LEAVE_OCB = 0x6d NL80211_CMD_LINKS_REMOVED = 0x9a - NL80211_CMD_MAX = 0x9f + NL80211_CMD_MAX = 0xa7 NL80211_CMD_MICHAEL_MIC_FAILURE = 0x29 NL80211_CMD_MODIFY_LINK_STA = 0x97 NL80211_CMD_NAN_MATCH = 0x78 @@ -5514,7 +5595,7 @@ const ( NL80211_FREQUENCY_ATTR_GO_CONCURRENT = 0xf NL80211_FREQUENCY_ATTR_INDOOR_ONLY = 0xe NL80211_FREQUENCY_ATTR_IR_CONCURRENT = 0xf - NL80211_FREQUENCY_ATTR_MAX = 0x27 + NL80211_FREQUENCY_ATTR_MAX = 0x29 NL80211_FREQUENCY_ATTR_MAX_TX_POWER = 0x6 NL80211_FREQUENCY_ATTR_NO_10MHZ = 0x11 NL80211_FREQUENCY_ATTR_NO_160MHZ = 0xc @@ -5587,7 +5668,7 @@ const ( NL80211_IFTYPE_AKM_ATTR_SUITES = 0x2 NL80211_IFTYPE_AP = 0x3 NL80211_IFTYPE_AP_VLAN = 0x4 - NL80211_IFTYPE_MAX = 0xc + NL80211_IFTYPE_MAX = 0xe NL80211_IFTYPE_MESH_POINT = 0x7 NL80211_IFTYPE_MONITOR = 0x6 NL80211_IFTYPE_NAN = 0xc @@ -5612,7 +5693,7 @@ const ( NL80211_KEY_DEFAULT_TYPES = 0x8 NL80211_KEY_DEFAULT_TYPE_UNICAST = 0x1 NL80211_KEY_IDX = 0x2 - NL80211_KEY_MAX = 0xa + NL80211_KEY_MAX = 0xb NL80211_KEY_MODE = 0x9 NL80211_KEY_NO_TX = 0x1 NL80211_KEY_RX_TX = 0x0 @@ -5770,7 +5851,7 @@ const ( NL80211_PMKSA_CANDIDATE_BSSID = 0x2 NL80211_PMKSA_CANDIDATE_INDEX = 0x1 NL80211_PMKSA_CANDIDATE_PREAUTH = 0x3 - NL80211_PMSR_ATTR_MAX = 0x5 + NL80211_PMSR_ATTR_MAX = 0x7 NL80211_PMSR_ATTR_MAX_PEERS = 0x1 NL80211_PMSR_ATTR_PEERS = 0x5 NL80211_PMSR_ATTR_RANDOMIZE_MAC_ADDR = 0x3 @@ -5779,7 +5860,7 @@ const ( NL80211_PMSR_FTM_CAPA_ATTR_ASAP = 0x1 NL80211_PMSR_FTM_CAPA_ATTR_BANDWIDTHS = 0x6 NL80211_PMSR_FTM_CAPA_ATTR_MAX_BURSTS_EXPONENT = 0x7 - NL80211_PMSR_FTM_CAPA_ATTR_MAX = 0x12 + NL80211_PMSR_FTM_CAPA_ATTR_MAX = 0x1f NL80211_PMSR_FTM_CAPA_ATTR_MAX_FTMS_PER_BURST = 0x8 NL80211_PMSR_FTM_CAPA_ATTR_NON_ASAP = 0x2 NL80211_PMSR_FTM_CAPA_ATTR_NON_TRIGGER_BASED = 0xa @@ -5801,7 +5882,7 @@ const ( NL80211_PMSR_FTM_REQ_ATTR_BURST_PERIOD = 0x4 NL80211_PMSR_FTM_REQ_ATTR_FTMS_PER_BURST = 0x6 NL80211_PMSR_FTM_REQ_ATTR_LMR_FEEDBACK = 0xc - NL80211_PMSR_FTM_REQ_ATTR_MAX = 0xe + NL80211_PMSR_FTM_REQ_ATTR_MAX = 0x17 NL80211_PMSR_FTM_REQ_ATTR_NON_TRIGGER_BASED = 0xb NL80211_PMSR_FTM_REQ_ATTR_NUM_BURSTS_EXP = 0x3 NL80211_PMSR_FTM_REQ_ATTR_NUM_FTMR_RETRIES = 0x7 @@ -5819,7 +5900,7 @@ const ( NL80211_PMSR_FTM_RESP_ATTR_FAIL_REASON = 0x1 NL80211_PMSR_FTM_RESP_ATTR_FTMS_PER_BURST = 0x8 NL80211_PMSR_FTM_RESP_ATTR_LCI = 0x13 - NL80211_PMSR_FTM_RESP_ATTR_MAX = 0x16 + NL80211_PMSR_FTM_RESP_ATTR_MAX = 0x21 NL80211_PMSR_FTM_RESP_ATTR_NUM_BURSTS_EXP = 0x6 NL80211_PMSR_FTM_RESP_ATTR_NUM_FTMR_ATTEMPTS = 0x3 NL80211_PMSR_FTM_RESP_ATTR_NUM_FTMR_SUCCESSES = 0x4 @@ -5833,7 +5914,7 @@ const ( NL80211_PMSR_FTM_RESP_ATTR_TX_RATE = 0xb NL80211_PMSR_PEER_ATTR_ADDR = 0x1 NL80211_PMSR_PEER_ATTR_CHAN = 0x2 - NL80211_PMSR_PEER_ATTR_MAX = 0x4 + NL80211_PMSR_PEER_ATTR_MAX = 0x5 NL80211_PMSR_PEER_ATTR_REQ = 0x3 NL80211_PMSR_PEER_ATTR_RESP = 0x4 NL80211_PMSR_REQ_ATTR_DATA = 0x1 @@ -6473,3 +6554,23 @@ type GPIOV2LineEvent struct { Line_seqno uint32 _ [6]uint32 } + +const ( + IPMI_MAX_ADDR_SIZE = 0x20 + IPMI_SYSTEM_INTERFACE_ADDR_TYPE = 0xc + IPMI_BMC_CHANNEL = 0xf + IPMI_RESPONSE_RECV_TYPE = 0x1 +) + +type IPMISystemInterfaceAddr struct { + Type int32 + Channel int16 + Lun uint8 + _ [1]byte +} +type IPMIMsg struct { + Netfn uint8 + Cmd uint8 + Len uint16 + Data *uint8 +} diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_386.go b/vendor/golang.org/x/sys/unix/ztypes_linux_386.go index aede1de..c7ec66d 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_386.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_386.go @@ -163,6 +163,11 @@ type Msghdr struct { Flags int32 } +type Mmsghdr struct { + Hdr Msghdr + Len uint32 +} + type Cmsghdr struct { Len uint32 Level int32 @@ -178,6 +183,7 @@ const ( SizeofSockaddrNFCLLCP = 0x58 SizeofIovec = 0x8 SizeofMsghdr = 0x1c + SizeofMmsghdr = 0x20 SizeofCmsghdr = 0xc ) @@ -680,7 +686,18 @@ const ( ) const ( - PIDFD_NONBLOCK = 0x800 + PIDFD_NONBLOCK = 0x800 + PIDFD_THREAD = 0x80 + PIDFD_GET_CGROUP_NAMESPACE = 0xff01 + PIDFD_GET_IPC_NAMESPACE = 0xff02 + PIDFD_GET_MNT_NAMESPACE = 0xff03 + PIDFD_GET_NET_NAMESPACE = 0xff04 + PIDFD_GET_PID_NAMESPACE = 0xff05 + PIDFD_GET_PID_FOR_CHILDREN_NAMESPACE = 0xff06 + PIDFD_GET_TIME_NAMESPACE = 0xff07 + PIDFD_GET_TIME_FOR_CHILDREN_NAMESPACE = 0xff08 + PIDFD_GET_USER_NAMESPACE = 0xff09 + PIDFD_GET_UTS_NAMESPACE = 0xff0a ) type SysvIpcPerm struct { @@ -715,3 +732,22 @@ type SysvShmDesc struct { const ( GPIO_GET_CHIPINFO_IOCTL = 0x8044b401 ) + +const ( + IPMICTL_SEND_COMMAND = 0x8014690d + IPMICTL_RECEIVE_MSG = 0xc018690c +) + +type IPMIReq struct { + Addr *uint8 + Len uint32 + Msgid int32 + Msg IPMIMsg +} +type IPMIRecv struct { + Recv_type int32 + Addr *uint8 + Addr_len uint32 + Msgid int32 + Msg IPMIMsg +} diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_amd64.go b/vendor/golang.org/x/sys/unix/ztypes_linux_amd64.go index bb3bc4d..abe072e 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_amd64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_amd64.go @@ -166,6 +166,12 @@ type Msghdr struct { _ [4]byte } +type Mmsghdr struct { + Hdr Msghdr + Len uint32 + _ [4]byte +} + type Cmsghdr struct { Len uint64 Level int32 @@ -181,6 +187,7 @@ const ( SizeofSockaddrNFCLLCP = 0x60 SizeofIovec = 0x10 SizeofMsghdr = 0x38 + SizeofMmsghdr = 0x40 SizeofCmsghdr = 0x10 ) @@ -697,7 +704,18 @@ const ( ) const ( - PIDFD_NONBLOCK = 0x800 + PIDFD_NONBLOCK = 0x800 + PIDFD_THREAD = 0x80 + PIDFD_GET_CGROUP_NAMESPACE = 0xff01 + PIDFD_GET_IPC_NAMESPACE = 0xff02 + PIDFD_GET_MNT_NAMESPACE = 0xff03 + PIDFD_GET_NET_NAMESPACE = 0xff04 + PIDFD_GET_PID_NAMESPACE = 0xff05 + PIDFD_GET_PID_FOR_CHILDREN_NAMESPACE = 0xff06 + PIDFD_GET_TIME_NAMESPACE = 0xff07 + PIDFD_GET_TIME_FOR_CHILDREN_NAMESPACE = 0xff08 + PIDFD_GET_USER_NAMESPACE = 0xff09 + PIDFD_GET_UTS_NAMESPACE = 0xff0a ) type SysvIpcPerm struct { @@ -729,3 +747,22 @@ type SysvShmDesc struct { const ( GPIO_GET_CHIPINFO_IOCTL = 0x8044b401 ) + +const ( + IPMICTL_SEND_COMMAND = 0x8028690d + IPMICTL_RECEIVE_MSG = 0xc030690c +) + +type IPMIReq struct { + Addr *uint8 + Len uint32 + Msgid int64 + Msg IPMIMsg +} +type IPMIRecv struct { + Recv_type int32 + Addr *uint8 + Addr_len uint32 + Msgid int64 + Msg IPMIMsg +} diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_arm.go b/vendor/golang.org/x/sys/unix/ztypes_linux_arm.go index 1fdf4c5..4ba7cea 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_arm.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_arm.go @@ -169,6 +169,11 @@ type Msghdr struct { Flags int32 } +type Mmsghdr struct { + Hdr Msghdr + Len uint32 +} + type Cmsghdr struct { Len uint32 Level int32 @@ -184,6 +189,7 @@ const ( SizeofSockaddrNFCLLCP = 0x58 SizeofIovec = 0x8 SizeofMsghdr = 0x1c + SizeofMmsghdr = 0x20 SizeofCmsghdr = 0xc ) @@ -674,7 +680,18 @@ const ( ) const ( - PIDFD_NONBLOCK = 0x800 + PIDFD_NONBLOCK = 0x800 + PIDFD_THREAD = 0x80 + PIDFD_GET_CGROUP_NAMESPACE = 0xff01 + PIDFD_GET_IPC_NAMESPACE = 0xff02 + PIDFD_GET_MNT_NAMESPACE = 0xff03 + PIDFD_GET_NET_NAMESPACE = 0xff04 + PIDFD_GET_PID_NAMESPACE = 0xff05 + PIDFD_GET_PID_FOR_CHILDREN_NAMESPACE = 0xff06 + PIDFD_GET_TIME_NAMESPACE = 0xff07 + PIDFD_GET_TIME_FOR_CHILDREN_NAMESPACE = 0xff08 + PIDFD_GET_USER_NAMESPACE = 0xff09 + PIDFD_GET_UTS_NAMESPACE = 0xff0a ) type SysvIpcPerm struct { @@ -709,3 +726,22 @@ type SysvShmDesc struct { const ( GPIO_GET_CHIPINFO_IOCTL = 0x8044b401 ) + +const ( + IPMICTL_SEND_COMMAND = 0x8014690d + IPMICTL_RECEIVE_MSG = 0xc018690c +) + +type IPMIReq struct { + Addr *uint8 + Len uint32 + Msgid int32 + Msg IPMIMsg +} +type IPMIRecv struct { + Recv_type int32 + Addr *uint8 + Addr_len uint32 + Msgid int32 + Msg IPMIMsg +} diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_arm64.go b/vendor/golang.org/x/sys/unix/ztypes_linux_arm64.go index 063e6f0..3f55ca4 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_arm64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_arm64.go @@ -167,6 +167,12 @@ type Msghdr struct { _ [4]byte } +type Mmsghdr struct { + Hdr Msghdr + Len uint32 + _ [4]byte +} + type Cmsghdr struct { Len uint64 Level int32 @@ -182,6 +188,7 @@ const ( SizeofSockaddrNFCLLCP = 0x60 SizeofIovec = 0x10 SizeofMsghdr = 0x38 + SizeofMmsghdr = 0x40 SizeofCmsghdr = 0x10 ) @@ -676,7 +683,18 @@ const ( ) const ( - PIDFD_NONBLOCK = 0x800 + PIDFD_NONBLOCK = 0x800 + PIDFD_THREAD = 0x80 + PIDFD_GET_CGROUP_NAMESPACE = 0xff01 + PIDFD_GET_IPC_NAMESPACE = 0xff02 + PIDFD_GET_MNT_NAMESPACE = 0xff03 + PIDFD_GET_NET_NAMESPACE = 0xff04 + PIDFD_GET_PID_NAMESPACE = 0xff05 + PIDFD_GET_PID_FOR_CHILDREN_NAMESPACE = 0xff06 + PIDFD_GET_TIME_NAMESPACE = 0xff07 + PIDFD_GET_TIME_FOR_CHILDREN_NAMESPACE = 0xff08 + PIDFD_GET_USER_NAMESPACE = 0xff09 + PIDFD_GET_UTS_NAMESPACE = 0xff0a ) type SysvIpcPerm struct { @@ -708,3 +726,22 @@ type SysvShmDesc struct { const ( GPIO_GET_CHIPINFO_IOCTL = 0x8044b401 ) + +const ( + IPMICTL_SEND_COMMAND = 0x8028690d + IPMICTL_RECEIVE_MSG = 0xc030690c +) + +type IPMIReq struct { + Addr *uint8 + Len uint32 + Msgid int64 + Msg IPMIMsg +} +type IPMIRecv struct { + Recv_type int32 + Addr *uint8 + Addr_len uint32 + Msgid int64 + Msg IPMIMsg +} diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_loong64.go b/vendor/golang.org/x/sys/unix/ztypes_linux_loong64.go index 9cf836c..445b2a2 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_loong64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_loong64.go @@ -167,6 +167,12 @@ type Msghdr struct { _ [4]byte } +type Mmsghdr struct { + Hdr Msghdr + Len uint32 + _ [4]byte +} + type Cmsghdr struct { Len uint64 Level int32 @@ -182,6 +188,7 @@ const ( SizeofSockaddrNFCLLCP = 0x60 SizeofIovec = 0x10 SizeofMsghdr = 0x38 + SizeofMmsghdr = 0x40 SizeofCmsghdr = 0x10 ) @@ -677,7 +684,18 @@ const ( ) const ( - PIDFD_NONBLOCK = 0x800 + PIDFD_NONBLOCK = 0x800 + PIDFD_THREAD = 0x80 + PIDFD_GET_CGROUP_NAMESPACE = 0xff01 + PIDFD_GET_IPC_NAMESPACE = 0xff02 + PIDFD_GET_MNT_NAMESPACE = 0xff03 + PIDFD_GET_NET_NAMESPACE = 0xff04 + PIDFD_GET_PID_NAMESPACE = 0xff05 + PIDFD_GET_PID_FOR_CHILDREN_NAMESPACE = 0xff06 + PIDFD_GET_TIME_NAMESPACE = 0xff07 + PIDFD_GET_TIME_FOR_CHILDREN_NAMESPACE = 0xff08 + PIDFD_GET_USER_NAMESPACE = 0xff09 + PIDFD_GET_UTS_NAMESPACE = 0xff0a ) type SysvIpcPerm struct { @@ -709,3 +727,22 @@ type SysvShmDesc struct { const ( GPIO_GET_CHIPINFO_IOCTL = 0x8044b401 ) + +const ( + IPMICTL_SEND_COMMAND = 0x8028690d + IPMICTL_RECEIVE_MSG = 0xc030690c +) + +type IPMIReq struct { + Addr *uint8 + Len uint32 + Msgid int64 + Msg IPMIMsg +} +type IPMIRecv struct { + Recv_type int32 + Addr *uint8 + Addr_len uint32 + Msgid int64 + Msg IPMIMsg +} diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_mips.go b/vendor/golang.org/x/sys/unix/ztypes_linux_mips.go index 1d222fc..6a52e25 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_mips.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_mips.go @@ -168,6 +168,11 @@ type Msghdr struct { Flags int32 } +type Mmsghdr struct { + Hdr Msghdr + Len uint32 +} + type Cmsghdr struct { Len uint32 Level int32 @@ -183,6 +188,7 @@ const ( SizeofSockaddrNFCLLCP = 0x58 SizeofIovec = 0x8 SizeofMsghdr = 0x1c + SizeofMmsghdr = 0x20 SizeofCmsghdr = 0xc ) @@ -680,7 +686,18 @@ const ( ) const ( - PIDFD_NONBLOCK = 0x80 + PIDFD_NONBLOCK = 0x80 + PIDFD_THREAD = 0x400 + PIDFD_GET_CGROUP_NAMESPACE = 0x2000ff01 + PIDFD_GET_IPC_NAMESPACE = 0x2000ff02 + PIDFD_GET_MNT_NAMESPACE = 0x2000ff03 + PIDFD_GET_NET_NAMESPACE = 0x2000ff04 + PIDFD_GET_PID_NAMESPACE = 0x2000ff05 + PIDFD_GET_PID_FOR_CHILDREN_NAMESPACE = 0x2000ff06 + PIDFD_GET_TIME_NAMESPACE = 0x2000ff07 + PIDFD_GET_TIME_FOR_CHILDREN_NAMESPACE = 0x2000ff08 + PIDFD_GET_USER_NAMESPACE = 0x2000ff09 + PIDFD_GET_UTS_NAMESPACE = 0x2000ff0a ) type SysvIpcPerm struct { @@ -714,3 +731,22 @@ type SysvShmDesc struct { const ( GPIO_GET_CHIPINFO_IOCTL = 0x4044b401 ) + +const ( + IPMICTL_SEND_COMMAND = 0x4014690d + IPMICTL_RECEIVE_MSG = 0xc018690c +) + +type IPMIReq struct { + Addr *uint8 + Len uint32 + Msgid int32 + Msg IPMIMsg +} +type IPMIRecv struct { + Recv_type int32 + Addr *uint8 + Addr_len uint32 + Msgid int32 + Msg IPMIMsg +} diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_mips64.go b/vendor/golang.org/x/sys/unix/ztypes_linux_mips64.go index 912cc4a..fafd89d 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_mips64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_mips64.go @@ -167,6 +167,12 @@ type Msghdr struct { _ [4]byte } +type Mmsghdr struct { + Hdr Msghdr + Len uint32 + _ [4]byte +} + type Cmsghdr struct { Len uint64 Level int32 @@ -182,6 +188,7 @@ const ( SizeofSockaddrNFCLLCP = 0x60 SizeofIovec = 0x10 SizeofMsghdr = 0x38 + SizeofMmsghdr = 0x40 SizeofCmsghdr = 0x10 ) @@ -679,7 +686,18 @@ const ( ) const ( - PIDFD_NONBLOCK = 0x80 + PIDFD_NONBLOCK = 0x80 + PIDFD_THREAD = 0x400 + PIDFD_GET_CGROUP_NAMESPACE = 0x2000ff01 + PIDFD_GET_IPC_NAMESPACE = 0x2000ff02 + PIDFD_GET_MNT_NAMESPACE = 0x2000ff03 + PIDFD_GET_NET_NAMESPACE = 0x2000ff04 + PIDFD_GET_PID_NAMESPACE = 0x2000ff05 + PIDFD_GET_PID_FOR_CHILDREN_NAMESPACE = 0x2000ff06 + PIDFD_GET_TIME_NAMESPACE = 0x2000ff07 + PIDFD_GET_TIME_FOR_CHILDREN_NAMESPACE = 0x2000ff08 + PIDFD_GET_USER_NAMESPACE = 0x2000ff09 + PIDFD_GET_UTS_NAMESPACE = 0x2000ff0a ) type SysvIpcPerm struct { @@ -711,3 +729,22 @@ type SysvShmDesc struct { const ( GPIO_GET_CHIPINFO_IOCTL = 0x4044b401 ) + +const ( + IPMICTL_SEND_COMMAND = 0x4028690d + IPMICTL_RECEIVE_MSG = 0xc030690c +) + +type IPMIReq struct { + Addr *uint8 + Len uint32 + Msgid int64 + Msg IPMIMsg +} +type IPMIRecv struct { + Recv_type int32 + Addr *uint8 + Addr_len uint32 + Msgid int64 + Msg IPMIMsg +} diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_mips64le.go b/vendor/golang.org/x/sys/unix/ztypes_linux_mips64le.go index 1e358ef..5fb6f4c 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_mips64le.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_mips64le.go @@ -167,6 +167,12 @@ type Msghdr struct { _ [4]byte } +type Mmsghdr struct { + Hdr Msghdr + Len uint32 + _ [4]byte +} + type Cmsghdr struct { Len uint64 Level int32 @@ -182,6 +188,7 @@ const ( SizeofSockaddrNFCLLCP = 0x60 SizeofIovec = 0x10 SizeofMsghdr = 0x38 + SizeofMmsghdr = 0x40 SizeofCmsghdr = 0x10 ) @@ -679,7 +686,18 @@ const ( ) const ( - PIDFD_NONBLOCK = 0x80 + PIDFD_NONBLOCK = 0x80 + PIDFD_THREAD = 0x400 + PIDFD_GET_CGROUP_NAMESPACE = 0x2000ff01 + PIDFD_GET_IPC_NAMESPACE = 0x2000ff02 + PIDFD_GET_MNT_NAMESPACE = 0x2000ff03 + PIDFD_GET_NET_NAMESPACE = 0x2000ff04 + PIDFD_GET_PID_NAMESPACE = 0x2000ff05 + PIDFD_GET_PID_FOR_CHILDREN_NAMESPACE = 0x2000ff06 + PIDFD_GET_TIME_NAMESPACE = 0x2000ff07 + PIDFD_GET_TIME_FOR_CHILDREN_NAMESPACE = 0x2000ff08 + PIDFD_GET_USER_NAMESPACE = 0x2000ff09 + PIDFD_GET_UTS_NAMESPACE = 0x2000ff0a ) type SysvIpcPerm struct { @@ -711,3 +729,22 @@ type SysvShmDesc struct { const ( GPIO_GET_CHIPINFO_IOCTL = 0x4044b401 ) + +const ( + IPMICTL_SEND_COMMAND = 0x4028690d + IPMICTL_RECEIVE_MSG = 0xc030690c +) + +type IPMIReq struct { + Addr *uint8 + Len uint32 + Msgid int64 + Msg IPMIMsg +} +type IPMIRecv struct { + Recv_type int32 + Addr *uint8 + Addr_len uint32 + Msgid int64 + Msg IPMIMsg +} diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_mipsle.go b/vendor/golang.org/x/sys/unix/ztypes_linux_mipsle.go index df59f32..a50187b 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_mipsle.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_mipsle.go @@ -168,6 +168,11 @@ type Msghdr struct { Flags int32 } +type Mmsghdr struct { + Hdr Msghdr + Len uint32 +} + type Cmsghdr struct { Len uint32 Level int32 @@ -183,6 +188,7 @@ const ( SizeofSockaddrNFCLLCP = 0x58 SizeofIovec = 0x8 SizeofMsghdr = 0x1c + SizeofMmsghdr = 0x20 SizeofCmsghdr = 0xc ) @@ -680,7 +686,18 @@ const ( ) const ( - PIDFD_NONBLOCK = 0x80 + PIDFD_NONBLOCK = 0x80 + PIDFD_THREAD = 0x400 + PIDFD_GET_CGROUP_NAMESPACE = 0x2000ff01 + PIDFD_GET_IPC_NAMESPACE = 0x2000ff02 + PIDFD_GET_MNT_NAMESPACE = 0x2000ff03 + PIDFD_GET_NET_NAMESPACE = 0x2000ff04 + PIDFD_GET_PID_NAMESPACE = 0x2000ff05 + PIDFD_GET_PID_FOR_CHILDREN_NAMESPACE = 0x2000ff06 + PIDFD_GET_TIME_NAMESPACE = 0x2000ff07 + PIDFD_GET_TIME_FOR_CHILDREN_NAMESPACE = 0x2000ff08 + PIDFD_GET_USER_NAMESPACE = 0x2000ff09 + PIDFD_GET_UTS_NAMESPACE = 0x2000ff0a ) type SysvIpcPerm struct { @@ -714,3 +731,22 @@ type SysvShmDesc struct { const ( GPIO_GET_CHIPINFO_IOCTL = 0x4044b401 ) + +const ( + IPMICTL_SEND_COMMAND = 0x4014690d + IPMICTL_RECEIVE_MSG = 0xc018690c +) + +type IPMIReq struct { + Addr *uint8 + Len uint32 + Msgid int32 + Msg IPMIMsg +} +type IPMIRecv struct { + Recv_type int32 + Addr *uint8 + Addr_len uint32 + Msgid int32 + Msg IPMIMsg +} diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_ppc.go b/vendor/golang.org/x/sys/unix/ztypes_linux_ppc.go index 29355aa..777b022 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_ppc.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_ppc.go @@ -169,6 +169,11 @@ type Msghdr struct { Flags int32 } +type Mmsghdr struct { + Hdr Msghdr + Len uint32 +} + type Cmsghdr struct { Len uint32 Level int32 @@ -184,6 +189,7 @@ const ( SizeofSockaddrNFCLLCP = 0x58 SizeofIovec = 0x8 SizeofMsghdr = 0x1c + SizeofMmsghdr = 0x20 SizeofCmsghdr = 0xc ) @@ -686,7 +692,18 @@ const ( ) const ( - PIDFD_NONBLOCK = 0x800 + PIDFD_NONBLOCK = 0x800 + PIDFD_THREAD = 0x80 + PIDFD_GET_CGROUP_NAMESPACE = 0x2000ff01 + PIDFD_GET_IPC_NAMESPACE = 0x2000ff02 + PIDFD_GET_MNT_NAMESPACE = 0x2000ff03 + PIDFD_GET_NET_NAMESPACE = 0x2000ff04 + PIDFD_GET_PID_NAMESPACE = 0x2000ff05 + PIDFD_GET_PID_FOR_CHILDREN_NAMESPACE = 0x2000ff06 + PIDFD_GET_TIME_NAMESPACE = 0x2000ff07 + PIDFD_GET_TIME_FOR_CHILDREN_NAMESPACE = 0x2000ff08 + PIDFD_GET_USER_NAMESPACE = 0x2000ff09 + PIDFD_GET_UTS_NAMESPACE = 0x2000ff0a ) type SysvIpcPerm struct { @@ -722,3 +739,22 @@ type SysvShmDesc struct { const ( GPIO_GET_CHIPINFO_IOCTL = 0x4044b401 ) + +const ( + IPMICTL_SEND_COMMAND = 0x4014690d + IPMICTL_RECEIVE_MSG = 0xc018690c +) + +type IPMIReq struct { + Addr *uint8 + Len uint32 + Msgid int32 + Msg IPMIMsg +} +type IPMIRecv struct { + Recv_type int32 + Addr *uint8 + Addr_len uint32 + Msgid int32 + Msg IPMIMsg +} diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64.go b/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64.go index c6083a1..48a6a5a 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64.go @@ -168,6 +168,12 @@ type Msghdr struct { _ [4]byte } +type Mmsghdr struct { + Hdr Msghdr + Len uint32 + _ [4]byte +} + type Cmsghdr struct { Len uint64 Level int32 @@ -183,6 +189,7 @@ const ( SizeofSockaddrNFCLLCP = 0x60 SizeofIovec = 0x10 SizeofMsghdr = 0x38 + SizeofMmsghdr = 0x40 SizeofCmsghdr = 0x10 ) @@ -686,7 +693,18 @@ const ( ) const ( - PIDFD_NONBLOCK = 0x800 + PIDFD_NONBLOCK = 0x800 + PIDFD_THREAD = 0x80 + PIDFD_GET_CGROUP_NAMESPACE = 0x2000ff01 + PIDFD_GET_IPC_NAMESPACE = 0x2000ff02 + PIDFD_GET_MNT_NAMESPACE = 0x2000ff03 + PIDFD_GET_NET_NAMESPACE = 0x2000ff04 + PIDFD_GET_PID_NAMESPACE = 0x2000ff05 + PIDFD_GET_PID_FOR_CHILDREN_NAMESPACE = 0x2000ff06 + PIDFD_GET_TIME_NAMESPACE = 0x2000ff07 + PIDFD_GET_TIME_FOR_CHILDREN_NAMESPACE = 0x2000ff08 + PIDFD_GET_USER_NAMESPACE = 0x2000ff09 + PIDFD_GET_UTS_NAMESPACE = 0x2000ff0a ) type SysvIpcPerm struct { @@ -717,3 +735,22 @@ type SysvShmDesc struct { const ( GPIO_GET_CHIPINFO_IOCTL = 0x4044b401 ) + +const ( + IPMICTL_SEND_COMMAND = 0x4028690d + IPMICTL_RECEIVE_MSG = 0xc030690c +) + +type IPMIReq struct { + Addr *uint8 + Len uint32 + Msgid int64 + Msg IPMIMsg +} +type IPMIRecv struct { + Recv_type int32 + Addr *uint8 + Addr_len uint32 + Msgid int64 + Msg IPMIMsg +} diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64le.go b/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64le.go index 6321cc7..1972c01 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64le.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64le.go @@ -168,6 +168,12 @@ type Msghdr struct { _ [4]byte } +type Mmsghdr struct { + Hdr Msghdr + Len uint32 + _ [4]byte +} + type Cmsghdr struct { Len uint64 Level int32 @@ -183,6 +189,7 @@ const ( SizeofSockaddrNFCLLCP = 0x60 SizeofIovec = 0x10 SizeofMsghdr = 0x38 + SizeofMmsghdr = 0x40 SizeofCmsghdr = 0x10 ) @@ -686,7 +693,18 @@ const ( ) const ( - PIDFD_NONBLOCK = 0x800 + PIDFD_NONBLOCK = 0x800 + PIDFD_THREAD = 0x80 + PIDFD_GET_CGROUP_NAMESPACE = 0x2000ff01 + PIDFD_GET_IPC_NAMESPACE = 0x2000ff02 + PIDFD_GET_MNT_NAMESPACE = 0x2000ff03 + PIDFD_GET_NET_NAMESPACE = 0x2000ff04 + PIDFD_GET_PID_NAMESPACE = 0x2000ff05 + PIDFD_GET_PID_FOR_CHILDREN_NAMESPACE = 0x2000ff06 + PIDFD_GET_TIME_NAMESPACE = 0x2000ff07 + PIDFD_GET_TIME_FOR_CHILDREN_NAMESPACE = 0x2000ff08 + PIDFD_GET_USER_NAMESPACE = 0x2000ff09 + PIDFD_GET_UTS_NAMESPACE = 0x2000ff0a ) type SysvIpcPerm struct { @@ -717,3 +735,22 @@ type SysvShmDesc struct { const ( GPIO_GET_CHIPINFO_IOCTL = 0x4044b401 ) + +const ( + IPMICTL_SEND_COMMAND = 0x4028690d + IPMICTL_RECEIVE_MSG = 0xc030690c +) + +type IPMIReq struct { + Addr *uint8 + Len uint32 + Msgid int64 + Msg IPMIMsg +} +type IPMIRecv struct { + Recv_type int32 + Addr *uint8 + Addr_len uint32 + Msgid int64 + Msg IPMIMsg +} diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_riscv64.go b/vendor/golang.org/x/sys/unix/ztypes_linux_riscv64.go index b44f402..87572ee 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_riscv64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_riscv64.go @@ -167,6 +167,12 @@ type Msghdr struct { _ [4]byte } +type Mmsghdr struct { + Hdr Msghdr + Len uint32 + _ [4]byte +} + type Cmsghdr struct { Len uint64 Level int32 @@ -182,6 +188,7 @@ const ( SizeofSockaddrNFCLLCP = 0x60 SizeofIovec = 0x10 SizeofMsghdr = 0x38 + SizeofMmsghdr = 0x40 SizeofCmsghdr = 0x10 ) @@ -704,7 +711,18 @@ const ( ) const ( - PIDFD_NONBLOCK = 0x800 + PIDFD_NONBLOCK = 0x800 + PIDFD_THREAD = 0x80 + PIDFD_GET_CGROUP_NAMESPACE = 0xff01 + PIDFD_GET_IPC_NAMESPACE = 0xff02 + PIDFD_GET_MNT_NAMESPACE = 0xff03 + PIDFD_GET_NET_NAMESPACE = 0xff04 + PIDFD_GET_PID_NAMESPACE = 0xff05 + PIDFD_GET_PID_FOR_CHILDREN_NAMESPACE = 0xff06 + PIDFD_GET_TIME_NAMESPACE = 0xff07 + PIDFD_GET_TIME_FOR_CHILDREN_NAMESPACE = 0xff08 + PIDFD_GET_USER_NAMESPACE = 0xff09 + PIDFD_GET_UTS_NAMESPACE = 0xff0a ) type SysvIpcPerm struct { @@ -796,3 +814,22 @@ const ( const ( GPIO_GET_CHIPINFO_IOCTL = 0x8044b401 ) + +const ( + IPMICTL_SEND_COMMAND = 0x8028690d + IPMICTL_RECEIVE_MSG = 0xc030690c +) + +type IPMIReq struct { + Addr *uint8 + Len uint32 + Msgid int64 + Msg IPMIMsg +} +type IPMIRecv struct { + Recv_type int32 + Addr *uint8 + Addr_len uint32 + Msgid int64 + Msg IPMIMsg +} diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_s390x.go b/vendor/golang.org/x/sys/unix/ztypes_linux_s390x.go index b22c795..f6a33e6 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_s390x.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_s390x.go @@ -166,6 +166,12 @@ type Msghdr struct { _ [4]byte } +type Mmsghdr struct { + Hdr Msghdr + Len uint32 + _ [4]byte +} + type Cmsghdr struct { Len uint64 Level int32 @@ -181,6 +187,7 @@ const ( SizeofSockaddrNFCLLCP = 0x60 SizeofIovec = 0x10 SizeofMsghdr = 0x38 + SizeofMmsghdr = 0x40 SizeofCmsghdr = 0x10 ) @@ -700,7 +707,18 @@ const ( ) const ( - PIDFD_NONBLOCK = 0x800 + PIDFD_NONBLOCK = 0x800 + PIDFD_THREAD = 0x80 + PIDFD_GET_CGROUP_NAMESPACE = 0xff01 + PIDFD_GET_IPC_NAMESPACE = 0xff02 + PIDFD_GET_MNT_NAMESPACE = 0xff03 + PIDFD_GET_NET_NAMESPACE = 0xff04 + PIDFD_GET_PID_NAMESPACE = 0xff05 + PIDFD_GET_PID_FOR_CHILDREN_NAMESPACE = 0xff06 + PIDFD_GET_TIME_NAMESPACE = 0xff07 + PIDFD_GET_TIME_FOR_CHILDREN_NAMESPACE = 0xff08 + PIDFD_GET_USER_NAMESPACE = 0xff09 + PIDFD_GET_UTS_NAMESPACE = 0xff0a ) type SysvIpcPerm struct { @@ -731,3 +749,22 @@ type SysvShmDesc struct { const ( GPIO_GET_CHIPINFO_IOCTL = 0x8044b401 ) + +const ( + IPMICTL_SEND_COMMAND = 0x8028690d + IPMICTL_RECEIVE_MSG = 0xc030690c +) + +type IPMIReq struct { + Addr *uint8 + Len uint32 + Msgid int64 + Msg IPMIMsg +} +type IPMIRecv struct { + Recv_type int32 + Addr *uint8 + Addr_len uint32 + Msgid int64 + Msg IPMIMsg +} diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_sparc64.go b/vendor/golang.org/x/sys/unix/ztypes_linux_sparc64.go index 0b18075..8b72614 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_sparc64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_sparc64.go @@ -84,22 +84,20 @@ type Rusage struct { type Stat_t struct { Dev uint64 - _ uint16 Ino uint64 + Nlink uint64 Mode uint32 - Nlink uint32 Uid uint32 Gid uint32 + _ uint32 Rdev uint64 - _ uint16 Size int64 Blksize int64 Blocks int64 Atim Timespec Mtim Timespec Ctim Timespec - _ uint64 - _ uint64 + _ [3]int64 } type Dirent struct { @@ -170,6 +168,12 @@ type Msghdr struct { _ [4]byte } +type Mmsghdr struct { + Hdr Msghdr + Len uint32 + _ [4]byte +} + type Cmsghdr struct { Len uint64 Level int32 @@ -185,6 +189,7 @@ const ( SizeofSockaddrNFCLLCP = 0x60 SizeofIovec = 0x10 SizeofMsghdr = 0x38 + SizeofMmsghdr = 0x40 SizeofCmsghdr = 0x10 ) @@ -681,7 +686,18 @@ const ( ) const ( - PIDFD_NONBLOCK = 0x4000 + PIDFD_NONBLOCK = 0x4000 + PIDFD_THREAD = 0x800 + PIDFD_GET_CGROUP_NAMESPACE = 0x2000ff01 + PIDFD_GET_IPC_NAMESPACE = 0x2000ff02 + PIDFD_GET_MNT_NAMESPACE = 0x2000ff03 + PIDFD_GET_NET_NAMESPACE = 0x2000ff04 + PIDFD_GET_PID_NAMESPACE = 0x2000ff05 + PIDFD_GET_PID_FOR_CHILDREN_NAMESPACE = 0x2000ff06 + PIDFD_GET_TIME_NAMESPACE = 0x2000ff07 + PIDFD_GET_TIME_FOR_CHILDREN_NAMESPACE = 0x2000ff08 + PIDFD_GET_USER_NAMESPACE = 0x2000ff09 + PIDFD_GET_UTS_NAMESPACE = 0x2000ff0a ) type SysvIpcPerm struct { @@ -712,3 +728,22 @@ type SysvShmDesc struct { const ( GPIO_GET_CHIPINFO_IOCTL = 0x4044b401 ) + +const ( + IPMICTL_SEND_COMMAND = 0x4028690d + IPMICTL_RECEIVE_MSG = 0xc030690c +) + +type IPMIReq struct { + Addr *uint8 + Len uint32 + Msgid int64 + Msg IPMIMsg +} +type IPMIRecv struct { + Recv_type int32 + Addr *uint8 + Addr_len uint32 + Msgid int64 + Msg IPMIMsg +} diff --git a/vendor/golang.org/x/sys/unix/ztypes_zos_s390x.go b/vendor/golang.org/x/sys/unix/ztypes_zos_s390x.go index 2e5d5a4..80d4c95 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_zos_s390x.go +++ b/vendor/golang.org/x/sys/unix/ztypes_zos_s390x.go @@ -209,6 +209,84 @@ type TCPInfo struct { Total_retrans uint32 } +// Ptrace structures for z/OS + +type PtraceRegs struct { + Psw PtracePsw + Gprs [16]uint64 + Acrs [16]uint32 + Orig_gpr2 uint64 + Fp_regs PtraceFpregs + Per_info PtracePer + Ieee_instruction_pointer uint64 +} + +type PtracePsw struct { + Mask uint64 + Addr uint64 +} + +type PtraceFpregs struct { + Fpc uint32 + Fprs [16]float64 +} + +type PtracePer struct { + Control_regs [3]uint64 + _ [8]byte + Starting_addr uint64 + Ending_addr uint64 + Perc_atmid uint16 + Address uint64 + Access_id uint8 + _ [7]byte +} + +// PT_BLOCKREQ structures for block ptrace requests +// Layout matches BPXYPTRC HLASM macro (PtBR_GPR + PtBR_GPR_EXT): +// +// Offset 0-1: Writebitflags (PtBR_GPR_CntlGPR, 2 bytes) +// Offset 2-3: Wpsw (PtBR_GPR_CntlMisc, 2 bytes with WPSW bit flag) +// Offset 4-15: Reserved (12 bytes) +// Offset 16-79: Gpr (64 bytes, 16 GPRs) +// Offset 80-143: Ctl (64 bytes, 16 CRs) +// Offset 144-151: Psw old format (8 bytes, PtBR_GPR_PSW) +// Offset 152-167: Pswg extended (16 bytes, PtBR_GPR_PSWG for 64-bit) +// Total: 168 bytes (base 152 + extended 16) +type PtraceBlkGpr struct { + Writebitflags uint16 // 2 bytes at offset 0 (PtBR_GPR_CntlGPR) + Wpsw uint16 // 2 bytes at offset 2 (PtBR_GPR_CntlMisc with WPSW flag) + _ [12]byte // 12 bytes reserved (offset 4-15) + Gpr [16]uint32 // 64 bytes at offset 16 (GPRs) + Ctl [16]uint32 // 64 bytes at offset 80 (CRs) + Psw [8]byte // 8 bytes at offset 144 (old PSW format) + Pswg [16]byte // 16 bytes at offset 152 (extended PSWG) + // Total: 2+2+12+64+64+8+16 = 168 bytes +} + +type PtraceBlkReqReq struct { + Reqtype int32 + Reqstat int32 + Reqdata uint32 + _ [4]byte +} + +type PtraceBlkReq struct { + Numreq int32 + _ [12]byte +} + +// PT_READ_U structures for reading user area (control info) +type PtraceBlkUarOcw struct { + Ofs uint32 // Control information offset + Ctl uint32 // Control information +} + +type PtraceBlkUar struct { + Num uint32 // Number of entries + _ [4]byte +} + type _Gid_t uint32 type rusage_zos struct { diff --git a/vendor/golang.org/x/sys/windows/memory_windows.go b/vendor/golang.org/x/sys/windows/memory_windows.go index 6dc0920..1adb607 100644 --- a/vendor/golang.org/x/sys/windows/memory_windows.go +++ b/vendor/golang.org/x/sys/windows/memory_windows.go @@ -35,14 +35,3 @@ const ( QUOTA_LIMITS_HARDWS_MAX_DISABLE = 0x00000008 QUOTA_LIMITS_HARDWS_MAX_ENABLE = 0x00000004 ) - -type MemoryBasicInformation struct { - BaseAddress uintptr - AllocationBase uintptr - AllocationProtect uint32 - PartitionId uint16 - RegionSize uintptr - State uint32 - Protect uint32 - Type uint32 -} diff --git a/vendor/golang.org/x/sys/windows/registry/zsyscall_windows.go b/vendor/golang.org/x/sys/windows/registry/zsyscall_windows.go index bc1ce43..59a6eb1 100644 --- a/vendor/golang.org/x/sys/windows/registry/zsyscall_windows.go +++ b/vendor/golang.org/x/sys/windows/registry/zsyscall_windows.go @@ -53,56 +53,56 @@ var ( func regConnectRegistry(machinename *uint16, key syscall.Handle, result *syscall.Handle) (regerrno error) { r0, _, _ := syscall.SyscallN(procRegConnectRegistryW.Addr(), uintptr(unsafe.Pointer(machinename)), uintptr(key), uintptr(unsafe.Pointer(result))) - if r0 != 0 { - regerrno = syscall.Errno(r0) + if uint32(r0) != 0 { + regerrno = syscall.Errno(uint32(r0)) } return } func regCreateKeyEx(key syscall.Handle, subkey *uint16, reserved uint32, class *uint16, options uint32, desired uint32, sa *syscall.SecurityAttributes, result *syscall.Handle, disposition *uint32) (regerrno error) { r0, _, _ := syscall.SyscallN(procRegCreateKeyExW.Addr(), uintptr(key), uintptr(unsafe.Pointer(subkey)), uintptr(reserved), uintptr(unsafe.Pointer(class)), uintptr(options), uintptr(desired), uintptr(unsafe.Pointer(sa)), uintptr(unsafe.Pointer(result)), uintptr(unsafe.Pointer(disposition))) - if r0 != 0 { - regerrno = syscall.Errno(r0) + if uint32(r0) != 0 { + regerrno = syscall.Errno(uint32(r0)) } return } func regDeleteKey(key syscall.Handle, subkey *uint16) (regerrno error) { r0, _, _ := syscall.SyscallN(procRegDeleteKeyW.Addr(), uintptr(key), uintptr(unsafe.Pointer(subkey))) - if r0 != 0 { - regerrno = syscall.Errno(r0) + if uint32(r0) != 0 { + regerrno = syscall.Errno(uint32(r0)) } return } func regDeleteValue(key syscall.Handle, name *uint16) (regerrno error) { r0, _, _ := syscall.SyscallN(procRegDeleteValueW.Addr(), uintptr(key), uintptr(unsafe.Pointer(name))) - if r0 != 0 { - regerrno = syscall.Errno(r0) + if uint32(r0) != 0 { + regerrno = syscall.Errno(uint32(r0)) } return } func regEnumValue(key syscall.Handle, index uint32, name *uint16, nameLen *uint32, reserved *uint32, valtype *uint32, buf *byte, buflen *uint32) (regerrno error) { r0, _, _ := syscall.SyscallN(procRegEnumValueW.Addr(), uintptr(key), uintptr(index), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(nameLen)), uintptr(unsafe.Pointer(reserved)), uintptr(unsafe.Pointer(valtype)), uintptr(unsafe.Pointer(buf)), uintptr(unsafe.Pointer(buflen))) - if r0 != 0 { - regerrno = syscall.Errno(r0) + if uint32(r0) != 0 { + regerrno = syscall.Errno(uint32(r0)) } return } func regLoadMUIString(key syscall.Handle, name *uint16, buf *uint16, buflen uint32, buflenCopied *uint32, flags uint32, dir *uint16) (regerrno error) { r0, _, _ := syscall.SyscallN(procRegLoadMUIStringW.Addr(), uintptr(key), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(buf)), uintptr(buflen), uintptr(unsafe.Pointer(buflenCopied)), uintptr(flags), uintptr(unsafe.Pointer(dir))) - if r0 != 0 { - regerrno = syscall.Errno(r0) + if uint32(r0) != 0 { + regerrno = syscall.Errno(uint32(r0)) } return } func regSetValueEx(key syscall.Handle, valueName *uint16, reserved uint32, vtype uint32, buf *byte, bufsize uint32) (regerrno error) { r0, _, _ := syscall.SyscallN(procRegSetValueExW.Addr(), uintptr(key), uintptr(unsafe.Pointer(valueName)), uintptr(reserved), uintptr(vtype), uintptr(unsafe.Pointer(buf)), uintptr(bufsize)) - if r0 != 0 { - regerrno = syscall.Errno(r0) + if uint32(r0) != 0 { + regerrno = syscall.Errno(uint32(r0)) } return } diff --git a/vendor/golang.org/x/sys/windows/syscall_windows.go b/vendor/golang.org/x/sys/windows/syscall_windows.go index e6966b4..bf0ae9c 100644 --- a/vendor/golang.org/x/sys/windows/syscall_windows.go +++ b/vendor/golang.org/x/sys/windows/syscall_windows.go @@ -507,7 +507,7 @@ func CurrentThread() Handle { return Handle(^uintptr(2 - 1)) } // GetProcAddressByOrdinal retrieves the address of the exported // function from module by ordinal. func GetProcAddressByOrdinal(module Handle, ordinal uintptr) (proc uintptr, err error) { - r0, _, e1 := syscall.Syscall(procGetProcAddress.Addr(), 2, uintptr(module), ordinal, 0) + r0, _, e1 := syscall.SyscallN(procGetProcAddress.Addr(), uintptr(module), ordinal) proc = uintptr(r0) if proc == 0 { err = errnoErr(e1) @@ -1206,7 +1206,7 @@ func LoadConnectEx() error { } func connectEx(s Handle, name unsafe.Pointer, namelen int32, sendBuf *byte, sendDataLen uint32, bytesSent *uint32, overlapped *Overlapped) (err error) { - r1, _, e1 := syscall.Syscall9(connectExFunc.addr, 7, uintptr(s), uintptr(name), uintptr(namelen), uintptr(unsafe.Pointer(sendBuf)), uintptr(sendDataLen), uintptr(unsafe.Pointer(bytesSent)), uintptr(unsafe.Pointer(overlapped)), 0, 0) + r1, _, e1 := syscall.SyscallN(connectExFunc.addr, uintptr(s), uintptr(name), uintptr(namelen), uintptr(unsafe.Pointer(sendBuf)), uintptr(sendDataLen), uintptr(unsafe.Pointer(bytesSent)), uintptr(unsafe.Pointer(overlapped))) if r1 == 0 { if e1 != 0 { err = error(e1) @@ -1271,7 +1271,7 @@ func WSASendMsg(fd Handle, msg *WSAMsg, flags uint32, bytesSent *uint32, overlap if err != nil { return err } - r1, _, e1 := syscall.Syscall6(sendRecvMsgFunc.sendAddr, 6, uintptr(fd), uintptr(unsafe.Pointer(msg)), uintptr(flags), uintptr(unsafe.Pointer(bytesSent)), uintptr(unsafe.Pointer(overlapped)), uintptr(unsafe.Pointer(croutine))) + r1, _, e1 := syscall.SyscallN(sendRecvMsgFunc.sendAddr, uintptr(fd), uintptr(unsafe.Pointer(msg)), uintptr(flags), uintptr(unsafe.Pointer(bytesSent)), uintptr(unsafe.Pointer(overlapped)), uintptr(unsafe.Pointer(croutine))) if r1 == socket_error { err = errnoErr(e1) } @@ -1283,7 +1283,7 @@ func WSARecvMsg(fd Handle, msg *WSAMsg, bytesReceived *uint32, overlapped *Overl if err != nil { return err } - r1, _, e1 := syscall.Syscall6(sendRecvMsgFunc.recvAddr, 5, uintptr(fd), uintptr(unsafe.Pointer(msg)), uintptr(unsafe.Pointer(bytesReceived)), uintptr(unsafe.Pointer(overlapped)), uintptr(unsafe.Pointer(croutine)), 0) + r1, _, e1 := syscall.SyscallN(sendRecvMsgFunc.recvAddr, uintptr(fd), uintptr(unsafe.Pointer(msg)), uintptr(unsafe.Pointer(bytesReceived)), uintptr(unsafe.Pointer(overlapped)), uintptr(unsafe.Pointer(croutine))) if r1 == socket_error { err = errnoErr(e1) } @@ -1805,7 +1805,7 @@ type PSAPI_WORKING_SET_EX_BLOCK uint64 // Valid returns the validity of this page. // If this bit is 1, the subsequent members are valid; otherwise they should be ignored. func (b PSAPI_WORKING_SET_EX_BLOCK) Valid() bool { - return (b & 1) == 1 + return (b & 1) != 0 } // ShareCount is the number of processes that share this page. The maximum value of this member is 7. @@ -1822,7 +1822,7 @@ func (b PSAPI_WORKING_SET_EX_BLOCK) Win32Protection() uint64 { // Shared returns the shared status of this page. // If this bit is 1, the page can be shared. func (b PSAPI_WORKING_SET_EX_BLOCK) Shared() bool { - return (b & (1 << 15)) == 1 + return (b & (1 << 15)) != 0 } // Node is the NUMA node. The maximum value of this member is 63. @@ -1833,19 +1833,19 @@ func (b PSAPI_WORKING_SET_EX_BLOCK) Node() uint64 { // Locked returns the locked status of this page. // If this bit is 1, the virtual page is locked in physical memory. func (b PSAPI_WORKING_SET_EX_BLOCK) Locked() bool { - return (b & (1 << 22)) == 1 + return (b & (1 << 22)) != 0 } // LargePage returns the large page status of this page. // If this bit is 1, the page is a large page. func (b PSAPI_WORKING_SET_EX_BLOCK) LargePage() bool { - return (b & (1 << 23)) == 1 + return (b & (1 << 23)) != 0 } // Bad returns the bad status of this page. // If this bit is 1, the page is has been reported as bad. func (b PSAPI_WORKING_SET_EX_BLOCK) Bad() bool { - return (b & (1 << 31)) == 1 + return (b & (1 << 31)) != 0 } // intField extracts an integer field in the PSAPI_WORKING_SET_EX_BLOCK union. diff --git a/vendor/golang.org/x/sys/windows/types_windows.go b/vendor/golang.org/x/sys/windows/types_windows.go index 75a50b3..643737d 100644 --- a/vendor/golang.org/x/sys/windows/types_windows.go +++ b/vendor/golang.org/x/sys/windows/types_windows.go @@ -1065,6 +1065,7 @@ const ( SO_BROADCAST = 32 SO_LINGER = 128 SO_RCVBUF = 0x1002 + SO_SNDTIMEO = 0x1005 SO_RCVTIMEO = 0x1006 SO_SNDBUF = 0x1001 SO_UPDATE_ACCEPT_CONTEXT = 0x700b diff --git a/vendor/golang.org/x/sys/windows/types_windows_386.go b/vendor/golang.org/x/sys/windows/types_windows_386.go index 8bce3e2..b445f07 100644 --- a/vendor/golang.org/x/sys/windows/types_windows_386.go +++ b/vendor/golang.org/x/sys/windows/types_windows_386.go @@ -33,3 +33,13 @@ type JOBOBJECT_BASIC_LIMIT_INFORMATION struct { SchedulingClass uint32 _ uint32 // pad to 8 byte boundary } + +type MemoryBasicInformation struct { + BaseAddress uintptr + AllocationBase uintptr + AllocationProtect uint32 + RegionSize uintptr + State uint32 + Protect uint32 + Type uint32 +} diff --git a/vendor/golang.org/x/sys/windows/types_windows_amd64.go b/vendor/golang.org/x/sys/windows/types_windows_amd64.go index fdddc0c..1c2be24 100644 --- a/vendor/golang.org/x/sys/windows/types_windows_amd64.go +++ b/vendor/golang.org/x/sys/windows/types_windows_amd64.go @@ -32,3 +32,14 @@ type JOBOBJECT_BASIC_LIMIT_INFORMATION struct { PriorityClass uint32 SchedulingClass uint32 } + +type MemoryBasicInformation struct { + BaseAddress uintptr + AllocationBase uintptr + AllocationProtect uint32 + PartitionId uint16 + RegionSize uintptr + State uint32 + Protect uint32 + Type uint32 +} diff --git a/vendor/golang.org/x/sys/windows/types_windows_arm.go b/vendor/golang.org/x/sys/windows/types_windows_arm.go deleted file mode 100644 index 321872c..0000000 --- a/vendor/golang.org/x/sys/windows/types_windows_arm.go +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright 2018 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 windows - -type WSAData struct { - Version uint16 - HighVersion uint16 - Description [WSADESCRIPTION_LEN + 1]byte - SystemStatus [WSASYS_STATUS_LEN + 1]byte - MaxSockets uint16 - MaxUdpDg uint16 - VendorInfo *byte -} - -type Servent struct { - Name *byte - Aliases **byte - Port uint16 - Proto *byte -} - -type JOBOBJECT_BASIC_LIMIT_INFORMATION struct { - PerProcessUserTimeLimit int64 - PerJobUserTimeLimit int64 - LimitFlags uint32 - MinimumWorkingSetSize uintptr - MaximumWorkingSetSize uintptr - ActiveProcessLimit uint32 - Affinity uintptr - PriorityClass uint32 - SchedulingClass uint32 - _ uint32 // pad to 8 byte boundary -} diff --git a/vendor/golang.org/x/sys/windows/types_windows_arm64.go b/vendor/golang.org/x/sys/windows/types_windows_arm64.go index fdddc0c..1c2be24 100644 --- a/vendor/golang.org/x/sys/windows/types_windows_arm64.go +++ b/vendor/golang.org/x/sys/windows/types_windows_arm64.go @@ -32,3 +32,14 @@ type JOBOBJECT_BASIC_LIMIT_INFORMATION struct { PriorityClass uint32 SchedulingClass uint32 } + +type MemoryBasicInformation struct { + BaseAddress uintptr + AllocationBase uintptr + AllocationProtect uint32 + PartitionId uint16 + RegionSize uintptr + State uint32 + Protect uint32 + Type uint32 +} diff --git a/vendor/golang.org/x/sys/windows/zsyscall_windows.go b/vendor/golang.org/x/sys/windows/zsyscall_windows.go index 192d193..347ab61 100644 --- a/vendor/golang.org/x/sys/windows/zsyscall_windows.go +++ b/vendor/golang.org/x/sys/windows/zsyscall_windows.go @@ -589,7 +589,7 @@ func AdjustTokenGroups(token Token, resetToDefault bool, newstate *Tokengroups, _p0 = 1 } r1, _, e1 := syscall.SyscallN(procAdjustTokenGroups.Addr(), uintptr(token), uintptr(_p0), uintptr(unsafe.Pointer(newstate)), uintptr(buflen), uintptr(unsafe.Pointer(prevstate)), uintptr(unsafe.Pointer(returnlen))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -601,7 +601,7 @@ func AdjustTokenPrivileges(token Token, disableAllPrivileges bool, newstate *Tok _p0 = 1 } r1, _, e1 := syscall.SyscallN(procAdjustTokenPrivileges.Addr(), uintptr(token), uintptr(_p0), uintptr(unsafe.Pointer(newstate)), uintptr(buflen), uintptr(unsafe.Pointer(prevstate)), uintptr(unsafe.Pointer(returnlen))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -609,7 +609,7 @@ func AdjustTokenPrivileges(token Token, disableAllPrivileges bool, newstate *Tok func AllocateAndInitializeSid(identAuth *SidIdentifierAuthority, subAuth byte, subAuth0 uint32, subAuth1 uint32, subAuth2 uint32, subAuth3 uint32, subAuth4 uint32, subAuth5 uint32, subAuth6 uint32, subAuth7 uint32, sid **SID) (err error) { r1, _, e1 := syscall.SyscallN(procAllocateAndInitializeSid.Addr(), uintptr(unsafe.Pointer(identAuth)), uintptr(subAuth), uintptr(subAuth0), uintptr(subAuth1), uintptr(subAuth2), uintptr(subAuth3), uintptr(subAuth4), uintptr(subAuth5), uintptr(subAuth6), uintptr(subAuth7), uintptr(unsafe.Pointer(sid))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -617,15 +617,15 @@ func AllocateAndInitializeSid(identAuth *SidIdentifierAuthority, subAuth byte, s func buildSecurityDescriptor(owner *TRUSTEE, group *TRUSTEE, countAccessEntries uint32, accessEntries *EXPLICIT_ACCESS, countAuditEntries uint32, auditEntries *EXPLICIT_ACCESS, oldSecurityDescriptor *SECURITY_DESCRIPTOR, sizeNewSecurityDescriptor *uint32, newSecurityDescriptor **SECURITY_DESCRIPTOR) (ret error) { r0, _, _ := syscall.SyscallN(procBuildSecurityDescriptorW.Addr(), uintptr(unsafe.Pointer(owner)), uintptr(unsafe.Pointer(group)), uintptr(countAccessEntries), uintptr(unsafe.Pointer(accessEntries)), uintptr(countAuditEntries), uintptr(unsafe.Pointer(auditEntries)), uintptr(unsafe.Pointer(oldSecurityDescriptor)), uintptr(unsafe.Pointer(sizeNewSecurityDescriptor)), uintptr(unsafe.Pointer(newSecurityDescriptor))) - if r0 != 0 { - ret = syscall.Errno(r0) + if uint32(r0) != 0 { + ret = syscall.Errno(uint32(r0)) } return } func ChangeServiceConfig2(service Handle, infoLevel uint32, info *byte) (err error) { r1, _, e1 := syscall.SyscallN(procChangeServiceConfig2W.Addr(), uintptr(service), uintptr(infoLevel), uintptr(unsafe.Pointer(info))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -633,7 +633,7 @@ func ChangeServiceConfig2(service Handle, infoLevel uint32, info *byte) (err err func ChangeServiceConfig(service Handle, serviceType uint32, startType uint32, errorControl uint32, binaryPathName *uint16, loadOrderGroup *uint16, tagId *uint32, dependencies *uint16, serviceStartName *uint16, password *uint16, displayName *uint16) (err error) { r1, _, e1 := syscall.SyscallN(procChangeServiceConfigW.Addr(), uintptr(service), uintptr(serviceType), uintptr(startType), uintptr(errorControl), uintptr(unsafe.Pointer(binaryPathName)), uintptr(unsafe.Pointer(loadOrderGroup)), uintptr(unsafe.Pointer(tagId)), uintptr(unsafe.Pointer(dependencies)), uintptr(unsafe.Pointer(serviceStartName)), uintptr(unsafe.Pointer(password)), uintptr(unsafe.Pointer(displayName))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -641,7 +641,7 @@ func ChangeServiceConfig(service Handle, serviceType uint32, startType uint32, e func checkTokenMembership(tokenHandle Token, sidToCheck *SID, isMember *int32) (err error) { r1, _, e1 := syscall.SyscallN(procCheckTokenMembership.Addr(), uintptr(tokenHandle), uintptr(unsafe.Pointer(sidToCheck)), uintptr(unsafe.Pointer(isMember))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -649,7 +649,7 @@ func checkTokenMembership(tokenHandle Token, sidToCheck *SID, isMember *int32) ( func CloseServiceHandle(handle Handle) (err error) { r1, _, e1 := syscall.SyscallN(procCloseServiceHandle.Addr(), uintptr(handle)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -657,7 +657,7 @@ func CloseServiceHandle(handle Handle) (err error) { func ControlService(service Handle, control uint32, status *SERVICE_STATUS) (err error) { r1, _, e1 := syscall.SyscallN(procControlService.Addr(), uintptr(service), uintptr(control), uintptr(unsafe.Pointer(status))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -665,7 +665,7 @@ func ControlService(service Handle, control uint32, status *SERVICE_STATUS) (err func convertSecurityDescriptorToStringSecurityDescriptor(sd *SECURITY_DESCRIPTOR, revision uint32, securityInformation SECURITY_INFORMATION, str **uint16, strLen *uint32) (err error) { r1, _, e1 := syscall.SyscallN(procConvertSecurityDescriptorToStringSecurityDescriptorW.Addr(), uintptr(unsafe.Pointer(sd)), uintptr(revision), uintptr(securityInformation), uintptr(unsafe.Pointer(str)), uintptr(unsafe.Pointer(strLen))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -673,7 +673,7 @@ func convertSecurityDescriptorToStringSecurityDescriptor(sd *SECURITY_DESCRIPTOR func ConvertSidToStringSid(sid *SID, stringSid **uint16) (err error) { r1, _, e1 := syscall.SyscallN(procConvertSidToStringSidW.Addr(), uintptr(unsafe.Pointer(sid)), uintptr(unsafe.Pointer(stringSid))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -690,7 +690,7 @@ func convertStringSecurityDescriptorToSecurityDescriptor(str string, revision ui func _convertStringSecurityDescriptorToSecurityDescriptor(str *uint16, revision uint32, sd **SECURITY_DESCRIPTOR, size *uint32) (err error) { r1, _, e1 := syscall.SyscallN(procConvertStringSecurityDescriptorToSecurityDescriptorW.Addr(), uintptr(unsafe.Pointer(str)), uintptr(revision), uintptr(unsafe.Pointer(sd)), uintptr(unsafe.Pointer(size))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -698,7 +698,7 @@ func _convertStringSecurityDescriptorToSecurityDescriptor(str *uint16, revision func ConvertStringSidToSid(stringSid *uint16, sid **SID) (err error) { r1, _, e1 := syscall.SyscallN(procConvertStringSidToSidW.Addr(), uintptr(unsafe.Pointer(stringSid)), uintptr(unsafe.Pointer(sid))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -706,7 +706,7 @@ func ConvertStringSidToSid(stringSid *uint16, sid **SID) (err error) { func CopySid(destSidLen uint32, destSid *SID, srcSid *SID) (err error) { r1, _, e1 := syscall.SyscallN(procCopySid.Addr(), uintptr(destSidLen), uintptr(unsafe.Pointer(destSid)), uintptr(unsafe.Pointer(srcSid))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -718,7 +718,7 @@ func CreateProcessAsUser(token Token, appName *uint16, commandLine *uint16, proc _p0 = 1 } r1, _, e1 := syscall.SyscallN(procCreateProcessAsUserW.Addr(), uintptr(token), uintptr(unsafe.Pointer(appName)), uintptr(unsafe.Pointer(commandLine)), uintptr(unsafe.Pointer(procSecurity)), uintptr(unsafe.Pointer(threadSecurity)), uintptr(_p0), uintptr(creationFlags), uintptr(unsafe.Pointer(env)), uintptr(unsafe.Pointer(currentDir)), uintptr(unsafe.Pointer(startupInfo)), uintptr(unsafe.Pointer(outProcInfo))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -735,7 +735,7 @@ func CreateService(mgr Handle, serviceName *uint16, displayName *uint16, access func createWellKnownSid(sidType WELL_KNOWN_SID_TYPE, domainSid *SID, sid *SID, sizeSid *uint32) (err error) { r1, _, e1 := syscall.SyscallN(procCreateWellKnownSid.Addr(), uintptr(sidType), uintptr(unsafe.Pointer(domainSid)), uintptr(unsafe.Pointer(sid)), uintptr(unsafe.Pointer(sizeSid))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -743,7 +743,7 @@ func createWellKnownSid(sidType WELL_KNOWN_SID_TYPE, domainSid *SID, sid *SID, s func CryptAcquireContext(provhandle *Handle, container *uint16, provider *uint16, provtype uint32, flags uint32) (err error) { r1, _, e1 := syscall.SyscallN(procCryptAcquireContextW.Addr(), uintptr(unsafe.Pointer(provhandle)), uintptr(unsafe.Pointer(container)), uintptr(unsafe.Pointer(provider)), uintptr(provtype), uintptr(flags)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -751,7 +751,7 @@ func CryptAcquireContext(provhandle *Handle, container *uint16, provider *uint16 func CryptGenRandom(provhandle Handle, buflen uint32, buf *byte) (err error) { r1, _, e1 := syscall.SyscallN(procCryptGenRandom.Addr(), uintptr(provhandle), uintptr(buflen), uintptr(unsafe.Pointer(buf))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -759,7 +759,7 @@ func CryptGenRandom(provhandle Handle, buflen uint32, buf *byte) (err error) { func CryptReleaseContext(provhandle Handle, flags uint32) (err error) { r1, _, e1 := syscall.SyscallN(procCryptReleaseContext.Addr(), uintptr(provhandle), uintptr(flags)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -767,7 +767,7 @@ func CryptReleaseContext(provhandle Handle, flags uint32) (err error) { func DeleteService(service Handle) (err error) { r1, _, e1 := syscall.SyscallN(procDeleteService.Addr(), uintptr(service)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -775,7 +775,7 @@ func DeleteService(service Handle) (err error) { func DeregisterEventSource(handle Handle) (err error) { r1, _, e1 := syscall.SyscallN(procDeregisterEventSource.Addr(), uintptr(handle)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -783,7 +783,7 @@ func DeregisterEventSource(handle Handle) (err error) { func DuplicateTokenEx(existingToken Token, desiredAccess uint32, tokenAttributes *SecurityAttributes, impersonationLevel uint32, tokenType uint32, newToken *Token) (err error) { r1, _, e1 := syscall.SyscallN(procDuplicateTokenEx.Addr(), uintptr(existingToken), uintptr(desiredAccess), uintptr(unsafe.Pointer(tokenAttributes)), uintptr(impersonationLevel), uintptr(tokenType), uintptr(unsafe.Pointer(newToken))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -791,7 +791,7 @@ func DuplicateTokenEx(existingToken Token, desiredAccess uint32, tokenAttributes func EnumDependentServices(service Handle, activityState uint32, services *ENUM_SERVICE_STATUS, buffSize uint32, bytesNeeded *uint32, servicesReturned *uint32) (err error) { r1, _, e1 := syscall.SyscallN(procEnumDependentServicesW.Addr(), uintptr(service), uintptr(activityState), uintptr(unsafe.Pointer(services)), uintptr(buffSize), uintptr(unsafe.Pointer(bytesNeeded)), uintptr(unsafe.Pointer(servicesReturned))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -799,7 +799,7 @@ func EnumDependentServices(service Handle, activityState uint32, services *ENUM_ func EnumServicesStatusEx(mgr Handle, infoLevel uint32, serviceType uint32, serviceState uint32, services *byte, bufSize uint32, bytesNeeded *uint32, servicesReturned *uint32, resumeHandle *uint32, groupName *uint16) (err error) { r1, _, e1 := syscall.SyscallN(procEnumServicesStatusExW.Addr(), uintptr(mgr), uintptr(infoLevel), uintptr(serviceType), uintptr(serviceState), uintptr(unsafe.Pointer(services)), uintptr(bufSize), uintptr(unsafe.Pointer(bytesNeeded)), uintptr(unsafe.Pointer(servicesReturned)), uintptr(unsafe.Pointer(resumeHandle)), uintptr(unsafe.Pointer(groupName))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -807,7 +807,7 @@ func EnumServicesStatusEx(mgr Handle, infoLevel uint32, serviceType uint32, serv func EqualSid(sid1 *SID, sid2 *SID) (isEqual bool) { r0, _, _ := syscall.SyscallN(procEqualSid.Addr(), uintptr(unsafe.Pointer(sid1)), uintptr(unsafe.Pointer(sid2))) - isEqual = r0 != 0 + isEqual = uint32(r0) != 0 return } @@ -821,7 +821,7 @@ func FreeSid(sid *SID) (err error) { func GetAce(acl *ACL, aceIndex uint32, pAce **ACCESS_ALLOWED_ACE) (err error) { r1, _, e1 := syscall.SyscallN(procGetAce.Addr(), uintptr(unsafe.Pointer(acl)), uintptr(aceIndex), uintptr(unsafe.Pointer(pAce))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -844,15 +844,15 @@ func getNamedSecurityInfo(objectName string, objectType SE_OBJECT_TYPE, security func _getNamedSecurityInfo(objectName *uint16, objectType SE_OBJECT_TYPE, securityInformation SECURITY_INFORMATION, owner **SID, group **SID, dacl **ACL, sacl **ACL, sd **SECURITY_DESCRIPTOR) (ret error) { r0, _, _ := syscall.SyscallN(procGetNamedSecurityInfoW.Addr(), uintptr(unsafe.Pointer(objectName)), uintptr(objectType), uintptr(securityInformation), uintptr(unsafe.Pointer(owner)), uintptr(unsafe.Pointer(group)), uintptr(unsafe.Pointer(dacl)), uintptr(unsafe.Pointer(sacl)), uintptr(unsafe.Pointer(sd))) - if r0 != 0 { - ret = syscall.Errno(r0) + if uint32(r0) != 0 { + ret = syscall.Errno(uint32(r0)) } return } func getSecurityDescriptorControl(sd *SECURITY_DESCRIPTOR, control *SECURITY_DESCRIPTOR_CONTROL, revision *uint32) (err error) { r1, _, e1 := syscall.SyscallN(procGetSecurityDescriptorControl.Addr(), uintptr(unsafe.Pointer(sd)), uintptr(unsafe.Pointer(control)), uintptr(unsafe.Pointer(revision))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -870,7 +870,7 @@ func getSecurityDescriptorDacl(sd *SECURITY_DESCRIPTOR, daclPresent *bool, dacl r1, _, e1 := syscall.SyscallN(procGetSecurityDescriptorDacl.Addr(), uintptr(unsafe.Pointer(sd)), uintptr(unsafe.Pointer(&_p0)), uintptr(unsafe.Pointer(dacl)), uintptr(unsafe.Pointer(&_p1))) *daclPresent = _p0 != 0 *daclDefaulted = _p1 != 0 - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -883,7 +883,7 @@ func getSecurityDescriptorGroup(sd *SECURITY_DESCRIPTOR, group **SID, groupDefau } r1, _, e1 := syscall.SyscallN(procGetSecurityDescriptorGroup.Addr(), uintptr(unsafe.Pointer(sd)), uintptr(unsafe.Pointer(group)), uintptr(unsafe.Pointer(&_p0))) *groupDefaulted = _p0 != 0 - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -902,7 +902,7 @@ func getSecurityDescriptorOwner(sd *SECURITY_DESCRIPTOR, owner **SID, ownerDefau } r1, _, e1 := syscall.SyscallN(procGetSecurityDescriptorOwner.Addr(), uintptr(unsafe.Pointer(sd)), uintptr(unsafe.Pointer(owner)), uintptr(unsafe.Pointer(&_p0))) *ownerDefaulted = _p0 != 0 - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -910,8 +910,8 @@ func getSecurityDescriptorOwner(sd *SECURITY_DESCRIPTOR, owner **SID, ownerDefau func getSecurityDescriptorRMControl(sd *SECURITY_DESCRIPTOR, rmControl *uint8) (ret error) { r0, _, _ := syscall.SyscallN(procGetSecurityDescriptorRMControl.Addr(), uintptr(unsafe.Pointer(sd)), uintptr(unsafe.Pointer(rmControl))) - if r0 != 0 { - ret = syscall.Errno(r0) + if uint32(r0) != 0 { + ret = syscall.Errno(uint32(r0)) } return } @@ -928,7 +928,7 @@ func getSecurityDescriptorSacl(sd *SECURITY_DESCRIPTOR, saclPresent *bool, sacl r1, _, e1 := syscall.SyscallN(procGetSecurityDescriptorSacl.Addr(), uintptr(unsafe.Pointer(sd)), uintptr(unsafe.Pointer(&_p0)), uintptr(unsafe.Pointer(sacl)), uintptr(unsafe.Pointer(&_p1))) *saclPresent = _p0 != 0 *saclDefaulted = _p1 != 0 - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -936,8 +936,8 @@ func getSecurityDescriptorSacl(sd *SECURITY_DESCRIPTOR, saclPresent *bool, sacl func getSecurityInfo(handle Handle, objectType SE_OBJECT_TYPE, securityInformation SECURITY_INFORMATION, owner **SID, group **SID, dacl **ACL, sacl **ACL, sd **SECURITY_DESCRIPTOR) (ret error) { r0, _, _ := syscall.SyscallN(procGetSecurityInfo.Addr(), uintptr(handle), uintptr(objectType), uintptr(securityInformation), uintptr(unsafe.Pointer(owner)), uintptr(unsafe.Pointer(group)), uintptr(unsafe.Pointer(dacl)), uintptr(unsafe.Pointer(sacl)), uintptr(unsafe.Pointer(sd))) - if r0 != 0 { - ret = syscall.Errno(r0) + if uint32(r0) != 0 { + ret = syscall.Errno(uint32(r0)) } return } @@ -962,7 +962,7 @@ func getSidSubAuthorityCount(sid *SID) (count *uint8) { func GetTokenInformation(token Token, infoClass uint32, info *byte, infoLen uint32, returnedLen *uint32) (err error) { r1, _, e1 := syscall.SyscallN(procGetTokenInformation.Addr(), uintptr(token), uintptr(infoClass), uintptr(unsafe.Pointer(info)), uintptr(infoLen), uintptr(unsafe.Pointer(returnedLen))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -970,7 +970,7 @@ func GetTokenInformation(token Token, infoClass uint32, info *byte, infoLen uint func ImpersonateSelf(impersonationlevel uint32) (err error) { r1, _, e1 := syscall.SyscallN(procImpersonateSelf.Addr(), uintptr(impersonationlevel)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -978,7 +978,7 @@ func ImpersonateSelf(impersonationlevel uint32) (err error) { func initializeSecurityDescriptor(absoluteSD *SECURITY_DESCRIPTOR, revision uint32) (err error) { r1, _, e1 := syscall.SyscallN(procInitializeSecurityDescriptor.Addr(), uintptr(unsafe.Pointer(absoluteSD)), uintptr(revision)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -994,7 +994,7 @@ func InitiateSystemShutdownEx(machineName *uint16, message *uint16, timeout uint _p1 = 1 } r1, _, e1 := syscall.SyscallN(procInitiateSystemShutdownExW.Addr(), uintptr(unsafe.Pointer(machineName)), uintptr(unsafe.Pointer(message)), uintptr(timeout), uintptr(_p0), uintptr(_p1), uintptr(reason)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -1002,7 +1002,7 @@ func InitiateSystemShutdownEx(machineName *uint16, message *uint16, timeout uint func isTokenRestricted(tokenHandle Token) (ret bool, err error) { r0, _, e1 := syscall.SyscallN(procIsTokenRestricted.Addr(), uintptr(tokenHandle)) - ret = r0 != 0 + ret = uint32(r0) != 0 if !ret { err = errnoErr(e1) } @@ -1011,25 +1011,25 @@ func isTokenRestricted(tokenHandle Token) (ret bool, err error) { func isValidSecurityDescriptor(sd *SECURITY_DESCRIPTOR) (isValid bool) { r0, _, _ := syscall.SyscallN(procIsValidSecurityDescriptor.Addr(), uintptr(unsafe.Pointer(sd))) - isValid = r0 != 0 + isValid = uint32(r0) != 0 return } func isValidSid(sid *SID) (isValid bool) { r0, _, _ := syscall.SyscallN(procIsValidSid.Addr(), uintptr(unsafe.Pointer(sid))) - isValid = r0 != 0 + isValid = uint32(r0) != 0 return } func isWellKnownSid(sid *SID, sidType WELL_KNOWN_SID_TYPE) (isWellKnown bool) { r0, _, _ := syscall.SyscallN(procIsWellKnownSid.Addr(), uintptr(unsafe.Pointer(sid)), uintptr(sidType)) - isWellKnown = r0 != 0 + isWellKnown = uint32(r0) != 0 return } func LookupAccountName(systemName *uint16, accountName *uint16, sid *SID, sidLen *uint32, refdDomainName *uint16, refdDomainNameLen *uint32, use *uint32) (err error) { r1, _, e1 := syscall.SyscallN(procLookupAccountNameW.Addr(), uintptr(unsafe.Pointer(systemName)), uintptr(unsafe.Pointer(accountName)), uintptr(unsafe.Pointer(sid)), uintptr(unsafe.Pointer(sidLen)), uintptr(unsafe.Pointer(refdDomainName)), uintptr(unsafe.Pointer(refdDomainNameLen)), uintptr(unsafe.Pointer(use))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -1037,7 +1037,7 @@ func LookupAccountName(systemName *uint16, accountName *uint16, sid *SID, sidLen func LookupAccountSid(systemName *uint16, sid *SID, name *uint16, nameLen *uint32, refdDomainName *uint16, refdDomainNameLen *uint32, use *uint32) (err error) { r1, _, e1 := syscall.SyscallN(procLookupAccountSidW.Addr(), uintptr(unsafe.Pointer(systemName)), uintptr(unsafe.Pointer(sid)), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(nameLen)), uintptr(unsafe.Pointer(refdDomainName)), uintptr(unsafe.Pointer(refdDomainNameLen)), uintptr(unsafe.Pointer(use))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -1045,7 +1045,7 @@ func LookupAccountSid(systemName *uint16, sid *SID, name *uint16, nameLen *uint3 func LookupPrivilegeValue(systemname *uint16, name *uint16, luid *LUID) (err error) { r1, _, e1 := syscall.SyscallN(procLookupPrivilegeValueW.Addr(), uintptr(unsafe.Pointer(systemname)), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(luid))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -1053,7 +1053,7 @@ func LookupPrivilegeValue(systemname *uint16, name *uint16, luid *LUID) (err err func makeAbsoluteSD(selfRelativeSD *SECURITY_DESCRIPTOR, absoluteSD *SECURITY_DESCRIPTOR, absoluteSDSize *uint32, dacl *ACL, daclSize *uint32, sacl *ACL, saclSize *uint32, owner *SID, ownerSize *uint32, group *SID, groupSize *uint32) (err error) { r1, _, e1 := syscall.SyscallN(procMakeAbsoluteSD.Addr(), uintptr(unsafe.Pointer(selfRelativeSD)), uintptr(unsafe.Pointer(absoluteSD)), uintptr(unsafe.Pointer(absoluteSDSize)), uintptr(unsafe.Pointer(dacl)), uintptr(unsafe.Pointer(daclSize)), uintptr(unsafe.Pointer(sacl)), uintptr(unsafe.Pointer(saclSize)), uintptr(unsafe.Pointer(owner)), uintptr(unsafe.Pointer(ownerSize)), uintptr(unsafe.Pointer(group)), uintptr(unsafe.Pointer(groupSize))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -1061,7 +1061,7 @@ func makeAbsoluteSD(selfRelativeSD *SECURITY_DESCRIPTOR, absoluteSD *SECURITY_DE func makeSelfRelativeSD(absoluteSD *SECURITY_DESCRIPTOR, selfRelativeSD *SECURITY_DESCRIPTOR, selfRelativeSDSize *uint32) (err error) { r1, _, e1 := syscall.SyscallN(procMakeSelfRelativeSD.Addr(), uintptr(unsafe.Pointer(absoluteSD)), uintptr(unsafe.Pointer(selfRelativeSD)), uintptr(unsafe.Pointer(selfRelativeSDSize))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -1069,15 +1069,15 @@ func makeSelfRelativeSD(absoluteSD *SECURITY_DESCRIPTOR, selfRelativeSD *SECURIT func NotifyServiceStatusChange(service Handle, notifyMask uint32, notifier *SERVICE_NOTIFY) (ret error) { r0, _, _ := syscall.SyscallN(procNotifyServiceStatusChangeW.Addr(), uintptr(service), uintptr(notifyMask), uintptr(unsafe.Pointer(notifier))) - if r0 != 0 { - ret = syscall.Errno(r0) + if uint32(r0) != 0 { + ret = syscall.Errno(uint32(r0)) } return } func OpenProcessToken(process Handle, access uint32, token *Token) (err error) { r1, _, e1 := syscall.SyscallN(procOpenProcessToken.Addr(), uintptr(process), uintptr(access), uintptr(unsafe.Pointer(token))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -1107,7 +1107,7 @@ func OpenThreadToken(thread Handle, access uint32, openAsSelf bool, token *Token _p0 = 1 } r1, _, e1 := syscall.SyscallN(procOpenThreadToken.Addr(), uintptr(thread), uintptr(access), uintptr(_p0), uintptr(unsafe.Pointer(token))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -1115,7 +1115,7 @@ func OpenThreadToken(thread Handle, access uint32, openAsSelf bool, token *Token func QueryServiceConfig2(service Handle, infoLevel uint32, buff *byte, buffSize uint32, bytesNeeded *uint32) (err error) { r1, _, e1 := syscall.SyscallN(procQueryServiceConfig2W.Addr(), uintptr(service), uintptr(infoLevel), uintptr(unsafe.Pointer(buff)), uintptr(buffSize), uintptr(unsafe.Pointer(bytesNeeded))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -1123,7 +1123,7 @@ func QueryServiceConfig2(service Handle, infoLevel uint32, buff *byte, buffSize func QueryServiceConfig(service Handle, serviceConfig *QUERY_SERVICE_CONFIG, bufSize uint32, bytesNeeded *uint32) (err error) { r1, _, e1 := syscall.SyscallN(procQueryServiceConfigW.Addr(), uintptr(service), uintptr(unsafe.Pointer(serviceConfig)), uintptr(bufSize), uintptr(unsafe.Pointer(bytesNeeded))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -1135,7 +1135,7 @@ func QueryServiceDynamicInformation(service Handle, infoLevel uint32, dynamicInf return } r1, _, e1 := syscall.SyscallN(procQueryServiceDynamicInformation.Addr(), uintptr(service), uintptr(infoLevel), uintptr(dynamicInfo)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -1143,7 +1143,7 @@ func QueryServiceDynamicInformation(service Handle, infoLevel uint32, dynamicInf func QueryServiceLockStatus(mgr Handle, lockStatus *QUERY_SERVICE_LOCK_STATUS, bufSize uint32, bytesNeeded *uint32) (err error) { r1, _, e1 := syscall.SyscallN(procQueryServiceLockStatusW.Addr(), uintptr(mgr), uintptr(unsafe.Pointer(lockStatus)), uintptr(bufSize), uintptr(unsafe.Pointer(bytesNeeded))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -1151,7 +1151,7 @@ func QueryServiceLockStatus(mgr Handle, lockStatus *QUERY_SERVICE_LOCK_STATUS, b func QueryServiceStatus(service Handle, status *SERVICE_STATUS) (err error) { r1, _, e1 := syscall.SyscallN(procQueryServiceStatus.Addr(), uintptr(service), uintptr(unsafe.Pointer(status))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -1159,7 +1159,7 @@ func QueryServiceStatus(service Handle, status *SERVICE_STATUS) (err error) { func QueryServiceStatusEx(service Handle, infoLevel uint32, buff *byte, buffSize uint32, bytesNeeded *uint32) (err error) { r1, _, e1 := syscall.SyscallN(procQueryServiceStatusEx.Addr(), uintptr(service), uintptr(infoLevel), uintptr(unsafe.Pointer(buff)), uintptr(buffSize), uintptr(unsafe.Pointer(bytesNeeded))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -1167,16 +1167,16 @@ func QueryServiceStatusEx(service Handle, infoLevel uint32, buff *byte, buffSize func RegCloseKey(key Handle) (regerrno error) { r0, _, _ := syscall.SyscallN(procRegCloseKey.Addr(), uintptr(key)) - if r0 != 0 { - regerrno = syscall.Errno(r0) + if uint32(r0) != 0 { + regerrno = syscall.Errno(uint32(r0)) } return } func RegEnumKeyEx(key Handle, index uint32, name *uint16, nameLen *uint32, reserved *uint32, class *uint16, classLen *uint32, lastWriteTime *Filetime) (regerrno error) { r0, _, _ := syscall.SyscallN(procRegEnumKeyExW.Addr(), uintptr(key), uintptr(index), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(nameLen)), uintptr(unsafe.Pointer(reserved)), uintptr(unsafe.Pointer(class)), uintptr(unsafe.Pointer(classLen)), uintptr(unsafe.Pointer(lastWriteTime))) - if r0 != 0 { - regerrno = syscall.Errno(r0) + if uint32(r0) != 0 { + regerrno = syscall.Errno(uint32(r0)) } return } @@ -1191,32 +1191,32 @@ func RegNotifyChangeKeyValue(key Handle, watchSubtree bool, notifyFilter uint32, _p1 = 1 } r0, _, _ := syscall.SyscallN(procRegNotifyChangeKeyValue.Addr(), uintptr(key), uintptr(_p0), uintptr(notifyFilter), uintptr(event), uintptr(_p1)) - if r0 != 0 { - regerrno = syscall.Errno(r0) + if uint32(r0) != 0 { + regerrno = syscall.Errno(uint32(r0)) } return } func RegOpenKeyEx(key Handle, subkey *uint16, options uint32, desiredAccess uint32, result *Handle) (regerrno error) { r0, _, _ := syscall.SyscallN(procRegOpenKeyExW.Addr(), uintptr(key), uintptr(unsafe.Pointer(subkey)), uintptr(options), uintptr(desiredAccess), uintptr(unsafe.Pointer(result))) - if r0 != 0 { - regerrno = syscall.Errno(r0) + if uint32(r0) != 0 { + regerrno = syscall.Errno(uint32(r0)) } return } func RegQueryInfoKey(key Handle, class *uint16, classLen *uint32, reserved *uint32, subkeysLen *uint32, maxSubkeyLen *uint32, maxClassLen *uint32, valuesLen *uint32, maxValueNameLen *uint32, maxValueLen *uint32, saLen *uint32, lastWriteTime *Filetime) (regerrno error) { r0, _, _ := syscall.SyscallN(procRegQueryInfoKeyW.Addr(), uintptr(key), uintptr(unsafe.Pointer(class)), uintptr(unsafe.Pointer(classLen)), uintptr(unsafe.Pointer(reserved)), uintptr(unsafe.Pointer(subkeysLen)), uintptr(unsafe.Pointer(maxSubkeyLen)), uintptr(unsafe.Pointer(maxClassLen)), uintptr(unsafe.Pointer(valuesLen)), uintptr(unsafe.Pointer(maxValueNameLen)), uintptr(unsafe.Pointer(maxValueLen)), uintptr(unsafe.Pointer(saLen)), uintptr(unsafe.Pointer(lastWriteTime))) - if r0 != 0 { - regerrno = syscall.Errno(r0) + if uint32(r0) != 0 { + regerrno = syscall.Errno(uint32(r0)) } return } func RegQueryValueEx(key Handle, name *uint16, reserved *uint32, valtype *uint32, buf *byte, buflen *uint32) (regerrno error) { r0, _, _ := syscall.SyscallN(procRegQueryValueExW.Addr(), uintptr(key), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(reserved)), uintptr(unsafe.Pointer(valtype)), uintptr(unsafe.Pointer(buf)), uintptr(unsafe.Pointer(buflen))) - if r0 != 0 { - regerrno = syscall.Errno(r0) + if uint32(r0) != 0 { + regerrno = syscall.Errno(uint32(r0)) } return } @@ -1241,7 +1241,7 @@ func RegisterServiceCtrlHandlerEx(serviceName *uint16, handlerProc uintptr, cont func ReportEvent(log Handle, etype uint16, category uint16, eventId uint32, usrSId uintptr, numStrings uint16, dataSize uint32, strings **uint16, rawData *byte) (err error) { r1, _, e1 := syscall.SyscallN(procReportEventW.Addr(), uintptr(log), uintptr(etype), uintptr(category), uintptr(eventId), uintptr(usrSId), uintptr(numStrings), uintptr(dataSize), uintptr(unsafe.Pointer(strings)), uintptr(unsafe.Pointer(rawData))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -1249,7 +1249,7 @@ func ReportEvent(log Handle, etype uint16, category uint16, eventId uint32, usrS func RevertToSelf() (err error) { r1, _, e1 := syscall.SyscallN(procRevertToSelf.Addr()) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -1257,15 +1257,15 @@ func RevertToSelf() (err error) { func setEntriesInAcl(countExplicitEntries uint32, explicitEntries *EXPLICIT_ACCESS, oldACL *ACL, newACL **ACL) (ret error) { r0, _, _ := syscall.SyscallN(procSetEntriesInAclW.Addr(), uintptr(countExplicitEntries), uintptr(unsafe.Pointer(explicitEntries)), uintptr(unsafe.Pointer(oldACL)), uintptr(unsafe.Pointer(newACL))) - if r0 != 0 { - ret = syscall.Errno(r0) + if uint32(r0) != 0 { + ret = syscall.Errno(uint32(r0)) } return } func SetKernelObjectSecurity(handle Handle, securityInformation SECURITY_INFORMATION, securityDescriptor *SECURITY_DESCRIPTOR) (err error) { r1, _, e1 := syscall.SyscallN(procSetKernelObjectSecurity.Addr(), uintptr(handle), uintptr(securityInformation), uintptr(unsafe.Pointer(securityDescriptor))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -1282,15 +1282,15 @@ func SetNamedSecurityInfo(objectName string, objectType SE_OBJECT_TYPE, security func _SetNamedSecurityInfo(objectName *uint16, objectType SE_OBJECT_TYPE, securityInformation SECURITY_INFORMATION, owner *SID, group *SID, dacl *ACL, sacl *ACL) (ret error) { r0, _, _ := syscall.SyscallN(procSetNamedSecurityInfoW.Addr(), uintptr(unsafe.Pointer(objectName)), uintptr(objectType), uintptr(securityInformation), uintptr(unsafe.Pointer(owner)), uintptr(unsafe.Pointer(group)), uintptr(unsafe.Pointer(dacl)), uintptr(unsafe.Pointer(sacl))) - if r0 != 0 { - ret = syscall.Errno(r0) + if uint32(r0) != 0 { + ret = syscall.Errno(uint32(r0)) } return } func setSecurityDescriptorControl(sd *SECURITY_DESCRIPTOR, controlBitsOfInterest SECURITY_DESCRIPTOR_CONTROL, controlBitsToSet SECURITY_DESCRIPTOR_CONTROL) (err error) { r1, _, e1 := syscall.SyscallN(procSetSecurityDescriptorControl.Addr(), uintptr(unsafe.Pointer(sd)), uintptr(controlBitsOfInterest), uintptr(controlBitsToSet)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -1306,7 +1306,7 @@ func setSecurityDescriptorDacl(sd *SECURITY_DESCRIPTOR, daclPresent bool, dacl * _p1 = 1 } r1, _, e1 := syscall.SyscallN(procSetSecurityDescriptorDacl.Addr(), uintptr(unsafe.Pointer(sd)), uintptr(_p0), uintptr(unsafe.Pointer(dacl)), uintptr(_p1)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -1318,7 +1318,7 @@ func setSecurityDescriptorGroup(sd *SECURITY_DESCRIPTOR, group *SID, groupDefaul _p0 = 1 } r1, _, e1 := syscall.SyscallN(procSetSecurityDescriptorGroup.Addr(), uintptr(unsafe.Pointer(sd)), uintptr(unsafe.Pointer(group)), uintptr(_p0)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -1330,7 +1330,7 @@ func setSecurityDescriptorOwner(sd *SECURITY_DESCRIPTOR, owner *SID, ownerDefaul _p0 = 1 } r1, _, e1 := syscall.SyscallN(procSetSecurityDescriptorOwner.Addr(), uintptr(unsafe.Pointer(sd)), uintptr(unsafe.Pointer(owner)), uintptr(_p0)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -1351,7 +1351,7 @@ func setSecurityDescriptorSacl(sd *SECURITY_DESCRIPTOR, saclPresent bool, sacl * _p1 = 1 } r1, _, e1 := syscall.SyscallN(procSetSecurityDescriptorSacl.Addr(), uintptr(unsafe.Pointer(sd)), uintptr(_p0), uintptr(unsafe.Pointer(sacl)), uintptr(_p1)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -1359,15 +1359,15 @@ func setSecurityDescriptorSacl(sd *SECURITY_DESCRIPTOR, saclPresent bool, sacl * func SetSecurityInfo(handle Handle, objectType SE_OBJECT_TYPE, securityInformation SECURITY_INFORMATION, owner *SID, group *SID, dacl *ACL, sacl *ACL) (ret error) { r0, _, _ := syscall.SyscallN(procSetSecurityInfo.Addr(), uintptr(handle), uintptr(objectType), uintptr(securityInformation), uintptr(unsafe.Pointer(owner)), uintptr(unsafe.Pointer(group)), uintptr(unsafe.Pointer(dacl)), uintptr(unsafe.Pointer(sacl))) - if r0 != 0 { - ret = syscall.Errno(r0) + if uint32(r0) != 0 { + ret = syscall.Errno(uint32(r0)) } return } func SetServiceStatus(service Handle, serviceStatus *SERVICE_STATUS) (err error) { r1, _, e1 := syscall.SyscallN(procSetServiceStatus.Addr(), uintptr(service), uintptr(unsafe.Pointer(serviceStatus))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -1375,7 +1375,7 @@ func SetServiceStatus(service Handle, serviceStatus *SERVICE_STATUS) (err error) func SetThreadToken(thread *Handle, token Token) (err error) { r1, _, e1 := syscall.SyscallN(procSetThreadToken.Addr(), uintptr(unsafe.Pointer(thread)), uintptr(token)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -1383,7 +1383,7 @@ func SetThreadToken(thread *Handle, token Token) (err error) { func SetTokenInformation(token Token, infoClass uint32, info *byte, infoLen uint32) (err error) { r1, _, e1 := syscall.SyscallN(procSetTokenInformation.Addr(), uintptr(token), uintptr(infoClass), uintptr(unsafe.Pointer(info)), uintptr(infoLen)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -1391,7 +1391,7 @@ func SetTokenInformation(token Token, infoClass uint32, info *byte, infoLen uint func StartServiceCtrlDispatcher(serviceTable *SERVICE_TABLE_ENTRY) (err error) { r1, _, e1 := syscall.SyscallN(procStartServiceCtrlDispatcherW.Addr(), uintptr(unsafe.Pointer(serviceTable))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -1399,7 +1399,7 @@ func StartServiceCtrlDispatcher(serviceTable *SERVICE_TABLE_ENTRY) (err error) { func StartService(service Handle, numArgs uint32, argVectors **uint16) (err error) { r1, _, e1 := syscall.SyscallN(procStartServiceW.Addr(), uintptr(service), uintptr(numArgs), uintptr(unsafe.Pointer(argVectors))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -1407,7 +1407,7 @@ func StartService(service Handle, numArgs uint32, argVectors **uint16) (err erro func CertAddCertificateContextToStore(store Handle, certContext *CertContext, addDisposition uint32, storeContext **CertContext) (err error) { r1, _, e1 := syscall.SyscallN(procCertAddCertificateContextToStore.Addr(), uintptr(store), uintptr(unsafe.Pointer(certContext)), uintptr(addDisposition), uintptr(unsafe.Pointer(storeContext))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -1415,7 +1415,7 @@ func CertAddCertificateContextToStore(store Handle, certContext *CertContext, ad func CertCloseStore(store Handle, flags uint32) (err error) { r1, _, e1 := syscall.SyscallN(procCertCloseStore.Addr(), uintptr(store), uintptr(flags)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -1432,7 +1432,7 @@ func CertCreateCertificateContext(certEncodingType uint32, certEncoded *byte, en func CertDeleteCertificateFromStore(certContext *CertContext) (err error) { r1, _, e1 := syscall.SyscallN(procCertDeleteCertificateFromStore.Addr(), uintptr(unsafe.Pointer(certContext))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -1484,7 +1484,7 @@ func CertFreeCertificateChain(ctx *CertChainContext) { func CertFreeCertificateContext(ctx *CertContext) (err error) { r1, _, e1 := syscall.SyscallN(procCertFreeCertificateContext.Addr(), uintptr(unsafe.Pointer(ctx))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -1492,7 +1492,7 @@ func CertFreeCertificateContext(ctx *CertContext) (err error) { func CertGetCertificateChain(engine Handle, leaf *CertContext, time *Filetime, additionalStore Handle, para *CertChainPara, flags uint32, reserved uintptr, chainCtx **CertChainContext) (err error) { r1, _, e1 := syscall.SyscallN(procCertGetCertificateChain.Addr(), uintptr(engine), uintptr(unsafe.Pointer(leaf)), uintptr(unsafe.Pointer(time)), uintptr(additionalStore), uintptr(unsafe.Pointer(para)), uintptr(flags), uintptr(reserved), uintptr(unsafe.Pointer(chainCtx))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -1524,7 +1524,7 @@ func CertOpenSystemStore(hprov Handle, name *uint16) (store Handle, err error) { func CertVerifyCertificateChainPolicy(policyOID uintptr, chain *CertChainContext, para *CertChainPolicyPara, status *CertChainPolicyStatus) (err error) { r1, _, e1 := syscall.SyscallN(procCertVerifyCertificateChainPolicy.Addr(), uintptr(policyOID), uintptr(unsafe.Pointer(chain)), uintptr(unsafe.Pointer(para)), uintptr(unsafe.Pointer(status))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -1537,7 +1537,7 @@ func CryptAcquireCertificatePrivateKey(cert *CertContext, flags uint32, paramete } r1, _, e1 := syscall.SyscallN(procCryptAcquireCertificatePrivateKey.Addr(), uintptr(unsafe.Pointer(cert)), uintptr(flags), uintptr(parameters), uintptr(unsafe.Pointer(cryptProvOrNCryptKey)), uintptr(unsafe.Pointer(keySpec)), uintptr(unsafe.Pointer(&_p0))) *callerFreeProvOrNCryptKey = _p0 != 0 - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -1545,7 +1545,7 @@ func CryptAcquireCertificatePrivateKey(cert *CertContext, flags uint32, paramete func CryptDecodeObject(encodingType uint32, structType *byte, encodedBytes *byte, lenEncodedBytes uint32, flags uint32, decoded unsafe.Pointer, decodedLen *uint32) (err error) { r1, _, e1 := syscall.SyscallN(procCryptDecodeObject.Addr(), uintptr(encodingType), uintptr(unsafe.Pointer(structType)), uintptr(unsafe.Pointer(encodedBytes)), uintptr(lenEncodedBytes), uintptr(flags), uintptr(decoded), uintptr(unsafe.Pointer(decodedLen))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -1553,7 +1553,7 @@ func CryptDecodeObject(encodingType uint32, structType *byte, encodedBytes *byte func CryptProtectData(dataIn *DataBlob, name *uint16, optionalEntropy *DataBlob, reserved uintptr, promptStruct *CryptProtectPromptStruct, flags uint32, dataOut *DataBlob) (err error) { r1, _, e1 := syscall.SyscallN(procCryptProtectData.Addr(), uintptr(unsafe.Pointer(dataIn)), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(optionalEntropy)), uintptr(reserved), uintptr(unsafe.Pointer(promptStruct)), uintptr(flags), uintptr(unsafe.Pointer(dataOut))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -1561,7 +1561,7 @@ func CryptProtectData(dataIn *DataBlob, name *uint16, optionalEntropy *DataBlob, func CryptQueryObject(objectType uint32, object unsafe.Pointer, expectedContentTypeFlags uint32, expectedFormatTypeFlags uint32, flags uint32, msgAndCertEncodingType *uint32, contentType *uint32, formatType *uint32, certStore *Handle, msg *Handle, context *unsafe.Pointer) (err error) { r1, _, e1 := syscall.SyscallN(procCryptQueryObject.Addr(), uintptr(objectType), uintptr(object), uintptr(expectedContentTypeFlags), uintptr(expectedFormatTypeFlags), uintptr(flags), uintptr(unsafe.Pointer(msgAndCertEncodingType)), uintptr(unsafe.Pointer(contentType)), uintptr(unsafe.Pointer(formatType)), uintptr(unsafe.Pointer(certStore)), uintptr(unsafe.Pointer(msg)), uintptr(unsafe.Pointer(context))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -1569,7 +1569,7 @@ func CryptQueryObject(objectType uint32, object unsafe.Pointer, expectedContentT func CryptUnprotectData(dataIn *DataBlob, name **uint16, optionalEntropy *DataBlob, reserved uintptr, promptStruct *CryptProtectPromptStruct, flags uint32, dataOut *DataBlob) (err error) { r1, _, e1 := syscall.SyscallN(procCryptUnprotectData.Addr(), uintptr(unsafe.Pointer(dataIn)), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(optionalEntropy)), uintptr(reserved), uintptr(unsafe.Pointer(promptStruct)), uintptr(flags), uintptr(unsafe.Pointer(dataOut))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -1586,7 +1586,7 @@ func PFXImportCertStore(pfx *CryptDataBlob, password *uint16, flags uint32) (sto func DnsNameCompare(name1 *uint16, name2 *uint16) (same bool) { r0, _, _ := syscall.SyscallN(procDnsNameCompare_W.Addr(), uintptr(unsafe.Pointer(name1)), uintptr(unsafe.Pointer(name2))) - same = r0 != 0 + same = uint32(r0) != 0 return } @@ -1601,8 +1601,8 @@ func DnsQuery(name string, qtype uint16, options uint32, extra *byte, qrs **DNSR func _DnsQuery(name *uint16, qtype uint16, options uint32, extra *byte, qrs **DNSRecord, pr *byte) (status error) { r0, _, _ := syscall.SyscallN(procDnsQuery_W.Addr(), uintptr(unsafe.Pointer(name)), uintptr(qtype), uintptr(options), uintptr(unsafe.Pointer(extra)), uintptr(unsafe.Pointer(qrs)), uintptr(unsafe.Pointer(pr))) - if r0 != 0 { - status = syscall.Errno(r0) + if uint32(r0) != 0 { + status = syscall.Errno(uint32(r0)) } return } @@ -1614,24 +1614,24 @@ func DnsRecordListFree(rl *DNSRecord, freetype uint32) { func DwmGetWindowAttribute(hwnd HWND, attribute uint32, value unsafe.Pointer, size uint32) (ret error) { r0, _, _ := syscall.SyscallN(procDwmGetWindowAttribute.Addr(), uintptr(hwnd), uintptr(attribute), uintptr(value), uintptr(size)) - if r0 != 0 { - ret = syscall.Errno(r0) + if uint32(r0) != 0 { + ret = syscall.Errno(uint32(r0)) } return } func DwmSetWindowAttribute(hwnd HWND, attribute uint32, value unsafe.Pointer, size uint32) (ret error) { r0, _, _ := syscall.SyscallN(procDwmSetWindowAttribute.Addr(), uintptr(hwnd), uintptr(attribute), uintptr(value), uintptr(size)) - if r0 != 0 { - ret = syscall.Errno(r0) + if uint32(r0) != 0 { + ret = syscall.Errno(uint32(r0)) } return } func CancelMibChangeNotify2(notificationHandle Handle) (errcode error) { r0, _, _ := syscall.SyscallN(procCancelMibChangeNotify2.Addr(), uintptr(notificationHandle)) - if r0 != 0 { - errcode = syscall.Errno(r0) + if uint32(r0) != 0 { + errcode = syscall.Errno(uint32(r0)) } return } @@ -1643,96 +1643,96 @@ func FreeMibTable(memory unsafe.Pointer) { func GetAdaptersAddresses(family uint32, flags uint32, reserved uintptr, adapterAddresses *IpAdapterAddresses, sizePointer *uint32) (errcode error) { r0, _, _ := syscall.SyscallN(procGetAdaptersAddresses.Addr(), uintptr(family), uintptr(flags), uintptr(reserved), uintptr(unsafe.Pointer(adapterAddresses)), uintptr(unsafe.Pointer(sizePointer))) - if r0 != 0 { - errcode = syscall.Errno(r0) + if uint32(r0) != 0 { + errcode = syscall.Errno(uint32(r0)) } return } func GetAdaptersInfo(ai *IpAdapterInfo, ol *uint32) (errcode error) { r0, _, _ := syscall.SyscallN(procGetAdaptersInfo.Addr(), uintptr(unsafe.Pointer(ai)), uintptr(unsafe.Pointer(ol))) - if r0 != 0 { - errcode = syscall.Errno(r0) + if uint32(r0) != 0 { + errcode = syscall.Errno(uint32(r0)) } return } func getBestInterfaceEx(sockaddr unsafe.Pointer, pdwBestIfIndex *uint32) (errcode error) { r0, _, _ := syscall.SyscallN(procGetBestInterfaceEx.Addr(), uintptr(sockaddr), uintptr(unsafe.Pointer(pdwBestIfIndex))) - if r0 != 0 { - errcode = syscall.Errno(r0) + if uint32(r0) != 0 { + errcode = syscall.Errno(uint32(r0)) } return } func GetIfEntry(pIfRow *MibIfRow) (errcode error) { r0, _, _ := syscall.SyscallN(procGetIfEntry.Addr(), uintptr(unsafe.Pointer(pIfRow))) - if r0 != 0 { - errcode = syscall.Errno(r0) + if uint32(r0) != 0 { + errcode = syscall.Errno(uint32(r0)) } return } func GetIfEntry2Ex(level uint32, row *MibIfRow2) (errcode error) { r0, _, _ := syscall.SyscallN(procGetIfEntry2Ex.Addr(), uintptr(level), uintptr(unsafe.Pointer(row))) - if r0 != 0 { - errcode = syscall.Errno(r0) + if uint32(r0) != 0 { + errcode = syscall.Errno(uint32(r0)) } return } func GetIfTable2Ex(level uint32, table **MibIfTable2) (errcode error) { r0, _, _ := syscall.SyscallN(procGetIfTable2Ex.Addr(), uintptr(level), uintptr(unsafe.Pointer(table))) - if r0 != 0 { - errcode = syscall.Errno(r0) + if uint32(r0) != 0 { + errcode = syscall.Errno(uint32(r0)) } return } func GetIpForwardEntry2(row *MibIpForwardRow2) (errcode error) { r0, _, _ := syscall.SyscallN(procGetIpForwardEntry2.Addr(), uintptr(unsafe.Pointer(row))) - if r0 != 0 { - errcode = syscall.Errno(r0) + if uint32(r0) != 0 { + errcode = syscall.Errno(uint32(r0)) } return } func GetIpForwardTable2(family uint16, table **MibIpForwardTable2) (errcode error) { r0, _, _ := syscall.SyscallN(procGetIpForwardTable2.Addr(), uintptr(family), uintptr(unsafe.Pointer(table))) - if r0 != 0 { - errcode = syscall.Errno(r0) + if uint32(r0) != 0 { + errcode = syscall.Errno(uint32(r0)) } return } func GetIpInterfaceEntry(row *MibIpInterfaceRow) (errcode error) { r0, _, _ := syscall.SyscallN(procGetIpInterfaceEntry.Addr(), uintptr(unsafe.Pointer(row))) - if r0 != 0 { - errcode = syscall.Errno(r0) + if uint32(r0) != 0 { + errcode = syscall.Errno(uint32(r0)) } return } func GetIpInterfaceTable(family uint16, table **MibIpInterfaceTable) (errcode error) { r0, _, _ := syscall.SyscallN(procGetIpInterfaceTable.Addr(), uintptr(family), uintptr(unsafe.Pointer(table))) - if r0 != 0 { - errcode = syscall.Errno(r0) + if uint32(r0) != 0 { + errcode = syscall.Errno(uint32(r0)) } return } func GetUnicastIpAddressEntry(row *MibUnicastIpAddressRow) (errcode error) { r0, _, _ := syscall.SyscallN(procGetUnicastIpAddressEntry.Addr(), uintptr(unsafe.Pointer(row))) - if r0 != 0 { - errcode = syscall.Errno(r0) + if uint32(r0) != 0 { + errcode = syscall.Errno(uint32(r0)) } return } func GetUnicastIpAddressTable(family uint16, table **MibUnicastIpAddressTable) (errcode error) { r0, _, _ := syscall.SyscallN(procGetUnicastIpAddressTable.Addr(), uintptr(family), uintptr(unsafe.Pointer(table))) - if r0 != 0 { - errcode = syscall.Errno(r0) + if uint32(r0) != 0 { + errcode = syscall.Errno(uint32(r0)) } return } @@ -1743,8 +1743,8 @@ func NotifyIpInterfaceChange(family uint16, callback uintptr, callerContext unsa _p0 = 1 } r0, _, _ := syscall.SyscallN(procNotifyIpInterfaceChange.Addr(), uintptr(family), uintptr(callback), uintptr(callerContext), uintptr(_p0), uintptr(unsafe.Pointer(notificationHandle))) - if r0 != 0 { - errcode = syscall.Errno(r0) + if uint32(r0) != 0 { + errcode = syscall.Errno(uint32(r0)) } return } @@ -1755,8 +1755,8 @@ func NotifyRouteChange2(family uint16, callback uintptr, callerContext unsafe.Po _p0 = 1 } r0, _, _ := syscall.SyscallN(procNotifyRouteChange2.Addr(), uintptr(family), uintptr(callback), uintptr(callerContext), uintptr(_p0), uintptr(unsafe.Pointer(notificationHandle))) - if r0 != 0 { - errcode = syscall.Errno(r0) + if uint32(r0) != 0 { + errcode = syscall.Errno(uint32(r0)) } return } @@ -1767,8 +1767,8 @@ func NotifyUnicastIpAddressChange(family uint16, callback uintptr, callerContext _p0 = 1 } r0, _, _ := syscall.SyscallN(procNotifyUnicastIpAddressChange.Addr(), uintptr(family), uintptr(callback), uintptr(callerContext), uintptr(_p0), uintptr(unsafe.Pointer(notificationHandle))) - if r0 != 0 { - errcode = syscall.Errno(r0) + if uint32(r0) != 0 { + errcode = syscall.Errno(uint32(r0)) } return } @@ -1784,7 +1784,7 @@ func AddDllDirectory(path *uint16) (cookie uintptr, err error) { func AssignProcessToJobObject(job Handle, process Handle) (err error) { r1, _, e1 := syscall.SyscallN(procAssignProcessToJobObject.Addr(), uintptr(job), uintptr(process)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -1792,7 +1792,7 @@ func AssignProcessToJobObject(job Handle, process Handle) (err error) { func CancelIo(s Handle) (err error) { r1, _, e1 := syscall.SyscallN(procCancelIo.Addr(), uintptr(s)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -1800,7 +1800,7 @@ func CancelIo(s Handle) (err error) { func CancelIoEx(s Handle, o *Overlapped) (err error) { r1, _, e1 := syscall.SyscallN(procCancelIoEx.Addr(), uintptr(s), uintptr(unsafe.Pointer(o))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -1808,7 +1808,7 @@ func CancelIoEx(s Handle, o *Overlapped) (err error) { func ClearCommBreak(handle Handle) (err error) { r1, _, e1 := syscall.SyscallN(procClearCommBreak.Addr(), uintptr(handle)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -1816,7 +1816,7 @@ func ClearCommBreak(handle Handle) (err error) { func ClearCommError(handle Handle, lpErrors *uint32, lpStat *ComStat) (err error) { r1, _, e1 := syscall.SyscallN(procClearCommError.Addr(), uintptr(handle), uintptr(unsafe.Pointer(lpErrors)), uintptr(unsafe.Pointer(lpStat))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -1824,7 +1824,7 @@ func ClearCommError(handle Handle, lpErrors *uint32, lpStat *ComStat) (err error func CloseHandle(handle Handle) (err error) { r1, _, e1 := syscall.SyscallN(procCloseHandle.Addr(), uintptr(handle)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -1837,7 +1837,7 @@ func ClosePseudoConsole(console Handle) { func ConnectNamedPipe(pipe Handle, overlapped *Overlapped) (err error) { r1, _, e1 := syscall.SyscallN(procConnectNamedPipe.Addr(), uintptr(pipe), uintptr(unsafe.Pointer(overlapped))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -1845,7 +1845,7 @@ func ConnectNamedPipe(pipe Handle, overlapped *Overlapped) (err error) { func CreateDirectory(path *uint16, sa *SecurityAttributes) (err error) { r1, _, e1 := syscall.SyscallN(procCreateDirectoryW.Addr(), uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(sa))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -1946,7 +1946,7 @@ func CreateNamedPipe(name *uint16, flags uint32, pipeMode uint32, maxInstances u func CreatePipe(readhandle *Handle, writehandle *Handle, sa *SecurityAttributes, size uint32) (err error) { r1, _, e1 := syscall.SyscallN(procCreatePipe.Addr(), uintptr(unsafe.Pointer(readhandle)), uintptr(unsafe.Pointer(writehandle)), uintptr(unsafe.Pointer(sa)), uintptr(size)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -1958,7 +1958,7 @@ func CreateProcess(appName *uint16, commandLine *uint16, procSecurity *SecurityA _p0 = 1 } r1, _, e1 := syscall.SyscallN(procCreateProcessW.Addr(), uintptr(unsafe.Pointer(appName)), uintptr(unsafe.Pointer(commandLine)), uintptr(unsafe.Pointer(procSecurity)), uintptr(unsafe.Pointer(threadSecurity)), uintptr(_p0), uintptr(creationFlags), uintptr(unsafe.Pointer(env)), uintptr(unsafe.Pointer(currentDir)), uintptr(unsafe.Pointer(startupInfo)), uintptr(unsafe.Pointer(outProcInfo))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -1966,8 +1966,8 @@ func CreateProcess(appName *uint16, commandLine *uint16, procSecurity *SecurityA func createPseudoConsole(size uint32, in Handle, out Handle, flags uint32, pconsole *Handle) (hr error) { r0, _, _ := syscall.SyscallN(procCreatePseudoConsole.Addr(), uintptr(size), uintptr(in), uintptr(out), uintptr(flags), uintptr(unsafe.Pointer(pconsole))) - if r0 != 0 { - hr = syscall.Errno(r0) + if uint32(r0) != 0 { + hr = syscall.Errno(uint32(r0)) } return } @@ -1991,7 +1991,7 @@ func CreateToolhelp32Snapshot(flags uint32, processId uint32) (handle Handle, er func DefineDosDevice(flags uint32, deviceName *uint16, targetPath *uint16) (err error) { r1, _, e1 := syscall.SyscallN(procDefineDosDeviceW.Addr(), uintptr(flags), uintptr(unsafe.Pointer(deviceName)), uintptr(unsafe.Pointer(targetPath))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -1999,7 +1999,7 @@ func DefineDosDevice(flags uint32, deviceName *uint16, targetPath *uint16) (err func DeleteFile(path *uint16) (err error) { r1, _, e1 := syscall.SyscallN(procDeleteFileW.Addr(), uintptr(unsafe.Pointer(path))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -2012,7 +2012,7 @@ func deleteProcThreadAttributeList(attrlist *ProcThreadAttributeList) { func DeleteVolumeMountPoint(volumeMountPoint *uint16) (err error) { r1, _, e1 := syscall.SyscallN(procDeleteVolumeMountPointW.Addr(), uintptr(unsafe.Pointer(volumeMountPoint))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -2020,7 +2020,7 @@ func DeleteVolumeMountPoint(volumeMountPoint *uint16) (err error) { func DeviceIoControl(handle Handle, ioControlCode uint32, inBuffer *byte, inBufferSize uint32, outBuffer *byte, outBufferSize uint32, bytesReturned *uint32, overlapped *Overlapped) (err error) { r1, _, e1 := syscall.SyscallN(procDeviceIoControl.Addr(), uintptr(handle), uintptr(ioControlCode), uintptr(unsafe.Pointer(inBuffer)), uintptr(inBufferSize), uintptr(unsafe.Pointer(outBuffer)), uintptr(outBufferSize), uintptr(unsafe.Pointer(bytesReturned)), uintptr(unsafe.Pointer(overlapped))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -2028,7 +2028,7 @@ func DeviceIoControl(handle Handle, ioControlCode uint32, inBuffer *byte, inBuff func DisconnectNamedPipe(pipe Handle) (err error) { r1, _, e1 := syscall.SyscallN(procDisconnectNamedPipe.Addr(), uintptr(pipe)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -2040,7 +2040,7 @@ func DuplicateHandle(hSourceProcessHandle Handle, hSourceHandle Handle, hTargetP _p0 = 1 } r1, _, e1 := syscall.SyscallN(procDuplicateHandle.Addr(), uintptr(hSourceProcessHandle), uintptr(hSourceHandle), uintptr(hTargetProcessHandle), uintptr(unsafe.Pointer(lpTargetHandle)), uintptr(dwDesiredAccess), uintptr(_p0), uintptr(dwOptions)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -2048,7 +2048,7 @@ func DuplicateHandle(hSourceProcessHandle Handle, hSourceHandle Handle, hTargetP func EscapeCommFunction(handle Handle, dwFunc uint32) (err error) { r1, _, e1 := syscall.SyscallN(procEscapeCommFunction.Addr(), uintptr(handle), uintptr(dwFunc)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -2070,7 +2070,7 @@ func ExpandEnvironmentStrings(src *uint16, dst *uint16, size uint32) (n uint32, func FindClose(handle Handle) (err error) { r1, _, e1 := syscall.SyscallN(procFindClose.Addr(), uintptr(handle)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -2078,7 +2078,7 @@ func FindClose(handle Handle) (err error) { func FindCloseChangeNotification(handle Handle) (err error) { r1, _, e1 := syscall.SyscallN(procFindCloseChangeNotification.Addr(), uintptr(handle)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -2135,7 +2135,7 @@ func FindFirstVolume(volumeName *uint16, bufferLength uint32) (handle Handle, er func FindNextChangeNotification(handle Handle) (err error) { r1, _, e1 := syscall.SyscallN(procFindNextChangeNotification.Addr(), uintptr(handle)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -2143,7 +2143,7 @@ func FindNextChangeNotification(handle Handle) (err error) { func findNextFile1(handle Handle, data *win32finddata1) (err error) { r1, _, e1 := syscall.SyscallN(procFindNextFileW.Addr(), uintptr(handle), uintptr(unsafe.Pointer(data))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -2151,7 +2151,7 @@ func findNextFile1(handle Handle, data *win32finddata1) (err error) { func FindNextVolumeMountPoint(findVolumeMountPoint Handle, volumeMountPoint *uint16, bufferLength uint32) (err error) { r1, _, e1 := syscall.SyscallN(procFindNextVolumeMountPointW.Addr(), uintptr(findVolumeMountPoint), uintptr(unsafe.Pointer(volumeMountPoint)), uintptr(bufferLength)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -2159,7 +2159,7 @@ func FindNextVolumeMountPoint(findVolumeMountPoint Handle, volumeMountPoint *uin func FindNextVolume(findVolume Handle, volumeName *uint16, bufferLength uint32) (err error) { r1, _, e1 := syscall.SyscallN(procFindNextVolumeW.Addr(), uintptr(findVolume), uintptr(unsafe.Pointer(volumeName)), uintptr(bufferLength)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -2176,7 +2176,7 @@ func findResource(module Handle, name uintptr, resType uintptr) (resInfo Handle, func FindVolumeClose(findVolume Handle) (err error) { r1, _, e1 := syscall.SyscallN(procFindVolumeClose.Addr(), uintptr(findVolume)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -2184,7 +2184,7 @@ func FindVolumeClose(findVolume Handle) (err error) { func FindVolumeMountPointClose(findVolumeMountPoint Handle) (err error) { r1, _, e1 := syscall.SyscallN(procFindVolumeMountPointClose.Addr(), uintptr(findVolumeMountPoint)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -2192,7 +2192,7 @@ func FindVolumeMountPointClose(findVolumeMountPoint Handle) (err error) { func FlushConsoleInputBuffer(console Handle) (err error) { r1, _, e1 := syscall.SyscallN(procFlushConsoleInputBuffer.Addr(), uintptr(console)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -2200,7 +2200,7 @@ func FlushConsoleInputBuffer(console Handle) (err error) { func FlushFileBuffers(handle Handle) (err error) { r1, _, e1 := syscall.SyscallN(procFlushFileBuffers.Addr(), uintptr(handle)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -2208,7 +2208,7 @@ func FlushFileBuffers(handle Handle) (err error) { func FlushViewOfFile(addr uintptr, length uintptr) (err error) { r1, _, e1 := syscall.SyscallN(procFlushViewOfFile.Addr(), uintptr(addr), uintptr(length)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -2229,7 +2229,7 @@ func FormatMessage(flags uint32, msgsrc uintptr, msgid uint32, langid uint32, bu func FreeEnvironmentStrings(envs *uint16) (err error) { r1, _, e1 := syscall.SyscallN(procFreeEnvironmentStringsW.Addr(), uintptr(unsafe.Pointer(envs))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -2237,7 +2237,7 @@ func FreeEnvironmentStrings(envs *uint16) (err error) { func FreeLibrary(handle Handle) (err error) { r1, _, e1 := syscall.SyscallN(procFreeLibrary.Addr(), uintptr(handle)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -2245,7 +2245,7 @@ func FreeLibrary(handle Handle) (err error) { func GenerateConsoleCtrlEvent(ctrlEvent uint32, processGroupID uint32) (err error) { r1, _, e1 := syscall.SyscallN(procGenerateConsoleCtrlEvent.Addr(), uintptr(ctrlEvent), uintptr(processGroupID)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -2265,7 +2265,7 @@ func GetActiveProcessorCount(groupNumber uint16) (ret uint32) { func GetCommModemStatus(handle Handle, lpModemStat *uint32) (err error) { r1, _, e1 := syscall.SyscallN(procGetCommModemStatus.Addr(), uintptr(handle), uintptr(unsafe.Pointer(lpModemStat))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -2273,7 +2273,7 @@ func GetCommModemStatus(handle Handle, lpModemStat *uint32) (err error) { func GetCommState(handle Handle, lpDCB *DCB) (err error) { r1, _, e1 := syscall.SyscallN(procGetCommState.Addr(), uintptr(handle), uintptr(unsafe.Pointer(lpDCB))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -2281,7 +2281,7 @@ func GetCommState(handle Handle, lpDCB *DCB) (err error) { func GetCommTimeouts(handle Handle, timeouts *CommTimeouts) (err error) { r1, _, e1 := syscall.SyscallN(procGetCommTimeouts.Addr(), uintptr(handle), uintptr(unsafe.Pointer(timeouts))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -2295,7 +2295,7 @@ func GetCommandLine() (cmd *uint16) { func GetComputerNameEx(nametype uint32, buf *uint16, n *uint32) (err error) { r1, _, e1 := syscall.SyscallN(procGetComputerNameExW.Addr(), uintptr(nametype), uintptr(unsafe.Pointer(buf)), uintptr(unsafe.Pointer(n))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -2303,7 +2303,7 @@ func GetComputerNameEx(nametype uint32, buf *uint16, n *uint32) (err error) { func GetComputerName(buf *uint16, n *uint32) (err error) { r1, _, e1 := syscall.SyscallN(procGetComputerNameW.Addr(), uintptr(unsafe.Pointer(buf)), uintptr(unsafe.Pointer(n))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -2320,7 +2320,7 @@ func GetConsoleCP() (cp uint32, err error) { func GetConsoleMode(console Handle, mode *uint32) (err error) { r1, _, e1 := syscall.SyscallN(procGetConsoleMode.Addr(), uintptr(console), uintptr(unsafe.Pointer(mode))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -2337,7 +2337,7 @@ func GetConsoleOutputCP() (cp uint32, err error) { func GetConsoleScreenBufferInfo(console Handle, info *ConsoleScreenBufferInfo) (err error) { r1, _, e1 := syscall.SyscallN(procGetConsoleScreenBufferInfo.Addr(), uintptr(console), uintptr(unsafe.Pointer(info))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -2366,7 +2366,7 @@ func GetCurrentThreadId() (id uint32) { func GetDiskFreeSpaceEx(directoryName *uint16, freeBytesAvailableToCaller *uint64, totalNumberOfBytes *uint64, totalNumberOfFreeBytes *uint64) (err error) { r1, _, e1 := syscall.SyscallN(procGetDiskFreeSpaceExW.Addr(), uintptr(unsafe.Pointer(directoryName)), uintptr(unsafe.Pointer(freeBytesAvailableToCaller)), uintptr(unsafe.Pointer(totalNumberOfBytes)), uintptr(unsafe.Pointer(totalNumberOfFreeBytes))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -2398,7 +2398,7 @@ func GetEnvironmentVariable(name *uint16, buffer *uint16, size uint32) (n uint32 func GetExitCodeProcess(handle Handle, exitcode *uint32) (err error) { r1, _, e1 := syscall.SyscallN(procGetExitCodeProcess.Addr(), uintptr(handle), uintptr(unsafe.Pointer(exitcode))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -2406,7 +2406,7 @@ func GetExitCodeProcess(handle Handle, exitcode *uint32) (err error) { func GetFileAttributesEx(name *uint16, level uint32, info *byte) (err error) { r1, _, e1 := syscall.SyscallN(procGetFileAttributesExW.Addr(), uintptr(unsafe.Pointer(name)), uintptr(level), uintptr(unsafe.Pointer(info))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -2423,7 +2423,7 @@ func GetFileAttributes(name *uint16) (attrs uint32, err error) { func GetFileInformationByHandle(handle Handle, data *ByHandleFileInformation) (err error) { r1, _, e1 := syscall.SyscallN(procGetFileInformationByHandle.Addr(), uintptr(handle), uintptr(unsafe.Pointer(data))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -2431,7 +2431,7 @@ func GetFileInformationByHandle(handle Handle, data *ByHandleFileInformation) (e func GetFileInformationByHandleEx(handle Handle, class uint32, outBuffer *byte, outBufferLen uint32) (err error) { r1, _, e1 := syscall.SyscallN(procGetFileInformationByHandleEx.Addr(), uintptr(handle), uintptr(class), uintptr(unsafe.Pointer(outBuffer)), uintptr(outBufferLen)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -2439,7 +2439,7 @@ func GetFileInformationByHandleEx(handle Handle, class uint32, outBuffer *byte, func GetFileTime(handle Handle, ctime *Filetime, atime *Filetime, wtime *Filetime) (err error) { r1, _, e1 := syscall.SyscallN(procGetFileTime.Addr(), uintptr(handle), uintptr(unsafe.Pointer(ctime)), uintptr(unsafe.Pointer(atime)), uintptr(unsafe.Pointer(wtime))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -2480,8 +2480,8 @@ func GetLargePageMinimum() (size uintptr) { func GetLastError() (lasterr error) { r0, _, _ := syscall.SyscallN(procGetLastError.Addr()) - if r0 != 0 { - lasterr = syscall.Errno(r0) + if uint32(r0) != 0 { + lasterr = syscall.Errno(uint32(r0)) } return } @@ -2530,7 +2530,7 @@ func GetModuleFileName(module Handle, filename *uint16, size uint32) (n uint32, func GetModuleHandleEx(flags uint32, moduleName *uint16, module *Handle) (err error) { r1, _, e1 := syscall.SyscallN(procGetModuleHandleExW.Addr(), uintptr(flags), uintptr(unsafe.Pointer(moduleName)), uintptr(unsafe.Pointer(module))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -2538,7 +2538,7 @@ func GetModuleHandleEx(flags uint32, moduleName *uint16, module *Handle) (err er func GetNamedPipeClientProcessId(pipe Handle, clientProcessID *uint32) (err error) { r1, _, e1 := syscall.SyscallN(procGetNamedPipeClientProcessId.Addr(), uintptr(pipe), uintptr(unsafe.Pointer(clientProcessID))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -2546,7 +2546,7 @@ func GetNamedPipeClientProcessId(pipe Handle, clientProcessID *uint32) (err erro func GetNamedPipeHandleState(pipe Handle, state *uint32, curInstances *uint32, maxCollectionCount *uint32, collectDataTimeout *uint32, userName *uint16, maxUserNameSize uint32) (err error) { r1, _, e1 := syscall.SyscallN(procGetNamedPipeHandleStateW.Addr(), uintptr(pipe), uintptr(unsafe.Pointer(state)), uintptr(unsafe.Pointer(curInstances)), uintptr(unsafe.Pointer(maxCollectionCount)), uintptr(unsafe.Pointer(collectDataTimeout)), uintptr(unsafe.Pointer(userName)), uintptr(maxUserNameSize)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -2554,7 +2554,7 @@ func GetNamedPipeHandleState(pipe Handle, state *uint32, curInstances *uint32, m func GetNamedPipeInfo(pipe Handle, flags *uint32, outSize *uint32, inSize *uint32, maxInstances *uint32) (err error) { r1, _, e1 := syscall.SyscallN(procGetNamedPipeInfo.Addr(), uintptr(pipe), uintptr(unsafe.Pointer(flags)), uintptr(unsafe.Pointer(outSize)), uintptr(unsafe.Pointer(inSize)), uintptr(unsafe.Pointer(maxInstances))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -2562,7 +2562,7 @@ func GetNamedPipeInfo(pipe Handle, flags *uint32, outSize *uint32, inSize *uint3 func GetNamedPipeServerProcessId(pipe Handle, serverProcessID *uint32) (err error) { r1, _, e1 := syscall.SyscallN(procGetNamedPipeServerProcessId.Addr(), uintptr(pipe), uintptr(unsafe.Pointer(serverProcessID))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -2570,7 +2570,7 @@ func GetNamedPipeServerProcessId(pipe Handle, serverProcessID *uint32) (err erro func GetNumberOfConsoleInputEvents(console Handle, numevents *uint32) (err error) { r1, _, e1 := syscall.SyscallN(procGetNumberOfConsoleInputEvents.Addr(), uintptr(console), uintptr(unsafe.Pointer(numevents))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -2582,7 +2582,7 @@ func GetOverlappedResult(handle Handle, overlapped *Overlapped, done *uint32, wa _p0 = 1 } r1, _, e1 := syscall.SyscallN(procGetOverlappedResult.Addr(), uintptr(handle), uintptr(unsafe.Pointer(overlapped)), uintptr(unsafe.Pointer(done)), uintptr(_p0)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -2626,7 +2626,7 @@ func GetProcessId(process Handle) (id uint32, err error) { func getProcessPreferredUILanguages(flags uint32, numLanguages *uint32, buf *uint16, bufSize *uint32) (err error) { r1, _, e1 := syscall.SyscallN(procGetProcessPreferredUILanguages.Addr(), uintptr(flags), uintptr(unsafe.Pointer(numLanguages)), uintptr(unsafe.Pointer(buf)), uintptr(unsafe.Pointer(bufSize))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -2634,7 +2634,7 @@ func getProcessPreferredUILanguages(flags uint32, numLanguages *uint32, buf *uin func GetProcessShutdownParameters(level *uint32, flags *uint32) (err error) { r1, _, e1 := syscall.SyscallN(procGetProcessShutdownParameters.Addr(), uintptr(unsafe.Pointer(level)), uintptr(unsafe.Pointer(flags))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -2642,7 +2642,7 @@ func GetProcessShutdownParameters(level *uint32, flags *uint32) (err error) { func GetProcessTimes(handle Handle, creationTime *Filetime, exitTime *Filetime, kernelTime *Filetime, userTime *Filetime) (err error) { r1, _, e1 := syscall.SyscallN(procGetProcessTimes.Addr(), uintptr(handle), uintptr(unsafe.Pointer(creationTime)), uintptr(unsafe.Pointer(exitTime)), uintptr(unsafe.Pointer(kernelTime)), uintptr(unsafe.Pointer(userTime))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -2655,7 +2655,7 @@ func GetProcessWorkingSetSizeEx(hProcess Handle, lpMinimumWorkingSetSize *uintpt func GetQueuedCompletionStatus(cphandle Handle, qty *uint32, key *uintptr, overlapped **Overlapped, timeout uint32) (err error) { r1, _, e1 := syscall.SyscallN(procGetQueuedCompletionStatus.Addr(), uintptr(cphandle), uintptr(unsafe.Pointer(qty)), uintptr(unsafe.Pointer(key)), uintptr(unsafe.Pointer(overlapped)), uintptr(timeout)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -2695,7 +2695,7 @@ func getSystemDirectory(dir *uint16, dirLen uint32) (len uint32, err error) { func getSystemPreferredUILanguages(flags uint32, numLanguages *uint32, buf *uint16, bufSize *uint32) (err error) { r1, _, e1 := syscall.SyscallN(procGetSystemPreferredUILanguages.Addr(), uintptr(flags), uintptr(unsafe.Pointer(numLanguages)), uintptr(unsafe.Pointer(buf)), uintptr(unsafe.Pointer(bufSize))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -2731,7 +2731,7 @@ func GetTempPath(buflen uint32, buf *uint16) (n uint32, err error) { func getThreadPreferredUILanguages(flags uint32, numLanguages *uint32, buf *uint16, bufSize *uint32) (err error) { r1, _, e1 := syscall.SyscallN(procGetThreadPreferredUILanguages.Addr(), uintptr(flags), uintptr(unsafe.Pointer(numLanguages)), uintptr(unsafe.Pointer(buf)), uintptr(unsafe.Pointer(bufSize))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -2754,7 +2754,7 @@ func GetTimeZoneInformation(tzi *Timezoneinformation) (rc uint32, err error) { func getUserPreferredUILanguages(flags uint32, numLanguages *uint32, buf *uint16, bufSize *uint32) (err error) { r1, _, e1 := syscall.SyscallN(procGetUserPreferredUILanguages.Addr(), uintptr(flags), uintptr(unsafe.Pointer(numLanguages)), uintptr(unsafe.Pointer(buf)), uintptr(unsafe.Pointer(bufSize))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -2771,7 +2771,7 @@ func GetVersion() (ver uint32, err error) { func GetVolumeInformationByHandle(file Handle, volumeNameBuffer *uint16, volumeNameSize uint32, volumeNameSerialNumber *uint32, maximumComponentLength *uint32, fileSystemFlags *uint32, fileSystemNameBuffer *uint16, fileSystemNameSize uint32) (err error) { r1, _, e1 := syscall.SyscallN(procGetVolumeInformationByHandleW.Addr(), uintptr(file), uintptr(unsafe.Pointer(volumeNameBuffer)), uintptr(volumeNameSize), uintptr(unsafe.Pointer(volumeNameSerialNumber)), uintptr(unsafe.Pointer(maximumComponentLength)), uintptr(unsafe.Pointer(fileSystemFlags)), uintptr(unsafe.Pointer(fileSystemNameBuffer)), uintptr(fileSystemNameSize)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -2779,7 +2779,7 @@ func GetVolumeInformationByHandle(file Handle, volumeNameBuffer *uint16, volumeN func GetVolumeInformation(rootPathName *uint16, volumeNameBuffer *uint16, volumeNameSize uint32, volumeNameSerialNumber *uint32, maximumComponentLength *uint32, fileSystemFlags *uint32, fileSystemNameBuffer *uint16, fileSystemNameSize uint32) (err error) { r1, _, e1 := syscall.SyscallN(procGetVolumeInformationW.Addr(), uintptr(unsafe.Pointer(rootPathName)), uintptr(unsafe.Pointer(volumeNameBuffer)), uintptr(volumeNameSize), uintptr(unsafe.Pointer(volumeNameSerialNumber)), uintptr(unsafe.Pointer(maximumComponentLength)), uintptr(unsafe.Pointer(fileSystemFlags)), uintptr(unsafe.Pointer(fileSystemNameBuffer)), uintptr(fileSystemNameSize)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -2787,7 +2787,7 @@ func GetVolumeInformation(rootPathName *uint16, volumeNameBuffer *uint16, volume func GetVolumeNameForVolumeMountPoint(volumeMountPoint *uint16, volumeName *uint16, bufferlength uint32) (err error) { r1, _, e1 := syscall.SyscallN(procGetVolumeNameForVolumeMountPointW.Addr(), uintptr(unsafe.Pointer(volumeMountPoint)), uintptr(unsafe.Pointer(volumeName)), uintptr(bufferlength)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -2795,7 +2795,7 @@ func GetVolumeNameForVolumeMountPoint(volumeMountPoint *uint16, volumeName *uint func GetVolumePathName(fileName *uint16, volumePathName *uint16, bufferLength uint32) (err error) { r1, _, e1 := syscall.SyscallN(procGetVolumePathNameW.Addr(), uintptr(unsafe.Pointer(fileName)), uintptr(unsafe.Pointer(volumePathName)), uintptr(bufferLength)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -2803,7 +2803,7 @@ func GetVolumePathName(fileName *uint16, volumePathName *uint16, bufferLength ui func GetVolumePathNamesForVolumeName(volumeName *uint16, volumePathNames *uint16, bufferLength uint32, returnLength *uint32) (err error) { r1, _, e1 := syscall.SyscallN(procGetVolumePathNamesForVolumeNameW.Addr(), uintptr(unsafe.Pointer(volumeName)), uintptr(unsafe.Pointer(volumePathNames)), uintptr(bufferLength), uintptr(unsafe.Pointer(returnLength))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -2820,7 +2820,7 @@ func getWindowsDirectory(dir *uint16, dirLen uint32) (len uint32, err error) { func initializeProcThreadAttributeList(attrlist *ProcThreadAttributeList, attrcount uint32, flags uint32, size *uintptr) (err error) { r1, _, e1 := syscall.SyscallN(procInitializeProcThreadAttributeList.Addr(), uintptr(unsafe.Pointer(attrlist)), uintptr(attrcount), uintptr(flags), uintptr(unsafe.Pointer(size))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -2828,7 +2828,7 @@ func initializeProcThreadAttributeList(attrlist *ProcThreadAttributeList, attrco func IsProcessorFeaturePresent(ProcessorFeature uint32) (ret bool) { r0, _, _ := syscall.SyscallN(procIsProcessorFeaturePresent.Addr(), uintptr(ProcessorFeature)) - ret = r0 != 0 + ret = uint32(r0) != 0 return } @@ -2839,7 +2839,7 @@ func IsWow64Process(handle Handle, isWow64 *bool) (err error) { } r1, _, e1 := syscall.SyscallN(procIsWow64Process.Addr(), uintptr(handle), uintptr(unsafe.Pointer(&_p0))) *isWow64 = _p0 != 0 - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -2851,7 +2851,7 @@ func IsWow64Process2(handle Handle, processMachine *uint16, nativeMachine *uint1 return } r1, _, e1 := syscall.SyscallN(procIsWow64Process2.Addr(), uintptr(handle), uintptr(unsafe.Pointer(processMachine)), uintptr(unsafe.Pointer(nativeMachine))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -2922,7 +2922,7 @@ func LocalFree(hmem Handle) (handle Handle, err error) { func LockFileEx(file Handle, flags uint32, reserved uint32, bytesLow uint32, bytesHigh uint32, overlapped *Overlapped) (err error) { r1, _, e1 := syscall.SyscallN(procLockFileEx.Addr(), uintptr(file), uintptr(flags), uintptr(reserved), uintptr(bytesLow), uintptr(bytesHigh), uintptr(unsafe.Pointer(overlapped))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -2948,7 +2948,7 @@ func MapViewOfFile(handle Handle, access uint32, offsetHigh uint32, offsetLow ui func Module32First(snapshot Handle, moduleEntry *ModuleEntry32) (err error) { r1, _, e1 := syscall.SyscallN(procModule32FirstW.Addr(), uintptr(snapshot), uintptr(unsafe.Pointer(moduleEntry))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -2956,7 +2956,7 @@ func Module32First(snapshot Handle, moduleEntry *ModuleEntry32) (err error) { func Module32Next(snapshot Handle, moduleEntry *ModuleEntry32) (err error) { r1, _, e1 := syscall.SyscallN(procModule32NextW.Addr(), uintptr(snapshot), uintptr(unsafe.Pointer(moduleEntry))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -2964,7 +2964,7 @@ func Module32Next(snapshot Handle, moduleEntry *ModuleEntry32) (err error) { func MoveFileEx(from *uint16, to *uint16, flags uint32) (err error) { r1, _, e1 := syscall.SyscallN(procMoveFileExW.Addr(), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(to)), uintptr(flags)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -2972,7 +2972,7 @@ func MoveFileEx(from *uint16, to *uint16, flags uint32) (err error) { func MoveFile(from *uint16, to *uint16) (err error) { r1, _, e1 := syscall.SyscallN(procMoveFileW.Addr(), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(to))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3041,7 +3041,7 @@ func OpenThread(desiredAccess uint32, inheritHandle bool, threadId uint32) (hand func PostQueuedCompletionStatus(cphandle Handle, qty uint32, key uintptr, overlapped *Overlapped) (err error) { r1, _, e1 := syscall.SyscallN(procPostQueuedCompletionStatus.Addr(), uintptr(cphandle), uintptr(qty), uintptr(key), uintptr(unsafe.Pointer(overlapped))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3049,7 +3049,7 @@ func PostQueuedCompletionStatus(cphandle Handle, qty uint32, key uintptr, overla func Process32First(snapshot Handle, procEntry *ProcessEntry32) (err error) { r1, _, e1 := syscall.SyscallN(procProcess32FirstW.Addr(), uintptr(snapshot), uintptr(unsafe.Pointer(procEntry))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3057,7 +3057,7 @@ func Process32First(snapshot Handle, procEntry *ProcessEntry32) (err error) { func Process32Next(snapshot Handle, procEntry *ProcessEntry32) (err error) { r1, _, e1 := syscall.SyscallN(procProcess32NextW.Addr(), uintptr(snapshot), uintptr(unsafe.Pointer(procEntry))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3065,7 +3065,7 @@ func Process32Next(snapshot Handle, procEntry *ProcessEntry32) (err error) { func ProcessIdToSessionId(pid uint32, sessionid *uint32) (err error) { r1, _, e1 := syscall.SyscallN(procProcessIdToSessionId.Addr(), uintptr(pid), uintptr(unsafe.Pointer(sessionid))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3073,7 +3073,7 @@ func ProcessIdToSessionId(pid uint32, sessionid *uint32) (err error) { func PulseEvent(event Handle) (err error) { r1, _, e1 := syscall.SyscallN(procPulseEvent.Addr(), uintptr(event)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3081,7 +3081,7 @@ func PulseEvent(event Handle) (err error) { func PurgeComm(handle Handle, dwFlags uint32) (err error) { r1, _, e1 := syscall.SyscallN(procPurgeComm.Addr(), uintptr(handle), uintptr(dwFlags)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3098,7 +3098,7 @@ func QueryDosDevice(deviceName *uint16, targetPath *uint16, max uint32) (n uint3 func QueryFullProcessImageName(proc Handle, flags uint32, exeName *uint16, size *uint32) (err error) { r1, _, e1 := syscall.SyscallN(procQueryFullProcessImageNameW.Addr(), uintptr(proc), uintptr(flags), uintptr(unsafe.Pointer(exeName)), uintptr(unsafe.Pointer(size))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3106,7 +3106,7 @@ func QueryFullProcessImageName(proc Handle, flags uint32, exeName *uint16, size func QueryInformationJobObject(job Handle, JobObjectInformationClass int32, JobObjectInformation uintptr, JobObjectInformationLength uint32, retlen *uint32) (err error) { r1, _, e1 := syscall.SyscallN(procQueryInformationJobObject.Addr(), uintptr(job), uintptr(JobObjectInformationClass), uintptr(JobObjectInformation), uintptr(JobObjectInformationLength), uintptr(unsafe.Pointer(retlen))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3114,7 +3114,7 @@ func QueryInformationJobObject(job Handle, JobObjectInformationClass int32, JobO func ReadConsole(console Handle, buf *uint16, toread uint32, read *uint32, inputControl *byte) (err error) { r1, _, e1 := syscall.SyscallN(procReadConsoleW.Addr(), uintptr(console), uintptr(unsafe.Pointer(buf)), uintptr(toread), uintptr(unsafe.Pointer(read)), uintptr(unsafe.Pointer(inputControl))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3126,7 +3126,7 @@ func ReadDirectoryChanges(handle Handle, buf *byte, buflen uint32, watchSubTree _p0 = 1 } r1, _, e1 := syscall.SyscallN(procReadDirectoryChangesW.Addr(), uintptr(handle), uintptr(unsafe.Pointer(buf)), uintptr(buflen), uintptr(_p0), uintptr(mask), uintptr(unsafe.Pointer(retlen)), uintptr(unsafe.Pointer(overlapped)), uintptr(completionRoutine)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3138,7 +3138,7 @@ func readFile(handle Handle, buf []byte, done *uint32, overlapped *Overlapped) ( _p0 = &buf[0] } r1, _, e1 := syscall.SyscallN(procReadFile.Addr(), uintptr(handle), uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), uintptr(unsafe.Pointer(done)), uintptr(unsafe.Pointer(overlapped))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3146,7 +3146,7 @@ func readFile(handle Handle, buf []byte, done *uint32, overlapped *Overlapped) ( func ReadProcessMemory(process Handle, baseAddress uintptr, buffer *byte, size uintptr, numberOfBytesRead *uintptr) (err error) { r1, _, e1 := syscall.SyscallN(procReadProcessMemory.Addr(), uintptr(process), uintptr(baseAddress), uintptr(unsafe.Pointer(buffer)), uintptr(size), uintptr(unsafe.Pointer(numberOfBytesRead))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3154,7 +3154,7 @@ func ReadProcessMemory(process Handle, baseAddress uintptr, buffer *byte, size u func ReleaseMutex(mutex Handle) (err error) { r1, _, e1 := syscall.SyscallN(procReleaseMutex.Addr(), uintptr(mutex)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3162,7 +3162,7 @@ func ReleaseMutex(mutex Handle) (err error) { func RemoveDirectory(path *uint16) (err error) { r1, _, e1 := syscall.SyscallN(procRemoveDirectoryW.Addr(), uintptr(unsafe.Pointer(path))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3170,7 +3170,7 @@ func RemoveDirectory(path *uint16) (err error) { func RemoveDllDirectory(cookie uintptr) (err error) { r1, _, e1 := syscall.SyscallN(procRemoveDllDirectory.Addr(), uintptr(cookie)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3178,7 +3178,7 @@ func RemoveDllDirectory(cookie uintptr) (err error) { func ResetEvent(event Handle) (err error) { r1, _, e1 := syscall.SyscallN(procResetEvent.Addr(), uintptr(event)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3186,8 +3186,8 @@ func ResetEvent(event Handle) (err error) { func resizePseudoConsole(pconsole Handle, size uint32) (hr error) { r0, _, _ := syscall.SyscallN(procResizePseudoConsole.Addr(), uintptr(pconsole), uintptr(size)) - if r0 != 0 { - hr = syscall.Errno(r0) + if uint32(r0) != 0 { + hr = syscall.Errno(uint32(r0)) } return } @@ -3203,7 +3203,7 @@ func ResumeThread(thread Handle) (ret uint32, err error) { func SetCommBreak(handle Handle) (err error) { r1, _, e1 := syscall.SyscallN(procSetCommBreak.Addr(), uintptr(handle)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3211,7 +3211,7 @@ func SetCommBreak(handle Handle) (err error) { func SetCommMask(handle Handle, dwEvtMask uint32) (err error) { r1, _, e1 := syscall.SyscallN(procSetCommMask.Addr(), uintptr(handle), uintptr(dwEvtMask)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3219,7 +3219,7 @@ func SetCommMask(handle Handle, dwEvtMask uint32) (err error) { func SetCommState(handle Handle, lpDCB *DCB) (err error) { r1, _, e1 := syscall.SyscallN(procSetCommState.Addr(), uintptr(handle), uintptr(unsafe.Pointer(lpDCB))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3227,7 +3227,7 @@ func SetCommState(handle Handle, lpDCB *DCB) (err error) { func SetCommTimeouts(handle Handle, timeouts *CommTimeouts) (err error) { r1, _, e1 := syscall.SyscallN(procSetCommTimeouts.Addr(), uintptr(handle), uintptr(unsafe.Pointer(timeouts))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3235,7 +3235,7 @@ func SetCommTimeouts(handle Handle, timeouts *CommTimeouts) (err error) { func SetConsoleCP(cp uint32) (err error) { r1, _, e1 := syscall.SyscallN(procSetConsoleCP.Addr(), uintptr(cp)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3243,7 +3243,7 @@ func SetConsoleCP(cp uint32) (err error) { func setConsoleCursorPosition(console Handle, position uint32) (err error) { r1, _, e1 := syscall.SyscallN(procSetConsoleCursorPosition.Addr(), uintptr(console), uintptr(position)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3251,7 +3251,7 @@ func setConsoleCursorPosition(console Handle, position uint32) (err error) { func SetConsoleMode(console Handle, mode uint32) (err error) { r1, _, e1 := syscall.SyscallN(procSetConsoleMode.Addr(), uintptr(console), uintptr(mode)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3259,7 +3259,7 @@ func SetConsoleMode(console Handle, mode uint32) (err error) { func SetConsoleOutputCP(cp uint32) (err error) { r1, _, e1 := syscall.SyscallN(procSetConsoleOutputCP.Addr(), uintptr(cp)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3267,7 +3267,7 @@ func SetConsoleOutputCP(cp uint32) (err error) { func SetCurrentDirectory(path *uint16) (err error) { r1, _, e1 := syscall.SyscallN(procSetCurrentDirectoryW.Addr(), uintptr(unsafe.Pointer(path))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3275,7 +3275,7 @@ func SetCurrentDirectory(path *uint16) (err error) { func SetDefaultDllDirectories(directoryFlags uint32) (err error) { r1, _, e1 := syscall.SyscallN(procSetDefaultDllDirectories.Addr(), uintptr(directoryFlags)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3292,7 +3292,7 @@ func SetDllDirectory(path string) (err error) { func _SetDllDirectory(path *uint16) (err error) { r1, _, e1 := syscall.SyscallN(procSetDllDirectoryW.Addr(), uintptr(unsafe.Pointer(path))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3300,7 +3300,7 @@ func _SetDllDirectory(path *uint16) (err error) { func SetEndOfFile(handle Handle) (err error) { r1, _, e1 := syscall.SyscallN(procSetEndOfFile.Addr(), uintptr(handle)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3308,7 +3308,7 @@ func SetEndOfFile(handle Handle) (err error) { func SetEnvironmentVariable(name *uint16, value *uint16) (err error) { r1, _, e1 := syscall.SyscallN(procSetEnvironmentVariableW.Addr(), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(value))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3322,7 +3322,7 @@ func SetErrorMode(mode uint32) (ret uint32) { func SetEvent(event Handle) (err error) { r1, _, e1 := syscall.SyscallN(procSetEvent.Addr(), uintptr(event)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3330,7 +3330,7 @@ func SetEvent(event Handle) (err error) { func SetFileAttributes(name *uint16, attrs uint32) (err error) { r1, _, e1 := syscall.SyscallN(procSetFileAttributesW.Addr(), uintptr(unsafe.Pointer(name)), uintptr(attrs)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3338,7 +3338,7 @@ func SetFileAttributes(name *uint16, attrs uint32) (err error) { func SetFileCompletionNotificationModes(handle Handle, flags uint8) (err error) { r1, _, e1 := syscall.SyscallN(procSetFileCompletionNotificationModes.Addr(), uintptr(handle), uintptr(flags)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3346,7 +3346,7 @@ func SetFileCompletionNotificationModes(handle Handle, flags uint8) (err error) func SetFileInformationByHandle(handle Handle, class uint32, inBuffer *byte, inBufferLen uint32) (err error) { r1, _, e1 := syscall.SyscallN(procSetFileInformationByHandle.Addr(), uintptr(handle), uintptr(class), uintptr(unsafe.Pointer(inBuffer)), uintptr(inBufferLen)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3363,7 +3363,7 @@ func SetFilePointer(handle Handle, lowoffset int32, highoffsetptr *int32, whence func SetFileTime(handle Handle, ctime *Filetime, atime *Filetime, wtime *Filetime) (err error) { r1, _, e1 := syscall.SyscallN(procSetFileTime.Addr(), uintptr(handle), uintptr(unsafe.Pointer(ctime)), uintptr(unsafe.Pointer(atime)), uintptr(unsafe.Pointer(wtime))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3371,7 +3371,7 @@ func SetFileTime(handle Handle, ctime *Filetime, atime *Filetime, wtime *Filetim func SetFileValidData(handle Handle, validDataLength int64) (err error) { r1, _, e1 := syscall.SyscallN(procSetFileValidData.Addr(), uintptr(handle), uintptr(validDataLength)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3379,7 +3379,7 @@ func SetFileValidData(handle Handle, validDataLength int64) (err error) { func SetHandleInformation(handle Handle, mask uint32, flags uint32) (err error) { r1, _, e1 := syscall.SyscallN(procSetHandleInformation.Addr(), uintptr(handle), uintptr(mask), uintptr(flags)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3396,7 +3396,7 @@ func SetInformationJobObject(job Handle, JobObjectInformationClass uint32, JobOb func SetNamedPipeHandleState(pipe Handle, state *uint32, maxCollectionCount *uint32, collectDataTimeout *uint32) (err error) { r1, _, e1 := syscall.SyscallN(procSetNamedPipeHandleState.Addr(), uintptr(pipe), uintptr(unsafe.Pointer(state)), uintptr(unsafe.Pointer(maxCollectionCount)), uintptr(unsafe.Pointer(collectDataTimeout))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3404,7 +3404,7 @@ func SetNamedPipeHandleState(pipe Handle, state *uint32, maxCollectionCount *uin func SetPriorityClass(process Handle, priorityClass uint32) (err error) { r1, _, e1 := syscall.SyscallN(procSetPriorityClass.Addr(), uintptr(process), uintptr(priorityClass)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3416,7 +3416,7 @@ func SetProcessPriorityBoost(process Handle, disable bool) (err error) { _p0 = 1 } r1, _, e1 := syscall.SyscallN(procSetProcessPriorityBoost.Addr(), uintptr(process), uintptr(_p0)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3424,7 +3424,7 @@ func SetProcessPriorityBoost(process Handle, disable bool) (err error) { func SetProcessShutdownParameters(level uint32, flags uint32) (err error) { r1, _, e1 := syscall.SyscallN(procSetProcessShutdownParameters.Addr(), uintptr(level), uintptr(flags)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3432,7 +3432,7 @@ func SetProcessShutdownParameters(level uint32, flags uint32) (err error) { func SetProcessWorkingSetSizeEx(hProcess Handle, dwMinimumWorkingSetSize uintptr, dwMaximumWorkingSetSize uintptr, flags uint32) (err error) { r1, _, e1 := syscall.SyscallN(procSetProcessWorkingSetSizeEx.Addr(), uintptr(hProcess), uintptr(dwMinimumWorkingSetSize), uintptr(dwMaximumWorkingSetSize), uintptr(flags)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3440,7 +3440,7 @@ func SetProcessWorkingSetSizeEx(hProcess Handle, dwMinimumWorkingSetSize uintptr func SetStdHandle(stdhandle uint32, handle Handle) (err error) { r1, _, e1 := syscall.SyscallN(procSetStdHandle.Addr(), uintptr(stdhandle), uintptr(handle)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3448,7 +3448,7 @@ func SetStdHandle(stdhandle uint32, handle Handle) (err error) { func SetVolumeLabel(rootPathName *uint16, volumeName *uint16) (err error) { r1, _, e1 := syscall.SyscallN(procSetVolumeLabelW.Addr(), uintptr(unsafe.Pointer(rootPathName)), uintptr(unsafe.Pointer(volumeName))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3456,7 +3456,7 @@ func SetVolumeLabel(rootPathName *uint16, volumeName *uint16) (err error) { func SetVolumeMountPoint(volumeMountPoint *uint16, volumeName *uint16) (err error) { r1, _, e1 := syscall.SyscallN(procSetVolumeMountPointW.Addr(), uintptr(unsafe.Pointer(volumeMountPoint)), uintptr(unsafe.Pointer(volumeName))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3464,7 +3464,7 @@ func SetVolumeMountPoint(volumeMountPoint *uint16, volumeName *uint16) (err erro func SetupComm(handle Handle, dwInQueue uint32, dwOutQueue uint32) (err error) { r1, _, e1 := syscall.SyscallN(procSetupComm.Addr(), uintptr(handle), uintptr(dwInQueue), uintptr(dwOutQueue)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3491,7 +3491,7 @@ func SleepEx(milliseconds uint32, alertable bool) (ret uint32) { func TerminateJobObject(job Handle, exitCode uint32) (err error) { r1, _, e1 := syscall.SyscallN(procTerminateJobObject.Addr(), uintptr(job), uintptr(exitCode)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3499,7 +3499,7 @@ func TerminateJobObject(job Handle, exitCode uint32) (err error) { func TerminateProcess(handle Handle, exitcode uint32) (err error) { r1, _, e1 := syscall.SyscallN(procTerminateProcess.Addr(), uintptr(handle), uintptr(exitcode)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3507,7 +3507,7 @@ func TerminateProcess(handle Handle, exitcode uint32) (err error) { func Thread32First(snapshot Handle, threadEntry *ThreadEntry32) (err error) { r1, _, e1 := syscall.SyscallN(procThread32First.Addr(), uintptr(snapshot), uintptr(unsafe.Pointer(threadEntry))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3515,7 +3515,7 @@ func Thread32First(snapshot Handle, threadEntry *ThreadEntry32) (err error) { func Thread32Next(snapshot Handle, threadEntry *ThreadEntry32) (err error) { r1, _, e1 := syscall.SyscallN(procThread32Next.Addr(), uintptr(snapshot), uintptr(unsafe.Pointer(threadEntry))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3523,7 +3523,7 @@ func Thread32Next(snapshot Handle, threadEntry *ThreadEntry32) (err error) { func UnlockFileEx(file Handle, reserved uint32, bytesLow uint32, bytesHigh uint32, overlapped *Overlapped) (err error) { r1, _, e1 := syscall.SyscallN(procUnlockFileEx.Addr(), uintptr(file), uintptr(reserved), uintptr(bytesLow), uintptr(bytesHigh), uintptr(unsafe.Pointer(overlapped))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3531,7 +3531,7 @@ func UnlockFileEx(file Handle, reserved uint32, bytesLow uint32, bytesHigh uint3 func UnmapViewOfFile(addr uintptr) (err error) { r1, _, e1 := syscall.SyscallN(procUnmapViewOfFile.Addr(), uintptr(addr)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3539,7 +3539,7 @@ func UnmapViewOfFile(addr uintptr) (err error) { func updateProcThreadAttribute(attrlist *ProcThreadAttributeList, flags uint32, attr uintptr, value unsafe.Pointer, size uintptr, prevvalue unsafe.Pointer, returnedsize *uintptr) (err error) { r1, _, e1 := syscall.SyscallN(procUpdateProcThreadAttribute.Addr(), uintptr(unsafe.Pointer(attrlist)), uintptr(flags), uintptr(attr), uintptr(value), uintptr(size), uintptr(prevvalue), uintptr(unsafe.Pointer(returnedsize))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3556,7 +3556,7 @@ func VirtualAlloc(address uintptr, size uintptr, alloctype uint32, protect uint3 func VirtualFree(address uintptr, size uintptr, freetype uint32) (err error) { r1, _, e1 := syscall.SyscallN(procVirtualFree.Addr(), uintptr(address), uintptr(size), uintptr(freetype)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3564,7 +3564,7 @@ func VirtualFree(address uintptr, size uintptr, freetype uint32) (err error) { func VirtualLock(addr uintptr, length uintptr) (err error) { r1, _, e1 := syscall.SyscallN(procVirtualLock.Addr(), uintptr(addr), uintptr(length)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3572,7 +3572,7 @@ func VirtualLock(addr uintptr, length uintptr) (err error) { func VirtualProtect(address uintptr, size uintptr, newprotect uint32, oldprotect *uint32) (err error) { r1, _, e1 := syscall.SyscallN(procVirtualProtect.Addr(), uintptr(address), uintptr(size), uintptr(newprotect), uintptr(unsafe.Pointer(oldprotect))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3580,7 +3580,7 @@ func VirtualProtect(address uintptr, size uintptr, newprotect uint32, oldprotect func VirtualProtectEx(process Handle, address uintptr, size uintptr, newProtect uint32, oldProtect *uint32) (err error) { r1, _, e1 := syscall.SyscallN(procVirtualProtectEx.Addr(), uintptr(process), uintptr(address), uintptr(size), uintptr(newProtect), uintptr(unsafe.Pointer(oldProtect))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3588,7 +3588,7 @@ func VirtualProtectEx(process Handle, address uintptr, size uintptr, newProtect func VirtualQuery(address uintptr, buffer *MemoryBasicInformation, length uintptr) (err error) { r1, _, e1 := syscall.SyscallN(procVirtualQuery.Addr(), uintptr(address), uintptr(unsafe.Pointer(buffer)), uintptr(length)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3596,7 +3596,7 @@ func VirtualQuery(address uintptr, buffer *MemoryBasicInformation, length uintpt func VirtualQueryEx(process Handle, address uintptr, buffer *MemoryBasicInformation, length uintptr) (err error) { r1, _, e1 := syscall.SyscallN(procVirtualQueryEx.Addr(), uintptr(process), uintptr(address), uintptr(unsafe.Pointer(buffer)), uintptr(length)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3604,7 +3604,7 @@ func VirtualQueryEx(process Handle, address uintptr, buffer *MemoryBasicInformat func VirtualUnlock(addr uintptr, length uintptr) (err error) { r1, _, e1 := syscall.SyscallN(procVirtualUnlock.Addr(), uintptr(addr), uintptr(length)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3618,7 +3618,7 @@ func WTSGetActiveConsoleSessionId() (sessionID uint32) { func WaitCommEvent(handle Handle, lpEvtMask *uint32, lpOverlapped *Overlapped) (err error) { r1, _, e1 := syscall.SyscallN(procWaitCommEvent.Addr(), uintptr(handle), uintptr(unsafe.Pointer(lpEvtMask)), uintptr(unsafe.Pointer(lpOverlapped))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3648,7 +3648,7 @@ func WaitForSingleObject(handle Handle, waitMilliseconds uint32) (event uint32, func WriteConsole(console Handle, buf *uint16, towrite uint32, written *uint32, reserved *byte) (err error) { r1, _, e1 := syscall.SyscallN(procWriteConsoleW.Addr(), uintptr(console), uintptr(unsafe.Pointer(buf)), uintptr(towrite), uintptr(unsafe.Pointer(written)), uintptr(unsafe.Pointer(reserved))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3660,7 +3660,7 @@ func writeFile(handle Handle, buf []byte, done *uint32, overlapped *Overlapped) _p0 = &buf[0] } r1, _, e1 := syscall.SyscallN(procWriteFile.Addr(), uintptr(handle), uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), uintptr(unsafe.Pointer(done)), uintptr(unsafe.Pointer(overlapped))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3668,7 +3668,7 @@ func writeFile(handle Handle, buf []byte, done *uint32, overlapped *Overlapped) func WriteProcessMemory(process Handle, baseAddress uintptr, buffer *byte, size uintptr, numberOfBytesWritten *uintptr) (err error) { r1, _, e1 := syscall.SyscallN(procWriteProcessMemory.Addr(), uintptr(process), uintptr(baseAddress), uintptr(unsafe.Pointer(buffer)), uintptr(size), uintptr(unsafe.Pointer(numberOfBytesWritten))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3676,7 +3676,7 @@ func WriteProcessMemory(process Handle, baseAddress uintptr, buffer *byte, size func AcceptEx(ls Handle, as Handle, buf *byte, rxdatalen uint32, laddrlen uint32, raddrlen uint32, recvd *uint32, overlapped *Overlapped) (err error) { r1, _, e1 := syscall.SyscallN(procAcceptEx.Addr(), uintptr(ls), uintptr(as), uintptr(unsafe.Pointer(buf)), uintptr(rxdatalen), uintptr(laddrlen), uintptr(raddrlen), uintptr(unsafe.Pointer(recvd)), uintptr(unsafe.Pointer(overlapped))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3689,7 +3689,7 @@ func GetAcceptExSockaddrs(buf *byte, rxdatalen uint32, laddrlen uint32, raddrlen func TransmitFile(s Handle, handle Handle, bytesToWrite uint32, bytsPerSend uint32, overlapped *Overlapped, transmitFileBuf *TransmitFileBuffers, flags uint32) (err error) { r1, _, e1 := syscall.SyscallN(procTransmitFile.Addr(), uintptr(s), uintptr(handle), uintptr(bytesToWrite), uintptr(bytsPerSend), uintptr(unsafe.Pointer(overlapped)), uintptr(unsafe.Pointer(transmitFileBuf)), uintptr(flags)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3697,48 +3697,48 @@ func TransmitFile(s Handle, handle Handle, bytesToWrite uint32, bytsPerSend uint func NetApiBufferFree(buf *byte) (neterr error) { r0, _, _ := syscall.SyscallN(procNetApiBufferFree.Addr(), uintptr(unsafe.Pointer(buf))) - if r0 != 0 { - neterr = syscall.Errno(r0) + if uint32(r0) != 0 { + neterr = syscall.Errno(uint32(r0)) } return } func NetGetJoinInformation(server *uint16, name **uint16, bufType *uint32) (neterr error) { r0, _, _ := syscall.SyscallN(procNetGetJoinInformation.Addr(), uintptr(unsafe.Pointer(server)), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(bufType))) - if r0 != 0 { - neterr = syscall.Errno(r0) + if uint32(r0) != 0 { + neterr = syscall.Errno(uint32(r0)) } return } func NetUserEnum(serverName *uint16, level uint32, filter uint32, buf **byte, prefMaxLen uint32, entriesRead *uint32, totalEntries *uint32, resumeHandle *uint32) (neterr error) { r0, _, _ := syscall.SyscallN(procNetUserEnum.Addr(), uintptr(unsafe.Pointer(serverName)), uintptr(level), uintptr(filter), uintptr(unsafe.Pointer(buf)), uintptr(prefMaxLen), uintptr(unsafe.Pointer(entriesRead)), uintptr(unsafe.Pointer(totalEntries)), uintptr(unsafe.Pointer(resumeHandle))) - if r0 != 0 { - neterr = syscall.Errno(r0) + if uint32(r0) != 0 { + neterr = syscall.Errno(uint32(r0)) } return } func NetUserGetInfo(serverName *uint16, userName *uint16, level uint32, buf **byte) (neterr error) { r0, _, _ := syscall.SyscallN(procNetUserGetInfo.Addr(), uintptr(unsafe.Pointer(serverName)), uintptr(unsafe.Pointer(userName)), uintptr(level), uintptr(unsafe.Pointer(buf))) - if r0 != 0 { - neterr = syscall.Errno(r0) + if uint32(r0) != 0 { + neterr = syscall.Errno(uint32(r0)) } return } func NtCreateFile(handle *Handle, access uint32, oa *OBJECT_ATTRIBUTES, iosb *IO_STATUS_BLOCK, allocationSize *int64, attributes uint32, share uint32, disposition uint32, options uint32, eabuffer uintptr, ealength uint32) (ntstatus error) { r0, _, _ := syscall.SyscallN(procNtCreateFile.Addr(), uintptr(unsafe.Pointer(handle)), uintptr(access), uintptr(unsafe.Pointer(oa)), uintptr(unsafe.Pointer(iosb)), uintptr(unsafe.Pointer(allocationSize)), uintptr(attributes), uintptr(share), uintptr(disposition), uintptr(options), uintptr(eabuffer), uintptr(ealength)) - if r0 != 0 { - ntstatus = NTStatus(r0) + if uint32(r0) != 0 { + ntstatus = NTStatus(uint32(r0)) } return } func NtCreateNamedPipeFile(pipe *Handle, access uint32, oa *OBJECT_ATTRIBUTES, iosb *IO_STATUS_BLOCK, share uint32, disposition uint32, options uint32, typ uint32, readMode uint32, completionMode uint32, maxInstances uint32, inboundQuota uint32, outputQuota uint32, timeout *int64) (ntstatus error) { r0, _, _ := syscall.SyscallN(procNtCreateNamedPipeFile.Addr(), uintptr(unsafe.Pointer(pipe)), uintptr(access), uintptr(unsafe.Pointer(oa)), uintptr(unsafe.Pointer(iosb)), uintptr(share), uintptr(disposition), uintptr(options), uintptr(typ), uintptr(readMode), uintptr(completionMode), uintptr(maxInstances), uintptr(inboundQuota), uintptr(outputQuota), uintptr(unsafe.Pointer(timeout))) - if r0 != 0 { - ntstatus = NTStatus(r0) + if uint32(r0) != 0 { + ntstatus = NTStatus(uint32(r0)) } return } @@ -3753,100 +3753,100 @@ func NtQueryEaFile(handle Handle, iosb *IO_STATUS_BLOCK, outBuffer *byte, outBuf _p1 = 1 } r0, _, _ := syscall.SyscallN(procNtQueryEaFile.Addr(), uintptr(handle), uintptr(unsafe.Pointer(iosb)), uintptr(unsafe.Pointer(outBuffer)), uintptr(outBufferLen), uintptr(_p0), uintptr(unsafe.Pointer(eaList)), uintptr(eaListLen), uintptr(unsafe.Pointer(eaIndex)), uintptr(_p1)) - if r0 != 0 { - ntstatus = NTStatus(r0) + if uint32(r0) != 0 { + ntstatus = NTStatus(uint32(r0)) } return } func NtQueryInformationFile(handle Handle, iosb *IO_STATUS_BLOCK, outBuffer *byte, outBufferLen uint32, class uint32) (ntstatus error) { r0, _, _ := syscall.SyscallN(procNtQueryInformationFile.Addr(), uintptr(handle), uintptr(unsafe.Pointer(iosb)), uintptr(unsafe.Pointer(outBuffer)), uintptr(outBufferLen), uintptr(class)) - if r0 != 0 { - ntstatus = NTStatus(r0) + if uint32(r0) != 0 { + ntstatus = NTStatus(uint32(r0)) } return } func NtQueryInformationProcess(proc Handle, procInfoClass int32, procInfo unsafe.Pointer, procInfoLen uint32, retLen *uint32) (ntstatus error) { r0, _, _ := syscall.SyscallN(procNtQueryInformationProcess.Addr(), uintptr(proc), uintptr(procInfoClass), uintptr(procInfo), uintptr(procInfoLen), uintptr(unsafe.Pointer(retLen))) - if r0 != 0 { - ntstatus = NTStatus(r0) + if uint32(r0) != 0 { + ntstatus = NTStatus(uint32(r0)) } return } func NtQuerySystemInformation(sysInfoClass int32, sysInfo unsafe.Pointer, sysInfoLen uint32, retLen *uint32) (ntstatus error) { r0, _, _ := syscall.SyscallN(procNtQuerySystemInformation.Addr(), uintptr(sysInfoClass), uintptr(sysInfo), uintptr(sysInfoLen), uintptr(unsafe.Pointer(retLen))) - if r0 != 0 { - ntstatus = NTStatus(r0) + if uint32(r0) != 0 { + ntstatus = NTStatus(uint32(r0)) } return } func NtSetEaFile(handle Handle, iosb *IO_STATUS_BLOCK, inBuffer *byte, inBufferLen uint32) (ntstatus error) { r0, _, _ := syscall.SyscallN(procNtSetEaFile.Addr(), uintptr(handle), uintptr(unsafe.Pointer(iosb)), uintptr(unsafe.Pointer(inBuffer)), uintptr(inBufferLen)) - if r0 != 0 { - ntstatus = NTStatus(r0) + if uint32(r0) != 0 { + ntstatus = NTStatus(uint32(r0)) } return } func NtSetInformationFile(handle Handle, iosb *IO_STATUS_BLOCK, inBuffer *byte, inBufferLen uint32, class uint32) (ntstatus error) { r0, _, _ := syscall.SyscallN(procNtSetInformationFile.Addr(), uintptr(handle), uintptr(unsafe.Pointer(iosb)), uintptr(unsafe.Pointer(inBuffer)), uintptr(inBufferLen), uintptr(class)) - if r0 != 0 { - ntstatus = NTStatus(r0) + if uint32(r0) != 0 { + ntstatus = NTStatus(uint32(r0)) } return } func NtSetInformationProcess(proc Handle, procInfoClass int32, procInfo unsafe.Pointer, procInfoLen uint32) (ntstatus error) { r0, _, _ := syscall.SyscallN(procNtSetInformationProcess.Addr(), uintptr(proc), uintptr(procInfoClass), uintptr(procInfo), uintptr(procInfoLen)) - if r0 != 0 { - ntstatus = NTStatus(r0) + if uint32(r0) != 0 { + ntstatus = NTStatus(uint32(r0)) } return } func NtSetSystemInformation(sysInfoClass int32, sysInfo unsafe.Pointer, sysInfoLen uint32) (ntstatus error) { r0, _, _ := syscall.SyscallN(procNtSetSystemInformation.Addr(), uintptr(sysInfoClass), uintptr(sysInfo), uintptr(sysInfoLen)) - if r0 != 0 { - ntstatus = NTStatus(r0) + if uint32(r0) != 0 { + ntstatus = NTStatus(uint32(r0)) } return } func RtlAddFunctionTable(functionTable *RUNTIME_FUNCTION, entryCount uint32, baseAddress uintptr) (ret bool) { r0, _, _ := syscall.SyscallN(procRtlAddFunctionTable.Addr(), uintptr(unsafe.Pointer(functionTable)), uintptr(entryCount), uintptr(baseAddress)) - ret = r0 != 0 + ret = uint32(r0) != 0 return } func RtlDefaultNpAcl(acl **ACL) (ntstatus error) { r0, _, _ := syscall.SyscallN(procRtlDefaultNpAcl.Addr(), uintptr(unsafe.Pointer(acl))) - if r0 != 0 { - ntstatus = NTStatus(r0) + if uint32(r0) != 0 { + ntstatus = NTStatus(uint32(r0)) } return } func RtlDeleteFunctionTable(functionTable *RUNTIME_FUNCTION) (ret bool) { r0, _, _ := syscall.SyscallN(procRtlDeleteFunctionTable.Addr(), uintptr(unsafe.Pointer(functionTable))) - ret = r0 != 0 + ret = uint32(r0) != 0 return } func RtlDosPathNameToNtPathName(dosName *uint16, ntName *NTUnicodeString, ntFileNamePart *uint16, relativeName *RTL_RELATIVE_NAME) (ntstatus error) { r0, _, _ := syscall.SyscallN(procRtlDosPathNameToNtPathName_U_WithStatus.Addr(), uintptr(unsafe.Pointer(dosName)), uintptr(unsafe.Pointer(ntName)), uintptr(unsafe.Pointer(ntFileNamePart)), uintptr(unsafe.Pointer(relativeName))) - if r0 != 0 { - ntstatus = NTStatus(r0) + if uint32(r0) != 0 { + ntstatus = NTStatus(uint32(r0)) } return } func RtlDosPathNameToRelativeNtPathName(dosName *uint16, ntName *NTUnicodeString, ntFileNamePart *uint16, relativeName *RTL_RELATIVE_NAME) (ntstatus error) { r0, _, _ := syscall.SyscallN(procRtlDosPathNameToRelativeNtPathName_U_WithStatus.Addr(), uintptr(unsafe.Pointer(dosName)), uintptr(unsafe.Pointer(ntName)), uintptr(unsafe.Pointer(ntFileNamePart)), uintptr(unsafe.Pointer(relativeName))) - if r0 != 0 { - ntstatus = NTStatus(r0) + if uint32(r0) != 0 { + ntstatus = NTStatus(uint32(r0)) } return } @@ -3864,8 +3864,8 @@ func rtlGetNtVersionNumbers(majorVersion *uint32, minorVersion *uint32, buildNum func rtlGetVersion(info *OsVersionInfoEx) (ntstatus error) { r0, _, _ := syscall.SyscallN(procRtlGetVersion.Addr(), uintptr(unsafe.Pointer(info))) - if r0 != 0 { - ntstatus = NTStatus(r0) + if uint32(r0) != 0 { + ntstatus = NTStatus(uint32(r0)) } return } @@ -3888,32 +3888,32 @@ func rtlNtStatusToDosErrorNoTeb(ntstatus NTStatus) (ret syscall.Errno) { func clsidFromString(lpsz *uint16, pclsid *GUID) (ret error) { r0, _, _ := syscall.SyscallN(procCLSIDFromString.Addr(), uintptr(unsafe.Pointer(lpsz)), uintptr(unsafe.Pointer(pclsid))) - if r0 != 0 { - ret = syscall.Errno(r0) + if uint32(r0) != 0 { + ret = syscall.Errno(uint32(r0)) } return } func coCreateGuid(pguid *GUID) (ret error) { r0, _, _ := syscall.SyscallN(procCoCreateGuid.Addr(), uintptr(unsafe.Pointer(pguid))) - if r0 != 0 { - ret = syscall.Errno(r0) + if uint32(r0) != 0 { + ret = syscall.Errno(uint32(r0)) } return } func CoGetObject(name *uint16, bindOpts *BIND_OPTS3, guid *GUID, functionTable **uintptr) (ret error) { r0, _, _ := syscall.SyscallN(procCoGetObject.Addr(), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(bindOpts)), uintptr(unsafe.Pointer(guid)), uintptr(unsafe.Pointer(functionTable))) - if r0 != 0 { - ret = syscall.Errno(r0) + if uint32(r0) != 0 { + ret = syscall.Errno(uint32(r0)) } return } func CoInitializeEx(reserved uintptr, coInit uint32) (ret error) { r0, _, _ := syscall.SyscallN(procCoInitializeEx.Addr(), uintptr(reserved), uintptr(coInit)) - if r0 != 0 { - ret = syscall.Errno(r0) + if uint32(r0) != 0 { + ret = syscall.Errno(uint32(r0)) } return } @@ -3936,7 +3936,7 @@ func stringFromGUID2(rguid *GUID, lpsz *uint16, cchMax int32) (chars int32) { func EnumProcessModules(process Handle, module *Handle, cb uint32, cbNeeded *uint32) (err error) { r1, _, e1 := syscall.SyscallN(procEnumProcessModules.Addr(), uintptr(process), uintptr(unsafe.Pointer(module)), uintptr(cb), uintptr(unsafe.Pointer(cbNeeded))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3944,7 +3944,7 @@ func EnumProcessModules(process Handle, module *Handle, cb uint32, cbNeeded *uin func EnumProcessModulesEx(process Handle, module *Handle, cb uint32, cbNeeded *uint32, filterFlag uint32) (err error) { r1, _, e1 := syscall.SyscallN(procEnumProcessModulesEx.Addr(), uintptr(process), uintptr(unsafe.Pointer(module)), uintptr(cb), uintptr(unsafe.Pointer(cbNeeded)), uintptr(filterFlag)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3952,7 +3952,7 @@ func EnumProcessModulesEx(process Handle, module *Handle, cb uint32, cbNeeded *u func enumProcesses(processIds *uint32, nSize uint32, bytesReturned *uint32) (err error) { r1, _, e1 := syscall.SyscallN(procEnumProcesses.Addr(), uintptr(unsafe.Pointer(processIds)), uintptr(nSize), uintptr(unsafe.Pointer(bytesReturned))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3960,7 +3960,7 @@ func enumProcesses(processIds *uint32, nSize uint32, bytesReturned *uint32) (err func GetModuleBaseName(process Handle, module Handle, baseName *uint16, size uint32) (err error) { r1, _, e1 := syscall.SyscallN(procGetModuleBaseNameW.Addr(), uintptr(process), uintptr(module), uintptr(unsafe.Pointer(baseName)), uintptr(size)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3968,7 +3968,7 @@ func GetModuleBaseName(process Handle, module Handle, baseName *uint16, size uin func GetModuleFileNameEx(process Handle, module Handle, filename *uint16, size uint32) (err error) { r1, _, e1 := syscall.SyscallN(procGetModuleFileNameExW.Addr(), uintptr(process), uintptr(module), uintptr(unsafe.Pointer(filename)), uintptr(size)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3976,7 +3976,7 @@ func GetModuleFileNameEx(process Handle, module Handle, filename *uint16, size u func GetModuleInformation(process Handle, module Handle, modinfo *ModuleInfo, cb uint32) (err error) { r1, _, e1 := syscall.SyscallN(procGetModuleInformation.Addr(), uintptr(process), uintptr(module), uintptr(unsafe.Pointer(modinfo)), uintptr(cb)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3984,7 +3984,7 @@ func GetModuleInformation(process Handle, module Handle, modinfo *ModuleInfo, cb func QueryWorkingSetEx(process Handle, pv uintptr, cb uint32) (err error) { r1, _, e1 := syscall.SyscallN(procQueryWorkingSetEx.Addr(), uintptr(process), uintptr(pv), uintptr(cb)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -3996,8 +3996,8 @@ func SubscribeServiceChangeNotifications(service Handle, eventType uint32, callb return } r0, _, _ := syscall.SyscallN(procSubscribeServiceChangeNotifications.Addr(), uintptr(service), uintptr(eventType), uintptr(callback), uintptr(callbackCtx), uintptr(unsafe.Pointer(subscription))) - if r0 != 0 { - ret = syscall.Errno(r0) + if uint32(r0) != 0 { + ret = syscall.Errno(uint32(r0)) } return } @@ -4029,7 +4029,7 @@ func TranslateName(accName *uint16, accNameFormat uint32, desiredNameFormat uint func SetupDiBuildDriverInfoList(deviceInfoSet DevInfo, deviceInfoData *DevInfoData, driverType SPDIT) (err error) { r1, _, e1 := syscall.SyscallN(procSetupDiBuildDriverInfoList.Addr(), uintptr(deviceInfoSet), uintptr(unsafe.Pointer(deviceInfoData)), uintptr(driverType)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -4037,7 +4037,7 @@ func SetupDiBuildDriverInfoList(deviceInfoSet DevInfo, deviceInfoData *DevInfoDa func SetupDiCallClassInstaller(installFunction DI_FUNCTION, deviceInfoSet DevInfo, deviceInfoData *DevInfoData) (err error) { r1, _, e1 := syscall.SyscallN(procSetupDiCallClassInstaller.Addr(), uintptr(installFunction), uintptr(deviceInfoSet), uintptr(unsafe.Pointer(deviceInfoData))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -4045,7 +4045,7 @@ func SetupDiCallClassInstaller(installFunction DI_FUNCTION, deviceInfoSet DevInf func SetupDiCancelDriverInfoSearch(deviceInfoSet DevInfo) (err error) { r1, _, e1 := syscall.SyscallN(procSetupDiCancelDriverInfoSearch.Addr(), uintptr(deviceInfoSet)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -4053,7 +4053,7 @@ func SetupDiCancelDriverInfoSearch(deviceInfoSet DevInfo) (err error) { func setupDiClassGuidsFromNameEx(className *uint16, classGuidList *GUID, classGuidListSize uint32, requiredSize *uint32, machineName *uint16, reserved uintptr) (err error) { r1, _, e1 := syscall.SyscallN(procSetupDiClassGuidsFromNameExW.Addr(), uintptr(unsafe.Pointer(className)), uintptr(unsafe.Pointer(classGuidList)), uintptr(classGuidListSize), uintptr(unsafe.Pointer(requiredSize)), uintptr(unsafe.Pointer(machineName)), uintptr(reserved)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -4061,7 +4061,7 @@ func setupDiClassGuidsFromNameEx(className *uint16, classGuidList *GUID, classGu func setupDiClassNameFromGuidEx(classGUID *GUID, className *uint16, classNameSize uint32, requiredSize *uint32, machineName *uint16, reserved uintptr) (err error) { r1, _, e1 := syscall.SyscallN(procSetupDiClassNameFromGuidExW.Addr(), uintptr(unsafe.Pointer(classGUID)), uintptr(unsafe.Pointer(className)), uintptr(classNameSize), uintptr(unsafe.Pointer(requiredSize)), uintptr(unsafe.Pointer(machineName)), uintptr(reserved)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -4078,7 +4078,7 @@ func setupDiCreateDeviceInfoListEx(classGUID *GUID, hwndParent uintptr, machineN func setupDiCreateDeviceInfo(deviceInfoSet DevInfo, DeviceName *uint16, classGUID *GUID, DeviceDescription *uint16, hwndParent uintptr, CreationFlags DICD, deviceInfoData *DevInfoData) (err error) { r1, _, e1 := syscall.SyscallN(procSetupDiCreateDeviceInfoW.Addr(), uintptr(deviceInfoSet), uintptr(unsafe.Pointer(DeviceName)), uintptr(unsafe.Pointer(classGUID)), uintptr(unsafe.Pointer(DeviceDescription)), uintptr(hwndParent), uintptr(CreationFlags), uintptr(unsafe.Pointer(deviceInfoData))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -4086,7 +4086,7 @@ func setupDiCreateDeviceInfo(deviceInfoSet DevInfo, DeviceName *uint16, classGUI func SetupDiDestroyDeviceInfoList(deviceInfoSet DevInfo) (err error) { r1, _, e1 := syscall.SyscallN(procSetupDiDestroyDeviceInfoList.Addr(), uintptr(deviceInfoSet)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -4094,7 +4094,7 @@ func SetupDiDestroyDeviceInfoList(deviceInfoSet DevInfo) (err error) { func SetupDiDestroyDriverInfoList(deviceInfoSet DevInfo, deviceInfoData *DevInfoData, driverType SPDIT) (err error) { r1, _, e1 := syscall.SyscallN(procSetupDiDestroyDriverInfoList.Addr(), uintptr(deviceInfoSet), uintptr(unsafe.Pointer(deviceInfoData)), uintptr(driverType)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -4102,7 +4102,7 @@ func SetupDiDestroyDriverInfoList(deviceInfoSet DevInfo, deviceInfoData *DevInfo func setupDiEnumDeviceInfo(deviceInfoSet DevInfo, memberIndex uint32, deviceInfoData *DevInfoData) (err error) { r1, _, e1 := syscall.SyscallN(procSetupDiEnumDeviceInfo.Addr(), uintptr(deviceInfoSet), uintptr(memberIndex), uintptr(unsafe.Pointer(deviceInfoData))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -4110,7 +4110,7 @@ func setupDiEnumDeviceInfo(deviceInfoSet DevInfo, memberIndex uint32, deviceInfo func setupDiEnumDriverInfo(deviceInfoSet DevInfo, deviceInfoData *DevInfoData, driverType SPDIT, memberIndex uint32, driverInfoData *DrvInfoData) (err error) { r1, _, e1 := syscall.SyscallN(procSetupDiEnumDriverInfoW.Addr(), uintptr(deviceInfoSet), uintptr(unsafe.Pointer(deviceInfoData)), uintptr(driverType), uintptr(memberIndex), uintptr(unsafe.Pointer(driverInfoData))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -4127,7 +4127,7 @@ func setupDiGetClassDevsEx(classGUID *GUID, Enumerator *uint16, hwndParent uintp func SetupDiGetClassInstallParams(deviceInfoSet DevInfo, deviceInfoData *DevInfoData, classInstallParams *ClassInstallHeader, classInstallParamsSize uint32, requiredSize *uint32) (err error) { r1, _, e1 := syscall.SyscallN(procSetupDiGetClassInstallParamsW.Addr(), uintptr(deviceInfoSet), uintptr(unsafe.Pointer(deviceInfoData)), uintptr(unsafe.Pointer(classInstallParams)), uintptr(classInstallParamsSize), uintptr(unsafe.Pointer(requiredSize))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -4135,7 +4135,7 @@ func SetupDiGetClassInstallParams(deviceInfoSet DevInfo, deviceInfoData *DevInfo func setupDiGetDeviceInfoListDetail(deviceInfoSet DevInfo, deviceInfoSetDetailData *DevInfoListDetailData) (err error) { r1, _, e1 := syscall.SyscallN(procSetupDiGetDeviceInfoListDetailW.Addr(), uintptr(deviceInfoSet), uintptr(unsafe.Pointer(deviceInfoSetDetailData))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -4143,7 +4143,7 @@ func setupDiGetDeviceInfoListDetail(deviceInfoSet DevInfo, deviceInfoSetDetailDa func setupDiGetDeviceInstallParams(deviceInfoSet DevInfo, deviceInfoData *DevInfoData, deviceInstallParams *DevInstallParams) (err error) { r1, _, e1 := syscall.SyscallN(procSetupDiGetDeviceInstallParamsW.Addr(), uintptr(deviceInfoSet), uintptr(unsafe.Pointer(deviceInfoData)), uintptr(unsafe.Pointer(deviceInstallParams))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -4151,7 +4151,7 @@ func setupDiGetDeviceInstallParams(deviceInfoSet DevInfo, deviceInfoData *DevInf func setupDiGetDeviceInstanceId(deviceInfoSet DevInfo, deviceInfoData *DevInfoData, instanceId *uint16, instanceIdSize uint32, instanceIdRequiredSize *uint32) (err error) { r1, _, e1 := syscall.SyscallN(procSetupDiGetDeviceInstanceIdW.Addr(), uintptr(deviceInfoSet), uintptr(unsafe.Pointer(deviceInfoData)), uintptr(unsafe.Pointer(instanceId)), uintptr(instanceIdSize), uintptr(unsafe.Pointer(instanceIdRequiredSize))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -4159,7 +4159,7 @@ func setupDiGetDeviceInstanceId(deviceInfoSet DevInfo, deviceInfoData *DevInfoDa func setupDiGetDeviceProperty(deviceInfoSet DevInfo, deviceInfoData *DevInfoData, propertyKey *DEVPROPKEY, propertyType *DEVPROPTYPE, propertyBuffer *byte, propertyBufferSize uint32, requiredSize *uint32, flags uint32) (err error) { r1, _, e1 := syscall.SyscallN(procSetupDiGetDevicePropertyW.Addr(), uintptr(deviceInfoSet), uintptr(unsafe.Pointer(deviceInfoData)), uintptr(unsafe.Pointer(propertyKey)), uintptr(unsafe.Pointer(propertyType)), uintptr(unsafe.Pointer(propertyBuffer)), uintptr(propertyBufferSize), uintptr(unsafe.Pointer(requiredSize)), uintptr(flags)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -4167,7 +4167,7 @@ func setupDiGetDeviceProperty(deviceInfoSet DevInfo, deviceInfoData *DevInfoData func setupDiGetDeviceRegistryProperty(deviceInfoSet DevInfo, deviceInfoData *DevInfoData, property SPDRP, propertyRegDataType *uint32, propertyBuffer *byte, propertyBufferSize uint32, requiredSize *uint32) (err error) { r1, _, e1 := syscall.SyscallN(procSetupDiGetDeviceRegistryPropertyW.Addr(), uintptr(deviceInfoSet), uintptr(unsafe.Pointer(deviceInfoData)), uintptr(property), uintptr(unsafe.Pointer(propertyRegDataType)), uintptr(unsafe.Pointer(propertyBuffer)), uintptr(propertyBufferSize), uintptr(unsafe.Pointer(requiredSize))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -4175,7 +4175,7 @@ func setupDiGetDeviceRegistryProperty(deviceInfoSet DevInfo, deviceInfoData *Dev func setupDiGetDriverInfoDetail(deviceInfoSet DevInfo, deviceInfoData *DevInfoData, driverInfoData *DrvInfoData, driverInfoDetailData *DrvInfoDetailData, driverInfoDetailDataSize uint32, requiredSize *uint32) (err error) { r1, _, e1 := syscall.SyscallN(procSetupDiGetDriverInfoDetailW.Addr(), uintptr(deviceInfoSet), uintptr(unsafe.Pointer(deviceInfoData)), uintptr(unsafe.Pointer(driverInfoData)), uintptr(unsafe.Pointer(driverInfoDetailData)), uintptr(driverInfoDetailDataSize), uintptr(unsafe.Pointer(requiredSize))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -4183,7 +4183,7 @@ func setupDiGetDriverInfoDetail(deviceInfoSet DevInfo, deviceInfoData *DevInfoDa func setupDiGetSelectedDevice(deviceInfoSet DevInfo, deviceInfoData *DevInfoData) (err error) { r1, _, e1 := syscall.SyscallN(procSetupDiGetSelectedDevice.Addr(), uintptr(deviceInfoSet), uintptr(unsafe.Pointer(deviceInfoData))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -4191,7 +4191,7 @@ func setupDiGetSelectedDevice(deviceInfoSet DevInfo, deviceInfoData *DevInfoData func setupDiGetSelectedDriver(deviceInfoSet DevInfo, deviceInfoData *DevInfoData, driverInfoData *DrvInfoData) (err error) { r1, _, e1 := syscall.SyscallN(procSetupDiGetSelectedDriverW.Addr(), uintptr(deviceInfoSet), uintptr(unsafe.Pointer(deviceInfoData)), uintptr(unsafe.Pointer(driverInfoData))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -4208,7 +4208,7 @@ func SetupDiOpenDevRegKey(deviceInfoSet DevInfo, deviceInfoData *DevInfoData, Sc func SetupDiSetClassInstallParams(deviceInfoSet DevInfo, deviceInfoData *DevInfoData, classInstallParams *ClassInstallHeader, classInstallParamsSize uint32) (err error) { r1, _, e1 := syscall.SyscallN(procSetupDiSetClassInstallParamsW.Addr(), uintptr(deviceInfoSet), uintptr(unsafe.Pointer(deviceInfoData)), uintptr(unsafe.Pointer(classInstallParams)), uintptr(classInstallParamsSize)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -4216,7 +4216,7 @@ func SetupDiSetClassInstallParams(deviceInfoSet DevInfo, deviceInfoData *DevInfo func SetupDiSetDeviceInstallParams(deviceInfoSet DevInfo, deviceInfoData *DevInfoData, deviceInstallParams *DevInstallParams) (err error) { r1, _, e1 := syscall.SyscallN(procSetupDiSetDeviceInstallParamsW.Addr(), uintptr(deviceInfoSet), uintptr(unsafe.Pointer(deviceInfoData)), uintptr(unsafe.Pointer(deviceInstallParams))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -4224,7 +4224,7 @@ func SetupDiSetDeviceInstallParams(deviceInfoSet DevInfo, deviceInfoData *DevInf func setupDiSetDeviceRegistryProperty(deviceInfoSet DevInfo, deviceInfoData *DevInfoData, property SPDRP, propertyBuffer *byte, propertyBufferSize uint32) (err error) { r1, _, e1 := syscall.SyscallN(procSetupDiSetDeviceRegistryPropertyW.Addr(), uintptr(deviceInfoSet), uintptr(unsafe.Pointer(deviceInfoData)), uintptr(property), uintptr(unsafe.Pointer(propertyBuffer)), uintptr(propertyBufferSize)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -4232,7 +4232,7 @@ func setupDiSetDeviceRegistryProperty(deviceInfoSet DevInfo, deviceInfoData *Dev func SetupDiSetSelectedDevice(deviceInfoSet DevInfo, deviceInfoData *DevInfoData) (err error) { r1, _, e1 := syscall.SyscallN(procSetupDiSetSelectedDevice.Addr(), uintptr(deviceInfoSet), uintptr(unsafe.Pointer(deviceInfoData))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -4240,7 +4240,7 @@ func SetupDiSetSelectedDevice(deviceInfoSet DevInfo, deviceInfoData *DevInfoData func SetupDiSetSelectedDriver(deviceInfoSet DevInfo, deviceInfoData *DevInfoData, driverInfoData *DrvInfoData) (err error) { r1, _, e1 := syscall.SyscallN(procSetupDiSetSelectedDriverW.Addr(), uintptr(deviceInfoSet), uintptr(unsafe.Pointer(deviceInfoData)), uintptr(unsafe.Pointer(driverInfoData))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -4248,7 +4248,7 @@ func SetupDiSetSelectedDriver(deviceInfoSet DevInfo, deviceInfoData *DevInfoData func setupUninstallOEMInf(infFileName *uint16, flags SUOI, reserved uintptr) (err error) { r1, _, e1 := syscall.SyscallN(procSetupUninstallOEMInfW.Addr(), uintptr(unsafe.Pointer(infFileName)), uintptr(flags), uintptr(reserved)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -4265,8 +4265,8 @@ func commandLineToArgv(cmd *uint16, argc *int32) (argv **uint16, err error) { func shGetKnownFolderPath(id *KNOWNFOLDERID, flags uint32, token Token, path **uint16) (ret error) { r0, _, _ := syscall.SyscallN(procSHGetKnownFolderPath.Addr(), uintptr(unsafe.Pointer(id)), uintptr(flags), uintptr(token), uintptr(unsafe.Pointer(path))) - if r0 != 0 { - ret = syscall.Errno(r0) + if uint32(r0) != 0 { + ret = syscall.Errno(uint32(r0)) } return } @@ -4286,7 +4286,7 @@ func EnumChildWindows(hwnd HWND, enumFunc uintptr, param unsafe.Pointer) { func EnumWindows(enumFunc uintptr, param unsafe.Pointer) (err error) { r1, _, e1 := syscall.SyscallN(procEnumWindows.Addr(), uintptr(enumFunc), uintptr(param)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -4294,7 +4294,7 @@ func EnumWindows(enumFunc uintptr, param unsafe.Pointer) (err error) { func ExitWindowsEx(flags uint32, reason uint32) (err error) { r1, _, e1 := syscall.SyscallN(procExitWindowsEx.Addr(), uintptr(flags), uintptr(reason)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -4323,7 +4323,7 @@ func GetForegroundWindow() (hwnd HWND) { func GetGUIThreadInfo(thread uint32, info *GUIThreadInfo) (err error) { r1, _, e1 := syscall.SyscallN(procGetGUIThreadInfo.Addr(), uintptr(thread), uintptr(unsafe.Pointer(info))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -4352,19 +4352,19 @@ func GetWindowThreadProcessId(hwnd HWND, pid *uint32) (tid uint32, err error) { func IsWindow(hwnd HWND) (isWindow bool) { r0, _, _ := syscall.SyscallN(procIsWindow.Addr(), uintptr(hwnd)) - isWindow = r0 != 0 + isWindow = uint32(r0) != 0 return } func IsWindowUnicode(hwnd HWND) (isUnicode bool) { r0, _, _ := syscall.SyscallN(procIsWindowUnicode.Addr(), uintptr(hwnd)) - isUnicode = r0 != 0 + isUnicode = uint32(r0) != 0 return } func IsWindowVisible(hwnd HWND) (isVisible bool) { r0, _, _ := syscall.SyscallN(procIsWindowVisible.Addr(), uintptr(hwnd)) - isVisible = r0 != 0 + isVisible = uint32(r0) != 0 return } @@ -4394,7 +4394,7 @@ func ToUnicodeEx(vkey uint32, scancode uint32, keystate *byte, pwszBuff *uint16, func UnloadKeyboardLayout(hkl Handle) (err error) { r1, _, e1 := syscall.SyscallN(procUnloadKeyboardLayout.Addr(), uintptr(hkl)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -4406,7 +4406,7 @@ func CreateEnvironmentBlock(block **uint16, token Token, inheritExisting bool) ( _p0 = 1 } r1, _, e1 := syscall.SyscallN(procCreateEnvironmentBlock.Addr(), uintptr(unsafe.Pointer(block)), uintptr(token), uintptr(_p0)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -4414,7 +4414,7 @@ func CreateEnvironmentBlock(block **uint16, token Token, inheritExisting bool) ( func DestroyEnvironmentBlock(block *uint16) (err error) { r1, _, e1 := syscall.SyscallN(procDestroyEnvironmentBlock.Addr(), uintptr(unsafe.Pointer(block))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -4422,7 +4422,7 @@ func DestroyEnvironmentBlock(block *uint16) (err error) { func GetUserProfileDirectory(t Token, dir *uint16, dirLen *uint32) (err error) { r1, _, e1 := syscall.SyscallN(procGetUserProfileDirectoryW.Addr(), uintptr(t), uintptr(unsafe.Pointer(dir)), uintptr(unsafe.Pointer(dirLen))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -4457,7 +4457,7 @@ func GetFileVersionInfo(filename string, handle uint32, bufSize uint32, buffer u func _GetFileVersionInfo(filename *uint16, handle uint32, bufSize uint32, buffer unsafe.Pointer) (err error) { r1, _, e1 := syscall.SyscallN(procGetFileVersionInfoW.Addr(), uintptr(unsafe.Pointer(filename)), uintptr(handle), uintptr(bufSize), uintptr(buffer)) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -4474,7 +4474,7 @@ func VerQueryValue(block unsafe.Pointer, subBlock string, pointerToBufferPointer func _VerQueryValue(block unsafe.Pointer, subBlock *uint16, pointerToBufferPointer unsafe.Pointer, bufSize *uint32) (err error) { r1, _, e1 := syscall.SyscallN(procVerQueryValueW.Addr(), uintptr(block), uintptr(unsafe.Pointer(subBlock)), uintptr(pointerToBufferPointer), uintptr(unsafe.Pointer(bufSize))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -4498,8 +4498,8 @@ func TimeEndPeriod(period uint32) (err error) { func WinVerifyTrustEx(hwnd HWND, actionId *GUID, data *WinTrustData) (ret error) { r0, _, _ := syscall.SyscallN(procWinVerifyTrustEx.Addr(), uintptr(hwnd), uintptr(unsafe.Pointer(actionId)), uintptr(unsafe.Pointer(data))) - if r0 != 0 { - ret = syscall.Errno(r0) + if uint32(r0) != 0 { + ret = syscall.Errno(uint32(r0)) } return } @@ -4511,8 +4511,8 @@ func FreeAddrInfoW(addrinfo *AddrinfoW) { func GetAddrInfoW(nodename *uint16, servicename *uint16, hints *AddrinfoW, result **AddrinfoW) (sockerr error) { r0, _, _ := syscall.SyscallN(procGetAddrInfoW.Addr(), uintptr(unsafe.Pointer(nodename)), uintptr(unsafe.Pointer(servicename)), uintptr(unsafe.Pointer(hints)), uintptr(unsafe.Pointer(result))) - if r0 != 0 { - sockerr = syscall.Errno(r0) + if uint32(r0) != 0 { + sockerr = syscall.Errno(uint32(r0)) } return } @@ -4548,7 +4548,7 @@ func WSAGetOverlappedResult(h Handle, o *Overlapped, bytes *uint32, wait bool, f _p0 = 1 } r1, _, e1 := syscall.SyscallN(procWSAGetOverlappedResult.Addr(), uintptr(h), uintptr(unsafe.Pointer(o)), uintptr(unsafe.Pointer(bytes)), uintptr(_p0), uintptr(unsafe.Pointer(flags))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -4629,8 +4629,8 @@ func WSASocket(af int32, typ int32, protocol int32, protoInfo *WSAProtocolInfo, func WSAStartup(verreq uint32, data *WSAData) (sockerr error) { r0, _, _ := syscall.SyscallN(procWSAStartup.Addr(), uintptr(verreq), uintptr(unsafe.Pointer(data))) - if r0 != 0 { - sockerr = syscall.Errno(r0) + if uint32(r0) != 0 { + sockerr = syscall.Errno(uint32(r0)) } return } @@ -4808,7 +4808,7 @@ func socket(af int32, typ int32, protocol int32) (handle Handle, err error) { func WTSEnumerateSessions(handle Handle, reserved uint32, version uint32, sessions **WTS_SESSION_INFO, count *uint32) (err error) { r1, _, e1 := syscall.SyscallN(procWTSEnumerateSessionsW.Addr(), uintptr(handle), uintptr(reserved), uintptr(version), uintptr(unsafe.Pointer(sessions)), uintptr(unsafe.Pointer(count))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return @@ -4821,7 +4821,7 @@ func WTSFreeMemory(ptr uintptr) { func WTSQueryUserToken(session uint32, token *Token) (err error) { r1, _, e1 := syscall.SyscallN(procWTSQueryUserToken.Addr(), uintptr(session), uintptr(unsafe.Pointer(token))) - if r1 == 0 { + if uint32(r1) == 0 { err = errnoErr(e1) } return diff --git a/vendor/golang.org/x/text/language/parse.go b/vendor/golang.org/x/text/language/parse.go index 053336e..65b53b9 100644 --- a/vendor/golang.org/x/text/language/parse.go +++ b/vendor/golang.org/x/text/language/parse.go @@ -166,7 +166,9 @@ func ParseAcceptLanguage(s string) (tag []Tag, q []float32, err error) { } }() - if strings.Count(s, "-") > 1000 { + // The BCP 47 scanner aliases '_' to '-' in scanner.init + // (internal/language/parse.go); the guard must count both. + if strings.Count(s, "-")+strings.Count(s, "_") > 1000 { return nil, nil, errTagListTooLarge } diff --git a/vendor/golang.org/x/text/secure/bidirule/bidirule.go b/vendor/golang.org/x/text/secure/bidirule/bidirule.go index 5386327..399cb89 100644 --- a/vendor/golang.org/x/text/secure/bidirule/bidirule.go +++ b/vendor/golang.org/x/text/secure/bidirule/bidirule.go @@ -10,6 +10,7 @@ package bidirule import ( "errors" + "sync" "unicode/utf8" "golang.org/x/text/transform" @@ -246,8 +247,9 @@ func (t *Transformer) Span(src []byte, atEOF bool) (n int, err error) { // Precomputing the ASCII values decreases running time for the ASCII fast path // by about 30%. var asciiTable [128]bidi.Properties +var asciiTableOnce sync.Once -func init() { +func initASCIITable() { for i := range asciiTable { p, _ := bidi.LookupRune(rune(i)) asciiTable[i] = p @@ -255,6 +257,8 @@ func init() { } func (t *Transformer) advance(s []byte) (n int, ok bool) { + asciiTableOnce.Do(initASCIITable) + var e bidi.Properties var sz int for n < len(s) { @@ -297,6 +301,8 @@ func (t *Transformer) advance(s []byte) (n int, ok bool) { } func (t *Transformer) advanceString(s string) (n int, ok bool) { + asciiTableOnce.Do(initASCIITable) + var e bidi.Properties var sz int for n < len(s) { diff --git a/vendor/golang.org/x/text/unicode/bidi/core.go b/vendor/golang.org/x/text/unicode/bidi/core.go index fb82732..fe5a46f 100644 --- a/vendor/golang.org/x/text/unicode/bidi/core.go +++ b/vendor/golang.org/x/text/unicode/bidi/core.go @@ -6,7 +6,6 @@ package bidi import ( "fmt" - "log" ) // This implementation is a port based on the reference implementation found at: @@ -209,27 +208,23 @@ func (p *paragraph) determineMatchingIsolates() { p.matchingIsolateInitiator[i] = -1 } + var open []int for i := range p.matchingPDI { p.matchingPDI[i] = -1 - if t := p.resultTypes[i]; t.in(LRI, RLI, FSI) { - depthCounter := 1 - for j := i + 1; j < p.Len(); j++ { - if u := p.resultTypes[j]; u.in(LRI, RLI, FSI) { - depthCounter++ - } else if u == PDI { - if depthCounter--; depthCounter == 0 { - p.matchingPDI[i] = j - p.matchingIsolateInitiator[j] = i - break - } - } - } - if p.matchingPDI[i] == -1 { - p.matchingPDI[i] = p.Len() - } + switch t := p.resultTypes[i]; { + case t.in(LRI, RLI, FSI): + open = append(open, i) + case t == PDI && len(open) > 0: + j := open[len(open)-1] + open = open[:len(open)-1] + p.matchingPDI[j] = i + p.matchingIsolateInitiator[i] = j } } + for _, i := range open { + p.matchingPDI[i] = p.Len() + } } // determineParagraphEmbeddingLevel reports the resolved paragraph direction of @@ -248,7 +243,7 @@ func (p *paragraph) determineParagraphEmbeddingLevel(start, end int) level { } else if t.in(FSI, LRI, RLI) { i = p.matchingPDI[i] // skip over to the matching PDI if i > end { - log.Panic("assert (i <= end)") + panic("assert (i <= end)") } } } @@ -497,16 +492,13 @@ func (s *isolatingRunSequence) resolveWeakTypes() { // Rule W2. // EN does not change at the start of the run, because sos != AL. + lastStrong := unknownClass for i, t := range s.types { - if t == EN { - for j := i - 1; j >= 0; j-- { - if t := s.types[j]; t.in(L, R, AL) { - if t == AL { - s.types[i] = AN - } - break - } - } + switch { + case t.in(L, R, AL): + lastStrong = t + case t == EN && lastStrong == AL: + s.types[i] = AN } } @@ -544,29 +536,30 @@ func (s *isolatingRunSequence) resolveWeakTypes() { } // Rule W5. - for i, t := range s.types { - if t == ET { - // locate end of sequence - runStart := i - runEnd := s.findRunLimit(runStart, ET) - - // check values at ends of sequence - t := s.sos - if runStart > 0 { - t = s.types[runStart-1] - } - if t != EN { - t = s.eos - if runEnd < len(s.types) { - t = s.types[runEnd] - } - } - if t == EN { - setTypes(s.types[runStart:runEnd], EN) - } - // continue at end of sequence - i = runEnd + for i := 0; i < len(s.types); i++ { + if s.types[i] != ET { + continue } + // locate end of sequence + runStart := i + runEnd := s.findRunLimit(runStart, ET) + + // check values at ends of sequence + t := s.sos + if runStart > 0 { + t = s.types[runStart-1] + } + if t != EN { + t = s.eos + if runEnd < len(s.types) { + t = s.types[runEnd] + } + } + if t == EN { + setTypes(s.types[runStart:runEnd], EN) + } + // continue at end of sequence + i = runEnd } // Rule W6. @@ -577,20 +570,13 @@ func (s *isolatingRunSequence) resolveWeakTypes() { } // Rule W7. + prevStrongType := s.sos for i, t := range s.types { - if t == EN { - // set default if we reach start of run - prevStrongType := s.sos - for j := i - 1; j >= 0; j-- { - t = s.types[j] - if t == L || t == R { // AL's have been changed to R - prevStrongType = t - break - } - } - if prevStrongType == L { - s.types[i] = L - } + switch { + case t == L || t == R: // AL's have been changed to R + prevStrongType = t + case t == EN && prevStrongType == L: + s.types[i] = L } } } @@ -729,7 +715,7 @@ loop: continue loop } } - log.Panicf("invalid bidi code %v present in assertOnly at position %d", t, s.indexes[i]) + panic(fmt.Errorf("invalid bidi code %v present in assertOnly at position %d", t, s.indexes[i])) } } diff --git a/vendor/golang.org/x/text/unicode/norm/composition.go b/vendor/golang.org/x/text/unicode/norm/composition.go index e2087bc..e024e74 100644 --- a/vendor/golang.org/x/text/unicode/norm/composition.go +++ b/vendor/golang.org/x/text/unicode/norm/composition.go @@ -449,6 +449,16 @@ func (rb *reorderBuffer) combineHangul(s, i, k int) { // ACxx plus 11Ax to LVT rb.assignRune(s, l+v-jamoTBase) default: + // Not a Hangul composition. The segment may still + // contain regular canonical compositions, such as + // combining marks following a Hangul syllable, so + // fall back to the composition table. + if b[i].combinesBackward() { + if combined := combine(l, v); combined != 0 { + rb.assignRune(s, combined) + continue + } + } b[k] = b[i] k++ } @@ -484,25 +494,27 @@ func (rb *reorderBuffer) compose() { return } ii := b[i] + // Track the last starter unconditionally: b[i] must be blocked by + // any starter between it and s, even one that b[i] itself cannot + // combine with, and even if the runes in between never enter the + // combinesBackward branch below. + cccB := b[k-1].ccc + cccC := ii.ccc + blocked := false // b[i] blocked by starter or greater or equal CCC? + if cccB == 0 { + s = k - 1 + } else { + blocked = s != k-1 && cccB >= cccC + } // We can only use combineForward as a filter if we later // get the info for the combined character. This is more // expensive than using the filter. Using combinesBackward() // is safe. - if ii.combinesBackward() { - cccB := b[k-1].ccc - cccC := ii.ccc - blocked := false // b[i] blocked by starter or greater or equal CCC? - if cccB == 0 { - s = k - 1 - } else { - blocked = s != k-1 && cccB >= cccC - } - if !blocked { - combined := combine(rb.runeAt(s), rb.runeAt(i)) - if combined != 0 { - rb.assignRune(s, combined) - continue - } + if ii.combinesBackward() && !blocked { + combined := combine(rb.runeAt(s), rb.runeAt(i)) + if combined != 0 { + rb.assignRune(s, combined) + continue } } b[k] = b[i] diff --git a/vendor/golang.org/x/text/unicode/norm/forminfo.go b/vendor/golang.org/x/text/unicode/norm/forminfo.go index b3cf5d9..956708e 100644 --- a/vendor/golang.org/x/text/unicode/norm/forminfo.go +++ b/vendor/golang.org/x/text/unicode/norm/forminfo.go @@ -191,30 +191,30 @@ func (p Properties) TrailCCC() uint8 { return ccc[p.tccc] } +// Recomposition +// Each entry of recompMapPacked holds the two runes of the key and the +// composed rune of the value packed into a big-endian uint64 as three +// 21-bit fields, which is wide enough for any rune. +// Note that the recomposition map for NFC and NFKC are identical. + +const recompShift = 21 + func buildRecompMap() { - recompMap = make(map[uint32]rune, len(recompMapPacked)/8) + recompMap = make(map[uint64]rune, len(recompMapPacked)/8) var buf [8]byte for i := 0; i < len(recompMapPacked); i += 8 { copy(buf[:], recompMapPacked[i:i+8]) - key := binary.BigEndian.Uint32(buf[:4]) - val := binary.BigEndian.Uint32(buf[4:]) - recompMap[key] = rune(val) + e := binary.BigEndian.Uint64(buf[:]) + recompMap[e>>recompShift] = rune(e & (1<" + // 0x006C030C: 0x0000013E - "\x00N\x03\x01\x00\x00\x01C" + // 0x004E0301: 0x00000143 - "\x00n\x03\x01\x00\x00\x01D" + // 0x006E0301: 0x00000144 - "\x00N\x03'\x00\x00\x01E" + // 0x004E0327: 0x00000145 - "\x00n\x03'\x00\x00\x01F" + // 0x006E0327: 0x00000146 - "\x00N\x03\f\x00\x00\x01G" + // 0x004E030C: 0x00000147 - "\x00n\x03\f\x00\x00\x01H" + // 0x006E030C: 0x00000148 - "\x00O\x03\x04\x00\x00\x01L" + // 0x004F0304: 0x0000014C - "\x00o\x03\x04\x00\x00\x01M" + // 0x006F0304: 0x0000014D - "\x00O\x03\x06\x00\x00\x01N" + // 0x004F0306: 0x0000014E - "\x00o\x03\x06\x00\x00\x01O" + // 0x006F0306: 0x0000014F - "\x00O\x03\v\x00\x00\x01P" + // 0x004F030B: 0x00000150 - "\x00o\x03\v\x00\x00\x01Q" + // 0x006F030B: 0x00000151 - "\x00R\x03\x01\x00\x00\x01T" + // 0x00520301: 0x00000154 - "\x00r\x03\x01\x00\x00\x01U" + // 0x00720301: 0x00000155 - "\x00R\x03'\x00\x00\x01V" + // 0x00520327: 0x00000156 - "\x00r\x03'\x00\x00\x01W" + // 0x00720327: 0x00000157 - "\x00R\x03\f\x00\x00\x01X" + // 0x0052030C: 0x00000158 - "\x00r\x03\f\x00\x00\x01Y" + // 0x0072030C: 0x00000159 - "\x00S\x03\x01\x00\x00\x01Z" + // 0x00530301: 0x0000015A - "\x00s\x03\x01\x00\x00\x01[" + // 0x00730301: 0x0000015B - "\x00S\x03\x02\x00\x00\x01\\" + // 0x00530302: 0x0000015C - "\x00s\x03\x02\x00\x00\x01]" + // 0x00730302: 0x0000015D - "\x00S\x03'\x00\x00\x01^" + // 0x00530327: 0x0000015E - "\x00s\x03'\x00\x00\x01_" + // 0x00730327: 0x0000015F - "\x00S\x03\f\x00\x00\x01`" + // 0x0053030C: 0x00000160 - "\x00s\x03\f\x00\x00\x01a" + // 0x0073030C: 0x00000161 - "\x00T\x03'\x00\x00\x01b" + // 0x00540327: 0x00000162 - "\x00t\x03'\x00\x00\x01c" + // 0x00740327: 0x00000163 - "\x00T\x03\f\x00\x00\x01d" + // 0x0054030C: 0x00000164 - "\x00t\x03\f\x00\x00\x01e" + // 0x0074030C: 0x00000165 - "\x00U\x03\x03\x00\x00\x01h" + // 0x00550303: 0x00000168 - "\x00u\x03\x03\x00\x00\x01i" + // 0x00750303: 0x00000169 - "\x00U\x03\x04\x00\x00\x01j" + // 0x00550304: 0x0000016A - "\x00u\x03\x04\x00\x00\x01k" + // 0x00750304: 0x0000016B - "\x00U\x03\x06\x00\x00\x01l" + // 0x00550306: 0x0000016C - "\x00u\x03\x06\x00\x00\x01m" + // 0x00750306: 0x0000016D - "\x00U\x03\n\x00\x00\x01n" + // 0x0055030A: 0x0000016E - "\x00u\x03\n\x00\x00\x01o" + // 0x0075030A: 0x0000016F - "\x00U\x03\v\x00\x00\x01p" + // 0x0055030B: 0x00000170 - "\x00u\x03\v\x00\x00\x01q" + // 0x0075030B: 0x00000171 - "\x00U\x03(\x00\x00\x01r" + // 0x00550328: 0x00000172 - "\x00u\x03(\x00\x00\x01s" + // 0x00750328: 0x00000173 - "\x00W\x03\x02\x00\x00\x01t" + // 0x00570302: 0x00000174 - "\x00w\x03\x02\x00\x00\x01u" + // 0x00770302: 0x00000175 - "\x00Y\x03\x02\x00\x00\x01v" + // 0x00590302: 0x00000176 - "\x00y\x03\x02\x00\x00\x01w" + // 0x00790302: 0x00000177 - "\x00Y\x03\b\x00\x00\x01x" + // 0x00590308: 0x00000178 - "\x00Z\x03\x01\x00\x00\x01y" + // 0x005A0301: 0x00000179 - "\x00z\x03\x01\x00\x00\x01z" + // 0x007A0301: 0x0000017A - "\x00Z\x03\a\x00\x00\x01{" + // 0x005A0307: 0x0000017B - "\x00z\x03\a\x00\x00\x01|" + // 0x007A0307: 0x0000017C - "\x00Z\x03\f\x00\x00\x01}" + // 0x005A030C: 0x0000017D - "\x00z\x03\f\x00\x00\x01~" + // 0x007A030C: 0x0000017E - "\x00O\x03\x1b\x00\x00\x01\xa0" + // 0x004F031B: 0x000001A0 - "\x00o\x03\x1b\x00\x00\x01\xa1" + // 0x006F031B: 0x000001A1 - "\x00U\x03\x1b\x00\x00\x01\xaf" + // 0x0055031B: 0x000001AF - "\x00u\x03\x1b\x00\x00\x01\xb0" + // 0x0075031B: 0x000001B0 - "\x00A\x03\f\x00\x00\x01\xcd" + // 0x0041030C: 0x000001CD - "\x00a\x03\f\x00\x00\x01\xce" + // 0x0061030C: 0x000001CE - "\x00I\x03\f\x00\x00\x01\xcf" + // 0x0049030C: 0x000001CF - "\x00i\x03\f\x00\x00\x01\xd0" + // 0x0069030C: 0x000001D0 - "\x00O\x03\f\x00\x00\x01\xd1" + // 0x004F030C: 0x000001D1 - "\x00o\x03\f\x00\x00\x01\xd2" + // 0x006F030C: 0x000001D2 - "\x00U\x03\f\x00\x00\x01\xd3" + // 0x0055030C: 0x000001D3 - "\x00u\x03\f\x00\x00\x01\xd4" + // 0x0075030C: 0x000001D4 - "\x00\xdc\x03\x04\x00\x00\x01\xd5" + // 0x00DC0304: 0x000001D5 - "\x00\xfc\x03\x04\x00\x00\x01\xd6" + // 0x00FC0304: 0x000001D6 - "\x00\xdc\x03\x01\x00\x00\x01\xd7" + // 0x00DC0301: 0x000001D7 - "\x00\xfc\x03\x01\x00\x00\x01\xd8" + // 0x00FC0301: 0x000001D8 - "\x00\xdc\x03\f\x00\x00\x01\xd9" + // 0x00DC030C: 0x000001D9 - "\x00\xfc\x03\f\x00\x00\x01\xda" + // 0x00FC030C: 0x000001DA - "\x00\xdc\x03\x00\x00\x00\x01\xdb" + // 0x00DC0300: 0x000001DB - "\x00\xfc\x03\x00\x00\x00\x01\xdc" + // 0x00FC0300: 0x000001DC - "\x00\xc4\x03\x04\x00\x00\x01\xde" + // 0x00C40304: 0x000001DE - "\x00\xe4\x03\x04\x00\x00\x01\xdf" + // 0x00E40304: 0x000001DF - "\x02&\x03\x04\x00\x00\x01\xe0" + // 0x02260304: 0x000001E0 - "\x02'\x03\x04\x00\x00\x01\xe1" + // 0x02270304: 0x000001E1 - "\x00\xc6\x03\x04\x00\x00\x01\xe2" + // 0x00C60304: 0x000001E2 - "\x00\xe6\x03\x04\x00\x00\x01\xe3" + // 0x00E60304: 0x000001E3 - "\x00G\x03\f\x00\x00\x01\xe6" + // 0x0047030C: 0x000001E6 - "\x00g\x03\f\x00\x00\x01\xe7" + // 0x0067030C: 0x000001E7 - "\x00K\x03\f\x00\x00\x01\xe8" + // 0x004B030C: 0x000001E8 - "\x00k\x03\f\x00\x00\x01\xe9" + // 0x006B030C: 0x000001E9 - "\x00O\x03(\x00\x00\x01\xea" + // 0x004F0328: 0x000001EA - "\x00o\x03(\x00\x00\x01\xeb" + // 0x006F0328: 0x000001EB - "\x01\xea\x03\x04\x00\x00\x01\xec" + // 0x01EA0304: 0x000001EC - "\x01\xeb\x03\x04\x00\x00\x01\xed" + // 0x01EB0304: 0x000001ED - "\x01\xb7\x03\f\x00\x00\x01\xee" + // 0x01B7030C: 0x000001EE - "\x02\x92\x03\f\x00\x00\x01\xef" + // 0x0292030C: 0x000001EF - "\x00j\x03\f\x00\x00\x01\xf0" + // 0x006A030C: 0x000001F0 - "\x00G\x03\x01\x00\x00\x01\xf4" + // 0x00470301: 0x000001F4 - "\x00g\x03\x01\x00\x00\x01\xf5" + // 0x00670301: 0x000001F5 - "\x00N\x03\x00\x00\x00\x01\xf8" + // 0x004E0300: 0x000001F8 - "\x00n\x03\x00\x00\x00\x01\xf9" + // 0x006E0300: 0x000001F9 - "\x00\xc5\x03\x01\x00\x00\x01\xfa" + // 0x00C50301: 0x000001FA - "\x00\xe5\x03\x01\x00\x00\x01\xfb" + // 0x00E50301: 0x000001FB - "\x00\xc6\x03\x01\x00\x00\x01\xfc" + // 0x00C60301: 0x000001FC - "\x00\xe6\x03\x01\x00\x00\x01\xfd" + // 0x00E60301: 0x000001FD - "\x00\xd8\x03\x01\x00\x00\x01\xfe" + // 0x00D80301: 0x000001FE - "\x00\xf8\x03\x01\x00\x00\x01\xff" + // 0x00F80301: 0x000001FF - "\x00A\x03\x0f\x00\x00\x02\x00" + // 0x0041030F: 0x00000200 - "\x00a\x03\x0f\x00\x00\x02\x01" + // 0x0061030F: 0x00000201 - "\x00A\x03\x11\x00\x00\x02\x02" + // 0x00410311: 0x00000202 - "\x00a\x03\x11\x00\x00\x02\x03" + // 0x00610311: 0x00000203 - "\x00E\x03\x0f\x00\x00\x02\x04" + // 0x0045030F: 0x00000204 - "\x00e\x03\x0f\x00\x00\x02\x05" + // 0x0065030F: 0x00000205 - "\x00E\x03\x11\x00\x00\x02\x06" + // 0x00450311: 0x00000206 - "\x00e\x03\x11\x00\x00\x02\a" + // 0x00650311: 0x00000207 - "\x00I\x03\x0f\x00\x00\x02\b" + // 0x0049030F: 0x00000208 - "\x00i\x03\x0f\x00\x00\x02\t" + // 0x0069030F: 0x00000209 - "\x00I\x03\x11\x00\x00\x02\n" + // 0x00490311: 0x0000020A - "\x00i\x03\x11\x00\x00\x02\v" + // 0x00690311: 0x0000020B - "\x00O\x03\x0f\x00\x00\x02\f" + // 0x004F030F: 0x0000020C - "\x00o\x03\x0f\x00\x00\x02\r" + // 0x006F030F: 0x0000020D - "\x00O\x03\x11\x00\x00\x02\x0e" + // 0x004F0311: 0x0000020E - "\x00o\x03\x11\x00\x00\x02\x0f" + // 0x006F0311: 0x0000020F - "\x00R\x03\x0f\x00\x00\x02\x10" + // 0x0052030F: 0x00000210 - "\x00r\x03\x0f\x00\x00\x02\x11" + // 0x0072030F: 0x00000211 - "\x00R\x03\x11\x00\x00\x02\x12" + // 0x00520311: 0x00000212 - "\x00r\x03\x11\x00\x00\x02\x13" + // 0x00720311: 0x00000213 - "\x00U\x03\x0f\x00\x00\x02\x14" + // 0x0055030F: 0x00000214 - "\x00u\x03\x0f\x00\x00\x02\x15" + // 0x0075030F: 0x00000215 - "\x00U\x03\x11\x00\x00\x02\x16" + // 0x00550311: 0x00000216 - "\x00u\x03\x11\x00\x00\x02\x17" + // 0x00750311: 0x00000217 - "\x00S\x03&\x00\x00\x02\x18" + // 0x00530326: 0x00000218 - "\x00s\x03&\x00\x00\x02\x19" + // 0x00730326: 0x00000219 - "\x00T\x03&\x00\x00\x02\x1a" + // 0x00540326: 0x0000021A - "\x00t\x03&\x00\x00\x02\x1b" + // 0x00740326: 0x0000021B - "\x00H\x03\f\x00\x00\x02\x1e" + // 0x0048030C: 0x0000021E - "\x00h\x03\f\x00\x00\x02\x1f" + // 0x0068030C: 0x0000021F - "\x00A\x03\a\x00\x00\x02&" + // 0x00410307: 0x00000226 - "\x00a\x03\a\x00\x00\x02'" + // 0x00610307: 0x00000227 - "\x00E\x03'\x00\x00\x02(" + // 0x00450327: 0x00000228 - "\x00e\x03'\x00\x00\x02)" + // 0x00650327: 0x00000229 - "\x00\xd6\x03\x04\x00\x00\x02*" + // 0x00D60304: 0x0000022A - "\x00\xf6\x03\x04\x00\x00\x02+" + // 0x00F60304: 0x0000022B - "\x00\xd5\x03\x04\x00\x00\x02," + // 0x00D50304: 0x0000022C - "\x00\xf5\x03\x04\x00\x00\x02-" + // 0x00F50304: 0x0000022D - "\x00O\x03\a\x00\x00\x02." + // 0x004F0307: 0x0000022E - "\x00o\x03\a\x00\x00\x02/" + // 0x006F0307: 0x0000022F - "\x02.\x03\x04\x00\x00\x020" + // 0x022E0304: 0x00000230 - "\x02/\x03\x04\x00\x00\x021" + // 0x022F0304: 0x00000231 - "\x00Y\x03\x04\x00\x00\x022" + // 0x00590304: 0x00000232 - "\x00y\x03\x04\x00\x00\x023" + // 0x00790304: 0x00000233 - "\x00\xa8\x03\x01\x00\x00\x03\x85" + // 0x00A80301: 0x00000385 - "\x03\x91\x03\x01\x00\x00\x03\x86" + // 0x03910301: 0x00000386 - "\x03\x95\x03\x01\x00\x00\x03\x88" + // 0x03950301: 0x00000388 - "\x03\x97\x03\x01\x00\x00\x03\x89" + // 0x03970301: 0x00000389 - "\x03\x99\x03\x01\x00\x00\x03\x8a" + // 0x03990301: 0x0000038A - "\x03\x9f\x03\x01\x00\x00\x03\x8c" + // 0x039F0301: 0x0000038C - "\x03\xa5\x03\x01\x00\x00\x03\x8e" + // 0x03A50301: 0x0000038E - "\x03\xa9\x03\x01\x00\x00\x03\x8f" + // 0x03A90301: 0x0000038F - "\x03\xca\x03\x01\x00\x00\x03\x90" + // 0x03CA0301: 0x00000390 - "\x03\x99\x03\b\x00\x00\x03\xaa" + // 0x03990308: 0x000003AA - "\x03\xa5\x03\b\x00\x00\x03\xab" + // 0x03A50308: 0x000003AB - "\x03\xb1\x03\x01\x00\x00\x03\xac" + // 0x03B10301: 0x000003AC - "\x03\xb5\x03\x01\x00\x00\x03\xad" + // 0x03B50301: 0x000003AD - "\x03\xb7\x03\x01\x00\x00\x03\xae" + // 0x03B70301: 0x000003AE - "\x03\xb9\x03\x01\x00\x00\x03\xaf" + // 0x03B90301: 0x000003AF - "\x03\xcb\x03\x01\x00\x00\x03\xb0" + // 0x03CB0301: 0x000003B0 - "\x03\xb9\x03\b\x00\x00\x03\xca" + // 0x03B90308: 0x000003CA - "\x03\xc5\x03\b\x00\x00\x03\xcb" + // 0x03C50308: 0x000003CB - "\x03\xbf\x03\x01\x00\x00\x03\xcc" + // 0x03BF0301: 0x000003CC - "\x03\xc5\x03\x01\x00\x00\x03\xcd" + // 0x03C50301: 0x000003CD - "\x03\xc9\x03\x01\x00\x00\x03\xce" + // 0x03C90301: 0x000003CE - "\x03\xd2\x03\x01\x00\x00\x03\xd3" + // 0x03D20301: 0x000003D3 - "\x03\xd2\x03\b\x00\x00\x03\xd4" + // 0x03D20308: 0x000003D4 - "\x04\x15\x03\x00\x00\x00\x04\x00" + // 0x04150300: 0x00000400 - "\x04\x15\x03\b\x00\x00\x04\x01" + // 0x04150308: 0x00000401 - "\x04\x13\x03\x01\x00\x00\x04\x03" + // 0x04130301: 0x00000403 - "\x04\x06\x03\b\x00\x00\x04\a" + // 0x04060308: 0x00000407 - "\x04\x1a\x03\x01\x00\x00\x04\f" + // 0x041A0301: 0x0000040C - "\x04\x18\x03\x00\x00\x00\x04\r" + // 0x04180300: 0x0000040D - "\x04#\x03\x06\x00\x00\x04\x0e" + // 0x04230306: 0x0000040E - "\x04\x18\x03\x06\x00\x00\x04\x19" + // 0x04180306: 0x00000419 - "\x048\x03\x06\x00\x00\x049" + // 0x04380306: 0x00000439 - "\x045\x03\x00\x00\x00\x04P" + // 0x04350300: 0x00000450 - "\x045\x03\b\x00\x00\x04Q" + // 0x04350308: 0x00000451 - "\x043\x03\x01\x00\x00\x04S" + // 0x04330301: 0x00000453 - "\x04V\x03\b\x00\x00\x04W" + // 0x04560308: 0x00000457 - "\x04:\x03\x01\x00\x00\x04\\" + // 0x043A0301: 0x0000045C - "\x048\x03\x00\x00\x00\x04]" + // 0x04380300: 0x0000045D - "\x04C\x03\x06\x00\x00\x04^" + // 0x04430306: 0x0000045E - "\x04t\x03\x0f\x00\x00\x04v" + // 0x0474030F: 0x00000476 - "\x04u\x03\x0f\x00\x00\x04w" + // 0x0475030F: 0x00000477 - "\x04\x16\x03\x06\x00\x00\x04\xc1" + // 0x04160306: 0x000004C1 - "\x046\x03\x06\x00\x00\x04\xc2" + // 0x04360306: 0x000004C2 - "\x04\x10\x03\x06\x00\x00\x04\xd0" + // 0x04100306: 0x000004D0 - "\x040\x03\x06\x00\x00\x04\xd1" + // 0x04300306: 0x000004D1 - "\x04\x10\x03\b\x00\x00\x04\xd2" + // 0x04100308: 0x000004D2 - "\x040\x03\b\x00\x00\x04\xd3" + // 0x04300308: 0x000004D3 - "\x04\x15\x03\x06\x00\x00\x04\xd6" + // 0x04150306: 0x000004D6 - "\x045\x03\x06\x00\x00\x04\xd7" + // 0x04350306: 0x000004D7 - "\x04\xd8\x03\b\x00\x00\x04\xda" + // 0x04D80308: 0x000004DA - "\x04\xd9\x03\b\x00\x00\x04\xdb" + // 0x04D90308: 0x000004DB - "\x04\x16\x03\b\x00\x00\x04\xdc" + // 0x04160308: 0x000004DC - "\x046\x03\b\x00\x00\x04\xdd" + // 0x04360308: 0x000004DD - "\x04\x17\x03\b\x00\x00\x04\xde" + // 0x04170308: 0x000004DE - "\x047\x03\b\x00\x00\x04\xdf" + // 0x04370308: 0x000004DF - "\x04\x18\x03\x04\x00\x00\x04\xe2" + // 0x04180304: 0x000004E2 - "\x048\x03\x04\x00\x00\x04\xe3" + // 0x04380304: 0x000004E3 - "\x04\x18\x03\b\x00\x00\x04\xe4" + // 0x04180308: 0x000004E4 - "\x048\x03\b\x00\x00\x04\xe5" + // 0x04380308: 0x000004E5 - "\x04\x1e\x03\b\x00\x00\x04\xe6" + // 0x041E0308: 0x000004E6 - "\x04>\x03\b\x00\x00\x04\xe7" + // 0x043E0308: 0x000004E7 - "\x04\xe8\x03\b\x00\x00\x04\xea" + // 0x04E80308: 0x000004EA - "\x04\xe9\x03\b\x00\x00\x04\xeb" + // 0x04E90308: 0x000004EB - "\x04-\x03\b\x00\x00\x04\xec" + // 0x042D0308: 0x000004EC - "\x04M\x03\b\x00\x00\x04\xed" + // 0x044D0308: 0x000004ED - "\x04#\x03\x04\x00\x00\x04\xee" + // 0x04230304: 0x000004EE - "\x04C\x03\x04\x00\x00\x04\xef" + // 0x04430304: 0x000004EF - "\x04#\x03\b\x00\x00\x04\xf0" + // 0x04230308: 0x000004F0 - "\x04C\x03\b\x00\x00\x04\xf1" + // 0x04430308: 0x000004F1 - "\x04#\x03\v\x00\x00\x04\xf2" + // 0x0423030B: 0x000004F2 - "\x04C\x03\v\x00\x00\x04\xf3" + // 0x0443030B: 0x000004F3 - "\x04'\x03\b\x00\x00\x04\xf4" + // 0x04270308: 0x000004F4 - "\x04G\x03\b\x00\x00\x04\xf5" + // 0x04470308: 0x000004F5 - "\x04+\x03\b\x00\x00\x04\xf8" + // 0x042B0308: 0x000004F8 - "\x04K\x03\b\x00\x00\x04\xf9" + // 0x044B0308: 0x000004F9 - "\x06'\x06S\x00\x00\x06\"" + // 0x06270653: 0x00000622 - "\x06'\x06T\x00\x00\x06#" + // 0x06270654: 0x00000623 - "\x06H\x06T\x00\x00\x06$" + // 0x06480654: 0x00000624 - "\x06'\x06U\x00\x00\x06%" + // 0x06270655: 0x00000625 - "\x06J\x06T\x00\x00\x06&" + // 0x064A0654: 0x00000626 - "\x06\xd5\x06T\x00\x00\x06\xc0" + // 0x06D50654: 0x000006C0 - "\x06\xc1\x06T\x00\x00\x06\xc2" + // 0x06C10654: 0x000006C2 - "\x06\xd2\x06T\x00\x00\x06\xd3" + // 0x06D20654: 0x000006D3 - "\t(\t<\x00\x00\t)" + // 0x0928093C: 0x00000929 - "\t0\t<\x00\x00\t1" + // 0x0930093C: 0x00000931 - "\t3\t<\x00\x00\t4" + // 0x0933093C: 0x00000934 - "\t\xc7\t\xbe\x00\x00\t\xcb" + // 0x09C709BE: 0x000009CB - "\t\xc7\t\xd7\x00\x00\t\xcc" + // 0x09C709D7: 0x000009CC - "\vG\vV\x00\x00\vH" + // 0x0B470B56: 0x00000B48 - "\vG\v>\x00\x00\vK" + // 0x0B470B3E: 0x00000B4B - "\vG\vW\x00\x00\vL" + // 0x0B470B57: 0x00000B4C - "\v\x92\v\xd7\x00\x00\v\x94" + // 0x0B920BD7: 0x00000B94 - "\v\xc6\v\xbe\x00\x00\v\xca" + // 0x0BC60BBE: 0x00000BCA - "\v\xc7\v\xbe\x00\x00\v\xcb" + // 0x0BC70BBE: 0x00000BCB - "\v\xc6\v\xd7\x00\x00\v\xcc" + // 0x0BC60BD7: 0x00000BCC - "\fF\fV\x00\x00\fH" + // 0x0C460C56: 0x00000C48 - "\f\xbf\f\xd5\x00\x00\f\xc0" + // 0x0CBF0CD5: 0x00000CC0 - "\f\xc6\f\xd5\x00\x00\f\xc7" + // 0x0CC60CD5: 0x00000CC7 - "\f\xc6\f\xd6\x00\x00\f\xc8" + // 0x0CC60CD6: 0x00000CC8 - "\f\xc6\f\xc2\x00\x00\f\xca" + // 0x0CC60CC2: 0x00000CCA - "\f\xca\f\xd5\x00\x00\f\xcb" + // 0x0CCA0CD5: 0x00000CCB - "\rF\r>\x00\x00\rJ" + // 0x0D460D3E: 0x00000D4A - "\rG\r>\x00\x00\rK" + // 0x0D470D3E: 0x00000D4B - "\rF\rW\x00\x00\rL" + // 0x0D460D57: 0x00000D4C - "\r\xd9\r\xca\x00\x00\r\xda" + // 0x0DD90DCA: 0x00000DDA - "\r\xd9\r\xcf\x00\x00\r\xdc" + // 0x0DD90DCF: 0x00000DDC - "\r\xdc\r\xca\x00\x00\r\xdd" + // 0x0DDC0DCA: 0x00000DDD - "\r\xd9\r\xdf\x00\x00\r\xde" + // 0x0DD90DDF: 0x00000DDE - "\x10%\x10.\x00\x00\x10&" + // 0x1025102E: 0x00001026 - "\x1b\x05\x1b5\x00\x00\x1b\x06" + // 0x1B051B35: 0x00001B06 - "\x1b\a\x1b5\x00\x00\x1b\b" + // 0x1B071B35: 0x00001B08 - "\x1b\t\x1b5\x00\x00\x1b\n" + // 0x1B091B35: 0x00001B0A - "\x1b\v\x1b5\x00\x00\x1b\f" + // 0x1B0B1B35: 0x00001B0C - "\x1b\r\x1b5\x00\x00\x1b\x0e" + // 0x1B0D1B35: 0x00001B0E - "\x1b\x11\x1b5\x00\x00\x1b\x12" + // 0x1B111B35: 0x00001B12 - "\x1b:\x1b5\x00\x00\x1b;" + // 0x1B3A1B35: 0x00001B3B - "\x1b<\x1b5\x00\x00\x1b=" + // 0x1B3C1B35: 0x00001B3D - "\x1b>\x1b5\x00\x00\x1b@" + // 0x1B3E1B35: 0x00001B40 - "\x1b?\x1b5\x00\x00\x1bA" + // 0x1B3F1B35: 0x00001B41 - "\x1bB\x1b5\x00\x00\x1bC" + // 0x1B421B35: 0x00001B43 - "\x00A\x03%\x00\x00\x1e\x00" + // 0x00410325: 0x00001E00 - "\x00a\x03%\x00\x00\x1e\x01" + // 0x00610325: 0x00001E01 - "\x00B\x03\a\x00\x00\x1e\x02" + // 0x00420307: 0x00001E02 - "\x00b\x03\a\x00\x00\x1e\x03" + // 0x00620307: 0x00001E03 - "\x00B\x03#\x00\x00\x1e\x04" + // 0x00420323: 0x00001E04 - "\x00b\x03#\x00\x00\x1e\x05" + // 0x00620323: 0x00001E05 - "\x00B\x031\x00\x00\x1e\x06" + // 0x00420331: 0x00001E06 - "\x00b\x031\x00\x00\x1e\a" + // 0x00620331: 0x00001E07 - "\x00\xc7\x03\x01\x00\x00\x1e\b" + // 0x00C70301: 0x00001E08 - "\x00\xe7\x03\x01\x00\x00\x1e\t" + // 0x00E70301: 0x00001E09 - "\x00D\x03\a\x00\x00\x1e\n" + // 0x00440307: 0x00001E0A - "\x00d\x03\a\x00\x00\x1e\v" + // 0x00640307: 0x00001E0B - "\x00D\x03#\x00\x00\x1e\f" + // 0x00440323: 0x00001E0C - "\x00d\x03#\x00\x00\x1e\r" + // 0x00640323: 0x00001E0D - "\x00D\x031\x00\x00\x1e\x0e" + // 0x00440331: 0x00001E0E - "\x00d\x031\x00\x00\x1e\x0f" + // 0x00640331: 0x00001E0F - "\x00D\x03'\x00\x00\x1e\x10" + // 0x00440327: 0x00001E10 - "\x00d\x03'\x00\x00\x1e\x11" + // 0x00640327: 0x00001E11 - "\x00D\x03-\x00\x00\x1e\x12" + // 0x0044032D: 0x00001E12 - "\x00d\x03-\x00\x00\x1e\x13" + // 0x0064032D: 0x00001E13 - "\x01\x12\x03\x00\x00\x00\x1e\x14" + // 0x01120300: 0x00001E14 - "\x01\x13\x03\x00\x00\x00\x1e\x15" + // 0x01130300: 0x00001E15 - "\x01\x12\x03\x01\x00\x00\x1e\x16" + // 0x01120301: 0x00001E16 - "\x01\x13\x03\x01\x00\x00\x1e\x17" + // 0x01130301: 0x00001E17 - "\x00E\x03-\x00\x00\x1e\x18" + // 0x0045032D: 0x00001E18 - "\x00e\x03-\x00\x00\x1e\x19" + // 0x0065032D: 0x00001E19 - "\x00E\x030\x00\x00\x1e\x1a" + // 0x00450330: 0x00001E1A - "\x00e\x030\x00\x00\x1e\x1b" + // 0x00650330: 0x00001E1B - "\x02(\x03\x06\x00\x00\x1e\x1c" + // 0x02280306: 0x00001E1C - "\x02)\x03\x06\x00\x00\x1e\x1d" + // 0x02290306: 0x00001E1D - "\x00F\x03\a\x00\x00\x1e\x1e" + // 0x00460307: 0x00001E1E - "\x00f\x03\a\x00\x00\x1e\x1f" + // 0x00660307: 0x00001E1F - "\x00G\x03\x04\x00\x00\x1e " + // 0x00470304: 0x00001E20 - "\x00g\x03\x04\x00\x00\x1e!" + // 0x00670304: 0x00001E21 - "\x00H\x03\a\x00\x00\x1e\"" + // 0x00480307: 0x00001E22 - "\x00h\x03\a\x00\x00\x1e#" + // 0x00680307: 0x00001E23 - "\x00H\x03#\x00\x00\x1e$" + // 0x00480323: 0x00001E24 - "\x00h\x03#\x00\x00\x1e%" + // 0x00680323: 0x00001E25 - "\x00H\x03\b\x00\x00\x1e&" + // 0x00480308: 0x00001E26 - "\x00h\x03\b\x00\x00\x1e'" + // 0x00680308: 0x00001E27 - "\x00H\x03'\x00\x00\x1e(" + // 0x00480327: 0x00001E28 - "\x00h\x03'\x00\x00\x1e)" + // 0x00680327: 0x00001E29 - "\x00H\x03.\x00\x00\x1e*" + // 0x0048032E: 0x00001E2A - "\x00h\x03.\x00\x00\x1e+" + // 0x0068032E: 0x00001E2B - "\x00I\x030\x00\x00\x1e," + // 0x00490330: 0x00001E2C - "\x00i\x030\x00\x00\x1e-" + // 0x00690330: 0x00001E2D - "\x00\xcf\x03\x01\x00\x00\x1e." + // 0x00CF0301: 0x00001E2E - "\x00\xef\x03\x01\x00\x00\x1e/" + // 0x00EF0301: 0x00001E2F - "\x00K\x03\x01\x00\x00\x1e0" + // 0x004B0301: 0x00001E30 - "\x00k\x03\x01\x00\x00\x1e1" + // 0x006B0301: 0x00001E31 - "\x00K\x03#\x00\x00\x1e2" + // 0x004B0323: 0x00001E32 - "\x00k\x03#\x00\x00\x1e3" + // 0x006B0323: 0x00001E33 - "\x00K\x031\x00\x00\x1e4" + // 0x004B0331: 0x00001E34 - "\x00k\x031\x00\x00\x1e5" + // 0x006B0331: 0x00001E35 - "\x00L\x03#\x00\x00\x1e6" + // 0x004C0323: 0x00001E36 - "\x00l\x03#\x00\x00\x1e7" + // 0x006C0323: 0x00001E37 - "\x1e6\x03\x04\x00\x00\x1e8" + // 0x1E360304: 0x00001E38 - "\x1e7\x03\x04\x00\x00\x1e9" + // 0x1E370304: 0x00001E39 - "\x00L\x031\x00\x00\x1e:" + // 0x004C0331: 0x00001E3A - "\x00l\x031\x00\x00\x1e;" + // 0x006C0331: 0x00001E3B - "\x00L\x03-\x00\x00\x1e<" + // 0x004C032D: 0x00001E3C - "\x00l\x03-\x00\x00\x1e=" + // 0x006C032D: 0x00001E3D - "\x00M\x03\x01\x00\x00\x1e>" + // 0x004D0301: 0x00001E3E - "\x00m\x03\x01\x00\x00\x1e?" + // 0x006D0301: 0x00001E3F - "\x00M\x03\a\x00\x00\x1e@" + // 0x004D0307: 0x00001E40 - "\x00m\x03\a\x00\x00\x1eA" + // 0x006D0307: 0x00001E41 - "\x00M\x03#\x00\x00\x1eB" + // 0x004D0323: 0x00001E42 - "\x00m\x03#\x00\x00\x1eC" + // 0x006D0323: 0x00001E43 - "\x00N\x03\a\x00\x00\x1eD" + // 0x004E0307: 0x00001E44 - "\x00n\x03\a\x00\x00\x1eE" + // 0x006E0307: 0x00001E45 - "\x00N\x03#\x00\x00\x1eF" + // 0x004E0323: 0x00001E46 - "\x00n\x03#\x00\x00\x1eG" + // 0x006E0323: 0x00001E47 - "\x00N\x031\x00\x00\x1eH" + // 0x004E0331: 0x00001E48 - "\x00n\x031\x00\x00\x1eI" + // 0x006E0331: 0x00001E49 - "\x00N\x03-\x00\x00\x1eJ" + // 0x004E032D: 0x00001E4A - "\x00n\x03-\x00\x00\x1eK" + // 0x006E032D: 0x00001E4B - "\x00\xd5\x03\x01\x00\x00\x1eL" + // 0x00D50301: 0x00001E4C - "\x00\xf5\x03\x01\x00\x00\x1eM" + // 0x00F50301: 0x00001E4D - "\x00\xd5\x03\b\x00\x00\x1eN" + // 0x00D50308: 0x00001E4E - "\x00\xf5\x03\b\x00\x00\x1eO" + // 0x00F50308: 0x00001E4F - "\x01L\x03\x00\x00\x00\x1eP" + // 0x014C0300: 0x00001E50 - "\x01M\x03\x00\x00\x00\x1eQ" + // 0x014D0300: 0x00001E51 - "\x01L\x03\x01\x00\x00\x1eR" + // 0x014C0301: 0x00001E52 - "\x01M\x03\x01\x00\x00\x1eS" + // 0x014D0301: 0x00001E53 - "\x00P\x03\x01\x00\x00\x1eT" + // 0x00500301: 0x00001E54 - "\x00p\x03\x01\x00\x00\x1eU" + // 0x00700301: 0x00001E55 - "\x00P\x03\a\x00\x00\x1eV" + // 0x00500307: 0x00001E56 - "\x00p\x03\a\x00\x00\x1eW" + // 0x00700307: 0x00001E57 - "\x00R\x03\a\x00\x00\x1eX" + // 0x00520307: 0x00001E58 - "\x00r\x03\a\x00\x00\x1eY" + // 0x00720307: 0x00001E59 - "\x00R\x03#\x00\x00\x1eZ" + // 0x00520323: 0x00001E5A - "\x00r\x03#\x00\x00\x1e[" + // 0x00720323: 0x00001E5B - "\x1eZ\x03\x04\x00\x00\x1e\\" + // 0x1E5A0304: 0x00001E5C - "\x1e[\x03\x04\x00\x00\x1e]" + // 0x1E5B0304: 0x00001E5D - "\x00R\x031\x00\x00\x1e^" + // 0x00520331: 0x00001E5E - "\x00r\x031\x00\x00\x1e_" + // 0x00720331: 0x00001E5F - "\x00S\x03\a\x00\x00\x1e`" + // 0x00530307: 0x00001E60 - "\x00s\x03\a\x00\x00\x1ea" + // 0x00730307: 0x00001E61 - "\x00S\x03#\x00\x00\x1eb" + // 0x00530323: 0x00001E62 - "\x00s\x03#\x00\x00\x1ec" + // 0x00730323: 0x00001E63 - "\x01Z\x03\a\x00\x00\x1ed" + // 0x015A0307: 0x00001E64 - "\x01[\x03\a\x00\x00\x1ee" + // 0x015B0307: 0x00001E65 - "\x01`\x03\a\x00\x00\x1ef" + // 0x01600307: 0x00001E66 - "\x01a\x03\a\x00\x00\x1eg" + // 0x01610307: 0x00001E67 - "\x1eb\x03\a\x00\x00\x1eh" + // 0x1E620307: 0x00001E68 - "\x1ec\x03\a\x00\x00\x1ei" + // 0x1E630307: 0x00001E69 - "\x00T\x03\a\x00\x00\x1ej" + // 0x00540307: 0x00001E6A - "\x00t\x03\a\x00\x00\x1ek" + // 0x00740307: 0x00001E6B - "\x00T\x03#\x00\x00\x1el" + // 0x00540323: 0x00001E6C - "\x00t\x03#\x00\x00\x1em" + // 0x00740323: 0x00001E6D - "\x00T\x031\x00\x00\x1en" + // 0x00540331: 0x00001E6E - "\x00t\x031\x00\x00\x1eo" + // 0x00740331: 0x00001E6F - "\x00T\x03-\x00\x00\x1ep" + // 0x0054032D: 0x00001E70 - "\x00t\x03-\x00\x00\x1eq" + // 0x0074032D: 0x00001E71 - "\x00U\x03$\x00\x00\x1er" + // 0x00550324: 0x00001E72 - "\x00u\x03$\x00\x00\x1es" + // 0x00750324: 0x00001E73 - "\x00U\x030\x00\x00\x1et" + // 0x00550330: 0x00001E74 - "\x00u\x030\x00\x00\x1eu" + // 0x00750330: 0x00001E75 - "\x00U\x03-\x00\x00\x1ev" + // 0x0055032D: 0x00001E76 - "\x00u\x03-\x00\x00\x1ew" + // 0x0075032D: 0x00001E77 - "\x01h\x03\x01\x00\x00\x1ex" + // 0x01680301: 0x00001E78 - "\x01i\x03\x01\x00\x00\x1ey" + // 0x01690301: 0x00001E79 - "\x01j\x03\b\x00\x00\x1ez" + // 0x016A0308: 0x00001E7A - "\x01k\x03\b\x00\x00\x1e{" + // 0x016B0308: 0x00001E7B - "\x00V\x03\x03\x00\x00\x1e|" + // 0x00560303: 0x00001E7C - "\x00v\x03\x03\x00\x00\x1e}" + // 0x00760303: 0x00001E7D - "\x00V\x03#\x00\x00\x1e~" + // 0x00560323: 0x00001E7E - "\x00v\x03#\x00\x00\x1e\x7f" + // 0x00760323: 0x00001E7F - "\x00W\x03\x00\x00\x00\x1e\x80" + // 0x00570300: 0x00001E80 - "\x00w\x03\x00\x00\x00\x1e\x81" + // 0x00770300: 0x00001E81 - "\x00W\x03\x01\x00\x00\x1e\x82" + // 0x00570301: 0x00001E82 - "\x00w\x03\x01\x00\x00\x1e\x83" + // 0x00770301: 0x00001E83 - "\x00W\x03\b\x00\x00\x1e\x84" + // 0x00570308: 0x00001E84 - "\x00w\x03\b\x00\x00\x1e\x85" + // 0x00770308: 0x00001E85 - "\x00W\x03\a\x00\x00\x1e\x86" + // 0x00570307: 0x00001E86 - "\x00w\x03\a\x00\x00\x1e\x87" + // 0x00770307: 0x00001E87 - "\x00W\x03#\x00\x00\x1e\x88" + // 0x00570323: 0x00001E88 - "\x00w\x03#\x00\x00\x1e\x89" + // 0x00770323: 0x00001E89 - "\x00X\x03\a\x00\x00\x1e\x8a" + // 0x00580307: 0x00001E8A - "\x00x\x03\a\x00\x00\x1e\x8b" + // 0x00780307: 0x00001E8B - "\x00X\x03\b\x00\x00\x1e\x8c" + // 0x00580308: 0x00001E8C - "\x00x\x03\b\x00\x00\x1e\x8d" + // 0x00780308: 0x00001E8D - "\x00Y\x03\a\x00\x00\x1e\x8e" + // 0x00590307: 0x00001E8E - "\x00y\x03\a\x00\x00\x1e\x8f" + // 0x00790307: 0x00001E8F - "\x00Z\x03\x02\x00\x00\x1e\x90" + // 0x005A0302: 0x00001E90 - "\x00z\x03\x02\x00\x00\x1e\x91" + // 0x007A0302: 0x00001E91 - "\x00Z\x03#\x00\x00\x1e\x92" + // 0x005A0323: 0x00001E92 - "\x00z\x03#\x00\x00\x1e\x93" + // 0x007A0323: 0x00001E93 - "\x00Z\x031\x00\x00\x1e\x94" + // 0x005A0331: 0x00001E94 - "\x00z\x031\x00\x00\x1e\x95" + // 0x007A0331: 0x00001E95 - "\x00h\x031\x00\x00\x1e\x96" + // 0x00680331: 0x00001E96 - "\x00t\x03\b\x00\x00\x1e\x97" + // 0x00740308: 0x00001E97 - "\x00w\x03\n\x00\x00\x1e\x98" + // 0x0077030A: 0x00001E98 - "\x00y\x03\n\x00\x00\x1e\x99" + // 0x0079030A: 0x00001E99 - "\x01\x7f\x03\a\x00\x00\x1e\x9b" + // 0x017F0307: 0x00001E9B - "\x00A\x03#\x00\x00\x1e\xa0" + // 0x00410323: 0x00001EA0 - "\x00a\x03#\x00\x00\x1e\xa1" + // 0x00610323: 0x00001EA1 - "\x00A\x03\t\x00\x00\x1e\xa2" + // 0x00410309: 0x00001EA2 - "\x00a\x03\t\x00\x00\x1e\xa3" + // 0x00610309: 0x00001EA3 - "\x00\xc2\x03\x01\x00\x00\x1e\xa4" + // 0x00C20301: 0x00001EA4 - "\x00\xe2\x03\x01\x00\x00\x1e\xa5" + // 0x00E20301: 0x00001EA5 - "\x00\xc2\x03\x00\x00\x00\x1e\xa6" + // 0x00C20300: 0x00001EA6 - "\x00\xe2\x03\x00\x00\x00\x1e\xa7" + // 0x00E20300: 0x00001EA7 - "\x00\xc2\x03\t\x00\x00\x1e\xa8" + // 0x00C20309: 0x00001EA8 - "\x00\xe2\x03\t\x00\x00\x1e\xa9" + // 0x00E20309: 0x00001EA9 - "\x00\xc2\x03\x03\x00\x00\x1e\xaa" + // 0x00C20303: 0x00001EAA - "\x00\xe2\x03\x03\x00\x00\x1e\xab" + // 0x00E20303: 0x00001EAB - "\x1e\xa0\x03\x02\x00\x00\x1e\xac" + // 0x1EA00302: 0x00001EAC - "\x1e\xa1\x03\x02\x00\x00\x1e\xad" + // 0x1EA10302: 0x00001EAD - "\x01\x02\x03\x01\x00\x00\x1e\xae" + // 0x01020301: 0x00001EAE - "\x01\x03\x03\x01\x00\x00\x1e\xaf" + // 0x01030301: 0x00001EAF - "\x01\x02\x03\x00\x00\x00\x1e\xb0" + // 0x01020300: 0x00001EB0 - "\x01\x03\x03\x00\x00\x00\x1e\xb1" + // 0x01030300: 0x00001EB1 - "\x01\x02\x03\t\x00\x00\x1e\xb2" + // 0x01020309: 0x00001EB2 - "\x01\x03\x03\t\x00\x00\x1e\xb3" + // 0x01030309: 0x00001EB3 - "\x01\x02\x03\x03\x00\x00\x1e\xb4" + // 0x01020303: 0x00001EB4 - "\x01\x03\x03\x03\x00\x00\x1e\xb5" + // 0x01030303: 0x00001EB5 - "\x1e\xa0\x03\x06\x00\x00\x1e\xb6" + // 0x1EA00306: 0x00001EB6 - "\x1e\xa1\x03\x06\x00\x00\x1e\xb7" + // 0x1EA10306: 0x00001EB7 - "\x00E\x03#\x00\x00\x1e\xb8" + // 0x00450323: 0x00001EB8 - "\x00e\x03#\x00\x00\x1e\xb9" + // 0x00650323: 0x00001EB9 - "\x00E\x03\t\x00\x00\x1e\xba" + // 0x00450309: 0x00001EBA - "\x00e\x03\t\x00\x00\x1e\xbb" + // 0x00650309: 0x00001EBB - "\x00E\x03\x03\x00\x00\x1e\xbc" + // 0x00450303: 0x00001EBC - "\x00e\x03\x03\x00\x00\x1e\xbd" + // 0x00650303: 0x00001EBD - "\x00\xca\x03\x01\x00\x00\x1e\xbe" + // 0x00CA0301: 0x00001EBE - "\x00\xea\x03\x01\x00\x00\x1e\xbf" + // 0x00EA0301: 0x00001EBF - "\x00\xca\x03\x00\x00\x00\x1e\xc0" + // 0x00CA0300: 0x00001EC0 - "\x00\xea\x03\x00\x00\x00\x1e\xc1" + // 0x00EA0300: 0x00001EC1 - "\x00\xca\x03\t\x00\x00\x1e\xc2" + // 0x00CA0309: 0x00001EC2 - "\x00\xea\x03\t\x00\x00\x1e\xc3" + // 0x00EA0309: 0x00001EC3 - "\x00\xca\x03\x03\x00\x00\x1e\xc4" + // 0x00CA0303: 0x00001EC4 - "\x00\xea\x03\x03\x00\x00\x1e\xc5" + // 0x00EA0303: 0x00001EC5 - "\x1e\xb8\x03\x02\x00\x00\x1e\xc6" + // 0x1EB80302: 0x00001EC6 - "\x1e\xb9\x03\x02\x00\x00\x1e\xc7" + // 0x1EB90302: 0x00001EC7 - "\x00I\x03\t\x00\x00\x1e\xc8" + // 0x00490309: 0x00001EC8 - "\x00i\x03\t\x00\x00\x1e\xc9" + // 0x00690309: 0x00001EC9 - "\x00I\x03#\x00\x00\x1e\xca" + // 0x00490323: 0x00001ECA - "\x00i\x03#\x00\x00\x1e\xcb" + // 0x00690323: 0x00001ECB - "\x00O\x03#\x00\x00\x1e\xcc" + // 0x004F0323: 0x00001ECC - "\x00o\x03#\x00\x00\x1e\xcd" + // 0x006F0323: 0x00001ECD - "\x00O\x03\t\x00\x00\x1e\xce" + // 0x004F0309: 0x00001ECE - "\x00o\x03\t\x00\x00\x1e\xcf" + // 0x006F0309: 0x00001ECF - "\x00\xd4\x03\x01\x00\x00\x1e\xd0" + // 0x00D40301: 0x00001ED0 - "\x00\xf4\x03\x01\x00\x00\x1e\xd1" + // 0x00F40301: 0x00001ED1 - "\x00\xd4\x03\x00\x00\x00\x1e\xd2" + // 0x00D40300: 0x00001ED2 - "\x00\xf4\x03\x00\x00\x00\x1e\xd3" + // 0x00F40300: 0x00001ED3 - "\x00\xd4\x03\t\x00\x00\x1e\xd4" + // 0x00D40309: 0x00001ED4 - "\x00\xf4\x03\t\x00\x00\x1e\xd5" + // 0x00F40309: 0x00001ED5 - "\x00\xd4\x03\x03\x00\x00\x1e\xd6" + // 0x00D40303: 0x00001ED6 - "\x00\xf4\x03\x03\x00\x00\x1e\xd7" + // 0x00F40303: 0x00001ED7 - "\x1e\xcc\x03\x02\x00\x00\x1e\xd8" + // 0x1ECC0302: 0x00001ED8 - "\x1e\xcd\x03\x02\x00\x00\x1e\xd9" + // 0x1ECD0302: 0x00001ED9 - "\x01\xa0\x03\x01\x00\x00\x1e\xda" + // 0x01A00301: 0x00001EDA - "\x01\xa1\x03\x01\x00\x00\x1e\xdb" + // 0x01A10301: 0x00001EDB - "\x01\xa0\x03\x00\x00\x00\x1e\xdc" + // 0x01A00300: 0x00001EDC - "\x01\xa1\x03\x00\x00\x00\x1e\xdd" + // 0x01A10300: 0x00001EDD - "\x01\xa0\x03\t\x00\x00\x1e\xde" + // 0x01A00309: 0x00001EDE - "\x01\xa1\x03\t\x00\x00\x1e\xdf" + // 0x01A10309: 0x00001EDF - "\x01\xa0\x03\x03\x00\x00\x1e\xe0" + // 0x01A00303: 0x00001EE0 - "\x01\xa1\x03\x03\x00\x00\x1e\xe1" + // 0x01A10303: 0x00001EE1 - "\x01\xa0\x03#\x00\x00\x1e\xe2" + // 0x01A00323: 0x00001EE2 - "\x01\xa1\x03#\x00\x00\x1e\xe3" + // 0x01A10323: 0x00001EE3 - "\x00U\x03#\x00\x00\x1e\xe4" + // 0x00550323: 0x00001EE4 - "\x00u\x03#\x00\x00\x1e\xe5" + // 0x00750323: 0x00001EE5 - "\x00U\x03\t\x00\x00\x1e\xe6" + // 0x00550309: 0x00001EE6 - "\x00u\x03\t\x00\x00\x1e\xe7" + // 0x00750309: 0x00001EE7 - "\x01\xaf\x03\x01\x00\x00\x1e\xe8" + // 0x01AF0301: 0x00001EE8 - "\x01\xb0\x03\x01\x00\x00\x1e\xe9" + // 0x01B00301: 0x00001EE9 - "\x01\xaf\x03\x00\x00\x00\x1e\xea" + // 0x01AF0300: 0x00001EEA - "\x01\xb0\x03\x00\x00\x00\x1e\xeb" + // 0x01B00300: 0x00001EEB - "\x01\xaf\x03\t\x00\x00\x1e\xec" + // 0x01AF0309: 0x00001EEC - "\x01\xb0\x03\t\x00\x00\x1e\xed" + // 0x01B00309: 0x00001EED - "\x01\xaf\x03\x03\x00\x00\x1e\xee" + // 0x01AF0303: 0x00001EEE - "\x01\xb0\x03\x03\x00\x00\x1e\xef" + // 0x01B00303: 0x00001EEF - "\x01\xaf\x03#\x00\x00\x1e\xf0" + // 0x01AF0323: 0x00001EF0 - "\x01\xb0\x03#\x00\x00\x1e\xf1" + // 0x01B00323: 0x00001EF1 - "\x00Y\x03\x00\x00\x00\x1e\xf2" + // 0x00590300: 0x00001EF2 - "\x00y\x03\x00\x00\x00\x1e\xf3" + // 0x00790300: 0x00001EF3 - "\x00Y\x03#\x00\x00\x1e\xf4" + // 0x00590323: 0x00001EF4 - "\x00y\x03#\x00\x00\x1e\xf5" + // 0x00790323: 0x00001EF5 - "\x00Y\x03\t\x00\x00\x1e\xf6" + // 0x00590309: 0x00001EF6 - "\x00y\x03\t\x00\x00\x1e\xf7" + // 0x00790309: 0x00001EF7 - "\x00Y\x03\x03\x00\x00\x1e\xf8" + // 0x00590303: 0x00001EF8 - "\x00y\x03\x03\x00\x00\x1e\xf9" + // 0x00790303: 0x00001EF9 - "\x03\xb1\x03\x13\x00\x00\x1f\x00" + // 0x03B10313: 0x00001F00 - "\x03\xb1\x03\x14\x00\x00\x1f\x01" + // 0x03B10314: 0x00001F01 - "\x1f\x00\x03\x00\x00\x00\x1f\x02" + // 0x1F000300: 0x00001F02 - "\x1f\x01\x03\x00\x00\x00\x1f\x03" + // 0x1F010300: 0x00001F03 - "\x1f\x00\x03\x01\x00\x00\x1f\x04" + // 0x1F000301: 0x00001F04 - "\x1f\x01\x03\x01\x00\x00\x1f\x05" + // 0x1F010301: 0x00001F05 - "\x1f\x00\x03B\x00\x00\x1f\x06" + // 0x1F000342: 0x00001F06 - "\x1f\x01\x03B\x00\x00\x1f\a" + // 0x1F010342: 0x00001F07 - "\x03\x91\x03\x13\x00\x00\x1f\b" + // 0x03910313: 0x00001F08 - "\x03\x91\x03\x14\x00\x00\x1f\t" + // 0x03910314: 0x00001F09 - "\x1f\b\x03\x00\x00\x00\x1f\n" + // 0x1F080300: 0x00001F0A - "\x1f\t\x03\x00\x00\x00\x1f\v" + // 0x1F090300: 0x00001F0B - "\x1f\b\x03\x01\x00\x00\x1f\f" + // 0x1F080301: 0x00001F0C - "\x1f\t\x03\x01\x00\x00\x1f\r" + // 0x1F090301: 0x00001F0D - "\x1f\b\x03B\x00\x00\x1f\x0e" + // 0x1F080342: 0x00001F0E - "\x1f\t\x03B\x00\x00\x1f\x0f" + // 0x1F090342: 0x00001F0F - "\x03\xb5\x03\x13\x00\x00\x1f\x10" + // 0x03B50313: 0x00001F10 - "\x03\xb5\x03\x14\x00\x00\x1f\x11" + // 0x03B50314: 0x00001F11 - "\x1f\x10\x03\x00\x00\x00\x1f\x12" + // 0x1F100300: 0x00001F12 - "\x1f\x11\x03\x00\x00\x00\x1f\x13" + // 0x1F110300: 0x00001F13 - "\x1f\x10\x03\x01\x00\x00\x1f\x14" + // 0x1F100301: 0x00001F14 - "\x1f\x11\x03\x01\x00\x00\x1f\x15" + // 0x1F110301: 0x00001F15 - "\x03\x95\x03\x13\x00\x00\x1f\x18" + // 0x03950313: 0x00001F18 - "\x03\x95\x03\x14\x00\x00\x1f\x19" + // 0x03950314: 0x00001F19 - "\x1f\x18\x03\x00\x00\x00\x1f\x1a" + // 0x1F180300: 0x00001F1A - "\x1f\x19\x03\x00\x00\x00\x1f\x1b" + // 0x1F190300: 0x00001F1B - "\x1f\x18\x03\x01\x00\x00\x1f\x1c" + // 0x1F180301: 0x00001F1C - "\x1f\x19\x03\x01\x00\x00\x1f\x1d" + // 0x1F190301: 0x00001F1D - "\x03\xb7\x03\x13\x00\x00\x1f " + // 0x03B70313: 0x00001F20 - "\x03\xb7\x03\x14\x00\x00\x1f!" + // 0x03B70314: 0x00001F21 - "\x1f \x03\x00\x00\x00\x1f\"" + // 0x1F200300: 0x00001F22 - "\x1f!\x03\x00\x00\x00\x1f#" + // 0x1F210300: 0x00001F23 - "\x1f \x03\x01\x00\x00\x1f$" + // 0x1F200301: 0x00001F24 - "\x1f!\x03\x01\x00\x00\x1f%" + // 0x1F210301: 0x00001F25 - "\x1f \x03B\x00\x00\x1f&" + // 0x1F200342: 0x00001F26 - "\x1f!\x03B\x00\x00\x1f'" + // 0x1F210342: 0x00001F27 - "\x03\x97\x03\x13\x00\x00\x1f(" + // 0x03970313: 0x00001F28 - "\x03\x97\x03\x14\x00\x00\x1f)" + // 0x03970314: 0x00001F29 - "\x1f(\x03\x00\x00\x00\x1f*" + // 0x1F280300: 0x00001F2A - "\x1f)\x03\x00\x00\x00\x1f+" + // 0x1F290300: 0x00001F2B - "\x1f(\x03\x01\x00\x00\x1f," + // 0x1F280301: 0x00001F2C - "\x1f)\x03\x01\x00\x00\x1f-" + // 0x1F290301: 0x00001F2D - "\x1f(\x03B\x00\x00\x1f." + // 0x1F280342: 0x00001F2E - "\x1f)\x03B\x00\x00\x1f/" + // 0x1F290342: 0x00001F2F - "\x03\xb9\x03\x13\x00\x00\x1f0" + // 0x03B90313: 0x00001F30 - "\x03\xb9\x03\x14\x00\x00\x1f1" + // 0x03B90314: 0x00001F31 - "\x1f0\x03\x00\x00\x00\x1f2" + // 0x1F300300: 0x00001F32 - "\x1f1\x03\x00\x00\x00\x1f3" + // 0x1F310300: 0x00001F33 - "\x1f0\x03\x01\x00\x00\x1f4" + // 0x1F300301: 0x00001F34 - "\x1f1\x03\x01\x00\x00\x1f5" + // 0x1F310301: 0x00001F35 - "\x1f0\x03B\x00\x00\x1f6" + // 0x1F300342: 0x00001F36 - "\x1f1\x03B\x00\x00\x1f7" + // 0x1F310342: 0x00001F37 - "\x03\x99\x03\x13\x00\x00\x1f8" + // 0x03990313: 0x00001F38 - "\x03\x99\x03\x14\x00\x00\x1f9" + // 0x03990314: 0x00001F39 - "\x1f8\x03\x00\x00\x00\x1f:" + // 0x1F380300: 0x00001F3A - "\x1f9\x03\x00\x00\x00\x1f;" + // 0x1F390300: 0x00001F3B - "\x1f8\x03\x01\x00\x00\x1f<" + // 0x1F380301: 0x00001F3C - "\x1f9\x03\x01\x00\x00\x1f=" + // 0x1F390301: 0x00001F3D - "\x1f8\x03B\x00\x00\x1f>" + // 0x1F380342: 0x00001F3E - "\x1f9\x03B\x00\x00\x1f?" + // 0x1F390342: 0x00001F3F - "\x03\xbf\x03\x13\x00\x00\x1f@" + // 0x03BF0313: 0x00001F40 - "\x03\xbf\x03\x14\x00\x00\x1fA" + // 0x03BF0314: 0x00001F41 - "\x1f@\x03\x00\x00\x00\x1fB" + // 0x1F400300: 0x00001F42 - "\x1fA\x03\x00\x00\x00\x1fC" + // 0x1F410300: 0x00001F43 - "\x1f@\x03\x01\x00\x00\x1fD" + // 0x1F400301: 0x00001F44 - "\x1fA\x03\x01\x00\x00\x1fE" + // 0x1F410301: 0x00001F45 - "\x03\x9f\x03\x13\x00\x00\x1fH" + // 0x039F0313: 0x00001F48 - "\x03\x9f\x03\x14\x00\x00\x1fI" + // 0x039F0314: 0x00001F49 - "\x1fH\x03\x00\x00\x00\x1fJ" + // 0x1F480300: 0x00001F4A - "\x1fI\x03\x00\x00\x00\x1fK" + // 0x1F490300: 0x00001F4B - "\x1fH\x03\x01\x00\x00\x1fL" + // 0x1F480301: 0x00001F4C - "\x1fI\x03\x01\x00\x00\x1fM" + // 0x1F490301: 0x00001F4D - "\x03\xc5\x03\x13\x00\x00\x1fP" + // 0x03C50313: 0x00001F50 - "\x03\xc5\x03\x14\x00\x00\x1fQ" + // 0x03C50314: 0x00001F51 - "\x1fP\x03\x00\x00\x00\x1fR" + // 0x1F500300: 0x00001F52 - "\x1fQ\x03\x00\x00\x00\x1fS" + // 0x1F510300: 0x00001F53 - "\x1fP\x03\x01\x00\x00\x1fT" + // 0x1F500301: 0x00001F54 - "\x1fQ\x03\x01\x00\x00\x1fU" + // 0x1F510301: 0x00001F55 - "\x1fP\x03B\x00\x00\x1fV" + // 0x1F500342: 0x00001F56 - "\x1fQ\x03B\x00\x00\x1fW" + // 0x1F510342: 0x00001F57 - "\x03\xa5\x03\x14\x00\x00\x1fY" + // 0x03A50314: 0x00001F59 - "\x1fY\x03\x00\x00\x00\x1f[" + // 0x1F590300: 0x00001F5B - "\x1fY\x03\x01\x00\x00\x1f]" + // 0x1F590301: 0x00001F5D - "\x1fY\x03B\x00\x00\x1f_" + // 0x1F590342: 0x00001F5F - "\x03\xc9\x03\x13\x00\x00\x1f`" + // 0x03C90313: 0x00001F60 - "\x03\xc9\x03\x14\x00\x00\x1fa" + // 0x03C90314: 0x00001F61 - "\x1f`\x03\x00\x00\x00\x1fb" + // 0x1F600300: 0x00001F62 - "\x1fa\x03\x00\x00\x00\x1fc" + // 0x1F610300: 0x00001F63 - "\x1f`\x03\x01\x00\x00\x1fd" + // 0x1F600301: 0x00001F64 - "\x1fa\x03\x01\x00\x00\x1fe" + // 0x1F610301: 0x00001F65 - "\x1f`\x03B\x00\x00\x1ff" + // 0x1F600342: 0x00001F66 - "\x1fa\x03B\x00\x00\x1fg" + // 0x1F610342: 0x00001F67 - "\x03\xa9\x03\x13\x00\x00\x1fh" + // 0x03A90313: 0x00001F68 - "\x03\xa9\x03\x14\x00\x00\x1fi" + // 0x03A90314: 0x00001F69 - "\x1fh\x03\x00\x00\x00\x1fj" + // 0x1F680300: 0x00001F6A - "\x1fi\x03\x00\x00\x00\x1fk" + // 0x1F690300: 0x00001F6B - "\x1fh\x03\x01\x00\x00\x1fl" + // 0x1F680301: 0x00001F6C - "\x1fi\x03\x01\x00\x00\x1fm" + // 0x1F690301: 0x00001F6D - "\x1fh\x03B\x00\x00\x1fn" + // 0x1F680342: 0x00001F6E - "\x1fi\x03B\x00\x00\x1fo" + // 0x1F690342: 0x00001F6F - "\x03\xb1\x03\x00\x00\x00\x1fp" + // 0x03B10300: 0x00001F70 - "\x03\xb5\x03\x00\x00\x00\x1fr" + // 0x03B50300: 0x00001F72 - "\x03\xb7\x03\x00\x00\x00\x1ft" + // 0x03B70300: 0x00001F74 - "\x03\xb9\x03\x00\x00\x00\x1fv" + // 0x03B90300: 0x00001F76 - "\x03\xbf\x03\x00\x00\x00\x1fx" + // 0x03BF0300: 0x00001F78 - "\x03\xc5\x03\x00\x00\x00\x1fz" + // 0x03C50300: 0x00001F7A - "\x03\xc9\x03\x00\x00\x00\x1f|" + // 0x03C90300: 0x00001F7C - "\x1f\x00\x03E\x00\x00\x1f\x80" + // 0x1F000345: 0x00001F80 - "\x1f\x01\x03E\x00\x00\x1f\x81" + // 0x1F010345: 0x00001F81 - "\x1f\x02\x03E\x00\x00\x1f\x82" + // 0x1F020345: 0x00001F82 - "\x1f\x03\x03E\x00\x00\x1f\x83" + // 0x1F030345: 0x00001F83 - "\x1f\x04\x03E\x00\x00\x1f\x84" + // 0x1F040345: 0x00001F84 - "\x1f\x05\x03E\x00\x00\x1f\x85" + // 0x1F050345: 0x00001F85 - "\x1f\x06\x03E\x00\x00\x1f\x86" + // 0x1F060345: 0x00001F86 - "\x1f\a\x03E\x00\x00\x1f\x87" + // 0x1F070345: 0x00001F87 - "\x1f\b\x03E\x00\x00\x1f\x88" + // 0x1F080345: 0x00001F88 - "\x1f\t\x03E\x00\x00\x1f\x89" + // 0x1F090345: 0x00001F89 - "\x1f\n\x03E\x00\x00\x1f\x8a" + // 0x1F0A0345: 0x00001F8A - "\x1f\v\x03E\x00\x00\x1f\x8b" + // 0x1F0B0345: 0x00001F8B - "\x1f\f\x03E\x00\x00\x1f\x8c" + // 0x1F0C0345: 0x00001F8C - "\x1f\r\x03E\x00\x00\x1f\x8d" + // 0x1F0D0345: 0x00001F8D - "\x1f\x0e\x03E\x00\x00\x1f\x8e" + // 0x1F0E0345: 0x00001F8E - "\x1f\x0f\x03E\x00\x00\x1f\x8f" + // 0x1F0F0345: 0x00001F8F - "\x1f \x03E\x00\x00\x1f\x90" + // 0x1F200345: 0x00001F90 - "\x1f!\x03E\x00\x00\x1f\x91" + // 0x1F210345: 0x00001F91 - "\x1f\"\x03E\x00\x00\x1f\x92" + // 0x1F220345: 0x00001F92 - "\x1f#\x03E\x00\x00\x1f\x93" + // 0x1F230345: 0x00001F93 - "\x1f$\x03E\x00\x00\x1f\x94" + // 0x1F240345: 0x00001F94 - "\x1f%\x03E\x00\x00\x1f\x95" + // 0x1F250345: 0x00001F95 - "\x1f&\x03E\x00\x00\x1f\x96" + // 0x1F260345: 0x00001F96 - "\x1f'\x03E\x00\x00\x1f\x97" + // 0x1F270345: 0x00001F97 - "\x1f(\x03E\x00\x00\x1f\x98" + // 0x1F280345: 0x00001F98 - "\x1f)\x03E\x00\x00\x1f\x99" + // 0x1F290345: 0x00001F99 - "\x1f*\x03E\x00\x00\x1f\x9a" + // 0x1F2A0345: 0x00001F9A - "\x1f+\x03E\x00\x00\x1f\x9b" + // 0x1F2B0345: 0x00001F9B - "\x1f,\x03E\x00\x00\x1f\x9c" + // 0x1F2C0345: 0x00001F9C - "\x1f-\x03E\x00\x00\x1f\x9d" + // 0x1F2D0345: 0x00001F9D - "\x1f.\x03E\x00\x00\x1f\x9e" + // 0x1F2E0345: 0x00001F9E - "\x1f/\x03E\x00\x00\x1f\x9f" + // 0x1F2F0345: 0x00001F9F - "\x1f`\x03E\x00\x00\x1f\xa0" + // 0x1F600345: 0x00001FA0 - "\x1fa\x03E\x00\x00\x1f\xa1" + // 0x1F610345: 0x00001FA1 - "\x1fb\x03E\x00\x00\x1f\xa2" + // 0x1F620345: 0x00001FA2 - "\x1fc\x03E\x00\x00\x1f\xa3" + // 0x1F630345: 0x00001FA3 - "\x1fd\x03E\x00\x00\x1f\xa4" + // 0x1F640345: 0x00001FA4 - "\x1fe\x03E\x00\x00\x1f\xa5" + // 0x1F650345: 0x00001FA5 - "\x1ff\x03E\x00\x00\x1f\xa6" + // 0x1F660345: 0x00001FA6 - "\x1fg\x03E\x00\x00\x1f\xa7" + // 0x1F670345: 0x00001FA7 - "\x1fh\x03E\x00\x00\x1f\xa8" + // 0x1F680345: 0x00001FA8 - "\x1fi\x03E\x00\x00\x1f\xa9" + // 0x1F690345: 0x00001FA9 - "\x1fj\x03E\x00\x00\x1f\xaa" + // 0x1F6A0345: 0x00001FAA - "\x1fk\x03E\x00\x00\x1f\xab" + // 0x1F6B0345: 0x00001FAB - "\x1fl\x03E\x00\x00\x1f\xac" + // 0x1F6C0345: 0x00001FAC - "\x1fm\x03E\x00\x00\x1f\xad" + // 0x1F6D0345: 0x00001FAD - "\x1fn\x03E\x00\x00\x1f\xae" + // 0x1F6E0345: 0x00001FAE - "\x1fo\x03E\x00\x00\x1f\xaf" + // 0x1F6F0345: 0x00001FAF - "\x03\xb1\x03\x06\x00\x00\x1f\xb0" + // 0x03B10306: 0x00001FB0 - "\x03\xb1\x03\x04\x00\x00\x1f\xb1" + // 0x03B10304: 0x00001FB1 - "\x1fp\x03E\x00\x00\x1f\xb2" + // 0x1F700345: 0x00001FB2 - "\x03\xb1\x03E\x00\x00\x1f\xb3" + // 0x03B10345: 0x00001FB3 - "\x03\xac\x03E\x00\x00\x1f\xb4" + // 0x03AC0345: 0x00001FB4 - "\x03\xb1\x03B\x00\x00\x1f\xb6" + // 0x03B10342: 0x00001FB6 - "\x1f\xb6\x03E\x00\x00\x1f\xb7" + // 0x1FB60345: 0x00001FB7 - "\x03\x91\x03\x06\x00\x00\x1f\xb8" + // 0x03910306: 0x00001FB8 - "\x03\x91\x03\x04\x00\x00\x1f\xb9" + // 0x03910304: 0x00001FB9 - "\x03\x91\x03\x00\x00\x00\x1f\xba" + // 0x03910300: 0x00001FBA - "\x03\x91\x03E\x00\x00\x1f\xbc" + // 0x03910345: 0x00001FBC - "\x00\xa8\x03B\x00\x00\x1f\xc1" + // 0x00A80342: 0x00001FC1 - "\x1ft\x03E\x00\x00\x1f\xc2" + // 0x1F740345: 0x00001FC2 - "\x03\xb7\x03E\x00\x00\x1f\xc3" + // 0x03B70345: 0x00001FC3 - "\x03\xae\x03E\x00\x00\x1f\xc4" + // 0x03AE0345: 0x00001FC4 - "\x03\xb7\x03B\x00\x00\x1f\xc6" + // 0x03B70342: 0x00001FC6 - "\x1f\xc6\x03E\x00\x00\x1f\xc7" + // 0x1FC60345: 0x00001FC7 - "\x03\x95\x03\x00\x00\x00\x1f\xc8" + // 0x03950300: 0x00001FC8 - "\x03\x97\x03\x00\x00\x00\x1f\xca" + // 0x03970300: 0x00001FCA - "\x03\x97\x03E\x00\x00\x1f\xcc" + // 0x03970345: 0x00001FCC - "\x1f\xbf\x03\x00\x00\x00\x1f\xcd" + // 0x1FBF0300: 0x00001FCD - "\x1f\xbf\x03\x01\x00\x00\x1f\xce" + // 0x1FBF0301: 0x00001FCE - "\x1f\xbf\x03B\x00\x00\x1f\xcf" + // 0x1FBF0342: 0x00001FCF - "\x03\xb9\x03\x06\x00\x00\x1f\xd0" + // 0x03B90306: 0x00001FD0 - "\x03\xb9\x03\x04\x00\x00\x1f\xd1" + // 0x03B90304: 0x00001FD1 - "\x03\xca\x03\x00\x00\x00\x1f\xd2" + // 0x03CA0300: 0x00001FD2 - "\x03\xb9\x03B\x00\x00\x1f\xd6" + // 0x03B90342: 0x00001FD6 - "\x03\xca\x03B\x00\x00\x1f\xd7" + // 0x03CA0342: 0x00001FD7 - "\x03\x99\x03\x06\x00\x00\x1f\xd8" + // 0x03990306: 0x00001FD8 - "\x03\x99\x03\x04\x00\x00\x1f\xd9" + // 0x03990304: 0x00001FD9 - "\x03\x99\x03\x00\x00\x00\x1f\xda" + // 0x03990300: 0x00001FDA - "\x1f\xfe\x03\x00\x00\x00\x1f\xdd" + // 0x1FFE0300: 0x00001FDD - "\x1f\xfe\x03\x01\x00\x00\x1f\xde" + // 0x1FFE0301: 0x00001FDE - "\x1f\xfe\x03B\x00\x00\x1f\xdf" + // 0x1FFE0342: 0x00001FDF - "\x03\xc5\x03\x06\x00\x00\x1f\xe0" + // 0x03C50306: 0x00001FE0 - "\x03\xc5\x03\x04\x00\x00\x1f\xe1" + // 0x03C50304: 0x00001FE1 - "\x03\xcb\x03\x00\x00\x00\x1f\xe2" + // 0x03CB0300: 0x00001FE2 - "\x03\xc1\x03\x13\x00\x00\x1f\xe4" + // 0x03C10313: 0x00001FE4 - "\x03\xc1\x03\x14\x00\x00\x1f\xe5" + // 0x03C10314: 0x00001FE5 - "\x03\xc5\x03B\x00\x00\x1f\xe6" + // 0x03C50342: 0x00001FE6 - "\x03\xcb\x03B\x00\x00\x1f\xe7" + // 0x03CB0342: 0x00001FE7 - "\x03\xa5\x03\x06\x00\x00\x1f\xe8" + // 0x03A50306: 0x00001FE8 - "\x03\xa5\x03\x04\x00\x00\x1f\xe9" + // 0x03A50304: 0x00001FE9 - "\x03\xa5\x03\x00\x00\x00\x1f\xea" + // 0x03A50300: 0x00001FEA - "\x03\xa1\x03\x14\x00\x00\x1f\xec" + // 0x03A10314: 0x00001FEC - "\x00\xa8\x03\x00\x00\x00\x1f\xed" + // 0x00A80300: 0x00001FED - "\x1f|\x03E\x00\x00\x1f\xf2" + // 0x1F7C0345: 0x00001FF2 - "\x03\xc9\x03E\x00\x00\x1f\xf3" + // 0x03C90345: 0x00001FF3 - "\x03\xce\x03E\x00\x00\x1f\xf4" + // 0x03CE0345: 0x00001FF4 - "\x03\xc9\x03B\x00\x00\x1f\xf6" + // 0x03C90342: 0x00001FF6 - "\x1f\xf6\x03E\x00\x00\x1f\xf7" + // 0x1FF60345: 0x00001FF7 - "\x03\x9f\x03\x00\x00\x00\x1f\xf8" + // 0x039F0300: 0x00001FF8 - "\x03\xa9\x03\x00\x00\x00\x1f\xfa" + // 0x03A90300: 0x00001FFA - "\x03\xa9\x03E\x00\x00\x1f\xfc" + // 0x03A90345: 0x00001FFC - "!\x90\x038\x00\x00!\x9a" + // 0x21900338: 0x0000219A - "!\x92\x038\x00\x00!\x9b" + // 0x21920338: 0x0000219B - "!\x94\x038\x00\x00!\xae" + // 0x21940338: 0x000021AE - "!\xd0\x038\x00\x00!\xcd" + // 0x21D00338: 0x000021CD - "!\xd4\x038\x00\x00!\xce" + // 0x21D40338: 0x000021CE - "!\xd2\x038\x00\x00!\xcf" + // 0x21D20338: 0x000021CF - "\"\x03\x038\x00\x00\"\x04" + // 0x22030338: 0x00002204 - "\"\b\x038\x00\x00\"\t" + // 0x22080338: 0x00002209 - "\"\v\x038\x00\x00\"\f" + // 0x220B0338: 0x0000220C - "\"#\x038\x00\x00\"$" + // 0x22230338: 0x00002224 - "\"%\x038\x00\x00\"&" + // 0x22250338: 0x00002226 - "\"<\x038\x00\x00\"A" + // 0x223C0338: 0x00002241 - "\"C\x038\x00\x00\"D" + // 0x22430338: 0x00002244 - "\"E\x038\x00\x00\"G" + // 0x22450338: 0x00002247 - "\"H\x038\x00\x00\"I" + // 0x22480338: 0x00002249 - "\x00=\x038\x00\x00\"`" + // 0x003D0338: 0x00002260 - "\"a\x038\x00\x00\"b" + // 0x22610338: 0x00002262 - "\"M\x038\x00\x00\"m" + // 0x224D0338: 0x0000226D - "\x00<\x038\x00\x00\"n" + // 0x003C0338: 0x0000226E - "\x00>\x038\x00\x00\"o" + // 0x003E0338: 0x0000226F - "\"d\x038\x00\x00\"p" + // 0x22640338: 0x00002270 - "\"e\x038\x00\x00\"q" + // 0x22650338: 0x00002271 - "\"r\x038\x00\x00\"t" + // 0x22720338: 0x00002274 - "\"s\x038\x00\x00\"u" + // 0x22730338: 0x00002275 - "\"v\x038\x00\x00\"x" + // 0x22760338: 0x00002278 - "\"w\x038\x00\x00\"y" + // 0x22770338: 0x00002279 - "\"z\x038\x00\x00\"\x80" + // 0x227A0338: 0x00002280 - "\"{\x038\x00\x00\"\x81" + // 0x227B0338: 0x00002281 - "\"\x82\x038\x00\x00\"\x84" + // 0x22820338: 0x00002284 - "\"\x83\x038\x00\x00\"\x85" + // 0x22830338: 0x00002285 - "\"\x86\x038\x00\x00\"\x88" + // 0x22860338: 0x00002288 - "\"\x87\x038\x00\x00\"\x89" + // 0x22870338: 0x00002289 - "\"\xa2\x038\x00\x00\"\xac" + // 0x22A20338: 0x000022AC - "\"\xa8\x038\x00\x00\"\xad" + // 0x22A80338: 0x000022AD - "\"\xa9\x038\x00\x00\"\xae" + // 0x22A90338: 0x000022AE - "\"\xab\x038\x00\x00\"\xaf" + // 0x22AB0338: 0x000022AF - "\"|\x038\x00\x00\"\xe0" + // 0x227C0338: 0x000022E0 - "\"}\x038\x00\x00\"\xe1" + // 0x227D0338: 0x000022E1 - "\"\x91\x038\x00\x00\"\xe2" + // 0x22910338: 0x000022E2 - "\"\x92\x038\x00\x00\"\xe3" + // 0x22920338: 0x000022E3 - "\"\xb2\x038\x00\x00\"\xea" + // 0x22B20338: 0x000022EA - "\"\xb3\x038\x00\x00\"\xeb" + // 0x22B30338: 0x000022EB - "\"\xb4\x038\x00\x00\"\xec" + // 0x22B40338: 0x000022EC - "\"\xb5\x038\x00\x00\"\xed" + // 0x22B50338: 0x000022ED - "0K0\x99\x00\x000L" + // 0x304B3099: 0x0000304C - "0M0\x99\x00\x000N" + // 0x304D3099: 0x0000304E - "0O0\x99\x00\x000P" + // 0x304F3099: 0x00003050 - "0Q0\x99\x00\x000R" + // 0x30513099: 0x00003052 - "0S0\x99\x00\x000T" + // 0x30533099: 0x00003054 - "0U0\x99\x00\x000V" + // 0x30553099: 0x00003056 - "0W0\x99\x00\x000X" + // 0x30573099: 0x00003058 - "0Y0\x99\x00\x000Z" + // 0x30593099: 0x0000305A - "0[0\x99\x00\x000\\" + // 0x305B3099: 0x0000305C - "0]0\x99\x00\x000^" + // 0x305D3099: 0x0000305E - "0_0\x99\x00\x000`" + // 0x305F3099: 0x00003060 - "0a0\x99\x00\x000b" + // 0x30613099: 0x00003062 - "0d0\x99\x00\x000e" + // 0x30643099: 0x00003065 - "0f0\x99\x00\x000g" + // 0x30663099: 0x00003067 - "0h0\x99\x00\x000i" + // 0x30683099: 0x00003069 - "0o0\x99\x00\x000p" + // 0x306F3099: 0x00003070 - "0o0\x9a\x00\x000q" + // 0x306F309A: 0x00003071 - "0r0\x99\x00\x000s" + // 0x30723099: 0x00003073 - "0r0\x9a\x00\x000t" + // 0x3072309A: 0x00003074 - "0u0\x99\x00\x000v" + // 0x30753099: 0x00003076 - "0u0\x9a\x00\x000w" + // 0x3075309A: 0x00003077 - "0x0\x99\x00\x000y" + // 0x30783099: 0x00003079 - "0x0\x9a\x00\x000z" + // 0x3078309A: 0x0000307A - "0{0\x99\x00\x000|" + // 0x307B3099: 0x0000307C - "0{0\x9a\x00\x000}" + // 0x307B309A: 0x0000307D - "0F0\x99\x00\x000\x94" + // 0x30463099: 0x00003094 - "0\x9d0\x99\x00\x000\x9e" + // 0x309D3099: 0x0000309E - "0\xab0\x99\x00\x000\xac" + // 0x30AB3099: 0x000030AC - "0\xad0\x99\x00\x000\xae" + // 0x30AD3099: 0x000030AE - "0\xaf0\x99\x00\x000\xb0" + // 0x30AF3099: 0x000030B0 - "0\xb10\x99\x00\x000\xb2" + // 0x30B13099: 0x000030B2 - "0\xb30\x99\x00\x000\xb4" + // 0x30B33099: 0x000030B4 - "0\xb50\x99\x00\x000\xb6" + // 0x30B53099: 0x000030B6 - "0\xb70\x99\x00\x000\xb8" + // 0x30B73099: 0x000030B8 - "0\xb90\x99\x00\x000\xba" + // 0x30B93099: 0x000030BA - "0\xbb0\x99\x00\x000\xbc" + // 0x30BB3099: 0x000030BC - "0\xbd0\x99\x00\x000\xbe" + // 0x30BD3099: 0x000030BE - "0\xbf0\x99\x00\x000\xc0" + // 0x30BF3099: 0x000030C0 - "0\xc10\x99\x00\x000\xc2" + // 0x30C13099: 0x000030C2 - "0\xc40\x99\x00\x000\xc5" + // 0x30C43099: 0x000030C5 - "0\xc60\x99\x00\x000\xc7" + // 0x30C63099: 0x000030C7 - "0\xc80\x99\x00\x000\xc9" + // 0x30C83099: 0x000030C9 - "0\xcf0\x99\x00\x000\xd0" + // 0x30CF3099: 0x000030D0 - "0\xcf0\x9a\x00\x000\xd1" + // 0x30CF309A: 0x000030D1 - "0\xd20\x99\x00\x000\xd3" + // 0x30D23099: 0x000030D3 - "0\xd20\x9a\x00\x000\xd4" + // 0x30D2309A: 0x000030D4 - "0\xd50\x99\x00\x000\xd6" + // 0x30D53099: 0x000030D6 - "0\xd50\x9a\x00\x000\xd7" + // 0x30D5309A: 0x000030D7 - "0\xd80\x99\x00\x000\xd9" + // 0x30D83099: 0x000030D9 - "0\xd80\x9a\x00\x000\xda" + // 0x30D8309A: 0x000030DA - "0\xdb0\x99\x00\x000\xdc" + // 0x30DB3099: 0x000030DC - "0\xdb0\x9a\x00\x000\xdd" + // 0x30DB309A: 0x000030DD - "0\xa60\x99\x00\x000\xf4" + // 0x30A63099: 0x000030F4 - "0\xef0\x99\x00\x000\xf7" + // 0x30EF3099: 0x000030F7 - "0\xf00\x99\x00\x000\xf8" + // 0x30F03099: 0x000030F8 - "0\xf10\x99\x00\x000\xf9" + // 0x30F13099: 0x000030F9 - "0\xf20\x99\x00\x000\xfa" + // 0x30F23099: 0x000030FA - "0\xfd0\x99\x00\x000\xfe" + // 0x30FD3099: 0x000030FE - "\x10\x99\x10\xba\x00\x01\x10\x9a" + // 0x109910BA: 0x0001109A - "\x10\x9b\x10\xba\x00\x01\x10\x9c" + // 0x109B10BA: 0x0001109C - "\x10\xa5\x10\xba\x00\x01\x10\xab" + // 0x10A510BA: 0x000110AB - "\x111\x11'\x00\x01\x11." + // 0x11311127: 0x0001112E - "\x112\x11'\x00\x01\x11/" + // 0x11321127: 0x0001112F - "\x13G\x13>\x00\x01\x13K" + // 0x1347133E: 0x0001134B - "\x13G\x13W\x00\x01\x13L" + // 0x13471357: 0x0001134C - "\x14\xb9\x14\xba\x00\x01\x14\xbb" + // 0x14B914BA: 0x000114BB - "\x14\xb9\x14\xb0\x00\x01\x14\xbc" + // 0x14B914B0: 0x000114BC - "\x14\xb9\x14\xbd\x00\x01\x14\xbe" + // 0x14B914BD: 0x000114BE - "\x15\xb8\x15\xaf\x00\x01\x15\xba" + // 0x15B815AF: 0x000115BA - "\x15\xb9\x15\xaf\x00\x01\x15\xbb" + // 0x15B915AF: 0x000115BB - "\x195\x190\x00\x01\x198" + // 0x19351930: 0x00011938 + "\x00\x01\x04\x00`\x00\x00\xc0" + // 0x00041 0x00300: 0x000C0 + "\x00\x01\x04\x00` \x00\xc1" + // 0x00041 0x00301: 0x000C1 + "\x00\x01\x04\x00`@\x00\xc2" + // 0x00041 0x00302: 0x000C2 + "\x00\x01\x04\x00``\x00\xc3" + // 0x00041 0x00303: 0x000C3 + "\x00\x01\x04\x00a\x00\x00\xc4" + // 0x00041 0x00308: 0x000C4 + "\x00\x01\x04\x00a@\x00\xc5" + // 0x00041 0x0030A: 0x000C5 + "\x00\x01\f\x00d\xe0\x00\xc7" + // 0x00043 0x00327: 0x000C7 + "\x00\x01\x14\x00`\x00\x00\xc8" + // 0x00045 0x00300: 0x000C8 + "\x00\x01\x14\x00` \x00\xc9" + // 0x00045 0x00301: 0x000C9 + "\x00\x01\x14\x00`@\x00\xca" + // 0x00045 0x00302: 0x000CA + "\x00\x01\x14\x00a\x00\x00\xcb" + // 0x00045 0x00308: 0x000CB + "\x00\x01$\x00`\x00\x00\xcc" + // 0x00049 0x00300: 0x000CC + "\x00\x01$\x00` \x00\xcd" + // 0x00049 0x00301: 0x000CD + "\x00\x01$\x00`@\x00\xce" + // 0x00049 0x00302: 0x000CE + "\x00\x01$\x00a\x00\x00\xcf" + // 0x00049 0x00308: 0x000CF + "\x00\x018\x00``\x00\xd1" + // 0x0004E 0x00303: 0x000D1 + "\x00\x01<\x00`\x00\x00\xd2" + // 0x0004F 0x00300: 0x000D2 + "\x00\x01<\x00` \x00\xd3" + // 0x0004F 0x00301: 0x000D3 + "\x00\x01<\x00`@\x00\xd4" + // 0x0004F 0x00302: 0x000D4 + "\x00\x01<\x00``\x00\xd5" + // 0x0004F 0x00303: 0x000D5 + "\x00\x01<\x00a\x00\x00\xd6" + // 0x0004F 0x00308: 0x000D6 + "\x00\x01T\x00`\x00\x00\xd9" + // 0x00055 0x00300: 0x000D9 + "\x00\x01T\x00` \x00\xda" + // 0x00055 0x00301: 0x000DA + "\x00\x01T\x00`@\x00\xdb" + // 0x00055 0x00302: 0x000DB + "\x00\x01T\x00a\x00\x00\xdc" + // 0x00055 0x00308: 0x000DC + "\x00\x01d\x00` \x00\xdd" + // 0x00059 0x00301: 0x000DD + "\x00\x01\x84\x00`\x00\x00\xe0" + // 0x00061 0x00300: 0x000E0 + "\x00\x01\x84\x00` \x00\xe1" + // 0x00061 0x00301: 0x000E1 + "\x00\x01\x84\x00`@\x00\xe2" + // 0x00061 0x00302: 0x000E2 + "\x00\x01\x84\x00``\x00\xe3" + // 0x00061 0x00303: 0x000E3 + "\x00\x01\x84\x00a\x00\x00\xe4" + // 0x00061 0x00308: 0x000E4 + "\x00\x01\x84\x00a@\x00\xe5" + // 0x00061 0x0030A: 0x000E5 + "\x00\x01\x8c\x00d\xe0\x00\xe7" + // 0x00063 0x00327: 0x000E7 + "\x00\x01\x94\x00`\x00\x00\xe8" + // 0x00065 0x00300: 0x000E8 + "\x00\x01\x94\x00` \x00\xe9" + // 0x00065 0x00301: 0x000E9 + "\x00\x01\x94\x00`@\x00\xea" + // 0x00065 0x00302: 0x000EA + "\x00\x01\x94\x00a\x00\x00\xeb" + // 0x00065 0x00308: 0x000EB + "\x00\x01\xa4\x00`\x00\x00\xec" + // 0x00069 0x00300: 0x000EC + "\x00\x01\xa4\x00` \x00\xed" + // 0x00069 0x00301: 0x000ED + "\x00\x01\xa4\x00`@\x00\xee" + // 0x00069 0x00302: 0x000EE + "\x00\x01\xa4\x00a\x00\x00\xef" + // 0x00069 0x00308: 0x000EF + "\x00\x01\xb8\x00``\x00\xf1" + // 0x0006E 0x00303: 0x000F1 + "\x00\x01\xbc\x00`\x00\x00\xf2" + // 0x0006F 0x00300: 0x000F2 + "\x00\x01\xbc\x00` \x00\xf3" + // 0x0006F 0x00301: 0x000F3 + "\x00\x01\xbc\x00`@\x00\xf4" + // 0x0006F 0x00302: 0x000F4 + "\x00\x01\xbc\x00``\x00\xf5" + // 0x0006F 0x00303: 0x000F5 + "\x00\x01\xbc\x00a\x00\x00\xf6" + // 0x0006F 0x00308: 0x000F6 + "\x00\x01\xd4\x00`\x00\x00\xf9" + // 0x00075 0x00300: 0x000F9 + "\x00\x01\xd4\x00` \x00\xfa" + // 0x00075 0x00301: 0x000FA + "\x00\x01\xd4\x00`@\x00\xfb" + // 0x00075 0x00302: 0x000FB + "\x00\x01\xd4\x00a\x00\x00\xfc" + // 0x00075 0x00308: 0x000FC + "\x00\x01\xe4\x00` \x00\xfd" + // 0x00079 0x00301: 0x000FD + "\x00\x01\xe4\x00a\x00\x00\xff" + // 0x00079 0x00308: 0x000FF + "\x00\x01\x04\x00`\x80\x01\x00" + // 0x00041 0x00304: 0x00100 + "\x00\x01\x84\x00`\x80\x01\x01" + // 0x00061 0x00304: 0x00101 + "\x00\x01\x04\x00`\xc0\x01\x02" + // 0x00041 0x00306: 0x00102 + "\x00\x01\x84\x00`\xc0\x01\x03" + // 0x00061 0x00306: 0x00103 + "\x00\x01\x04\x00e\x00\x01\x04" + // 0x00041 0x00328: 0x00104 + "\x00\x01\x84\x00e\x00\x01\x05" + // 0x00061 0x00328: 0x00105 + "\x00\x01\f\x00` \x01\x06" + // 0x00043 0x00301: 0x00106 + "\x00\x01\x8c\x00` \x01\a" + // 0x00063 0x00301: 0x00107 + "\x00\x01\f\x00`@\x01\b" + // 0x00043 0x00302: 0x00108 + "\x00\x01\x8c\x00`@\x01\t" + // 0x00063 0x00302: 0x00109 + "\x00\x01\f\x00`\xe0\x01\n" + // 0x00043 0x00307: 0x0010A + "\x00\x01\x8c\x00`\xe0\x01\v" + // 0x00063 0x00307: 0x0010B + "\x00\x01\f\x00a\x80\x01\f" + // 0x00043 0x0030C: 0x0010C + "\x00\x01\x8c\x00a\x80\x01\r" + // 0x00063 0x0030C: 0x0010D + "\x00\x01\x10\x00a\x80\x01\x0e" + // 0x00044 0x0030C: 0x0010E + "\x00\x01\x90\x00a\x80\x01\x0f" + // 0x00064 0x0030C: 0x0010F + "\x00\x01\x14\x00`\x80\x01\x12" + // 0x00045 0x00304: 0x00112 + "\x00\x01\x94\x00`\x80\x01\x13" + // 0x00065 0x00304: 0x00113 + "\x00\x01\x14\x00`\xc0\x01\x14" + // 0x00045 0x00306: 0x00114 + "\x00\x01\x94\x00`\xc0\x01\x15" + // 0x00065 0x00306: 0x00115 + "\x00\x01\x14\x00`\xe0\x01\x16" + // 0x00045 0x00307: 0x00116 + "\x00\x01\x94\x00`\xe0\x01\x17" + // 0x00065 0x00307: 0x00117 + "\x00\x01\x14\x00e\x00\x01\x18" + // 0x00045 0x00328: 0x00118 + "\x00\x01\x94\x00e\x00\x01\x19" + // 0x00065 0x00328: 0x00119 + "\x00\x01\x14\x00a\x80\x01\x1a" + // 0x00045 0x0030C: 0x0011A + "\x00\x01\x94\x00a\x80\x01\x1b" + // 0x00065 0x0030C: 0x0011B + "\x00\x01\x1c\x00`@\x01\x1c" + // 0x00047 0x00302: 0x0011C + "\x00\x01\x9c\x00`@\x01\x1d" + // 0x00067 0x00302: 0x0011D + "\x00\x01\x1c\x00`\xc0\x01\x1e" + // 0x00047 0x00306: 0x0011E + "\x00\x01\x9c\x00`\xc0\x01\x1f" + // 0x00067 0x00306: 0x0011F + "\x00\x01\x1c\x00`\xe0\x01 " + // 0x00047 0x00307: 0x00120 + "\x00\x01\x9c\x00`\xe0\x01!" + // 0x00067 0x00307: 0x00121 + "\x00\x01\x1c\x00d\xe0\x01\"" + // 0x00047 0x00327: 0x00122 + "\x00\x01\x9c\x00d\xe0\x01#" + // 0x00067 0x00327: 0x00123 + "\x00\x01 \x00`@\x01$" + // 0x00048 0x00302: 0x00124 + "\x00\x01\xa0\x00`@\x01%" + // 0x00068 0x00302: 0x00125 + "\x00\x01$\x00``\x01(" + // 0x00049 0x00303: 0x00128 + "\x00\x01\xa4\x00``\x01)" + // 0x00069 0x00303: 0x00129 + "\x00\x01$\x00`\x80\x01*" + // 0x00049 0x00304: 0x0012A + "\x00\x01\xa4\x00`\x80\x01+" + // 0x00069 0x00304: 0x0012B + "\x00\x01$\x00`\xc0\x01," + // 0x00049 0x00306: 0x0012C + "\x00\x01\xa4\x00`\xc0\x01-" + // 0x00069 0x00306: 0x0012D + "\x00\x01$\x00e\x00\x01." + // 0x00049 0x00328: 0x0012E + "\x00\x01\xa4\x00e\x00\x01/" + // 0x00069 0x00328: 0x0012F + "\x00\x01$\x00`\xe0\x010" + // 0x00049 0x00307: 0x00130 + "\x00\x01(\x00`@\x014" + // 0x0004A 0x00302: 0x00134 + "\x00\x01\xa8\x00`@\x015" + // 0x0006A 0x00302: 0x00135 + "\x00\x01,\x00d\xe0\x016" + // 0x0004B 0x00327: 0x00136 + "\x00\x01\xac\x00d\xe0\x017" + // 0x0006B 0x00327: 0x00137 + "\x00\x010\x00` \x019" + // 0x0004C 0x00301: 0x00139 + "\x00\x01\xb0\x00` \x01:" + // 0x0006C 0x00301: 0x0013A + "\x00\x010\x00d\xe0\x01;" + // 0x0004C 0x00327: 0x0013B + "\x00\x01\xb0\x00d\xe0\x01<" + // 0x0006C 0x00327: 0x0013C + "\x00\x010\x00a\x80\x01=" + // 0x0004C 0x0030C: 0x0013D + "\x00\x01\xb0\x00a\x80\x01>" + // 0x0006C 0x0030C: 0x0013E + "\x00\x018\x00` \x01C" + // 0x0004E 0x00301: 0x00143 + "\x00\x01\xb8\x00` \x01D" + // 0x0006E 0x00301: 0x00144 + "\x00\x018\x00d\xe0\x01E" + // 0x0004E 0x00327: 0x00145 + "\x00\x01\xb8\x00d\xe0\x01F" + // 0x0006E 0x00327: 0x00146 + "\x00\x018\x00a\x80\x01G" + // 0x0004E 0x0030C: 0x00147 + "\x00\x01\xb8\x00a\x80\x01H" + // 0x0006E 0x0030C: 0x00148 + "\x00\x01<\x00`\x80\x01L" + // 0x0004F 0x00304: 0x0014C + "\x00\x01\xbc\x00`\x80\x01M" + // 0x0006F 0x00304: 0x0014D + "\x00\x01<\x00`\xc0\x01N" + // 0x0004F 0x00306: 0x0014E + "\x00\x01\xbc\x00`\xc0\x01O" + // 0x0006F 0x00306: 0x0014F + "\x00\x01<\x00a`\x01P" + // 0x0004F 0x0030B: 0x00150 + "\x00\x01\xbc\x00a`\x01Q" + // 0x0006F 0x0030B: 0x00151 + "\x00\x01H\x00` \x01T" + // 0x00052 0x00301: 0x00154 + "\x00\x01\xc8\x00` \x01U" + // 0x00072 0x00301: 0x00155 + "\x00\x01H\x00d\xe0\x01V" + // 0x00052 0x00327: 0x00156 + "\x00\x01\xc8\x00d\xe0\x01W" + // 0x00072 0x00327: 0x00157 + "\x00\x01H\x00a\x80\x01X" + // 0x00052 0x0030C: 0x00158 + "\x00\x01\xc8\x00a\x80\x01Y" + // 0x00072 0x0030C: 0x00159 + "\x00\x01L\x00` \x01Z" + // 0x00053 0x00301: 0x0015A + "\x00\x01\xcc\x00` \x01[" + // 0x00073 0x00301: 0x0015B + "\x00\x01L\x00`@\x01\\" + // 0x00053 0x00302: 0x0015C + "\x00\x01\xcc\x00`@\x01]" + // 0x00073 0x00302: 0x0015D + "\x00\x01L\x00d\xe0\x01^" + // 0x00053 0x00327: 0x0015E + "\x00\x01\xcc\x00d\xe0\x01_" + // 0x00073 0x00327: 0x0015F + "\x00\x01L\x00a\x80\x01`" + // 0x00053 0x0030C: 0x00160 + "\x00\x01\xcc\x00a\x80\x01a" + // 0x00073 0x0030C: 0x00161 + "\x00\x01P\x00d\xe0\x01b" + // 0x00054 0x00327: 0x00162 + "\x00\x01\xd0\x00d\xe0\x01c" + // 0x00074 0x00327: 0x00163 + "\x00\x01P\x00a\x80\x01d" + // 0x00054 0x0030C: 0x00164 + "\x00\x01\xd0\x00a\x80\x01e" + // 0x00074 0x0030C: 0x00165 + "\x00\x01T\x00``\x01h" + // 0x00055 0x00303: 0x00168 + "\x00\x01\xd4\x00``\x01i" + // 0x00075 0x00303: 0x00169 + "\x00\x01T\x00`\x80\x01j" + // 0x00055 0x00304: 0x0016A + "\x00\x01\xd4\x00`\x80\x01k" + // 0x00075 0x00304: 0x0016B + "\x00\x01T\x00`\xc0\x01l" + // 0x00055 0x00306: 0x0016C + "\x00\x01\xd4\x00`\xc0\x01m" + // 0x00075 0x00306: 0x0016D + "\x00\x01T\x00a@\x01n" + // 0x00055 0x0030A: 0x0016E + "\x00\x01\xd4\x00a@\x01o" + // 0x00075 0x0030A: 0x0016F + "\x00\x01T\x00a`\x01p" + // 0x00055 0x0030B: 0x00170 + "\x00\x01\xd4\x00a`\x01q" + // 0x00075 0x0030B: 0x00171 + "\x00\x01T\x00e\x00\x01r" + // 0x00055 0x00328: 0x00172 + "\x00\x01\xd4\x00e\x00\x01s" + // 0x00075 0x00328: 0x00173 + "\x00\x01\\\x00`@\x01t" + // 0x00057 0x00302: 0x00174 + "\x00\x01\xdc\x00`@\x01u" + // 0x00077 0x00302: 0x00175 + "\x00\x01d\x00`@\x01v" + // 0x00059 0x00302: 0x00176 + "\x00\x01\xe4\x00`@\x01w" + // 0x00079 0x00302: 0x00177 + "\x00\x01d\x00a\x00\x01x" + // 0x00059 0x00308: 0x00178 + "\x00\x01h\x00` \x01y" + // 0x0005A 0x00301: 0x00179 + "\x00\x01\xe8\x00` \x01z" + // 0x0007A 0x00301: 0x0017A + "\x00\x01h\x00`\xe0\x01{" + // 0x0005A 0x00307: 0x0017B + "\x00\x01\xe8\x00`\xe0\x01|" + // 0x0007A 0x00307: 0x0017C + "\x00\x01h\x00a\x80\x01}" + // 0x0005A 0x0030C: 0x0017D + "\x00\x01\xe8\x00a\x80\x01~" + // 0x0007A 0x0030C: 0x0017E + "\x00\x01<\x00c`\x01\xa0" + // 0x0004F 0x0031B: 0x001A0 + "\x00\x01\xbc\x00c`\x01\xa1" + // 0x0006F 0x0031B: 0x001A1 + "\x00\x01T\x00c`\x01\xaf" + // 0x00055 0x0031B: 0x001AF + "\x00\x01\xd4\x00c`\x01\xb0" + // 0x00075 0x0031B: 0x001B0 + "\x00\x01\x04\x00a\x80\x01\xcd" + // 0x00041 0x0030C: 0x001CD + "\x00\x01\x84\x00a\x80\x01\xce" + // 0x00061 0x0030C: 0x001CE + "\x00\x01$\x00a\x80\x01\xcf" + // 0x00049 0x0030C: 0x001CF + "\x00\x01\xa4\x00a\x80\x01\xd0" + // 0x00069 0x0030C: 0x001D0 + "\x00\x01<\x00a\x80\x01\xd1" + // 0x0004F 0x0030C: 0x001D1 + "\x00\x01\xbc\x00a\x80\x01\xd2" + // 0x0006F 0x0030C: 0x001D2 + "\x00\x01T\x00a\x80\x01\xd3" + // 0x00055 0x0030C: 0x001D3 + "\x00\x01\xd4\x00a\x80\x01\xd4" + // 0x00075 0x0030C: 0x001D4 + "\x00\x03p\x00`\x80\x01\xd5" + // 0x000DC 0x00304: 0x001D5 + "\x00\x03\xf0\x00`\x80\x01\xd6" + // 0x000FC 0x00304: 0x001D6 + "\x00\x03p\x00` \x01\xd7" + // 0x000DC 0x00301: 0x001D7 + "\x00\x03\xf0\x00` \x01\xd8" + // 0x000FC 0x00301: 0x001D8 + "\x00\x03p\x00a\x80\x01\xd9" + // 0x000DC 0x0030C: 0x001D9 + "\x00\x03\xf0\x00a\x80\x01\xda" + // 0x000FC 0x0030C: 0x001DA + "\x00\x03p\x00`\x00\x01\xdb" + // 0x000DC 0x00300: 0x001DB + "\x00\x03\xf0\x00`\x00\x01\xdc" + // 0x000FC 0x00300: 0x001DC + "\x00\x03\x10\x00`\x80\x01\xde" + // 0x000C4 0x00304: 0x001DE + "\x00\x03\x90\x00`\x80\x01\xdf" + // 0x000E4 0x00304: 0x001DF + "\x00\b\x98\x00`\x80\x01\xe0" + // 0x00226 0x00304: 0x001E0 + "\x00\b\x9c\x00`\x80\x01\xe1" + // 0x00227 0x00304: 0x001E1 + "\x00\x03\x18\x00`\x80\x01\xe2" + // 0x000C6 0x00304: 0x001E2 + "\x00\x03\x98\x00`\x80\x01\xe3" + // 0x000E6 0x00304: 0x001E3 + "\x00\x01\x1c\x00a\x80\x01\xe6" + // 0x00047 0x0030C: 0x001E6 + "\x00\x01\x9c\x00a\x80\x01\xe7" + // 0x00067 0x0030C: 0x001E7 + "\x00\x01,\x00a\x80\x01\xe8" + // 0x0004B 0x0030C: 0x001E8 + "\x00\x01\xac\x00a\x80\x01\xe9" + // 0x0006B 0x0030C: 0x001E9 + "\x00\x01<\x00e\x00\x01\xea" + // 0x0004F 0x00328: 0x001EA + "\x00\x01\xbc\x00e\x00\x01\xeb" + // 0x0006F 0x00328: 0x001EB + "\x00\a\xa8\x00`\x80\x01\xec" + // 0x001EA 0x00304: 0x001EC + "\x00\a\xac\x00`\x80\x01\xed" + // 0x001EB 0x00304: 0x001ED + "\x00\x06\xdc\x00a\x80\x01\xee" + // 0x001B7 0x0030C: 0x001EE + "\x00\nH\x00a\x80\x01\xef" + // 0x00292 0x0030C: 0x001EF + "\x00\x01\xa8\x00a\x80\x01\xf0" + // 0x0006A 0x0030C: 0x001F0 + "\x00\x01\x1c\x00` \x01\xf4" + // 0x00047 0x00301: 0x001F4 + "\x00\x01\x9c\x00` \x01\xf5" + // 0x00067 0x00301: 0x001F5 + "\x00\x018\x00`\x00\x01\xf8" + // 0x0004E 0x00300: 0x001F8 + "\x00\x01\xb8\x00`\x00\x01\xf9" + // 0x0006E 0x00300: 0x001F9 + "\x00\x03\x14\x00` \x01\xfa" + // 0x000C5 0x00301: 0x001FA + "\x00\x03\x94\x00` \x01\xfb" + // 0x000E5 0x00301: 0x001FB + "\x00\x03\x18\x00` \x01\xfc" + // 0x000C6 0x00301: 0x001FC + "\x00\x03\x98\x00` \x01\xfd" + // 0x000E6 0x00301: 0x001FD + "\x00\x03`\x00` \x01\xfe" + // 0x000D8 0x00301: 0x001FE + "\x00\x03\xe0\x00` \x01\xff" + // 0x000F8 0x00301: 0x001FF + "\x00\x01\x04\x00a\xe0\x02\x00" + // 0x00041 0x0030F: 0x00200 + "\x00\x01\x84\x00a\xe0\x02\x01" + // 0x00061 0x0030F: 0x00201 + "\x00\x01\x04\x00b \x02\x02" + // 0x00041 0x00311: 0x00202 + "\x00\x01\x84\x00b \x02\x03" + // 0x00061 0x00311: 0x00203 + "\x00\x01\x14\x00a\xe0\x02\x04" + // 0x00045 0x0030F: 0x00204 + "\x00\x01\x94\x00a\xe0\x02\x05" + // 0x00065 0x0030F: 0x00205 + "\x00\x01\x14\x00b \x02\x06" + // 0x00045 0x00311: 0x00206 + "\x00\x01\x94\x00b \x02\a" + // 0x00065 0x00311: 0x00207 + "\x00\x01$\x00a\xe0\x02\b" + // 0x00049 0x0030F: 0x00208 + "\x00\x01\xa4\x00a\xe0\x02\t" + // 0x00069 0x0030F: 0x00209 + "\x00\x01$\x00b \x02\n" + // 0x00049 0x00311: 0x0020A + "\x00\x01\xa4\x00b \x02\v" + // 0x00069 0x00311: 0x0020B + "\x00\x01<\x00a\xe0\x02\f" + // 0x0004F 0x0030F: 0x0020C + "\x00\x01\xbc\x00a\xe0\x02\r" + // 0x0006F 0x0030F: 0x0020D + "\x00\x01<\x00b \x02\x0e" + // 0x0004F 0x00311: 0x0020E + "\x00\x01\xbc\x00b \x02\x0f" + // 0x0006F 0x00311: 0x0020F + "\x00\x01H\x00a\xe0\x02\x10" + // 0x00052 0x0030F: 0x00210 + "\x00\x01\xc8\x00a\xe0\x02\x11" + // 0x00072 0x0030F: 0x00211 + "\x00\x01H\x00b \x02\x12" + // 0x00052 0x00311: 0x00212 + "\x00\x01\xc8\x00b \x02\x13" + // 0x00072 0x00311: 0x00213 + "\x00\x01T\x00a\xe0\x02\x14" + // 0x00055 0x0030F: 0x00214 + "\x00\x01\xd4\x00a\xe0\x02\x15" + // 0x00075 0x0030F: 0x00215 + "\x00\x01T\x00b \x02\x16" + // 0x00055 0x00311: 0x00216 + "\x00\x01\xd4\x00b \x02\x17" + // 0x00075 0x00311: 0x00217 + "\x00\x01L\x00d\xc0\x02\x18" + // 0x00053 0x00326: 0x00218 + "\x00\x01\xcc\x00d\xc0\x02\x19" + // 0x00073 0x00326: 0x00219 + "\x00\x01P\x00d\xc0\x02\x1a" + // 0x00054 0x00326: 0x0021A + "\x00\x01\xd0\x00d\xc0\x02\x1b" + // 0x00074 0x00326: 0x0021B + "\x00\x01 \x00a\x80\x02\x1e" + // 0x00048 0x0030C: 0x0021E + "\x00\x01\xa0\x00a\x80\x02\x1f" + // 0x00068 0x0030C: 0x0021F + "\x00\x01\x04\x00`\xe0\x02&" + // 0x00041 0x00307: 0x00226 + "\x00\x01\x84\x00`\xe0\x02'" + // 0x00061 0x00307: 0x00227 + "\x00\x01\x14\x00d\xe0\x02(" + // 0x00045 0x00327: 0x00228 + "\x00\x01\x94\x00d\xe0\x02)" + // 0x00065 0x00327: 0x00229 + "\x00\x03X\x00`\x80\x02*" + // 0x000D6 0x00304: 0x0022A + "\x00\x03\xd8\x00`\x80\x02+" + // 0x000F6 0x00304: 0x0022B + "\x00\x03T\x00`\x80\x02," + // 0x000D5 0x00304: 0x0022C + "\x00\x03\xd4\x00`\x80\x02-" + // 0x000F5 0x00304: 0x0022D + "\x00\x01<\x00`\xe0\x02." + // 0x0004F 0x00307: 0x0022E + "\x00\x01\xbc\x00`\xe0\x02/" + // 0x0006F 0x00307: 0x0022F + "\x00\b\xb8\x00`\x80\x020" + // 0x0022E 0x00304: 0x00230 + "\x00\b\xbc\x00`\x80\x021" + // 0x0022F 0x00304: 0x00231 + "\x00\x01d\x00`\x80\x022" + // 0x00059 0x00304: 0x00232 + "\x00\x01\xe4\x00`\x80\x023" + // 0x00079 0x00304: 0x00233 + "\x00\x02\xa0\x00` \x03\x85" + // 0x000A8 0x00301: 0x00385 + "\x00\x0eD\x00` \x03\x86" + // 0x00391 0x00301: 0x00386 + "\x00\x0eT\x00` \x03\x88" + // 0x00395 0x00301: 0x00388 + "\x00\x0e\\\x00` \x03\x89" + // 0x00397 0x00301: 0x00389 + "\x00\x0ed\x00` \x03\x8a" + // 0x00399 0x00301: 0x0038A + "\x00\x0e|\x00` \x03\x8c" + // 0x0039F 0x00301: 0x0038C + "\x00\x0e\x94\x00` \x03\x8e" + // 0x003A5 0x00301: 0x0038E + "\x00\x0e\xa4\x00` \x03\x8f" + // 0x003A9 0x00301: 0x0038F + "\x00\x0f(\x00` \x03\x90" + // 0x003CA 0x00301: 0x00390 + "\x00\x0ed\x00a\x00\x03\xaa" + // 0x00399 0x00308: 0x003AA + "\x00\x0e\x94\x00a\x00\x03\xab" + // 0x003A5 0x00308: 0x003AB + "\x00\x0e\xc4\x00` \x03\xac" + // 0x003B1 0x00301: 0x003AC + "\x00\x0e\xd4\x00` \x03\xad" + // 0x003B5 0x00301: 0x003AD + "\x00\x0e\xdc\x00` \x03\xae" + // 0x003B7 0x00301: 0x003AE + "\x00\x0e\xe4\x00` \x03\xaf" + // 0x003B9 0x00301: 0x003AF + "\x00\x0f,\x00` \x03\xb0" + // 0x003CB 0x00301: 0x003B0 + "\x00\x0e\xe4\x00a\x00\x03\xca" + // 0x003B9 0x00308: 0x003CA + "\x00\x0f\x14\x00a\x00\x03\xcb" + // 0x003C5 0x00308: 0x003CB + "\x00\x0e\xfc\x00` \x03\xcc" + // 0x003BF 0x00301: 0x003CC + "\x00\x0f\x14\x00` \x03\xcd" + // 0x003C5 0x00301: 0x003CD + "\x00\x0f$\x00` \x03\xce" + // 0x003C9 0x00301: 0x003CE + "\x00\x0fH\x00` \x03\xd3" + // 0x003D2 0x00301: 0x003D3 + "\x00\x0fH\x00a\x00\x03\xd4" + // 0x003D2 0x00308: 0x003D4 + "\x00\x10T\x00`\x00\x04\x00" + // 0x00415 0x00300: 0x00400 + "\x00\x10T\x00a\x00\x04\x01" + // 0x00415 0x00308: 0x00401 + "\x00\x10L\x00` \x04\x03" + // 0x00413 0x00301: 0x00403 + "\x00\x10\x18\x00a\x00\x04\a" + // 0x00406 0x00308: 0x00407 + "\x00\x10h\x00` \x04\f" + // 0x0041A 0x00301: 0x0040C + "\x00\x10`\x00`\x00\x04\r" + // 0x00418 0x00300: 0x0040D + "\x00\x10\x8c\x00`\xc0\x04\x0e" + // 0x00423 0x00306: 0x0040E + "\x00\x10`\x00`\xc0\x04\x19" + // 0x00418 0x00306: 0x00419 + "\x00\x10\xe0\x00`\xc0\x049" + // 0x00438 0x00306: 0x00439 + "\x00\x10\xd4\x00`\x00\x04P" + // 0x00435 0x00300: 0x00450 + "\x00\x10\xd4\x00a\x00\x04Q" + // 0x00435 0x00308: 0x00451 + "\x00\x10\xcc\x00` \x04S" + // 0x00433 0x00301: 0x00453 + "\x00\x11X\x00a\x00\x04W" + // 0x00456 0x00308: 0x00457 + "\x00\x10\xe8\x00` \x04\\" + // 0x0043A 0x00301: 0x0045C + "\x00\x10\xe0\x00`\x00\x04]" + // 0x00438 0x00300: 0x0045D + "\x00\x11\f\x00`\xc0\x04^" + // 0x00443 0x00306: 0x0045E + "\x00\x11\xd0\x00a\xe0\x04v" + // 0x00474 0x0030F: 0x00476 + "\x00\x11\xd4\x00a\xe0\x04w" + // 0x00475 0x0030F: 0x00477 + "\x00\x10X\x00`\xc0\x04\xc1" + // 0x00416 0x00306: 0x004C1 + "\x00\x10\xd8\x00`\xc0\x04\xc2" + // 0x00436 0x00306: 0x004C2 + "\x00\x10@\x00`\xc0\x04\xd0" + // 0x00410 0x00306: 0x004D0 + "\x00\x10\xc0\x00`\xc0\x04\xd1" + // 0x00430 0x00306: 0x004D1 + "\x00\x10@\x00a\x00\x04\xd2" + // 0x00410 0x00308: 0x004D2 + "\x00\x10\xc0\x00a\x00\x04\xd3" + // 0x00430 0x00308: 0x004D3 + "\x00\x10T\x00`\xc0\x04\xd6" + // 0x00415 0x00306: 0x004D6 + "\x00\x10\xd4\x00`\xc0\x04\xd7" + // 0x00435 0x00306: 0x004D7 + "\x00\x13`\x00a\x00\x04\xda" + // 0x004D8 0x00308: 0x004DA + "\x00\x13d\x00a\x00\x04\xdb" + // 0x004D9 0x00308: 0x004DB + "\x00\x10X\x00a\x00\x04\xdc" + // 0x00416 0x00308: 0x004DC + "\x00\x10\xd8\x00a\x00\x04\xdd" + // 0x00436 0x00308: 0x004DD + "\x00\x10\\\x00a\x00\x04\xde" + // 0x00417 0x00308: 0x004DE + "\x00\x10\xdc\x00a\x00\x04\xdf" + // 0x00437 0x00308: 0x004DF + "\x00\x10`\x00`\x80\x04\xe2" + // 0x00418 0x00304: 0x004E2 + "\x00\x10\xe0\x00`\x80\x04\xe3" + // 0x00438 0x00304: 0x004E3 + "\x00\x10`\x00a\x00\x04\xe4" + // 0x00418 0x00308: 0x004E4 + "\x00\x10\xe0\x00a\x00\x04\xe5" + // 0x00438 0x00308: 0x004E5 + "\x00\x10x\x00a\x00\x04\xe6" + // 0x0041E 0x00308: 0x004E6 + "\x00\x10\xf8\x00a\x00\x04\xe7" + // 0x0043E 0x00308: 0x004E7 + "\x00\x13\xa0\x00a\x00\x04\xea" + // 0x004E8 0x00308: 0x004EA + "\x00\x13\xa4\x00a\x00\x04\xeb" + // 0x004E9 0x00308: 0x004EB + "\x00\x10\xb4\x00a\x00\x04\xec" + // 0x0042D 0x00308: 0x004EC + "\x00\x114\x00a\x00\x04\xed" + // 0x0044D 0x00308: 0x004ED + "\x00\x10\x8c\x00`\x80\x04\xee" + // 0x00423 0x00304: 0x004EE + "\x00\x11\f\x00`\x80\x04\xef" + // 0x00443 0x00304: 0x004EF + "\x00\x10\x8c\x00a\x00\x04\xf0" + // 0x00423 0x00308: 0x004F0 + "\x00\x11\f\x00a\x00\x04\xf1" + // 0x00443 0x00308: 0x004F1 + "\x00\x10\x8c\x00a`\x04\xf2" + // 0x00423 0x0030B: 0x004F2 + "\x00\x11\f\x00a`\x04\xf3" + // 0x00443 0x0030B: 0x004F3 + "\x00\x10\x9c\x00a\x00\x04\xf4" + // 0x00427 0x00308: 0x004F4 + "\x00\x11\x1c\x00a\x00\x04\xf5" + // 0x00447 0x00308: 0x004F5 + "\x00\x10\xac\x00a\x00\x04\xf8" + // 0x0042B 0x00308: 0x004F8 + "\x00\x11,\x00a\x00\x04\xf9" + // 0x0044B 0x00308: 0x004F9 + "\x00\x18\x9c\x00\xca`\x06\"" + // 0x00627 0x00653: 0x00622 + "\x00\x18\x9c\x00ʀ\x06#" + // 0x00627 0x00654: 0x00623 + "\x00\x19 \x00ʀ\x06$" + // 0x00648 0x00654: 0x00624 + "\x00\x18\x9c\x00ʠ\x06%" + // 0x00627 0x00655: 0x00625 + "\x00\x19(\x00ʀ\x06&" + // 0x0064A 0x00654: 0x00626 + "\x00\x1bT\x00ʀ\x06\xc0" + // 0x006D5 0x00654: 0x006C0 + "\x00\x1b\x04\x00ʀ\x06\xc2" + // 0x006C1 0x00654: 0x006C2 + "\x00\x1bH\x00ʀ\x06\xd3" + // 0x006D2 0x00654: 0x006D3 + "\x00$\xa0\x01'\x80\t)" + // 0x00928 0x0093C: 0x00929 + "\x00$\xc0\x01'\x80\t1" + // 0x00930 0x0093C: 0x00931 + "\x00$\xcc\x01'\x80\t4" + // 0x00933 0x0093C: 0x00934 + "\x00'\x1c\x017\xc0\t\xcb" + // 0x009C7 0x009BE: 0x009CB + "\x00'\x1c\x01:\xe0\t\xcc" + // 0x009C7 0x009D7: 0x009CC + "\x00-\x1c\x01j\xc0\vH" + // 0x00B47 0x00B56: 0x00B48 + "\x00-\x1c\x01g\xc0\vK" + // 0x00B47 0x00B3E: 0x00B4B + "\x00-\x1c\x01j\xe0\vL" + // 0x00B47 0x00B57: 0x00B4C + "\x00.H\x01z\xe0\v\x94" + // 0x00B92 0x00BD7: 0x00B94 + "\x00/\x18\x01w\xc0\v\xca" + // 0x00BC6 0x00BBE: 0x00BCA + "\x00/\x1c\x01w\xc0\v\xcb" + // 0x00BC7 0x00BBE: 0x00BCB + "\x00/\x18\x01z\xe0\v\xcc" + // 0x00BC6 0x00BD7: 0x00BCC + "\x001\x18\x01\x8a\xc0\fH" + // 0x00C46 0x00C56: 0x00C48 + "\x002\xfc\x01\x9a\xa0\f\xc0" + // 0x00CBF 0x00CD5: 0x00CC0 + "\x003\x18\x01\x9a\xa0\f\xc7" + // 0x00CC6 0x00CD5: 0x00CC7 + "\x003\x18\x01\x9a\xc0\f\xc8" + // 0x00CC6 0x00CD6: 0x00CC8 + "\x003\x18\x01\x98@\f\xca" + // 0x00CC6 0x00CC2: 0x00CCA + "\x003(\x01\x9a\xa0\f\xcb" + // 0x00CCA 0x00CD5: 0x00CCB + "\x005\x18\x01\xa7\xc0\rJ" + // 0x00D46 0x00D3E: 0x00D4A + "\x005\x1c\x01\xa7\xc0\rK" + // 0x00D47 0x00D3E: 0x00D4B + "\x005\x18\x01\xaa\xe0\rL" + // 0x00D46 0x00D57: 0x00D4C + "\x007d\x01\xb9@\r\xda" + // 0x00DD9 0x00DCA: 0x00DDA + "\x007d\x01\xb9\xe0\r\xdc" + // 0x00DD9 0x00DCF: 0x00DDC + "\x007p\x01\xb9@\r\xdd" + // 0x00DDC 0x00DCA: 0x00DDD + "\x007d\x01\xbb\xe0\r\xde" + // 0x00DD9 0x00DDF: 0x00DDE + "\x00@\x94\x02\x05\xc0\x10&" + // 0x01025 0x0102E: 0x01026 + "\x00l\x14\x03f\xa0\x1b\x06" + // 0x01B05 0x01B35: 0x01B06 + "\x00l\x1c\x03f\xa0\x1b\b" + // 0x01B07 0x01B35: 0x01B08 + "\x00l$\x03f\xa0\x1b\n" + // 0x01B09 0x01B35: 0x01B0A + "\x00l,\x03f\xa0\x1b\f" + // 0x01B0B 0x01B35: 0x01B0C + "\x00l4\x03f\xa0\x1b\x0e" + // 0x01B0D 0x01B35: 0x01B0E + "\x00lD\x03f\xa0\x1b\x12" + // 0x01B11 0x01B35: 0x01B12 + "\x00l\xe8\x03f\xa0\x1b;" + // 0x01B3A 0x01B35: 0x01B3B + "\x00l\xf0\x03f\xa0\x1b=" + // 0x01B3C 0x01B35: 0x01B3D + "\x00l\xf8\x03f\xa0\x1b@" + // 0x01B3E 0x01B35: 0x01B40 + "\x00l\xfc\x03f\xa0\x1bA" + // 0x01B3F 0x01B35: 0x01B41 + "\x00m\b\x03f\xa0\x1bC" + // 0x01B42 0x01B35: 0x01B43 + "\x00\x01\x04\x00d\xa0\x1e\x00" + // 0x00041 0x00325: 0x01E00 + "\x00\x01\x84\x00d\xa0\x1e\x01" + // 0x00061 0x00325: 0x01E01 + "\x00\x01\b\x00`\xe0\x1e\x02" + // 0x00042 0x00307: 0x01E02 + "\x00\x01\x88\x00`\xe0\x1e\x03" + // 0x00062 0x00307: 0x01E03 + "\x00\x01\b\x00d`\x1e\x04" + // 0x00042 0x00323: 0x01E04 + "\x00\x01\x88\x00d`\x1e\x05" + // 0x00062 0x00323: 0x01E05 + "\x00\x01\b\x00f \x1e\x06" + // 0x00042 0x00331: 0x01E06 + "\x00\x01\x88\x00f \x1e\a" + // 0x00062 0x00331: 0x01E07 + "\x00\x03\x1c\x00` \x1e\b" + // 0x000C7 0x00301: 0x01E08 + "\x00\x03\x9c\x00` \x1e\t" + // 0x000E7 0x00301: 0x01E09 + "\x00\x01\x10\x00`\xe0\x1e\n" + // 0x00044 0x00307: 0x01E0A + "\x00\x01\x90\x00`\xe0\x1e\v" + // 0x00064 0x00307: 0x01E0B + "\x00\x01\x10\x00d`\x1e\f" + // 0x00044 0x00323: 0x01E0C + "\x00\x01\x90\x00d`\x1e\r" + // 0x00064 0x00323: 0x01E0D + "\x00\x01\x10\x00f \x1e\x0e" + // 0x00044 0x00331: 0x01E0E + "\x00\x01\x90\x00f \x1e\x0f" + // 0x00064 0x00331: 0x01E0F + "\x00\x01\x10\x00d\xe0\x1e\x10" + // 0x00044 0x00327: 0x01E10 + "\x00\x01\x90\x00d\xe0\x1e\x11" + // 0x00064 0x00327: 0x01E11 + "\x00\x01\x10\x00e\xa0\x1e\x12" + // 0x00044 0x0032D: 0x01E12 + "\x00\x01\x90\x00e\xa0\x1e\x13" + // 0x00064 0x0032D: 0x01E13 + "\x00\x04H\x00`\x00\x1e\x14" + // 0x00112 0x00300: 0x01E14 + "\x00\x04L\x00`\x00\x1e\x15" + // 0x00113 0x00300: 0x01E15 + "\x00\x04H\x00` \x1e\x16" + // 0x00112 0x00301: 0x01E16 + "\x00\x04L\x00` \x1e\x17" + // 0x00113 0x00301: 0x01E17 + "\x00\x01\x14\x00e\xa0\x1e\x18" + // 0x00045 0x0032D: 0x01E18 + "\x00\x01\x94\x00e\xa0\x1e\x19" + // 0x00065 0x0032D: 0x01E19 + "\x00\x01\x14\x00f\x00\x1e\x1a" + // 0x00045 0x00330: 0x01E1A + "\x00\x01\x94\x00f\x00\x1e\x1b" + // 0x00065 0x00330: 0x01E1B + "\x00\b\xa0\x00`\xc0\x1e\x1c" + // 0x00228 0x00306: 0x01E1C + "\x00\b\xa4\x00`\xc0\x1e\x1d" + // 0x00229 0x00306: 0x01E1D + "\x00\x01\x18\x00`\xe0\x1e\x1e" + // 0x00046 0x00307: 0x01E1E + "\x00\x01\x98\x00`\xe0\x1e\x1f" + // 0x00066 0x00307: 0x01E1F + "\x00\x01\x1c\x00`\x80\x1e " + // 0x00047 0x00304: 0x01E20 + "\x00\x01\x9c\x00`\x80\x1e!" + // 0x00067 0x00304: 0x01E21 + "\x00\x01 \x00`\xe0\x1e\"" + // 0x00048 0x00307: 0x01E22 + "\x00\x01\xa0\x00`\xe0\x1e#" + // 0x00068 0x00307: 0x01E23 + "\x00\x01 \x00d`\x1e$" + // 0x00048 0x00323: 0x01E24 + "\x00\x01\xa0\x00d`\x1e%" + // 0x00068 0x00323: 0x01E25 + "\x00\x01 \x00a\x00\x1e&" + // 0x00048 0x00308: 0x01E26 + "\x00\x01\xa0\x00a\x00\x1e'" + // 0x00068 0x00308: 0x01E27 + "\x00\x01 \x00d\xe0\x1e(" + // 0x00048 0x00327: 0x01E28 + "\x00\x01\xa0\x00d\xe0\x1e)" + // 0x00068 0x00327: 0x01E29 + "\x00\x01 \x00e\xc0\x1e*" + // 0x00048 0x0032E: 0x01E2A + "\x00\x01\xa0\x00e\xc0\x1e+" + // 0x00068 0x0032E: 0x01E2B + "\x00\x01$\x00f\x00\x1e," + // 0x00049 0x00330: 0x01E2C + "\x00\x01\xa4\x00f\x00\x1e-" + // 0x00069 0x00330: 0x01E2D + "\x00\x03<\x00` \x1e." + // 0x000CF 0x00301: 0x01E2E + "\x00\x03\xbc\x00` \x1e/" + // 0x000EF 0x00301: 0x01E2F + "\x00\x01,\x00` \x1e0" + // 0x0004B 0x00301: 0x01E30 + "\x00\x01\xac\x00` \x1e1" + // 0x0006B 0x00301: 0x01E31 + "\x00\x01,\x00d`\x1e2" + // 0x0004B 0x00323: 0x01E32 + "\x00\x01\xac\x00d`\x1e3" + // 0x0006B 0x00323: 0x01E33 + "\x00\x01,\x00f \x1e4" + // 0x0004B 0x00331: 0x01E34 + "\x00\x01\xac\x00f \x1e5" + // 0x0006B 0x00331: 0x01E35 + "\x00\x010\x00d`\x1e6" + // 0x0004C 0x00323: 0x01E36 + "\x00\x01\xb0\x00d`\x1e7" + // 0x0006C 0x00323: 0x01E37 + "\x00x\xd8\x00`\x80\x1e8" + // 0x01E36 0x00304: 0x01E38 + "\x00x\xdc\x00`\x80\x1e9" + // 0x01E37 0x00304: 0x01E39 + "\x00\x010\x00f \x1e:" + // 0x0004C 0x00331: 0x01E3A + "\x00\x01\xb0\x00f \x1e;" + // 0x0006C 0x00331: 0x01E3B + "\x00\x010\x00e\xa0\x1e<" + // 0x0004C 0x0032D: 0x01E3C + "\x00\x01\xb0\x00e\xa0\x1e=" + // 0x0006C 0x0032D: 0x01E3D + "\x00\x014\x00` \x1e>" + // 0x0004D 0x00301: 0x01E3E + "\x00\x01\xb4\x00` \x1e?" + // 0x0006D 0x00301: 0x01E3F + "\x00\x014\x00`\xe0\x1e@" + // 0x0004D 0x00307: 0x01E40 + "\x00\x01\xb4\x00`\xe0\x1eA" + // 0x0006D 0x00307: 0x01E41 + "\x00\x014\x00d`\x1eB" + // 0x0004D 0x00323: 0x01E42 + "\x00\x01\xb4\x00d`\x1eC" + // 0x0006D 0x00323: 0x01E43 + "\x00\x018\x00`\xe0\x1eD" + // 0x0004E 0x00307: 0x01E44 + "\x00\x01\xb8\x00`\xe0\x1eE" + // 0x0006E 0x00307: 0x01E45 + "\x00\x018\x00d`\x1eF" + // 0x0004E 0x00323: 0x01E46 + "\x00\x01\xb8\x00d`\x1eG" + // 0x0006E 0x00323: 0x01E47 + "\x00\x018\x00f \x1eH" + // 0x0004E 0x00331: 0x01E48 + "\x00\x01\xb8\x00f \x1eI" + // 0x0006E 0x00331: 0x01E49 + "\x00\x018\x00e\xa0\x1eJ" + // 0x0004E 0x0032D: 0x01E4A + "\x00\x01\xb8\x00e\xa0\x1eK" + // 0x0006E 0x0032D: 0x01E4B + "\x00\x03T\x00` \x1eL" + // 0x000D5 0x00301: 0x01E4C + "\x00\x03\xd4\x00` \x1eM" + // 0x000F5 0x00301: 0x01E4D + "\x00\x03T\x00a\x00\x1eN" + // 0x000D5 0x00308: 0x01E4E + "\x00\x03\xd4\x00a\x00\x1eO" + // 0x000F5 0x00308: 0x01E4F + "\x00\x050\x00`\x00\x1eP" + // 0x0014C 0x00300: 0x01E50 + "\x00\x054\x00`\x00\x1eQ" + // 0x0014D 0x00300: 0x01E51 + "\x00\x050\x00` \x1eR" + // 0x0014C 0x00301: 0x01E52 + "\x00\x054\x00` \x1eS" + // 0x0014D 0x00301: 0x01E53 + "\x00\x01@\x00` \x1eT" + // 0x00050 0x00301: 0x01E54 + "\x00\x01\xc0\x00` \x1eU" + // 0x00070 0x00301: 0x01E55 + "\x00\x01@\x00`\xe0\x1eV" + // 0x00050 0x00307: 0x01E56 + "\x00\x01\xc0\x00`\xe0\x1eW" + // 0x00070 0x00307: 0x01E57 + "\x00\x01H\x00`\xe0\x1eX" + // 0x00052 0x00307: 0x01E58 + "\x00\x01\xc8\x00`\xe0\x1eY" + // 0x00072 0x00307: 0x01E59 + "\x00\x01H\x00d`\x1eZ" + // 0x00052 0x00323: 0x01E5A + "\x00\x01\xc8\x00d`\x1e[" + // 0x00072 0x00323: 0x01E5B + "\x00yh\x00`\x80\x1e\\" + // 0x01E5A 0x00304: 0x01E5C + "\x00yl\x00`\x80\x1e]" + // 0x01E5B 0x00304: 0x01E5D + "\x00\x01H\x00f \x1e^" + // 0x00052 0x00331: 0x01E5E + "\x00\x01\xc8\x00f \x1e_" + // 0x00072 0x00331: 0x01E5F + "\x00\x01L\x00`\xe0\x1e`" + // 0x00053 0x00307: 0x01E60 + "\x00\x01\xcc\x00`\xe0\x1ea" + // 0x00073 0x00307: 0x01E61 + "\x00\x01L\x00d`\x1eb" + // 0x00053 0x00323: 0x01E62 + "\x00\x01\xcc\x00d`\x1ec" + // 0x00073 0x00323: 0x01E63 + "\x00\x05h\x00`\xe0\x1ed" + // 0x0015A 0x00307: 0x01E64 + "\x00\x05l\x00`\xe0\x1ee" + // 0x0015B 0x00307: 0x01E65 + "\x00\x05\x80\x00`\xe0\x1ef" + // 0x00160 0x00307: 0x01E66 + "\x00\x05\x84\x00`\xe0\x1eg" + // 0x00161 0x00307: 0x01E67 + "\x00y\x88\x00`\xe0\x1eh" + // 0x01E62 0x00307: 0x01E68 + "\x00y\x8c\x00`\xe0\x1ei" + // 0x01E63 0x00307: 0x01E69 + "\x00\x01P\x00`\xe0\x1ej" + // 0x00054 0x00307: 0x01E6A + "\x00\x01\xd0\x00`\xe0\x1ek" + // 0x00074 0x00307: 0x01E6B + "\x00\x01P\x00d`\x1el" + // 0x00054 0x00323: 0x01E6C + "\x00\x01\xd0\x00d`\x1em" + // 0x00074 0x00323: 0x01E6D + "\x00\x01P\x00f \x1en" + // 0x00054 0x00331: 0x01E6E + "\x00\x01\xd0\x00f \x1eo" + // 0x00074 0x00331: 0x01E6F + "\x00\x01P\x00e\xa0\x1ep" + // 0x00054 0x0032D: 0x01E70 + "\x00\x01\xd0\x00e\xa0\x1eq" + // 0x00074 0x0032D: 0x01E71 + "\x00\x01T\x00d\x80\x1er" + // 0x00055 0x00324: 0x01E72 + "\x00\x01\xd4\x00d\x80\x1es" + // 0x00075 0x00324: 0x01E73 + "\x00\x01T\x00f\x00\x1et" + // 0x00055 0x00330: 0x01E74 + "\x00\x01\xd4\x00f\x00\x1eu" + // 0x00075 0x00330: 0x01E75 + "\x00\x01T\x00e\xa0\x1ev" + // 0x00055 0x0032D: 0x01E76 + "\x00\x01\xd4\x00e\xa0\x1ew" + // 0x00075 0x0032D: 0x01E77 + "\x00\x05\xa0\x00` \x1ex" + // 0x00168 0x00301: 0x01E78 + "\x00\x05\xa4\x00` \x1ey" + // 0x00169 0x00301: 0x01E79 + "\x00\x05\xa8\x00a\x00\x1ez" + // 0x0016A 0x00308: 0x01E7A + "\x00\x05\xac\x00a\x00\x1e{" + // 0x0016B 0x00308: 0x01E7B + "\x00\x01X\x00``\x1e|" + // 0x00056 0x00303: 0x01E7C + "\x00\x01\xd8\x00``\x1e}" + // 0x00076 0x00303: 0x01E7D + "\x00\x01X\x00d`\x1e~" + // 0x00056 0x00323: 0x01E7E + "\x00\x01\xd8\x00d`\x1e\x7f" + // 0x00076 0x00323: 0x01E7F + "\x00\x01\\\x00`\x00\x1e\x80" + // 0x00057 0x00300: 0x01E80 + "\x00\x01\xdc\x00`\x00\x1e\x81" + // 0x00077 0x00300: 0x01E81 + "\x00\x01\\\x00` \x1e\x82" + // 0x00057 0x00301: 0x01E82 + "\x00\x01\xdc\x00` \x1e\x83" + // 0x00077 0x00301: 0x01E83 + "\x00\x01\\\x00a\x00\x1e\x84" + // 0x00057 0x00308: 0x01E84 + "\x00\x01\xdc\x00a\x00\x1e\x85" + // 0x00077 0x00308: 0x01E85 + "\x00\x01\\\x00`\xe0\x1e\x86" + // 0x00057 0x00307: 0x01E86 + "\x00\x01\xdc\x00`\xe0\x1e\x87" + // 0x00077 0x00307: 0x01E87 + "\x00\x01\\\x00d`\x1e\x88" + // 0x00057 0x00323: 0x01E88 + "\x00\x01\xdc\x00d`\x1e\x89" + // 0x00077 0x00323: 0x01E89 + "\x00\x01`\x00`\xe0\x1e\x8a" + // 0x00058 0x00307: 0x01E8A + "\x00\x01\xe0\x00`\xe0\x1e\x8b" + // 0x00078 0x00307: 0x01E8B + "\x00\x01`\x00a\x00\x1e\x8c" + // 0x00058 0x00308: 0x01E8C + "\x00\x01\xe0\x00a\x00\x1e\x8d" + // 0x00078 0x00308: 0x01E8D + "\x00\x01d\x00`\xe0\x1e\x8e" + // 0x00059 0x00307: 0x01E8E + "\x00\x01\xe4\x00`\xe0\x1e\x8f" + // 0x00079 0x00307: 0x01E8F + "\x00\x01h\x00`@\x1e\x90" + // 0x0005A 0x00302: 0x01E90 + "\x00\x01\xe8\x00`@\x1e\x91" + // 0x0007A 0x00302: 0x01E91 + "\x00\x01h\x00d`\x1e\x92" + // 0x0005A 0x00323: 0x01E92 + "\x00\x01\xe8\x00d`\x1e\x93" + // 0x0007A 0x00323: 0x01E93 + "\x00\x01h\x00f \x1e\x94" + // 0x0005A 0x00331: 0x01E94 + "\x00\x01\xe8\x00f \x1e\x95" + // 0x0007A 0x00331: 0x01E95 + "\x00\x01\xa0\x00f \x1e\x96" + // 0x00068 0x00331: 0x01E96 + "\x00\x01\xd0\x00a\x00\x1e\x97" + // 0x00074 0x00308: 0x01E97 + "\x00\x01\xdc\x00a@\x1e\x98" + // 0x00077 0x0030A: 0x01E98 + "\x00\x01\xe4\x00a@\x1e\x99" + // 0x00079 0x0030A: 0x01E99 + "\x00\x05\xfc\x00`\xe0\x1e\x9b" + // 0x0017F 0x00307: 0x01E9B + "\x00\x01\x04\x00d`\x1e\xa0" + // 0x00041 0x00323: 0x01EA0 + "\x00\x01\x84\x00d`\x1e\xa1" + // 0x00061 0x00323: 0x01EA1 + "\x00\x01\x04\x00a \x1e\xa2" + // 0x00041 0x00309: 0x01EA2 + "\x00\x01\x84\x00a \x1e\xa3" + // 0x00061 0x00309: 0x01EA3 + "\x00\x03\b\x00` \x1e\xa4" + // 0x000C2 0x00301: 0x01EA4 + "\x00\x03\x88\x00` \x1e\xa5" + // 0x000E2 0x00301: 0x01EA5 + "\x00\x03\b\x00`\x00\x1e\xa6" + // 0x000C2 0x00300: 0x01EA6 + "\x00\x03\x88\x00`\x00\x1e\xa7" + // 0x000E2 0x00300: 0x01EA7 + "\x00\x03\b\x00a \x1e\xa8" + // 0x000C2 0x00309: 0x01EA8 + "\x00\x03\x88\x00a \x1e\xa9" + // 0x000E2 0x00309: 0x01EA9 + "\x00\x03\b\x00``\x1e\xaa" + // 0x000C2 0x00303: 0x01EAA + "\x00\x03\x88\x00``\x1e\xab" + // 0x000E2 0x00303: 0x01EAB + "\x00z\x80\x00`@\x1e\xac" + // 0x01EA0 0x00302: 0x01EAC + "\x00z\x84\x00`@\x1e\xad" + // 0x01EA1 0x00302: 0x01EAD + "\x00\x04\b\x00` \x1e\xae" + // 0x00102 0x00301: 0x01EAE + "\x00\x04\f\x00` \x1e\xaf" + // 0x00103 0x00301: 0x01EAF + "\x00\x04\b\x00`\x00\x1e\xb0" + // 0x00102 0x00300: 0x01EB0 + "\x00\x04\f\x00`\x00\x1e\xb1" + // 0x00103 0x00300: 0x01EB1 + "\x00\x04\b\x00a \x1e\xb2" + // 0x00102 0x00309: 0x01EB2 + "\x00\x04\f\x00a \x1e\xb3" + // 0x00103 0x00309: 0x01EB3 + "\x00\x04\b\x00``\x1e\xb4" + // 0x00102 0x00303: 0x01EB4 + "\x00\x04\f\x00``\x1e\xb5" + // 0x00103 0x00303: 0x01EB5 + "\x00z\x80\x00`\xc0\x1e\xb6" + // 0x01EA0 0x00306: 0x01EB6 + "\x00z\x84\x00`\xc0\x1e\xb7" + // 0x01EA1 0x00306: 0x01EB7 + "\x00\x01\x14\x00d`\x1e\xb8" + // 0x00045 0x00323: 0x01EB8 + "\x00\x01\x94\x00d`\x1e\xb9" + // 0x00065 0x00323: 0x01EB9 + "\x00\x01\x14\x00a \x1e\xba" + // 0x00045 0x00309: 0x01EBA + "\x00\x01\x94\x00a \x1e\xbb" + // 0x00065 0x00309: 0x01EBB + "\x00\x01\x14\x00``\x1e\xbc" + // 0x00045 0x00303: 0x01EBC + "\x00\x01\x94\x00``\x1e\xbd" + // 0x00065 0x00303: 0x01EBD + "\x00\x03(\x00` \x1e\xbe" + // 0x000CA 0x00301: 0x01EBE + "\x00\x03\xa8\x00` \x1e\xbf" + // 0x000EA 0x00301: 0x01EBF + "\x00\x03(\x00`\x00\x1e\xc0" + // 0x000CA 0x00300: 0x01EC0 + "\x00\x03\xa8\x00`\x00\x1e\xc1" + // 0x000EA 0x00300: 0x01EC1 + "\x00\x03(\x00a \x1e\xc2" + // 0x000CA 0x00309: 0x01EC2 + "\x00\x03\xa8\x00a \x1e\xc3" + // 0x000EA 0x00309: 0x01EC3 + "\x00\x03(\x00``\x1e\xc4" + // 0x000CA 0x00303: 0x01EC4 + "\x00\x03\xa8\x00``\x1e\xc5" + // 0x000EA 0x00303: 0x01EC5 + "\x00z\xe0\x00`@\x1e\xc6" + // 0x01EB8 0x00302: 0x01EC6 + "\x00z\xe4\x00`@\x1e\xc7" + // 0x01EB9 0x00302: 0x01EC7 + "\x00\x01$\x00a \x1e\xc8" + // 0x00049 0x00309: 0x01EC8 + "\x00\x01\xa4\x00a \x1e\xc9" + // 0x00069 0x00309: 0x01EC9 + "\x00\x01$\x00d`\x1e\xca" + // 0x00049 0x00323: 0x01ECA + "\x00\x01\xa4\x00d`\x1e\xcb" + // 0x00069 0x00323: 0x01ECB + "\x00\x01<\x00d`\x1e\xcc" + // 0x0004F 0x00323: 0x01ECC + "\x00\x01\xbc\x00d`\x1e\xcd" + // 0x0006F 0x00323: 0x01ECD + "\x00\x01<\x00a \x1e\xce" + // 0x0004F 0x00309: 0x01ECE + "\x00\x01\xbc\x00a \x1e\xcf" + // 0x0006F 0x00309: 0x01ECF + "\x00\x03P\x00` \x1e\xd0" + // 0x000D4 0x00301: 0x01ED0 + "\x00\x03\xd0\x00` \x1e\xd1" + // 0x000F4 0x00301: 0x01ED1 + "\x00\x03P\x00`\x00\x1e\xd2" + // 0x000D4 0x00300: 0x01ED2 + "\x00\x03\xd0\x00`\x00\x1e\xd3" + // 0x000F4 0x00300: 0x01ED3 + "\x00\x03P\x00a \x1e\xd4" + // 0x000D4 0x00309: 0x01ED4 + "\x00\x03\xd0\x00a \x1e\xd5" + // 0x000F4 0x00309: 0x01ED5 + "\x00\x03P\x00``\x1e\xd6" + // 0x000D4 0x00303: 0x01ED6 + "\x00\x03\xd0\x00``\x1e\xd7" + // 0x000F4 0x00303: 0x01ED7 + "\x00{0\x00`@\x1e\xd8" + // 0x01ECC 0x00302: 0x01ED8 + "\x00{4\x00`@\x1e\xd9" + // 0x01ECD 0x00302: 0x01ED9 + "\x00\x06\x80\x00` \x1e\xda" + // 0x001A0 0x00301: 0x01EDA + "\x00\x06\x84\x00` \x1e\xdb" + // 0x001A1 0x00301: 0x01EDB + "\x00\x06\x80\x00`\x00\x1e\xdc" + // 0x001A0 0x00300: 0x01EDC + "\x00\x06\x84\x00`\x00\x1e\xdd" + // 0x001A1 0x00300: 0x01EDD + "\x00\x06\x80\x00a \x1e\xde" + // 0x001A0 0x00309: 0x01EDE + "\x00\x06\x84\x00a \x1e\xdf" + // 0x001A1 0x00309: 0x01EDF + "\x00\x06\x80\x00``\x1e\xe0" + // 0x001A0 0x00303: 0x01EE0 + "\x00\x06\x84\x00``\x1e\xe1" + // 0x001A1 0x00303: 0x01EE1 + "\x00\x06\x80\x00d`\x1e\xe2" + // 0x001A0 0x00323: 0x01EE2 + "\x00\x06\x84\x00d`\x1e\xe3" + // 0x001A1 0x00323: 0x01EE3 + "\x00\x01T\x00d`\x1e\xe4" + // 0x00055 0x00323: 0x01EE4 + "\x00\x01\xd4\x00d`\x1e\xe5" + // 0x00075 0x00323: 0x01EE5 + "\x00\x01T\x00a \x1e\xe6" + // 0x00055 0x00309: 0x01EE6 + "\x00\x01\xd4\x00a \x1e\xe7" + // 0x00075 0x00309: 0x01EE7 + "\x00\x06\xbc\x00` \x1e\xe8" + // 0x001AF 0x00301: 0x01EE8 + "\x00\x06\xc0\x00` \x1e\xe9" + // 0x001B0 0x00301: 0x01EE9 + "\x00\x06\xbc\x00`\x00\x1e\xea" + // 0x001AF 0x00300: 0x01EEA + "\x00\x06\xc0\x00`\x00\x1e\xeb" + // 0x001B0 0x00300: 0x01EEB + "\x00\x06\xbc\x00a \x1e\xec" + // 0x001AF 0x00309: 0x01EEC + "\x00\x06\xc0\x00a \x1e\xed" + // 0x001B0 0x00309: 0x01EED + "\x00\x06\xbc\x00``\x1e\xee" + // 0x001AF 0x00303: 0x01EEE + "\x00\x06\xc0\x00``\x1e\xef" + // 0x001B0 0x00303: 0x01EEF + "\x00\x06\xbc\x00d`\x1e\xf0" + // 0x001AF 0x00323: 0x01EF0 + "\x00\x06\xc0\x00d`\x1e\xf1" + // 0x001B0 0x00323: 0x01EF1 + "\x00\x01d\x00`\x00\x1e\xf2" + // 0x00059 0x00300: 0x01EF2 + "\x00\x01\xe4\x00`\x00\x1e\xf3" + // 0x00079 0x00300: 0x01EF3 + "\x00\x01d\x00d`\x1e\xf4" + // 0x00059 0x00323: 0x01EF4 + "\x00\x01\xe4\x00d`\x1e\xf5" + // 0x00079 0x00323: 0x01EF5 + "\x00\x01d\x00a \x1e\xf6" + // 0x00059 0x00309: 0x01EF6 + "\x00\x01\xe4\x00a \x1e\xf7" + // 0x00079 0x00309: 0x01EF7 + "\x00\x01d\x00``\x1e\xf8" + // 0x00059 0x00303: 0x01EF8 + "\x00\x01\xe4\x00``\x1e\xf9" + // 0x00079 0x00303: 0x01EF9 + "\x00\x0e\xc4\x00b`\x1f\x00" + // 0x003B1 0x00313: 0x01F00 + "\x00\x0e\xc4\x00b\x80\x1f\x01" + // 0x003B1 0x00314: 0x01F01 + "\x00|\x00\x00`\x00\x1f\x02" + // 0x01F00 0x00300: 0x01F02 + "\x00|\x04\x00`\x00\x1f\x03" + // 0x01F01 0x00300: 0x01F03 + "\x00|\x00\x00` \x1f\x04" + // 0x01F00 0x00301: 0x01F04 + "\x00|\x04\x00` \x1f\x05" + // 0x01F01 0x00301: 0x01F05 + "\x00|\x00\x00h@\x1f\x06" + // 0x01F00 0x00342: 0x01F06 + "\x00|\x04\x00h@\x1f\a" + // 0x01F01 0x00342: 0x01F07 + "\x00\x0eD\x00b`\x1f\b" + // 0x00391 0x00313: 0x01F08 + "\x00\x0eD\x00b\x80\x1f\t" + // 0x00391 0x00314: 0x01F09 + "\x00| \x00`\x00\x1f\n" + // 0x01F08 0x00300: 0x01F0A + "\x00|$\x00`\x00\x1f\v" + // 0x01F09 0x00300: 0x01F0B + "\x00| \x00` \x1f\f" + // 0x01F08 0x00301: 0x01F0C + "\x00|$\x00` \x1f\r" + // 0x01F09 0x00301: 0x01F0D + "\x00| \x00h@\x1f\x0e" + // 0x01F08 0x00342: 0x01F0E + "\x00|$\x00h@\x1f\x0f" + // 0x01F09 0x00342: 0x01F0F + "\x00\x0e\xd4\x00b`\x1f\x10" + // 0x003B5 0x00313: 0x01F10 + "\x00\x0e\xd4\x00b\x80\x1f\x11" + // 0x003B5 0x00314: 0x01F11 + "\x00|@\x00`\x00\x1f\x12" + // 0x01F10 0x00300: 0x01F12 + "\x00|D\x00`\x00\x1f\x13" + // 0x01F11 0x00300: 0x01F13 + "\x00|@\x00` \x1f\x14" + // 0x01F10 0x00301: 0x01F14 + "\x00|D\x00` \x1f\x15" + // 0x01F11 0x00301: 0x01F15 + "\x00\x0eT\x00b`\x1f\x18" + // 0x00395 0x00313: 0x01F18 + "\x00\x0eT\x00b\x80\x1f\x19" + // 0x00395 0x00314: 0x01F19 + "\x00|`\x00`\x00\x1f\x1a" + // 0x01F18 0x00300: 0x01F1A + "\x00|d\x00`\x00\x1f\x1b" + // 0x01F19 0x00300: 0x01F1B + "\x00|`\x00` \x1f\x1c" + // 0x01F18 0x00301: 0x01F1C + "\x00|d\x00` \x1f\x1d" + // 0x01F19 0x00301: 0x01F1D + "\x00\x0e\xdc\x00b`\x1f " + // 0x003B7 0x00313: 0x01F20 + "\x00\x0e\xdc\x00b\x80\x1f!" + // 0x003B7 0x00314: 0x01F21 + "\x00|\x80\x00`\x00\x1f\"" + // 0x01F20 0x00300: 0x01F22 + "\x00|\x84\x00`\x00\x1f#" + // 0x01F21 0x00300: 0x01F23 + "\x00|\x80\x00` \x1f$" + // 0x01F20 0x00301: 0x01F24 + "\x00|\x84\x00` \x1f%" + // 0x01F21 0x00301: 0x01F25 + "\x00|\x80\x00h@\x1f&" + // 0x01F20 0x00342: 0x01F26 + "\x00|\x84\x00h@\x1f'" + // 0x01F21 0x00342: 0x01F27 + "\x00\x0e\\\x00b`\x1f(" + // 0x00397 0x00313: 0x01F28 + "\x00\x0e\\\x00b\x80\x1f)" + // 0x00397 0x00314: 0x01F29 + "\x00|\xa0\x00`\x00\x1f*" + // 0x01F28 0x00300: 0x01F2A + "\x00|\xa4\x00`\x00\x1f+" + // 0x01F29 0x00300: 0x01F2B + "\x00|\xa0\x00` \x1f," + // 0x01F28 0x00301: 0x01F2C + "\x00|\xa4\x00` \x1f-" + // 0x01F29 0x00301: 0x01F2D + "\x00|\xa0\x00h@\x1f." + // 0x01F28 0x00342: 0x01F2E + "\x00|\xa4\x00h@\x1f/" + // 0x01F29 0x00342: 0x01F2F + "\x00\x0e\xe4\x00b`\x1f0" + // 0x003B9 0x00313: 0x01F30 + "\x00\x0e\xe4\x00b\x80\x1f1" + // 0x003B9 0x00314: 0x01F31 + "\x00|\xc0\x00`\x00\x1f2" + // 0x01F30 0x00300: 0x01F32 + "\x00|\xc4\x00`\x00\x1f3" + // 0x01F31 0x00300: 0x01F33 + "\x00|\xc0\x00` \x1f4" + // 0x01F30 0x00301: 0x01F34 + "\x00|\xc4\x00` \x1f5" + // 0x01F31 0x00301: 0x01F35 + "\x00|\xc0\x00h@\x1f6" + // 0x01F30 0x00342: 0x01F36 + "\x00|\xc4\x00h@\x1f7" + // 0x01F31 0x00342: 0x01F37 + "\x00\x0ed\x00b`\x1f8" + // 0x00399 0x00313: 0x01F38 + "\x00\x0ed\x00b\x80\x1f9" + // 0x00399 0x00314: 0x01F39 + "\x00|\xe0\x00`\x00\x1f:" + // 0x01F38 0x00300: 0x01F3A + "\x00|\xe4\x00`\x00\x1f;" + // 0x01F39 0x00300: 0x01F3B + "\x00|\xe0\x00` \x1f<" + // 0x01F38 0x00301: 0x01F3C + "\x00|\xe4\x00` \x1f=" + // 0x01F39 0x00301: 0x01F3D + "\x00|\xe0\x00h@\x1f>" + // 0x01F38 0x00342: 0x01F3E + "\x00|\xe4\x00h@\x1f?" + // 0x01F39 0x00342: 0x01F3F + "\x00\x0e\xfc\x00b`\x1f@" + // 0x003BF 0x00313: 0x01F40 + "\x00\x0e\xfc\x00b\x80\x1fA" + // 0x003BF 0x00314: 0x01F41 + "\x00}\x00\x00`\x00\x1fB" + // 0x01F40 0x00300: 0x01F42 + "\x00}\x04\x00`\x00\x1fC" + // 0x01F41 0x00300: 0x01F43 + "\x00}\x00\x00` \x1fD" + // 0x01F40 0x00301: 0x01F44 + "\x00}\x04\x00` \x1fE" + // 0x01F41 0x00301: 0x01F45 + "\x00\x0e|\x00b`\x1fH" + // 0x0039F 0x00313: 0x01F48 + "\x00\x0e|\x00b\x80\x1fI" + // 0x0039F 0x00314: 0x01F49 + "\x00} \x00`\x00\x1fJ" + // 0x01F48 0x00300: 0x01F4A + "\x00}$\x00`\x00\x1fK" + // 0x01F49 0x00300: 0x01F4B + "\x00} \x00` \x1fL" + // 0x01F48 0x00301: 0x01F4C + "\x00}$\x00` \x1fM" + // 0x01F49 0x00301: 0x01F4D + "\x00\x0f\x14\x00b`\x1fP" + // 0x003C5 0x00313: 0x01F50 + "\x00\x0f\x14\x00b\x80\x1fQ" + // 0x003C5 0x00314: 0x01F51 + "\x00}@\x00`\x00\x1fR" + // 0x01F50 0x00300: 0x01F52 + "\x00}D\x00`\x00\x1fS" + // 0x01F51 0x00300: 0x01F53 + "\x00}@\x00` \x1fT" + // 0x01F50 0x00301: 0x01F54 + "\x00}D\x00` \x1fU" + // 0x01F51 0x00301: 0x01F55 + "\x00}@\x00h@\x1fV" + // 0x01F50 0x00342: 0x01F56 + "\x00}D\x00h@\x1fW" + // 0x01F51 0x00342: 0x01F57 + "\x00\x0e\x94\x00b\x80\x1fY" + // 0x003A5 0x00314: 0x01F59 + "\x00}d\x00`\x00\x1f[" + // 0x01F59 0x00300: 0x01F5B + "\x00}d\x00` \x1f]" + // 0x01F59 0x00301: 0x01F5D + "\x00}d\x00h@\x1f_" + // 0x01F59 0x00342: 0x01F5F + "\x00\x0f$\x00b`\x1f`" + // 0x003C9 0x00313: 0x01F60 + "\x00\x0f$\x00b\x80\x1fa" + // 0x003C9 0x00314: 0x01F61 + "\x00}\x80\x00`\x00\x1fb" + // 0x01F60 0x00300: 0x01F62 + "\x00}\x84\x00`\x00\x1fc" + // 0x01F61 0x00300: 0x01F63 + "\x00}\x80\x00` \x1fd" + // 0x01F60 0x00301: 0x01F64 + "\x00}\x84\x00` \x1fe" + // 0x01F61 0x00301: 0x01F65 + "\x00}\x80\x00h@\x1ff" + // 0x01F60 0x00342: 0x01F66 + "\x00}\x84\x00h@\x1fg" + // 0x01F61 0x00342: 0x01F67 + "\x00\x0e\xa4\x00b`\x1fh" + // 0x003A9 0x00313: 0x01F68 + "\x00\x0e\xa4\x00b\x80\x1fi" + // 0x003A9 0x00314: 0x01F69 + "\x00}\xa0\x00`\x00\x1fj" + // 0x01F68 0x00300: 0x01F6A + "\x00}\xa4\x00`\x00\x1fk" + // 0x01F69 0x00300: 0x01F6B + "\x00}\xa0\x00` \x1fl" + // 0x01F68 0x00301: 0x01F6C + "\x00}\xa4\x00` \x1fm" + // 0x01F69 0x00301: 0x01F6D + "\x00}\xa0\x00h@\x1fn" + // 0x01F68 0x00342: 0x01F6E + "\x00}\xa4\x00h@\x1fo" + // 0x01F69 0x00342: 0x01F6F + "\x00\x0e\xc4\x00`\x00\x1fp" + // 0x003B1 0x00300: 0x01F70 + "\x00\x0e\xd4\x00`\x00\x1fr" + // 0x003B5 0x00300: 0x01F72 + "\x00\x0e\xdc\x00`\x00\x1ft" + // 0x003B7 0x00300: 0x01F74 + "\x00\x0e\xe4\x00`\x00\x1fv" + // 0x003B9 0x00300: 0x01F76 + "\x00\x0e\xfc\x00`\x00\x1fx" + // 0x003BF 0x00300: 0x01F78 + "\x00\x0f\x14\x00`\x00\x1fz" + // 0x003C5 0x00300: 0x01F7A + "\x00\x0f$\x00`\x00\x1f|" + // 0x003C9 0x00300: 0x01F7C + "\x00|\x00\x00h\xa0\x1f\x80" + // 0x01F00 0x00345: 0x01F80 + "\x00|\x04\x00h\xa0\x1f\x81" + // 0x01F01 0x00345: 0x01F81 + "\x00|\b\x00h\xa0\x1f\x82" + // 0x01F02 0x00345: 0x01F82 + "\x00|\f\x00h\xa0\x1f\x83" + // 0x01F03 0x00345: 0x01F83 + "\x00|\x10\x00h\xa0\x1f\x84" + // 0x01F04 0x00345: 0x01F84 + "\x00|\x14\x00h\xa0\x1f\x85" + // 0x01F05 0x00345: 0x01F85 + "\x00|\x18\x00h\xa0\x1f\x86" + // 0x01F06 0x00345: 0x01F86 + "\x00|\x1c\x00h\xa0\x1f\x87" + // 0x01F07 0x00345: 0x01F87 + "\x00| \x00h\xa0\x1f\x88" + // 0x01F08 0x00345: 0x01F88 + "\x00|$\x00h\xa0\x1f\x89" + // 0x01F09 0x00345: 0x01F89 + "\x00|(\x00h\xa0\x1f\x8a" + // 0x01F0A 0x00345: 0x01F8A + "\x00|,\x00h\xa0\x1f\x8b" + // 0x01F0B 0x00345: 0x01F8B + "\x00|0\x00h\xa0\x1f\x8c" + // 0x01F0C 0x00345: 0x01F8C + "\x00|4\x00h\xa0\x1f\x8d" + // 0x01F0D 0x00345: 0x01F8D + "\x00|8\x00h\xa0\x1f\x8e" + // 0x01F0E 0x00345: 0x01F8E + "\x00|<\x00h\xa0\x1f\x8f" + // 0x01F0F 0x00345: 0x01F8F + "\x00|\x80\x00h\xa0\x1f\x90" + // 0x01F20 0x00345: 0x01F90 + "\x00|\x84\x00h\xa0\x1f\x91" + // 0x01F21 0x00345: 0x01F91 + "\x00|\x88\x00h\xa0\x1f\x92" + // 0x01F22 0x00345: 0x01F92 + "\x00|\x8c\x00h\xa0\x1f\x93" + // 0x01F23 0x00345: 0x01F93 + "\x00|\x90\x00h\xa0\x1f\x94" + // 0x01F24 0x00345: 0x01F94 + "\x00|\x94\x00h\xa0\x1f\x95" + // 0x01F25 0x00345: 0x01F95 + "\x00|\x98\x00h\xa0\x1f\x96" + // 0x01F26 0x00345: 0x01F96 + "\x00|\x9c\x00h\xa0\x1f\x97" + // 0x01F27 0x00345: 0x01F97 + "\x00|\xa0\x00h\xa0\x1f\x98" + // 0x01F28 0x00345: 0x01F98 + "\x00|\xa4\x00h\xa0\x1f\x99" + // 0x01F29 0x00345: 0x01F99 + "\x00|\xa8\x00h\xa0\x1f\x9a" + // 0x01F2A 0x00345: 0x01F9A + "\x00|\xac\x00h\xa0\x1f\x9b" + // 0x01F2B 0x00345: 0x01F9B + "\x00|\xb0\x00h\xa0\x1f\x9c" + // 0x01F2C 0x00345: 0x01F9C + "\x00|\xb4\x00h\xa0\x1f\x9d" + // 0x01F2D 0x00345: 0x01F9D + "\x00|\xb8\x00h\xa0\x1f\x9e" + // 0x01F2E 0x00345: 0x01F9E + "\x00|\xbc\x00h\xa0\x1f\x9f" + // 0x01F2F 0x00345: 0x01F9F + "\x00}\x80\x00h\xa0\x1f\xa0" + // 0x01F60 0x00345: 0x01FA0 + "\x00}\x84\x00h\xa0\x1f\xa1" + // 0x01F61 0x00345: 0x01FA1 + "\x00}\x88\x00h\xa0\x1f\xa2" + // 0x01F62 0x00345: 0x01FA2 + "\x00}\x8c\x00h\xa0\x1f\xa3" + // 0x01F63 0x00345: 0x01FA3 + "\x00}\x90\x00h\xa0\x1f\xa4" + // 0x01F64 0x00345: 0x01FA4 + "\x00}\x94\x00h\xa0\x1f\xa5" + // 0x01F65 0x00345: 0x01FA5 + "\x00}\x98\x00h\xa0\x1f\xa6" + // 0x01F66 0x00345: 0x01FA6 + "\x00}\x9c\x00h\xa0\x1f\xa7" + // 0x01F67 0x00345: 0x01FA7 + "\x00}\xa0\x00h\xa0\x1f\xa8" + // 0x01F68 0x00345: 0x01FA8 + "\x00}\xa4\x00h\xa0\x1f\xa9" + // 0x01F69 0x00345: 0x01FA9 + "\x00}\xa8\x00h\xa0\x1f\xaa" + // 0x01F6A 0x00345: 0x01FAA + "\x00}\xac\x00h\xa0\x1f\xab" + // 0x01F6B 0x00345: 0x01FAB + "\x00}\xb0\x00h\xa0\x1f\xac" + // 0x01F6C 0x00345: 0x01FAC + "\x00}\xb4\x00h\xa0\x1f\xad" + // 0x01F6D 0x00345: 0x01FAD + "\x00}\xb8\x00h\xa0\x1f\xae" + // 0x01F6E 0x00345: 0x01FAE + "\x00}\xbc\x00h\xa0\x1f\xaf" + // 0x01F6F 0x00345: 0x01FAF + "\x00\x0e\xc4\x00`\xc0\x1f\xb0" + // 0x003B1 0x00306: 0x01FB0 + "\x00\x0e\xc4\x00`\x80\x1f\xb1" + // 0x003B1 0x00304: 0x01FB1 + "\x00}\xc0\x00h\xa0\x1f\xb2" + // 0x01F70 0x00345: 0x01FB2 + "\x00\x0e\xc4\x00h\xa0\x1f\xb3" + // 0x003B1 0x00345: 0x01FB3 + "\x00\x0e\xb0\x00h\xa0\x1f\xb4" + // 0x003AC 0x00345: 0x01FB4 + "\x00\x0e\xc4\x00h@\x1f\xb6" + // 0x003B1 0x00342: 0x01FB6 + "\x00~\xd8\x00h\xa0\x1f\xb7" + // 0x01FB6 0x00345: 0x01FB7 + "\x00\x0eD\x00`\xc0\x1f\xb8" + // 0x00391 0x00306: 0x01FB8 + "\x00\x0eD\x00`\x80\x1f\xb9" + // 0x00391 0x00304: 0x01FB9 + "\x00\x0eD\x00`\x00\x1f\xba" + // 0x00391 0x00300: 0x01FBA + "\x00\x0eD\x00h\xa0\x1f\xbc" + // 0x00391 0x00345: 0x01FBC + "\x00\x02\xa0\x00h@\x1f\xc1" + // 0x000A8 0x00342: 0x01FC1 + "\x00}\xd0\x00h\xa0\x1f\xc2" + // 0x01F74 0x00345: 0x01FC2 + "\x00\x0e\xdc\x00h\xa0\x1f\xc3" + // 0x003B7 0x00345: 0x01FC3 + "\x00\x0e\xb8\x00h\xa0\x1f\xc4" + // 0x003AE 0x00345: 0x01FC4 + "\x00\x0e\xdc\x00h@\x1f\xc6" + // 0x003B7 0x00342: 0x01FC6 + "\x00\x7f\x18\x00h\xa0\x1f\xc7" + // 0x01FC6 0x00345: 0x01FC7 + "\x00\x0eT\x00`\x00\x1f\xc8" + // 0x00395 0x00300: 0x01FC8 + "\x00\x0e\\\x00`\x00\x1f\xca" + // 0x00397 0x00300: 0x01FCA + "\x00\x0e\\\x00h\xa0\x1f\xcc" + // 0x00397 0x00345: 0x01FCC + "\x00~\xfc\x00`\x00\x1f\xcd" + // 0x01FBF 0x00300: 0x01FCD + "\x00~\xfc\x00` \x1f\xce" + // 0x01FBF 0x00301: 0x01FCE + "\x00~\xfc\x00h@\x1f\xcf" + // 0x01FBF 0x00342: 0x01FCF + "\x00\x0e\xe4\x00`\xc0\x1f\xd0" + // 0x003B9 0x00306: 0x01FD0 + "\x00\x0e\xe4\x00`\x80\x1f\xd1" + // 0x003B9 0x00304: 0x01FD1 + "\x00\x0f(\x00`\x00\x1f\xd2" + // 0x003CA 0x00300: 0x01FD2 + "\x00\x0e\xe4\x00h@\x1f\xd6" + // 0x003B9 0x00342: 0x01FD6 + "\x00\x0f(\x00h@\x1f\xd7" + // 0x003CA 0x00342: 0x01FD7 + "\x00\x0ed\x00`\xc0\x1f\xd8" + // 0x00399 0x00306: 0x01FD8 + "\x00\x0ed\x00`\x80\x1f\xd9" + // 0x00399 0x00304: 0x01FD9 + "\x00\x0ed\x00`\x00\x1f\xda" + // 0x00399 0x00300: 0x01FDA + "\x00\x7f\xf8\x00`\x00\x1f\xdd" + // 0x01FFE 0x00300: 0x01FDD + "\x00\x7f\xf8\x00` \x1f\xde" + // 0x01FFE 0x00301: 0x01FDE + "\x00\x7f\xf8\x00h@\x1f\xdf" + // 0x01FFE 0x00342: 0x01FDF + "\x00\x0f\x14\x00`\xc0\x1f\xe0" + // 0x003C5 0x00306: 0x01FE0 + "\x00\x0f\x14\x00`\x80\x1f\xe1" + // 0x003C5 0x00304: 0x01FE1 + "\x00\x0f,\x00`\x00\x1f\xe2" + // 0x003CB 0x00300: 0x01FE2 + "\x00\x0f\x04\x00b`\x1f\xe4" + // 0x003C1 0x00313: 0x01FE4 + "\x00\x0f\x04\x00b\x80\x1f\xe5" + // 0x003C1 0x00314: 0x01FE5 + "\x00\x0f\x14\x00h@\x1f\xe6" + // 0x003C5 0x00342: 0x01FE6 + "\x00\x0f,\x00h@\x1f\xe7" + // 0x003CB 0x00342: 0x01FE7 + "\x00\x0e\x94\x00`\xc0\x1f\xe8" + // 0x003A5 0x00306: 0x01FE8 + "\x00\x0e\x94\x00`\x80\x1f\xe9" + // 0x003A5 0x00304: 0x01FE9 + "\x00\x0e\x94\x00`\x00\x1f\xea" + // 0x003A5 0x00300: 0x01FEA + "\x00\x0e\x84\x00b\x80\x1f\xec" + // 0x003A1 0x00314: 0x01FEC + "\x00\x02\xa0\x00`\x00\x1f\xed" + // 0x000A8 0x00300: 0x01FED + "\x00}\xf0\x00h\xa0\x1f\xf2" + // 0x01F7C 0x00345: 0x01FF2 + "\x00\x0f$\x00h\xa0\x1f\xf3" + // 0x003C9 0x00345: 0x01FF3 + "\x00\x0f8\x00h\xa0\x1f\xf4" + // 0x003CE 0x00345: 0x01FF4 + "\x00\x0f$\x00h@\x1f\xf6" + // 0x003C9 0x00342: 0x01FF6 + "\x00\x7f\xd8\x00h\xa0\x1f\xf7" + // 0x01FF6 0x00345: 0x01FF7 + "\x00\x0e|\x00`\x00\x1f\xf8" + // 0x0039F 0x00300: 0x01FF8 + "\x00\x0e\xa4\x00`\x00\x1f\xfa" + // 0x003A9 0x00300: 0x01FFA + "\x00\x0e\xa4\x00h\xa0\x1f\xfc" + // 0x003A9 0x00345: 0x01FFC + "\x00\x86@\x00g\x00!\x9a" + // 0x02190 0x00338: 0x0219A + "\x00\x86H\x00g\x00!\x9b" + // 0x02192 0x00338: 0x0219B + "\x00\x86P\x00g\x00!\xae" + // 0x02194 0x00338: 0x021AE + "\x00\x87@\x00g\x00!\xcd" + // 0x021D0 0x00338: 0x021CD + "\x00\x87P\x00g\x00!\xce" + // 0x021D4 0x00338: 0x021CE + "\x00\x87H\x00g\x00!\xcf" + // 0x021D2 0x00338: 0x021CF + "\x00\x88\f\x00g\x00\"\x04" + // 0x02203 0x00338: 0x02204 + "\x00\x88 \x00g\x00\"\t" + // 0x02208 0x00338: 0x02209 + "\x00\x88,\x00g\x00\"\f" + // 0x0220B 0x00338: 0x0220C + "\x00\x88\x8c\x00g\x00\"$" + // 0x02223 0x00338: 0x02224 + "\x00\x88\x94\x00g\x00\"&" + // 0x02225 0x00338: 0x02226 + "\x00\x88\xf0\x00g\x00\"A" + // 0x0223C 0x00338: 0x02241 + "\x00\x89\f\x00g\x00\"D" + // 0x02243 0x00338: 0x02244 + "\x00\x89\x14\x00g\x00\"G" + // 0x02245 0x00338: 0x02247 + "\x00\x89 \x00g\x00\"I" + // 0x02248 0x00338: 0x02249 + "\x00\x00\xf4\x00g\x00\"`" + // 0x0003D 0x00338: 0x02260 + "\x00\x89\x84\x00g\x00\"b" + // 0x02261 0x00338: 0x02262 + "\x00\x894\x00g\x00\"m" + // 0x0224D 0x00338: 0x0226D + "\x00\x00\xf0\x00g\x00\"n" + // 0x0003C 0x00338: 0x0226E + "\x00\x00\xf8\x00g\x00\"o" + // 0x0003E 0x00338: 0x0226F + "\x00\x89\x90\x00g\x00\"p" + // 0x02264 0x00338: 0x02270 + "\x00\x89\x94\x00g\x00\"q" + // 0x02265 0x00338: 0x02271 + "\x00\x89\xc8\x00g\x00\"t" + // 0x02272 0x00338: 0x02274 + "\x00\x89\xcc\x00g\x00\"u" + // 0x02273 0x00338: 0x02275 + "\x00\x89\xd8\x00g\x00\"x" + // 0x02276 0x00338: 0x02278 + "\x00\x89\xdc\x00g\x00\"y" + // 0x02277 0x00338: 0x02279 + "\x00\x89\xe8\x00g\x00\"\x80" + // 0x0227A 0x00338: 0x02280 + "\x00\x89\xec\x00g\x00\"\x81" + // 0x0227B 0x00338: 0x02281 + "\x00\x8a\b\x00g\x00\"\x84" + // 0x02282 0x00338: 0x02284 + "\x00\x8a\f\x00g\x00\"\x85" + // 0x02283 0x00338: 0x02285 + "\x00\x8a\x18\x00g\x00\"\x88" + // 0x02286 0x00338: 0x02288 + "\x00\x8a\x1c\x00g\x00\"\x89" + // 0x02287 0x00338: 0x02289 + "\x00\x8a\x88\x00g\x00\"\xac" + // 0x022A2 0x00338: 0x022AC + "\x00\x8a\xa0\x00g\x00\"\xad" + // 0x022A8 0x00338: 0x022AD + "\x00\x8a\xa4\x00g\x00\"\xae" + // 0x022A9 0x00338: 0x022AE + "\x00\x8a\xac\x00g\x00\"\xaf" + // 0x022AB 0x00338: 0x022AF + "\x00\x89\xf0\x00g\x00\"\xe0" + // 0x0227C 0x00338: 0x022E0 + "\x00\x89\xf4\x00g\x00\"\xe1" + // 0x0227D 0x00338: 0x022E1 + "\x00\x8aD\x00g\x00\"\xe2" + // 0x02291 0x00338: 0x022E2 + "\x00\x8aH\x00g\x00\"\xe3" + // 0x02292 0x00338: 0x022E3 + "\x00\x8a\xc8\x00g\x00\"\xea" + // 0x022B2 0x00338: 0x022EA + "\x00\x8a\xcc\x00g\x00\"\xeb" + // 0x022B3 0x00338: 0x022EB + "\x00\x8a\xd0\x00g\x00\"\xec" + // 0x022B4 0x00338: 0x022EC + "\x00\x8a\xd4\x00g\x00\"\xed" + // 0x022B5 0x00338: 0x022ED + "\x00\xc1,\x06\x13 0L" + // 0x0304B 0x03099: 0x0304C + "\x00\xc14\x06\x13 0N" + // 0x0304D 0x03099: 0x0304E + "\x00\xc1<\x06\x13 0P" + // 0x0304F 0x03099: 0x03050 + "\x00\xc1D\x06\x13 0R" + // 0x03051 0x03099: 0x03052 + "\x00\xc1L\x06\x13 0T" + // 0x03053 0x03099: 0x03054 + "\x00\xc1T\x06\x13 0V" + // 0x03055 0x03099: 0x03056 + "\x00\xc1\\\x06\x13 0X" + // 0x03057 0x03099: 0x03058 + "\x00\xc1d\x06\x13 0Z" + // 0x03059 0x03099: 0x0305A + "\x00\xc1l\x06\x13 0\\" + // 0x0305B 0x03099: 0x0305C + "\x00\xc1t\x06\x13 0^" + // 0x0305D 0x03099: 0x0305E + "\x00\xc1|\x06\x13 0`" + // 0x0305F 0x03099: 0x03060 + "\x00\xc1\x84\x06\x13 0b" + // 0x03061 0x03099: 0x03062 + "\x00\xc1\x90\x06\x13 0e" + // 0x03064 0x03099: 0x03065 + "\x00\xc1\x98\x06\x13 0g" + // 0x03066 0x03099: 0x03067 + "\x00\xc1\xa0\x06\x13 0i" + // 0x03068 0x03099: 0x03069 + "\x00\xc1\xbc\x06\x13 0p" + // 0x0306F 0x03099: 0x03070 + "\x00\xc1\xbc\x06\x13@0q" + // 0x0306F 0x0309A: 0x03071 + "\x00\xc1\xc8\x06\x13 0s" + // 0x03072 0x03099: 0x03073 + "\x00\xc1\xc8\x06\x13@0t" + // 0x03072 0x0309A: 0x03074 + "\x00\xc1\xd4\x06\x13 0v" + // 0x03075 0x03099: 0x03076 + "\x00\xc1\xd4\x06\x13@0w" + // 0x03075 0x0309A: 0x03077 + "\x00\xc1\xe0\x06\x13 0y" + // 0x03078 0x03099: 0x03079 + "\x00\xc1\xe0\x06\x13@0z" + // 0x03078 0x0309A: 0x0307A + "\x00\xc1\xec\x06\x13 0|" + // 0x0307B 0x03099: 0x0307C + "\x00\xc1\xec\x06\x13@0}" + // 0x0307B 0x0309A: 0x0307D + "\x00\xc1\x18\x06\x13 0\x94" + // 0x03046 0x03099: 0x03094 + "\x00\xc2t\x06\x13 0\x9e" + // 0x0309D 0x03099: 0x0309E + "\x00¬\x06\x13 0\xac" + // 0x030AB 0x03099: 0x030AC + "\x00´\x06\x13 0\xae" + // 0x030AD 0x03099: 0x030AE + "\x00¼\x06\x13 0\xb0" + // 0x030AF 0x03099: 0x030B0 + "\x00\xc2\xc4\x06\x13 0\xb2" + // 0x030B1 0x03099: 0x030B2 + "\x00\xc2\xcc\x06\x13 0\xb4" + // 0x030B3 0x03099: 0x030B4 + "\x00\xc2\xd4\x06\x13 0\xb6" + // 0x030B5 0x03099: 0x030B6 + "\x00\xc2\xdc\x06\x13 0\xb8" + // 0x030B7 0x03099: 0x030B8 + "\x00\xc2\xe4\x06\x13 0\xba" + // 0x030B9 0x03099: 0x030BA + "\x00\xc2\xec\x06\x13 0\xbc" + // 0x030BB 0x03099: 0x030BC + "\x00\xc2\xf4\x06\x13 0\xbe" + // 0x030BD 0x03099: 0x030BE + "\x00\xc2\xfc\x06\x13 0\xc0" + // 0x030BF 0x03099: 0x030C0 + "\x00\xc3\x04\x06\x13 0\xc2" + // 0x030C1 0x03099: 0x030C2 + "\x00\xc3\x10\x06\x13 0\xc5" + // 0x030C4 0x03099: 0x030C5 + "\x00\xc3\x18\x06\x13 0\xc7" + // 0x030C6 0x03099: 0x030C7 + "\x00\xc3 \x06\x13 0\xc9" + // 0x030C8 0x03099: 0x030C9 + "\x00\xc3<\x06\x13 0\xd0" + // 0x030CF 0x03099: 0x030D0 + "\x00\xc3<\x06\x13@0\xd1" + // 0x030CF 0x0309A: 0x030D1 + "\x00\xc3H\x06\x13 0\xd3" + // 0x030D2 0x03099: 0x030D3 + "\x00\xc3H\x06\x13@0\xd4" + // 0x030D2 0x0309A: 0x030D4 + "\x00\xc3T\x06\x13 0\xd6" + // 0x030D5 0x03099: 0x030D6 + "\x00\xc3T\x06\x13@0\xd7" + // 0x030D5 0x0309A: 0x030D7 + "\x00\xc3`\x06\x13 0\xd9" + // 0x030D8 0x03099: 0x030D9 + "\x00\xc3`\x06\x13@0\xda" + // 0x030D8 0x0309A: 0x030DA + "\x00\xc3l\x06\x13 0\xdc" + // 0x030DB 0x03099: 0x030DC + "\x00\xc3l\x06\x13@0\xdd" + // 0x030DB 0x0309A: 0x030DD + "\x00\u0098\x06\x13 0\xf4" + // 0x030A6 0x03099: 0x030F4 + "\x00ü\x06\x13 0\xf7" + // 0x030EF 0x03099: 0x030F7 + "\x00\xc3\xc0\x06\x13 0\xf8" + // 0x030F0 0x03099: 0x030F8 + "\x00\xc3\xc4\x06\x13 0\xf9" + // 0x030F1 0x03099: 0x030F9 + "\x00\xc3\xc8\x06\x13 0\xfa" + // 0x030F2 0x03099: 0x030FA + "\x00\xc3\xf4\x06\x13 0\xfe" + // 0x030FD 0x03099: 0x030FE + "\x04Bd\"\x17A\x10\x9a" + // 0x11099 0x110BA: 0x1109A + "\x04Bl\"\x17A\x10\x9c" + // 0x1109B 0x110BA: 0x1109C + "\x04B\x94\"\x17A\x10\xab" + // 0x110A5 0x110BA: 0x110AB + "\x04D\xc4\"$\xe1\x11." + // 0x11131 0x11127: 0x1112E + "\x04D\xc8\"$\xe1\x11/" + // 0x11132 0x11127: 0x1112F + "\x04M\x1c\"g\xc1\x13K" + // 0x11347 0x1133E: 0x1134B + "\x04M\x1c\"j\xe1\x13L" + // 0x11347 0x11357: 0x1134C + "\x04R\xe4\"\x97A\x14\xbb" + // 0x114B9 0x114BA: 0x114BB + "\x04R\xe4\"\x96\x01\x14\xbc" + // 0x114B9 0x114B0: 0x114BC + "\x04R\xe4\"\x97\xa1\x14\xbe" + // 0x114B9 0x114BD: 0x114BE + "\x04V\xe0\"\xb5\xe1\x15\xba" + // 0x115B8 0x115AF: 0x115BA + "\x04V\xe4\"\xb5\xe1\x15\xbb" + // 0x115B9 0x115AF: 0x115BB + "\x04d\xd4#&\x01\x198" + // 0x11935 0x11930: 0x11938 "" // Total size of tables: 56KB (57068 bytes) diff --git a/vendor/golang.org/x/text/unicode/norm/tables17.0.0.go b/vendor/golang.org/x/text/unicode/norm/tables17.0.0.go index dfd555f..c323189 100644 --- a/vendor/golang.org/x/text/unicode/norm/tables17.0.0.go +++ b/vendor/golang.org/x/text/unicode/norm/tables17.0.0.go @@ -7135,970 +7135,970 @@ var nfkcSparseValues = [980]valueRange{ } // recompMap: 7688 bytes (entries only) -var recompMap map[uint32]rune +var recompMap map[uint64]rune var recompMapOnce sync.Once const recompMapPacked = "" + - "\x00A\x03\x00\x00\x00\x00\xc0" + // 0x00410300: 0x000000C0 - "\x00A\x03\x01\x00\x00\x00\xc1" + // 0x00410301: 0x000000C1 - "\x00A\x03\x02\x00\x00\x00\xc2" + // 0x00410302: 0x000000C2 - "\x00A\x03\x03\x00\x00\x00\xc3" + // 0x00410303: 0x000000C3 - "\x00A\x03\b\x00\x00\x00\xc4" + // 0x00410308: 0x000000C4 - "\x00A\x03\n\x00\x00\x00\xc5" + // 0x0041030A: 0x000000C5 - "\x00C\x03'\x00\x00\x00\xc7" + // 0x00430327: 0x000000C7 - "\x00E\x03\x00\x00\x00\x00\xc8" + // 0x00450300: 0x000000C8 - "\x00E\x03\x01\x00\x00\x00\xc9" + // 0x00450301: 0x000000C9 - "\x00E\x03\x02\x00\x00\x00\xca" + // 0x00450302: 0x000000CA - "\x00E\x03\b\x00\x00\x00\xcb" + // 0x00450308: 0x000000CB - "\x00I\x03\x00\x00\x00\x00\xcc" + // 0x00490300: 0x000000CC - "\x00I\x03\x01\x00\x00\x00\xcd" + // 0x00490301: 0x000000CD - "\x00I\x03\x02\x00\x00\x00\xce" + // 0x00490302: 0x000000CE - "\x00I\x03\b\x00\x00\x00\xcf" + // 0x00490308: 0x000000CF - "\x00N\x03\x03\x00\x00\x00\xd1" + // 0x004E0303: 0x000000D1 - "\x00O\x03\x00\x00\x00\x00\xd2" + // 0x004F0300: 0x000000D2 - "\x00O\x03\x01\x00\x00\x00\xd3" + // 0x004F0301: 0x000000D3 - "\x00O\x03\x02\x00\x00\x00\xd4" + // 0x004F0302: 0x000000D4 - "\x00O\x03\x03\x00\x00\x00\xd5" + // 0x004F0303: 0x000000D5 - "\x00O\x03\b\x00\x00\x00\xd6" + // 0x004F0308: 0x000000D6 - "\x00U\x03\x00\x00\x00\x00\xd9" + // 0x00550300: 0x000000D9 - "\x00U\x03\x01\x00\x00\x00\xda" + // 0x00550301: 0x000000DA - "\x00U\x03\x02\x00\x00\x00\xdb" + // 0x00550302: 0x000000DB - "\x00U\x03\b\x00\x00\x00\xdc" + // 0x00550308: 0x000000DC - "\x00Y\x03\x01\x00\x00\x00\xdd" + // 0x00590301: 0x000000DD - "\x00a\x03\x00\x00\x00\x00\xe0" + // 0x00610300: 0x000000E0 - "\x00a\x03\x01\x00\x00\x00\xe1" + // 0x00610301: 0x000000E1 - "\x00a\x03\x02\x00\x00\x00\xe2" + // 0x00610302: 0x000000E2 - "\x00a\x03\x03\x00\x00\x00\xe3" + // 0x00610303: 0x000000E3 - "\x00a\x03\b\x00\x00\x00\xe4" + // 0x00610308: 0x000000E4 - "\x00a\x03\n\x00\x00\x00\xe5" + // 0x0061030A: 0x000000E5 - "\x00c\x03'\x00\x00\x00\xe7" + // 0x00630327: 0x000000E7 - "\x00e\x03\x00\x00\x00\x00\xe8" + // 0x00650300: 0x000000E8 - "\x00e\x03\x01\x00\x00\x00\xe9" + // 0x00650301: 0x000000E9 - "\x00e\x03\x02\x00\x00\x00\xea" + // 0x00650302: 0x000000EA - "\x00e\x03\b\x00\x00\x00\xeb" + // 0x00650308: 0x000000EB - "\x00i\x03\x00\x00\x00\x00\xec" + // 0x00690300: 0x000000EC - "\x00i\x03\x01\x00\x00\x00\xed" + // 0x00690301: 0x000000ED - "\x00i\x03\x02\x00\x00\x00\xee" + // 0x00690302: 0x000000EE - "\x00i\x03\b\x00\x00\x00\xef" + // 0x00690308: 0x000000EF - "\x00n\x03\x03\x00\x00\x00\xf1" + // 0x006E0303: 0x000000F1 - "\x00o\x03\x00\x00\x00\x00\xf2" + // 0x006F0300: 0x000000F2 - "\x00o\x03\x01\x00\x00\x00\xf3" + // 0x006F0301: 0x000000F3 - "\x00o\x03\x02\x00\x00\x00\xf4" + // 0x006F0302: 0x000000F4 - "\x00o\x03\x03\x00\x00\x00\xf5" + // 0x006F0303: 0x000000F5 - "\x00o\x03\b\x00\x00\x00\xf6" + // 0x006F0308: 0x000000F6 - "\x00u\x03\x00\x00\x00\x00\xf9" + // 0x00750300: 0x000000F9 - "\x00u\x03\x01\x00\x00\x00\xfa" + // 0x00750301: 0x000000FA - "\x00u\x03\x02\x00\x00\x00\xfb" + // 0x00750302: 0x000000FB - "\x00u\x03\b\x00\x00\x00\xfc" + // 0x00750308: 0x000000FC - "\x00y\x03\x01\x00\x00\x00\xfd" + // 0x00790301: 0x000000FD - "\x00y\x03\b\x00\x00\x00\xff" + // 0x00790308: 0x000000FF - "\x00A\x03\x04\x00\x00\x01\x00" + // 0x00410304: 0x00000100 - "\x00a\x03\x04\x00\x00\x01\x01" + // 0x00610304: 0x00000101 - "\x00A\x03\x06\x00\x00\x01\x02" + // 0x00410306: 0x00000102 - "\x00a\x03\x06\x00\x00\x01\x03" + // 0x00610306: 0x00000103 - "\x00A\x03(\x00\x00\x01\x04" + // 0x00410328: 0x00000104 - "\x00a\x03(\x00\x00\x01\x05" + // 0x00610328: 0x00000105 - "\x00C\x03\x01\x00\x00\x01\x06" + // 0x00430301: 0x00000106 - "\x00c\x03\x01\x00\x00\x01\a" + // 0x00630301: 0x00000107 - "\x00C\x03\x02\x00\x00\x01\b" + // 0x00430302: 0x00000108 - "\x00c\x03\x02\x00\x00\x01\t" + // 0x00630302: 0x00000109 - "\x00C\x03\a\x00\x00\x01\n" + // 0x00430307: 0x0000010A - "\x00c\x03\a\x00\x00\x01\v" + // 0x00630307: 0x0000010B - "\x00C\x03\f\x00\x00\x01\f" + // 0x0043030C: 0x0000010C - "\x00c\x03\f\x00\x00\x01\r" + // 0x0063030C: 0x0000010D - "\x00D\x03\f\x00\x00\x01\x0e" + // 0x0044030C: 0x0000010E - "\x00d\x03\f\x00\x00\x01\x0f" + // 0x0064030C: 0x0000010F - "\x00E\x03\x04\x00\x00\x01\x12" + // 0x00450304: 0x00000112 - "\x00e\x03\x04\x00\x00\x01\x13" + // 0x00650304: 0x00000113 - "\x00E\x03\x06\x00\x00\x01\x14" + // 0x00450306: 0x00000114 - "\x00e\x03\x06\x00\x00\x01\x15" + // 0x00650306: 0x00000115 - "\x00E\x03\a\x00\x00\x01\x16" + // 0x00450307: 0x00000116 - "\x00e\x03\a\x00\x00\x01\x17" + // 0x00650307: 0x00000117 - "\x00E\x03(\x00\x00\x01\x18" + // 0x00450328: 0x00000118 - "\x00e\x03(\x00\x00\x01\x19" + // 0x00650328: 0x00000119 - "\x00E\x03\f\x00\x00\x01\x1a" + // 0x0045030C: 0x0000011A - "\x00e\x03\f\x00\x00\x01\x1b" + // 0x0065030C: 0x0000011B - "\x00G\x03\x02\x00\x00\x01\x1c" + // 0x00470302: 0x0000011C - "\x00g\x03\x02\x00\x00\x01\x1d" + // 0x00670302: 0x0000011D - "\x00G\x03\x06\x00\x00\x01\x1e" + // 0x00470306: 0x0000011E - "\x00g\x03\x06\x00\x00\x01\x1f" + // 0x00670306: 0x0000011F - "\x00G\x03\a\x00\x00\x01 " + // 0x00470307: 0x00000120 - "\x00g\x03\a\x00\x00\x01!" + // 0x00670307: 0x00000121 - "\x00G\x03'\x00\x00\x01\"" + // 0x00470327: 0x00000122 - "\x00g\x03'\x00\x00\x01#" + // 0x00670327: 0x00000123 - "\x00H\x03\x02\x00\x00\x01$" + // 0x00480302: 0x00000124 - "\x00h\x03\x02\x00\x00\x01%" + // 0x00680302: 0x00000125 - "\x00I\x03\x03\x00\x00\x01(" + // 0x00490303: 0x00000128 - "\x00i\x03\x03\x00\x00\x01)" + // 0x00690303: 0x00000129 - "\x00I\x03\x04\x00\x00\x01*" + // 0x00490304: 0x0000012A - "\x00i\x03\x04\x00\x00\x01+" + // 0x00690304: 0x0000012B - "\x00I\x03\x06\x00\x00\x01," + // 0x00490306: 0x0000012C - "\x00i\x03\x06\x00\x00\x01-" + // 0x00690306: 0x0000012D - "\x00I\x03(\x00\x00\x01." + // 0x00490328: 0x0000012E - "\x00i\x03(\x00\x00\x01/" + // 0x00690328: 0x0000012F - "\x00I\x03\a\x00\x00\x010" + // 0x00490307: 0x00000130 - "\x00J\x03\x02\x00\x00\x014" + // 0x004A0302: 0x00000134 - "\x00j\x03\x02\x00\x00\x015" + // 0x006A0302: 0x00000135 - "\x00K\x03'\x00\x00\x016" + // 0x004B0327: 0x00000136 - "\x00k\x03'\x00\x00\x017" + // 0x006B0327: 0x00000137 - "\x00L\x03\x01\x00\x00\x019" + // 0x004C0301: 0x00000139 - "\x00l\x03\x01\x00\x00\x01:" + // 0x006C0301: 0x0000013A - "\x00L\x03'\x00\x00\x01;" + // 0x004C0327: 0x0000013B - "\x00l\x03'\x00\x00\x01<" + // 0x006C0327: 0x0000013C - "\x00L\x03\f\x00\x00\x01=" + // 0x004C030C: 0x0000013D - "\x00l\x03\f\x00\x00\x01>" + // 0x006C030C: 0x0000013E - "\x00N\x03\x01\x00\x00\x01C" + // 0x004E0301: 0x00000143 - "\x00n\x03\x01\x00\x00\x01D" + // 0x006E0301: 0x00000144 - "\x00N\x03'\x00\x00\x01E" + // 0x004E0327: 0x00000145 - "\x00n\x03'\x00\x00\x01F" + // 0x006E0327: 0x00000146 - "\x00N\x03\f\x00\x00\x01G" + // 0x004E030C: 0x00000147 - "\x00n\x03\f\x00\x00\x01H" + // 0x006E030C: 0x00000148 - "\x00O\x03\x04\x00\x00\x01L" + // 0x004F0304: 0x0000014C - "\x00o\x03\x04\x00\x00\x01M" + // 0x006F0304: 0x0000014D - "\x00O\x03\x06\x00\x00\x01N" + // 0x004F0306: 0x0000014E - "\x00o\x03\x06\x00\x00\x01O" + // 0x006F0306: 0x0000014F - "\x00O\x03\v\x00\x00\x01P" + // 0x004F030B: 0x00000150 - "\x00o\x03\v\x00\x00\x01Q" + // 0x006F030B: 0x00000151 - "\x00R\x03\x01\x00\x00\x01T" + // 0x00520301: 0x00000154 - "\x00r\x03\x01\x00\x00\x01U" + // 0x00720301: 0x00000155 - "\x00R\x03'\x00\x00\x01V" + // 0x00520327: 0x00000156 - "\x00r\x03'\x00\x00\x01W" + // 0x00720327: 0x00000157 - "\x00R\x03\f\x00\x00\x01X" + // 0x0052030C: 0x00000158 - "\x00r\x03\f\x00\x00\x01Y" + // 0x0072030C: 0x00000159 - "\x00S\x03\x01\x00\x00\x01Z" + // 0x00530301: 0x0000015A - "\x00s\x03\x01\x00\x00\x01[" + // 0x00730301: 0x0000015B - "\x00S\x03\x02\x00\x00\x01\\" + // 0x00530302: 0x0000015C - "\x00s\x03\x02\x00\x00\x01]" + // 0x00730302: 0x0000015D - "\x00S\x03'\x00\x00\x01^" + // 0x00530327: 0x0000015E - "\x00s\x03'\x00\x00\x01_" + // 0x00730327: 0x0000015F - "\x00S\x03\f\x00\x00\x01`" + // 0x0053030C: 0x00000160 - "\x00s\x03\f\x00\x00\x01a" + // 0x0073030C: 0x00000161 - "\x00T\x03'\x00\x00\x01b" + // 0x00540327: 0x00000162 - "\x00t\x03'\x00\x00\x01c" + // 0x00740327: 0x00000163 - "\x00T\x03\f\x00\x00\x01d" + // 0x0054030C: 0x00000164 - "\x00t\x03\f\x00\x00\x01e" + // 0x0074030C: 0x00000165 - "\x00U\x03\x03\x00\x00\x01h" + // 0x00550303: 0x00000168 - "\x00u\x03\x03\x00\x00\x01i" + // 0x00750303: 0x00000169 - "\x00U\x03\x04\x00\x00\x01j" + // 0x00550304: 0x0000016A - "\x00u\x03\x04\x00\x00\x01k" + // 0x00750304: 0x0000016B - "\x00U\x03\x06\x00\x00\x01l" + // 0x00550306: 0x0000016C - "\x00u\x03\x06\x00\x00\x01m" + // 0x00750306: 0x0000016D - "\x00U\x03\n\x00\x00\x01n" + // 0x0055030A: 0x0000016E - "\x00u\x03\n\x00\x00\x01o" + // 0x0075030A: 0x0000016F - "\x00U\x03\v\x00\x00\x01p" + // 0x0055030B: 0x00000170 - "\x00u\x03\v\x00\x00\x01q" + // 0x0075030B: 0x00000171 - "\x00U\x03(\x00\x00\x01r" + // 0x00550328: 0x00000172 - "\x00u\x03(\x00\x00\x01s" + // 0x00750328: 0x00000173 - "\x00W\x03\x02\x00\x00\x01t" + // 0x00570302: 0x00000174 - "\x00w\x03\x02\x00\x00\x01u" + // 0x00770302: 0x00000175 - "\x00Y\x03\x02\x00\x00\x01v" + // 0x00590302: 0x00000176 - "\x00y\x03\x02\x00\x00\x01w" + // 0x00790302: 0x00000177 - "\x00Y\x03\b\x00\x00\x01x" + // 0x00590308: 0x00000178 - "\x00Z\x03\x01\x00\x00\x01y" + // 0x005A0301: 0x00000179 - "\x00z\x03\x01\x00\x00\x01z" + // 0x007A0301: 0x0000017A - "\x00Z\x03\a\x00\x00\x01{" + // 0x005A0307: 0x0000017B - "\x00z\x03\a\x00\x00\x01|" + // 0x007A0307: 0x0000017C - "\x00Z\x03\f\x00\x00\x01}" + // 0x005A030C: 0x0000017D - "\x00z\x03\f\x00\x00\x01~" + // 0x007A030C: 0x0000017E - "\x00O\x03\x1b\x00\x00\x01\xa0" + // 0x004F031B: 0x000001A0 - "\x00o\x03\x1b\x00\x00\x01\xa1" + // 0x006F031B: 0x000001A1 - "\x00U\x03\x1b\x00\x00\x01\xaf" + // 0x0055031B: 0x000001AF - "\x00u\x03\x1b\x00\x00\x01\xb0" + // 0x0075031B: 0x000001B0 - "\x00A\x03\f\x00\x00\x01\xcd" + // 0x0041030C: 0x000001CD - "\x00a\x03\f\x00\x00\x01\xce" + // 0x0061030C: 0x000001CE - "\x00I\x03\f\x00\x00\x01\xcf" + // 0x0049030C: 0x000001CF - "\x00i\x03\f\x00\x00\x01\xd0" + // 0x0069030C: 0x000001D0 - "\x00O\x03\f\x00\x00\x01\xd1" + // 0x004F030C: 0x000001D1 - "\x00o\x03\f\x00\x00\x01\xd2" + // 0x006F030C: 0x000001D2 - "\x00U\x03\f\x00\x00\x01\xd3" + // 0x0055030C: 0x000001D3 - "\x00u\x03\f\x00\x00\x01\xd4" + // 0x0075030C: 0x000001D4 - "\x00\xdc\x03\x04\x00\x00\x01\xd5" + // 0x00DC0304: 0x000001D5 - "\x00\xfc\x03\x04\x00\x00\x01\xd6" + // 0x00FC0304: 0x000001D6 - "\x00\xdc\x03\x01\x00\x00\x01\xd7" + // 0x00DC0301: 0x000001D7 - "\x00\xfc\x03\x01\x00\x00\x01\xd8" + // 0x00FC0301: 0x000001D8 - "\x00\xdc\x03\f\x00\x00\x01\xd9" + // 0x00DC030C: 0x000001D9 - "\x00\xfc\x03\f\x00\x00\x01\xda" + // 0x00FC030C: 0x000001DA - "\x00\xdc\x03\x00\x00\x00\x01\xdb" + // 0x00DC0300: 0x000001DB - "\x00\xfc\x03\x00\x00\x00\x01\xdc" + // 0x00FC0300: 0x000001DC - "\x00\xc4\x03\x04\x00\x00\x01\xde" + // 0x00C40304: 0x000001DE - "\x00\xe4\x03\x04\x00\x00\x01\xdf" + // 0x00E40304: 0x000001DF - "\x02&\x03\x04\x00\x00\x01\xe0" + // 0x02260304: 0x000001E0 - "\x02'\x03\x04\x00\x00\x01\xe1" + // 0x02270304: 0x000001E1 - "\x00\xc6\x03\x04\x00\x00\x01\xe2" + // 0x00C60304: 0x000001E2 - "\x00\xe6\x03\x04\x00\x00\x01\xe3" + // 0x00E60304: 0x000001E3 - "\x00G\x03\f\x00\x00\x01\xe6" + // 0x0047030C: 0x000001E6 - "\x00g\x03\f\x00\x00\x01\xe7" + // 0x0067030C: 0x000001E7 - "\x00K\x03\f\x00\x00\x01\xe8" + // 0x004B030C: 0x000001E8 - "\x00k\x03\f\x00\x00\x01\xe9" + // 0x006B030C: 0x000001E9 - "\x00O\x03(\x00\x00\x01\xea" + // 0x004F0328: 0x000001EA - "\x00o\x03(\x00\x00\x01\xeb" + // 0x006F0328: 0x000001EB - "\x01\xea\x03\x04\x00\x00\x01\xec" + // 0x01EA0304: 0x000001EC - "\x01\xeb\x03\x04\x00\x00\x01\xed" + // 0x01EB0304: 0x000001ED - "\x01\xb7\x03\f\x00\x00\x01\xee" + // 0x01B7030C: 0x000001EE - "\x02\x92\x03\f\x00\x00\x01\xef" + // 0x0292030C: 0x000001EF - "\x00j\x03\f\x00\x00\x01\xf0" + // 0x006A030C: 0x000001F0 - "\x00G\x03\x01\x00\x00\x01\xf4" + // 0x00470301: 0x000001F4 - "\x00g\x03\x01\x00\x00\x01\xf5" + // 0x00670301: 0x000001F5 - "\x00N\x03\x00\x00\x00\x01\xf8" + // 0x004E0300: 0x000001F8 - "\x00n\x03\x00\x00\x00\x01\xf9" + // 0x006E0300: 0x000001F9 - "\x00\xc5\x03\x01\x00\x00\x01\xfa" + // 0x00C50301: 0x000001FA - "\x00\xe5\x03\x01\x00\x00\x01\xfb" + // 0x00E50301: 0x000001FB - "\x00\xc6\x03\x01\x00\x00\x01\xfc" + // 0x00C60301: 0x000001FC - "\x00\xe6\x03\x01\x00\x00\x01\xfd" + // 0x00E60301: 0x000001FD - "\x00\xd8\x03\x01\x00\x00\x01\xfe" + // 0x00D80301: 0x000001FE - "\x00\xf8\x03\x01\x00\x00\x01\xff" + // 0x00F80301: 0x000001FF - "\x00A\x03\x0f\x00\x00\x02\x00" + // 0x0041030F: 0x00000200 - "\x00a\x03\x0f\x00\x00\x02\x01" + // 0x0061030F: 0x00000201 - "\x00A\x03\x11\x00\x00\x02\x02" + // 0x00410311: 0x00000202 - "\x00a\x03\x11\x00\x00\x02\x03" + // 0x00610311: 0x00000203 - "\x00E\x03\x0f\x00\x00\x02\x04" + // 0x0045030F: 0x00000204 - "\x00e\x03\x0f\x00\x00\x02\x05" + // 0x0065030F: 0x00000205 - "\x00E\x03\x11\x00\x00\x02\x06" + // 0x00450311: 0x00000206 - "\x00e\x03\x11\x00\x00\x02\a" + // 0x00650311: 0x00000207 - "\x00I\x03\x0f\x00\x00\x02\b" + // 0x0049030F: 0x00000208 - "\x00i\x03\x0f\x00\x00\x02\t" + // 0x0069030F: 0x00000209 - "\x00I\x03\x11\x00\x00\x02\n" + // 0x00490311: 0x0000020A - "\x00i\x03\x11\x00\x00\x02\v" + // 0x00690311: 0x0000020B - "\x00O\x03\x0f\x00\x00\x02\f" + // 0x004F030F: 0x0000020C - "\x00o\x03\x0f\x00\x00\x02\r" + // 0x006F030F: 0x0000020D - "\x00O\x03\x11\x00\x00\x02\x0e" + // 0x004F0311: 0x0000020E - "\x00o\x03\x11\x00\x00\x02\x0f" + // 0x006F0311: 0x0000020F - "\x00R\x03\x0f\x00\x00\x02\x10" + // 0x0052030F: 0x00000210 - "\x00r\x03\x0f\x00\x00\x02\x11" + // 0x0072030F: 0x00000211 - "\x00R\x03\x11\x00\x00\x02\x12" + // 0x00520311: 0x00000212 - "\x00r\x03\x11\x00\x00\x02\x13" + // 0x00720311: 0x00000213 - "\x00U\x03\x0f\x00\x00\x02\x14" + // 0x0055030F: 0x00000214 - "\x00u\x03\x0f\x00\x00\x02\x15" + // 0x0075030F: 0x00000215 - "\x00U\x03\x11\x00\x00\x02\x16" + // 0x00550311: 0x00000216 - "\x00u\x03\x11\x00\x00\x02\x17" + // 0x00750311: 0x00000217 - "\x00S\x03&\x00\x00\x02\x18" + // 0x00530326: 0x00000218 - "\x00s\x03&\x00\x00\x02\x19" + // 0x00730326: 0x00000219 - "\x00T\x03&\x00\x00\x02\x1a" + // 0x00540326: 0x0000021A - "\x00t\x03&\x00\x00\x02\x1b" + // 0x00740326: 0x0000021B - "\x00H\x03\f\x00\x00\x02\x1e" + // 0x0048030C: 0x0000021E - "\x00h\x03\f\x00\x00\x02\x1f" + // 0x0068030C: 0x0000021F - "\x00A\x03\a\x00\x00\x02&" + // 0x00410307: 0x00000226 - "\x00a\x03\a\x00\x00\x02'" + // 0x00610307: 0x00000227 - "\x00E\x03'\x00\x00\x02(" + // 0x00450327: 0x00000228 - "\x00e\x03'\x00\x00\x02)" + // 0x00650327: 0x00000229 - "\x00\xd6\x03\x04\x00\x00\x02*" + // 0x00D60304: 0x0000022A - "\x00\xf6\x03\x04\x00\x00\x02+" + // 0x00F60304: 0x0000022B - "\x00\xd5\x03\x04\x00\x00\x02," + // 0x00D50304: 0x0000022C - "\x00\xf5\x03\x04\x00\x00\x02-" + // 0x00F50304: 0x0000022D - "\x00O\x03\a\x00\x00\x02." + // 0x004F0307: 0x0000022E - "\x00o\x03\a\x00\x00\x02/" + // 0x006F0307: 0x0000022F - "\x02.\x03\x04\x00\x00\x020" + // 0x022E0304: 0x00000230 - "\x02/\x03\x04\x00\x00\x021" + // 0x022F0304: 0x00000231 - "\x00Y\x03\x04\x00\x00\x022" + // 0x00590304: 0x00000232 - "\x00y\x03\x04\x00\x00\x023" + // 0x00790304: 0x00000233 - "\x00\xa8\x03\x01\x00\x00\x03\x85" + // 0x00A80301: 0x00000385 - "\x03\x91\x03\x01\x00\x00\x03\x86" + // 0x03910301: 0x00000386 - "\x03\x95\x03\x01\x00\x00\x03\x88" + // 0x03950301: 0x00000388 - "\x03\x97\x03\x01\x00\x00\x03\x89" + // 0x03970301: 0x00000389 - "\x03\x99\x03\x01\x00\x00\x03\x8a" + // 0x03990301: 0x0000038A - "\x03\x9f\x03\x01\x00\x00\x03\x8c" + // 0x039F0301: 0x0000038C - "\x03\xa5\x03\x01\x00\x00\x03\x8e" + // 0x03A50301: 0x0000038E - "\x03\xa9\x03\x01\x00\x00\x03\x8f" + // 0x03A90301: 0x0000038F - "\x03\xca\x03\x01\x00\x00\x03\x90" + // 0x03CA0301: 0x00000390 - "\x03\x99\x03\b\x00\x00\x03\xaa" + // 0x03990308: 0x000003AA - "\x03\xa5\x03\b\x00\x00\x03\xab" + // 0x03A50308: 0x000003AB - "\x03\xb1\x03\x01\x00\x00\x03\xac" + // 0x03B10301: 0x000003AC - "\x03\xb5\x03\x01\x00\x00\x03\xad" + // 0x03B50301: 0x000003AD - "\x03\xb7\x03\x01\x00\x00\x03\xae" + // 0x03B70301: 0x000003AE - "\x03\xb9\x03\x01\x00\x00\x03\xaf" + // 0x03B90301: 0x000003AF - "\x03\xcb\x03\x01\x00\x00\x03\xb0" + // 0x03CB0301: 0x000003B0 - "\x03\xb9\x03\b\x00\x00\x03\xca" + // 0x03B90308: 0x000003CA - "\x03\xc5\x03\b\x00\x00\x03\xcb" + // 0x03C50308: 0x000003CB - "\x03\xbf\x03\x01\x00\x00\x03\xcc" + // 0x03BF0301: 0x000003CC - "\x03\xc5\x03\x01\x00\x00\x03\xcd" + // 0x03C50301: 0x000003CD - "\x03\xc9\x03\x01\x00\x00\x03\xce" + // 0x03C90301: 0x000003CE - "\x03\xd2\x03\x01\x00\x00\x03\xd3" + // 0x03D20301: 0x000003D3 - "\x03\xd2\x03\b\x00\x00\x03\xd4" + // 0x03D20308: 0x000003D4 - "\x04\x15\x03\x00\x00\x00\x04\x00" + // 0x04150300: 0x00000400 - "\x04\x15\x03\b\x00\x00\x04\x01" + // 0x04150308: 0x00000401 - "\x04\x13\x03\x01\x00\x00\x04\x03" + // 0x04130301: 0x00000403 - "\x04\x06\x03\b\x00\x00\x04\a" + // 0x04060308: 0x00000407 - "\x04\x1a\x03\x01\x00\x00\x04\f" + // 0x041A0301: 0x0000040C - "\x04\x18\x03\x00\x00\x00\x04\r" + // 0x04180300: 0x0000040D - "\x04#\x03\x06\x00\x00\x04\x0e" + // 0x04230306: 0x0000040E - "\x04\x18\x03\x06\x00\x00\x04\x19" + // 0x04180306: 0x00000419 - "\x048\x03\x06\x00\x00\x049" + // 0x04380306: 0x00000439 - "\x045\x03\x00\x00\x00\x04P" + // 0x04350300: 0x00000450 - "\x045\x03\b\x00\x00\x04Q" + // 0x04350308: 0x00000451 - "\x043\x03\x01\x00\x00\x04S" + // 0x04330301: 0x00000453 - "\x04V\x03\b\x00\x00\x04W" + // 0x04560308: 0x00000457 - "\x04:\x03\x01\x00\x00\x04\\" + // 0x043A0301: 0x0000045C - "\x048\x03\x00\x00\x00\x04]" + // 0x04380300: 0x0000045D - "\x04C\x03\x06\x00\x00\x04^" + // 0x04430306: 0x0000045E - "\x04t\x03\x0f\x00\x00\x04v" + // 0x0474030F: 0x00000476 - "\x04u\x03\x0f\x00\x00\x04w" + // 0x0475030F: 0x00000477 - "\x04\x16\x03\x06\x00\x00\x04\xc1" + // 0x04160306: 0x000004C1 - "\x046\x03\x06\x00\x00\x04\xc2" + // 0x04360306: 0x000004C2 - "\x04\x10\x03\x06\x00\x00\x04\xd0" + // 0x04100306: 0x000004D0 - "\x040\x03\x06\x00\x00\x04\xd1" + // 0x04300306: 0x000004D1 - "\x04\x10\x03\b\x00\x00\x04\xd2" + // 0x04100308: 0x000004D2 - "\x040\x03\b\x00\x00\x04\xd3" + // 0x04300308: 0x000004D3 - "\x04\x15\x03\x06\x00\x00\x04\xd6" + // 0x04150306: 0x000004D6 - "\x045\x03\x06\x00\x00\x04\xd7" + // 0x04350306: 0x000004D7 - "\x04\xd8\x03\b\x00\x00\x04\xda" + // 0x04D80308: 0x000004DA - "\x04\xd9\x03\b\x00\x00\x04\xdb" + // 0x04D90308: 0x000004DB - "\x04\x16\x03\b\x00\x00\x04\xdc" + // 0x04160308: 0x000004DC - "\x046\x03\b\x00\x00\x04\xdd" + // 0x04360308: 0x000004DD - "\x04\x17\x03\b\x00\x00\x04\xde" + // 0x04170308: 0x000004DE - "\x047\x03\b\x00\x00\x04\xdf" + // 0x04370308: 0x000004DF - "\x04\x18\x03\x04\x00\x00\x04\xe2" + // 0x04180304: 0x000004E2 - "\x048\x03\x04\x00\x00\x04\xe3" + // 0x04380304: 0x000004E3 - "\x04\x18\x03\b\x00\x00\x04\xe4" + // 0x04180308: 0x000004E4 - "\x048\x03\b\x00\x00\x04\xe5" + // 0x04380308: 0x000004E5 - "\x04\x1e\x03\b\x00\x00\x04\xe6" + // 0x041E0308: 0x000004E6 - "\x04>\x03\b\x00\x00\x04\xe7" + // 0x043E0308: 0x000004E7 - "\x04\xe8\x03\b\x00\x00\x04\xea" + // 0x04E80308: 0x000004EA - "\x04\xe9\x03\b\x00\x00\x04\xeb" + // 0x04E90308: 0x000004EB - "\x04-\x03\b\x00\x00\x04\xec" + // 0x042D0308: 0x000004EC - "\x04M\x03\b\x00\x00\x04\xed" + // 0x044D0308: 0x000004ED - "\x04#\x03\x04\x00\x00\x04\xee" + // 0x04230304: 0x000004EE - "\x04C\x03\x04\x00\x00\x04\xef" + // 0x04430304: 0x000004EF - "\x04#\x03\b\x00\x00\x04\xf0" + // 0x04230308: 0x000004F0 - "\x04C\x03\b\x00\x00\x04\xf1" + // 0x04430308: 0x000004F1 - "\x04#\x03\v\x00\x00\x04\xf2" + // 0x0423030B: 0x000004F2 - "\x04C\x03\v\x00\x00\x04\xf3" + // 0x0443030B: 0x000004F3 - "\x04'\x03\b\x00\x00\x04\xf4" + // 0x04270308: 0x000004F4 - "\x04G\x03\b\x00\x00\x04\xf5" + // 0x04470308: 0x000004F5 - "\x04+\x03\b\x00\x00\x04\xf8" + // 0x042B0308: 0x000004F8 - "\x04K\x03\b\x00\x00\x04\xf9" + // 0x044B0308: 0x000004F9 - "\x06'\x06S\x00\x00\x06\"" + // 0x06270653: 0x00000622 - "\x06'\x06T\x00\x00\x06#" + // 0x06270654: 0x00000623 - "\x06H\x06T\x00\x00\x06$" + // 0x06480654: 0x00000624 - "\x06'\x06U\x00\x00\x06%" + // 0x06270655: 0x00000625 - "\x06J\x06T\x00\x00\x06&" + // 0x064A0654: 0x00000626 - "\x06\xd5\x06T\x00\x00\x06\xc0" + // 0x06D50654: 0x000006C0 - "\x06\xc1\x06T\x00\x00\x06\xc2" + // 0x06C10654: 0x000006C2 - "\x06\xd2\x06T\x00\x00\x06\xd3" + // 0x06D20654: 0x000006D3 - "\t(\t<\x00\x00\t)" + // 0x0928093C: 0x00000929 - "\t0\t<\x00\x00\t1" + // 0x0930093C: 0x00000931 - "\t3\t<\x00\x00\t4" + // 0x0933093C: 0x00000934 - "\t\xc7\t\xbe\x00\x00\t\xcb" + // 0x09C709BE: 0x000009CB - "\t\xc7\t\xd7\x00\x00\t\xcc" + // 0x09C709D7: 0x000009CC - "\vG\vV\x00\x00\vH" + // 0x0B470B56: 0x00000B48 - "\vG\v>\x00\x00\vK" + // 0x0B470B3E: 0x00000B4B - "\vG\vW\x00\x00\vL" + // 0x0B470B57: 0x00000B4C - "\v\x92\v\xd7\x00\x00\v\x94" + // 0x0B920BD7: 0x00000B94 - "\v\xc6\v\xbe\x00\x00\v\xca" + // 0x0BC60BBE: 0x00000BCA - "\v\xc7\v\xbe\x00\x00\v\xcb" + // 0x0BC70BBE: 0x00000BCB - "\v\xc6\v\xd7\x00\x00\v\xcc" + // 0x0BC60BD7: 0x00000BCC - "\fF\fV\x00\x00\fH" + // 0x0C460C56: 0x00000C48 - "\f\xbf\f\xd5\x00\x00\f\xc0" + // 0x0CBF0CD5: 0x00000CC0 - "\f\xc6\f\xd5\x00\x00\f\xc7" + // 0x0CC60CD5: 0x00000CC7 - "\f\xc6\f\xd6\x00\x00\f\xc8" + // 0x0CC60CD6: 0x00000CC8 - "\f\xc6\f\xc2\x00\x00\f\xca" + // 0x0CC60CC2: 0x00000CCA - "\f\xca\f\xd5\x00\x00\f\xcb" + // 0x0CCA0CD5: 0x00000CCB - "\rF\r>\x00\x00\rJ" + // 0x0D460D3E: 0x00000D4A - "\rG\r>\x00\x00\rK" + // 0x0D470D3E: 0x00000D4B - "\rF\rW\x00\x00\rL" + // 0x0D460D57: 0x00000D4C - "\r\xd9\r\xca\x00\x00\r\xda" + // 0x0DD90DCA: 0x00000DDA - "\r\xd9\r\xcf\x00\x00\r\xdc" + // 0x0DD90DCF: 0x00000DDC - "\r\xdc\r\xca\x00\x00\r\xdd" + // 0x0DDC0DCA: 0x00000DDD - "\r\xd9\r\xdf\x00\x00\r\xde" + // 0x0DD90DDF: 0x00000DDE - "\x10%\x10.\x00\x00\x10&" + // 0x1025102E: 0x00001026 - "\x1b\x05\x1b5\x00\x00\x1b\x06" + // 0x1B051B35: 0x00001B06 - "\x1b\a\x1b5\x00\x00\x1b\b" + // 0x1B071B35: 0x00001B08 - "\x1b\t\x1b5\x00\x00\x1b\n" + // 0x1B091B35: 0x00001B0A - "\x1b\v\x1b5\x00\x00\x1b\f" + // 0x1B0B1B35: 0x00001B0C - "\x1b\r\x1b5\x00\x00\x1b\x0e" + // 0x1B0D1B35: 0x00001B0E - "\x1b\x11\x1b5\x00\x00\x1b\x12" + // 0x1B111B35: 0x00001B12 - "\x1b:\x1b5\x00\x00\x1b;" + // 0x1B3A1B35: 0x00001B3B - "\x1b<\x1b5\x00\x00\x1b=" + // 0x1B3C1B35: 0x00001B3D - "\x1b>\x1b5\x00\x00\x1b@" + // 0x1B3E1B35: 0x00001B40 - "\x1b?\x1b5\x00\x00\x1bA" + // 0x1B3F1B35: 0x00001B41 - "\x1bB\x1b5\x00\x00\x1bC" + // 0x1B421B35: 0x00001B43 - "\x00A\x03%\x00\x00\x1e\x00" + // 0x00410325: 0x00001E00 - "\x00a\x03%\x00\x00\x1e\x01" + // 0x00610325: 0x00001E01 - "\x00B\x03\a\x00\x00\x1e\x02" + // 0x00420307: 0x00001E02 - "\x00b\x03\a\x00\x00\x1e\x03" + // 0x00620307: 0x00001E03 - "\x00B\x03#\x00\x00\x1e\x04" + // 0x00420323: 0x00001E04 - "\x00b\x03#\x00\x00\x1e\x05" + // 0x00620323: 0x00001E05 - "\x00B\x031\x00\x00\x1e\x06" + // 0x00420331: 0x00001E06 - "\x00b\x031\x00\x00\x1e\a" + // 0x00620331: 0x00001E07 - "\x00\xc7\x03\x01\x00\x00\x1e\b" + // 0x00C70301: 0x00001E08 - "\x00\xe7\x03\x01\x00\x00\x1e\t" + // 0x00E70301: 0x00001E09 - "\x00D\x03\a\x00\x00\x1e\n" + // 0x00440307: 0x00001E0A - "\x00d\x03\a\x00\x00\x1e\v" + // 0x00640307: 0x00001E0B - "\x00D\x03#\x00\x00\x1e\f" + // 0x00440323: 0x00001E0C - "\x00d\x03#\x00\x00\x1e\r" + // 0x00640323: 0x00001E0D - "\x00D\x031\x00\x00\x1e\x0e" + // 0x00440331: 0x00001E0E - "\x00d\x031\x00\x00\x1e\x0f" + // 0x00640331: 0x00001E0F - "\x00D\x03'\x00\x00\x1e\x10" + // 0x00440327: 0x00001E10 - "\x00d\x03'\x00\x00\x1e\x11" + // 0x00640327: 0x00001E11 - "\x00D\x03-\x00\x00\x1e\x12" + // 0x0044032D: 0x00001E12 - "\x00d\x03-\x00\x00\x1e\x13" + // 0x0064032D: 0x00001E13 - "\x01\x12\x03\x00\x00\x00\x1e\x14" + // 0x01120300: 0x00001E14 - "\x01\x13\x03\x00\x00\x00\x1e\x15" + // 0x01130300: 0x00001E15 - "\x01\x12\x03\x01\x00\x00\x1e\x16" + // 0x01120301: 0x00001E16 - "\x01\x13\x03\x01\x00\x00\x1e\x17" + // 0x01130301: 0x00001E17 - "\x00E\x03-\x00\x00\x1e\x18" + // 0x0045032D: 0x00001E18 - "\x00e\x03-\x00\x00\x1e\x19" + // 0x0065032D: 0x00001E19 - "\x00E\x030\x00\x00\x1e\x1a" + // 0x00450330: 0x00001E1A - "\x00e\x030\x00\x00\x1e\x1b" + // 0x00650330: 0x00001E1B - "\x02(\x03\x06\x00\x00\x1e\x1c" + // 0x02280306: 0x00001E1C - "\x02)\x03\x06\x00\x00\x1e\x1d" + // 0x02290306: 0x00001E1D - "\x00F\x03\a\x00\x00\x1e\x1e" + // 0x00460307: 0x00001E1E - "\x00f\x03\a\x00\x00\x1e\x1f" + // 0x00660307: 0x00001E1F - "\x00G\x03\x04\x00\x00\x1e " + // 0x00470304: 0x00001E20 - "\x00g\x03\x04\x00\x00\x1e!" + // 0x00670304: 0x00001E21 - "\x00H\x03\a\x00\x00\x1e\"" + // 0x00480307: 0x00001E22 - "\x00h\x03\a\x00\x00\x1e#" + // 0x00680307: 0x00001E23 - "\x00H\x03#\x00\x00\x1e$" + // 0x00480323: 0x00001E24 - "\x00h\x03#\x00\x00\x1e%" + // 0x00680323: 0x00001E25 - "\x00H\x03\b\x00\x00\x1e&" + // 0x00480308: 0x00001E26 - "\x00h\x03\b\x00\x00\x1e'" + // 0x00680308: 0x00001E27 - "\x00H\x03'\x00\x00\x1e(" + // 0x00480327: 0x00001E28 - "\x00h\x03'\x00\x00\x1e)" + // 0x00680327: 0x00001E29 - "\x00H\x03.\x00\x00\x1e*" + // 0x0048032E: 0x00001E2A - "\x00h\x03.\x00\x00\x1e+" + // 0x0068032E: 0x00001E2B - "\x00I\x030\x00\x00\x1e," + // 0x00490330: 0x00001E2C - "\x00i\x030\x00\x00\x1e-" + // 0x00690330: 0x00001E2D - "\x00\xcf\x03\x01\x00\x00\x1e." + // 0x00CF0301: 0x00001E2E - "\x00\xef\x03\x01\x00\x00\x1e/" + // 0x00EF0301: 0x00001E2F - "\x00K\x03\x01\x00\x00\x1e0" + // 0x004B0301: 0x00001E30 - "\x00k\x03\x01\x00\x00\x1e1" + // 0x006B0301: 0x00001E31 - "\x00K\x03#\x00\x00\x1e2" + // 0x004B0323: 0x00001E32 - "\x00k\x03#\x00\x00\x1e3" + // 0x006B0323: 0x00001E33 - "\x00K\x031\x00\x00\x1e4" + // 0x004B0331: 0x00001E34 - "\x00k\x031\x00\x00\x1e5" + // 0x006B0331: 0x00001E35 - "\x00L\x03#\x00\x00\x1e6" + // 0x004C0323: 0x00001E36 - "\x00l\x03#\x00\x00\x1e7" + // 0x006C0323: 0x00001E37 - "\x1e6\x03\x04\x00\x00\x1e8" + // 0x1E360304: 0x00001E38 - "\x1e7\x03\x04\x00\x00\x1e9" + // 0x1E370304: 0x00001E39 - "\x00L\x031\x00\x00\x1e:" + // 0x004C0331: 0x00001E3A - "\x00l\x031\x00\x00\x1e;" + // 0x006C0331: 0x00001E3B - "\x00L\x03-\x00\x00\x1e<" + // 0x004C032D: 0x00001E3C - "\x00l\x03-\x00\x00\x1e=" + // 0x006C032D: 0x00001E3D - "\x00M\x03\x01\x00\x00\x1e>" + // 0x004D0301: 0x00001E3E - "\x00m\x03\x01\x00\x00\x1e?" + // 0x006D0301: 0x00001E3F - "\x00M\x03\a\x00\x00\x1e@" + // 0x004D0307: 0x00001E40 - "\x00m\x03\a\x00\x00\x1eA" + // 0x006D0307: 0x00001E41 - "\x00M\x03#\x00\x00\x1eB" + // 0x004D0323: 0x00001E42 - "\x00m\x03#\x00\x00\x1eC" + // 0x006D0323: 0x00001E43 - "\x00N\x03\a\x00\x00\x1eD" + // 0x004E0307: 0x00001E44 - "\x00n\x03\a\x00\x00\x1eE" + // 0x006E0307: 0x00001E45 - "\x00N\x03#\x00\x00\x1eF" + // 0x004E0323: 0x00001E46 - "\x00n\x03#\x00\x00\x1eG" + // 0x006E0323: 0x00001E47 - "\x00N\x031\x00\x00\x1eH" + // 0x004E0331: 0x00001E48 - "\x00n\x031\x00\x00\x1eI" + // 0x006E0331: 0x00001E49 - "\x00N\x03-\x00\x00\x1eJ" + // 0x004E032D: 0x00001E4A - "\x00n\x03-\x00\x00\x1eK" + // 0x006E032D: 0x00001E4B - "\x00\xd5\x03\x01\x00\x00\x1eL" + // 0x00D50301: 0x00001E4C - "\x00\xf5\x03\x01\x00\x00\x1eM" + // 0x00F50301: 0x00001E4D - "\x00\xd5\x03\b\x00\x00\x1eN" + // 0x00D50308: 0x00001E4E - "\x00\xf5\x03\b\x00\x00\x1eO" + // 0x00F50308: 0x00001E4F - "\x01L\x03\x00\x00\x00\x1eP" + // 0x014C0300: 0x00001E50 - "\x01M\x03\x00\x00\x00\x1eQ" + // 0x014D0300: 0x00001E51 - "\x01L\x03\x01\x00\x00\x1eR" + // 0x014C0301: 0x00001E52 - "\x01M\x03\x01\x00\x00\x1eS" + // 0x014D0301: 0x00001E53 - "\x00P\x03\x01\x00\x00\x1eT" + // 0x00500301: 0x00001E54 - "\x00p\x03\x01\x00\x00\x1eU" + // 0x00700301: 0x00001E55 - "\x00P\x03\a\x00\x00\x1eV" + // 0x00500307: 0x00001E56 - "\x00p\x03\a\x00\x00\x1eW" + // 0x00700307: 0x00001E57 - "\x00R\x03\a\x00\x00\x1eX" + // 0x00520307: 0x00001E58 - "\x00r\x03\a\x00\x00\x1eY" + // 0x00720307: 0x00001E59 - "\x00R\x03#\x00\x00\x1eZ" + // 0x00520323: 0x00001E5A - "\x00r\x03#\x00\x00\x1e[" + // 0x00720323: 0x00001E5B - "\x1eZ\x03\x04\x00\x00\x1e\\" + // 0x1E5A0304: 0x00001E5C - "\x1e[\x03\x04\x00\x00\x1e]" + // 0x1E5B0304: 0x00001E5D - "\x00R\x031\x00\x00\x1e^" + // 0x00520331: 0x00001E5E - "\x00r\x031\x00\x00\x1e_" + // 0x00720331: 0x00001E5F - "\x00S\x03\a\x00\x00\x1e`" + // 0x00530307: 0x00001E60 - "\x00s\x03\a\x00\x00\x1ea" + // 0x00730307: 0x00001E61 - "\x00S\x03#\x00\x00\x1eb" + // 0x00530323: 0x00001E62 - "\x00s\x03#\x00\x00\x1ec" + // 0x00730323: 0x00001E63 - "\x01Z\x03\a\x00\x00\x1ed" + // 0x015A0307: 0x00001E64 - "\x01[\x03\a\x00\x00\x1ee" + // 0x015B0307: 0x00001E65 - "\x01`\x03\a\x00\x00\x1ef" + // 0x01600307: 0x00001E66 - "\x01a\x03\a\x00\x00\x1eg" + // 0x01610307: 0x00001E67 - "\x1eb\x03\a\x00\x00\x1eh" + // 0x1E620307: 0x00001E68 - "\x1ec\x03\a\x00\x00\x1ei" + // 0x1E630307: 0x00001E69 - "\x00T\x03\a\x00\x00\x1ej" + // 0x00540307: 0x00001E6A - "\x00t\x03\a\x00\x00\x1ek" + // 0x00740307: 0x00001E6B - "\x00T\x03#\x00\x00\x1el" + // 0x00540323: 0x00001E6C - "\x00t\x03#\x00\x00\x1em" + // 0x00740323: 0x00001E6D - "\x00T\x031\x00\x00\x1en" + // 0x00540331: 0x00001E6E - "\x00t\x031\x00\x00\x1eo" + // 0x00740331: 0x00001E6F - "\x00T\x03-\x00\x00\x1ep" + // 0x0054032D: 0x00001E70 - "\x00t\x03-\x00\x00\x1eq" + // 0x0074032D: 0x00001E71 - "\x00U\x03$\x00\x00\x1er" + // 0x00550324: 0x00001E72 - "\x00u\x03$\x00\x00\x1es" + // 0x00750324: 0x00001E73 - "\x00U\x030\x00\x00\x1et" + // 0x00550330: 0x00001E74 - "\x00u\x030\x00\x00\x1eu" + // 0x00750330: 0x00001E75 - "\x00U\x03-\x00\x00\x1ev" + // 0x0055032D: 0x00001E76 - "\x00u\x03-\x00\x00\x1ew" + // 0x0075032D: 0x00001E77 - "\x01h\x03\x01\x00\x00\x1ex" + // 0x01680301: 0x00001E78 - "\x01i\x03\x01\x00\x00\x1ey" + // 0x01690301: 0x00001E79 - "\x01j\x03\b\x00\x00\x1ez" + // 0x016A0308: 0x00001E7A - "\x01k\x03\b\x00\x00\x1e{" + // 0x016B0308: 0x00001E7B - "\x00V\x03\x03\x00\x00\x1e|" + // 0x00560303: 0x00001E7C - "\x00v\x03\x03\x00\x00\x1e}" + // 0x00760303: 0x00001E7D - "\x00V\x03#\x00\x00\x1e~" + // 0x00560323: 0x00001E7E - "\x00v\x03#\x00\x00\x1e\x7f" + // 0x00760323: 0x00001E7F - "\x00W\x03\x00\x00\x00\x1e\x80" + // 0x00570300: 0x00001E80 - "\x00w\x03\x00\x00\x00\x1e\x81" + // 0x00770300: 0x00001E81 - "\x00W\x03\x01\x00\x00\x1e\x82" + // 0x00570301: 0x00001E82 - "\x00w\x03\x01\x00\x00\x1e\x83" + // 0x00770301: 0x00001E83 - "\x00W\x03\b\x00\x00\x1e\x84" + // 0x00570308: 0x00001E84 - "\x00w\x03\b\x00\x00\x1e\x85" + // 0x00770308: 0x00001E85 - "\x00W\x03\a\x00\x00\x1e\x86" + // 0x00570307: 0x00001E86 - "\x00w\x03\a\x00\x00\x1e\x87" + // 0x00770307: 0x00001E87 - "\x00W\x03#\x00\x00\x1e\x88" + // 0x00570323: 0x00001E88 - "\x00w\x03#\x00\x00\x1e\x89" + // 0x00770323: 0x00001E89 - "\x00X\x03\a\x00\x00\x1e\x8a" + // 0x00580307: 0x00001E8A - "\x00x\x03\a\x00\x00\x1e\x8b" + // 0x00780307: 0x00001E8B - "\x00X\x03\b\x00\x00\x1e\x8c" + // 0x00580308: 0x00001E8C - "\x00x\x03\b\x00\x00\x1e\x8d" + // 0x00780308: 0x00001E8D - "\x00Y\x03\a\x00\x00\x1e\x8e" + // 0x00590307: 0x00001E8E - "\x00y\x03\a\x00\x00\x1e\x8f" + // 0x00790307: 0x00001E8F - "\x00Z\x03\x02\x00\x00\x1e\x90" + // 0x005A0302: 0x00001E90 - "\x00z\x03\x02\x00\x00\x1e\x91" + // 0x007A0302: 0x00001E91 - "\x00Z\x03#\x00\x00\x1e\x92" + // 0x005A0323: 0x00001E92 - "\x00z\x03#\x00\x00\x1e\x93" + // 0x007A0323: 0x00001E93 - "\x00Z\x031\x00\x00\x1e\x94" + // 0x005A0331: 0x00001E94 - "\x00z\x031\x00\x00\x1e\x95" + // 0x007A0331: 0x00001E95 - "\x00h\x031\x00\x00\x1e\x96" + // 0x00680331: 0x00001E96 - "\x00t\x03\b\x00\x00\x1e\x97" + // 0x00740308: 0x00001E97 - "\x00w\x03\n\x00\x00\x1e\x98" + // 0x0077030A: 0x00001E98 - "\x00y\x03\n\x00\x00\x1e\x99" + // 0x0079030A: 0x00001E99 - "\x01\x7f\x03\a\x00\x00\x1e\x9b" + // 0x017F0307: 0x00001E9B - "\x00A\x03#\x00\x00\x1e\xa0" + // 0x00410323: 0x00001EA0 - "\x00a\x03#\x00\x00\x1e\xa1" + // 0x00610323: 0x00001EA1 - "\x00A\x03\t\x00\x00\x1e\xa2" + // 0x00410309: 0x00001EA2 - "\x00a\x03\t\x00\x00\x1e\xa3" + // 0x00610309: 0x00001EA3 - "\x00\xc2\x03\x01\x00\x00\x1e\xa4" + // 0x00C20301: 0x00001EA4 - "\x00\xe2\x03\x01\x00\x00\x1e\xa5" + // 0x00E20301: 0x00001EA5 - "\x00\xc2\x03\x00\x00\x00\x1e\xa6" + // 0x00C20300: 0x00001EA6 - "\x00\xe2\x03\x00\x00\x00\x1e\xa7" + // 0x00E20300: 0x00001EA7 - "\x00\xc2\x03\t\x00\x00\x1e\xa8" + // 0x00C20309: 0x00001EA8 - "\x00\xe2\x03\t\x00\x00\x1e\xa9" + // 0x00E20309: 0x00001EA9 - "\x00\xc2\x03\x03\x00\x00\x1e\xaa" + // 0x00C20303: 0x00001EAA - "\x00\xe2\x03\x03\x00\x00\x1e\xab" + // 0x00E20303: 0x00001EAB - "\x1e\xa0\x03\x02\x00\x00\x1e\xac" + // 0x1EA00302: 0x00001EAC - "\x1e\xa1\x03\x02\x00\x00\x1e\xad" + // 0x1EA10302: 0x00001EAD - "\x01\x02\x03\x01\x00\x00\x1e\xae" + // 0x01020301: 0x00001EAE - "\x01\x03\x03\x01\x00\x00\x1e\xaf" + // 0x01030301: 0x00001EAF - "\x01\x02\x03\x00\x00\x00\x1e\xb0" + // 0x01020300: 0x00001EB0 - "\x01\x03\x03\x00\x00\x00\x1e\xb1" + // 0x01030300: 0x00001EB1 - "\x01\x02\x03\t\x00\x00\x1e\xb2" + // 0x01020309: 0x00001EB2 - "\x01\x03\x03\t\x00\x00\x1e\xb3" + // 0x01030309: 0x00001EB3 - "\x01\x02\x03\x03\x00\x00\x1e\xb4" + // 0x01020303: 0x00001EB4 - "\x01\x03\x03\x03\x00\x00\x1e\xb5" + // 0x01030303: 0x00001EB5 - "\x1e\xa0\x03\x06\x00\x00\x1e\xb6" + // 0x1EA00306: 0x00001EB6 - "\x1e\xa1\x03\x06\x00\x00\x1e\xb7" + // 0x1EA10306: 0x00001EB7 - "\x00E\x03#\x00\x00\x1e\xb8" + // 0x00450323: 0x00001EB8 - "\x00e\x03#\x00\x00\x1e\xb9" + // 0x00650323: 0x00001EB9 - "\x00E\x03\t\x00\x00\x1e\xba" + // 0x00450309: 0x00001EBA - "\x00e\x03\t\x00\x00\x1e\xbb" + // 0x00650309: 0x00001EBB - "\x00E\x03\x03\x00\x00\x1e\xbc" + // 0x00450303: 0x00001EBC - "\x00e\x03\x03\x00\x00\x1e\xbd" + // 0x00650303: 0x00001EBD - "\x00\xca\x03\x01\x00\x00\x1e\xbe" + // 0x00CA0301: 0x00001EBE - "\x00\xea\x03\x01\x00\x00\x1e\xbf" + // 0x00EA0301: 0x00001EBF - "\x00\xca\x03\x00\x00\x00\x1e\xc0" + // 0x00CA0300: 0x00001EC0 - "\x00\xea\x03\x00\x00\x00\x1e\xc1" + // 0x00EA0300: 0x00001EC1 - "\x00\xca\x03\t\x00\x00\x1e\xc2" + // 0x00CA0309: 0x00001EC2 - "\x00\xea\x03\t\x00\x00\x1e\xc3" + // 0x00EA0309: 0x00001EC3 - "\x00\xca\x03\x03\x00\x00\x1e\xc4" + // 0x00CA0303: 0x00001EC4 - "\x00\xea\x03\x03\x00\x00\x1e\xc5" + // 0x00EA0303: 0x00001EC5 - "\x1e\xb8\x03\x02\x00\x00\x1e\xc6" + // 0x1EB80302: 0x00001EC6 - "\x1e\xb9\x03\x02\x00\x00\x1e\xc7" + // 0x1EB90302: 0x00001EC7 - "\x00I\x03\t\x00\x00\x1e\xc8" + // 0x00490309: 0x00001EC8 - "\x00i\x03\t\x00\x00\x1e\xc9" + // 0x00690309: 0x00001EC9 - "\x00I\x03#\x00\x00\x1e\xca" + // 0x00490323: 0x00001ECA - "\x00i\x03#\x00\x00\x1e\xcb" + // 0x00690323: 0x00001ECB - "\x00O\x03#\x00\x00\x1e\xcc" + // 0x004F0323: 0x00001ECC - "\x00o\x03#\x00\x00\x1e\xcd" + // 0x006F0323: 0x00001ECD - "\x00O\x03\t\x00\x00\x1e\xce" + // 0x004F0309: 0x00001ECE - "\x00o\x03\t\x00\x00\x1e\xcf" + // 0x006F0309: 0x00001ECF - "\x00\xd4\x03\x01\x00\x00\x1e\xd0" + // 0x00D40301: 0x00001ED0 - "\x00\xf4\x03\x01\x00\x00\x1e\xd1" + // 0x00F40301: 0x00001ED1 - "\x00\xd4\x03\x00\x00\x00\x1e\xd2" + // 0x00D40300: 0x00001ED2 - "\x00\xf4\x03\x00\x00\x00\x1e\xd3" + // 0x00F40300: 0x00001ED3 - "\x00\xd4\x03\t\x00\x00\x1e\xd4" + // 0x00D40309: 0x00001ED4 - "\x00\xf4\x03\t\x00\x00\x1e\xd5" + // 0x00F40309: 0x00001ED5 - "\x00\xd4\x03\x03\x00\x00\x1e\xd6" + // 0x00D40303: 0x00001ED6 - "\x00\xf4\x03\x03\x00\x00\x1e\xd7" + // 0x00F40303: 0x00001ED7 - "\x1e\xcc\x03\x02\x00\x00\x1e\xd8" + // 0x1ECC0302: 0x00001ED8 - "\x1e\xcd\x03\x02\x00\x00\x1e\xd9" + // 0x1ECD0302: 0x00001ED9 - "\x01\xa0\x03\x01\x00\x00\x1e\xda" + // 0x01A00301: 0x00001EDA - "\x01\xa1\x03\x01\x00\x00\x1e\xdb" + // 0x01A10301: 0x00001EDB - "\x01\xa0\x03\x00\x00\x00\x1e\xdc" + // 0x01A00300: 0x00001EDC - "\x01\xa1\x03\x00\x00\x00\x1e\xdd" + // 0x01A10300: 0x00001EDD - "\x01\xa0\x03\t\x00\x00\x1e\xde" + // 0x01A00309: 0x00001EDE - "\x01\xa1\x03\t\x00\x00\x1e\xdf" + // 0x01A10309: 0x00001EDF - "\x01\xa0\x03\x03\x00\x00\x1e\xe0" + // 0x01A00303: 0x00001EE0 - "\x01\xa1\x03\x03\x00\x00\x1e\xe1" + // 0x01A10303: 0x00001EE1 - "\x01\xa0\x03#\x00\x00\x1e\xe2" + // 0x01A00323: 0x00001EE2 - "\x01\xa1\x03#\x00\x00\x1e\xe3" + // 0x01A10323: 0x00001EE3 - "\x00U\x03#\x00\x00\x1e\xe4" + // 0x00550323: 0x00001EE4 - "\x00u\x03#\x00\x00\x1e\xe5" + // 0x00750323: 0x00001EE5 - "\x00U\x03\t\x00\x00\x1e\xe6" + // 0x00550309: 0x00001EE6 - "\x00u\x03\t\x00\x00\x1e\xe7" + // 0x00750309: 0x00001EE7 - "\x01\xaf\x03\x01\x00\x00\x1e\xe8" + // 0x01AF0301: 0x00001EE8 - "\x01\xb0\x03\x01\x00\x00\x1e\xe9" + // 0x01B00301: 0x00001EE9 - "\x01\xaf\x03\x00\x00\x00\x1e\xea" + // 0x01AF0300: 0x00001EEA - "\x01\xb0\x03\x00\x00\x00\x1e\xeb" + // 0x01B00300: 0x00001EEB - "\x01\xaf\x03\t\x00\x00\x1e\xec" + // 0x01AF0309: 0x00001EEC - "\x01\xb0\x03\t\x00\x00\x1e\xed" + // 0x01B00309: 0x00001EED - "\x01\xaf\x03\x03\x00\x00\x1e\xee" + // 0x01AF0303: 0x00001EEE - "\x01\xb0\x03\x03\x00\x00\x1e\xef" + // 0x01B00303: 0x00001EEF - "\x01\xaf\x03#\x00\x00\x1e\xf0" + // 0x01AF0323: 0x00001EF0 - "\x01\xb0\x03#\x00\x00\x1e\xf1" + // 0x01B00323: 0x00001EF1 - "\x00Y\x03\x00\x00\x00\x1e\xf2" + // 0x00590300: 0x00001EF2 - "\x00y\x03\x00\x00\x00\x1e\xf3" + // 0x00790300: 0x00001EF3 - "\x00Y\x03#\x00\x00\x1e\xf4" + // 0x00590323: 0x00001EF4 - "\x00y\x03#\x00\x00\x1e\xf5" + // 0x00790323: 0x00001EF5 - "\x00Y\x03\t\x00\x00\x1e\xf6" + // 0x00590309: 0x00001EF6 - "\x00y\x03\t\x00\x00\x1e\xf7" + // 0x00790309: 0x00001EF7 - "\x00Y\x03\x03\x00\x00\x1e\xf8" + // 0x00590303: 0x00001EF8 - "\x00y\x03\x03\x00\x00\x1e\xf9" + // 0x00790303: 0x00001EF9 - "\x03\xb1\x03\x13\x00\x00\x1f\x00" + // 0x03B10313: 0x00001F00 - "\x03\xb1\x03\x14\x00\x00\x1f\x01" + // 0x03B10314: 0x00001F01 - "\x1f\x00\x03\x00\x00\x00\x1f\x02" + // 0x1F000300: 0x00001F02 - "\x1f\x01\x03\x00\x00\x00\x1f\x03" + // 0x1F010300: 0x00001F03 - "\x1f\x00\x03\x01\x00\x00\x1f\x04" + // 0x1F000301: 0x00001F04 - "\x1f\x01\x03\x01\x00\x00\x1f\x05" + // 0x1F010301: 0x00001F05 - "\x1f\x00\x03B\x00\x00\x1f\x06" + // 0x1F000342: 0x00001F06 - "\x1f\x01\x03B\x00\x00\x1f\a" + // 0x1F010342: 0x00001F07 - "\x03\x91\x03\x13\x00\x00\x1f\b" + // 0x03910313: 0x00001F08 - "\x03\x91\x03\x14\x00\x00\x1f\t" + // 0x03910314: 0x00001F09 - "\x1f\b\x03\x00\x00\x00\x1f\n" + // 0x1F080300: 0x00001F0A - "\x1f\t\x03\x00\x00\x00\x1f\v" + // 0x1F090300: 0x00001F0B - "\x1f\b\x03\x01\x00\x00\x1f\f" + // 0x1F080301: 0x00001F0C - "\x1f\t\x03\x01\x00\x00\x1f\r" + // 0x1F090301: 0x00001F0D - "\x1f\b\x03B\x00\x00\x1f\x0e" + // 0x1F080342: 0x00001F0E - "\x1f\t\x03B\x00\x00\x1f\x0f" + // 0x1F090342: 0x00001F0F - "\x03\xb5\x03\x13\x00\x00\x1f\x10" + // 0x03B50313: 0x00001F10 - "\x03\xb5\x03\x14\x00\x00\x1f\x11" + // 0x03B50314: 0x00001F11 - "\x1f\x10\x03\x00\x00\x00\x1f\x12" + // 0x1F100300: 0x00001F12 - "\x1f\x11\x03\x00\x00\x00\x1f\x13" + // 0x1F110300: 0x00001F13 - "\x1f\x10\x03\x01\x00\x00\x1f\x14" + // 0x1F100301: 0x00001F14 - "\x1f\x11\x03\x01\x00\x00\x1f\x15" + // 0x1F110301: 0x00001F15 - "\x03\x95\x03\x13\x00\x00\x1f\x18" + // 0x03950313: 0x00001F18 - "\x03\x95\x03\x14\x00\x00\x1f\x19" + // 0x03950314: 0x00001F19 - "\x1f\x18\x03\x00\x00\x00\x1f\x1a" + // 0x1F180300: 0x00001F1A - "\x1f\x19\x03\x00\x00\x00\x1f\x1b" + // 0x1F190300: 0x00001F1B - "\x1f\x18\x03\x01\x00\x00\x1f\x1c" + // 0x1F180301: 0x00001F1C - "\x1f\x19\x03\x01\x00\x00\x1f\x1d" + // 0x1F190301: 0x00001F1D - "\x03\xb7\x03\x13\x00\x00\x1f " + // 0x03B70313: 0x00001F20 - "\x03\xb7\x03\x14\x00\x00\x1f!" + // 0x03B70314: 0x00001F21 - "\x1f \x03\x00\x00\x00\x1f\"" + // 0x1F200300: 0x00001F22 - "\x1f!\x03\x00\x00\x00\x1f#" + // 0x1F210300: 0x00001F23 - "\x1f \x03\x01\x00\x00\x1f$" + // 0x1F200301: 0x00001F24 - "\x1f!\x03\x01\x00\x00\x1f%" + // 0x1F210301: 0x00001F25 - "\x1f \x03B\x00\x00\x1f&" + // 0x1F200342: 0x00001F26 - "\x1f!\x03B\x00\x00\x1f'" + // 0x1F210342: 0x00001F27 - "\x03\x97\x03\x13\x00\x00\x1f(" + // 0x03970313: 0x00001F28 - "\x03\x97\x03\x14\x00\x00\x1f)" + // 0x03970314: 0x00001F29 - "\x1f(\x03\x00\x00\x00\x1f*" + // 0x1F280300: 0x00001F2A - "\x1f)\x03\x00\x00\x00\x1f+" + // 0x1F290300: 0x00001F2B - "\x1f(\x03\x01\x00\x00\x1f," + // 0x1F280301: 0x00001F2C - "\x1f)\x03\x01\x00\x00\x1f-" + // 0x1F290301: 0x00001F2D - "\x1f(\x03B\x00\x00\x1f." + // 0x1F280342: 0x00001F2E - "\x1f)\x03B\x00\x00\x1f/" + // 0x1F290342: 0x00001F2F - "\x03\xb9\x03\x13\x00\x00\x1f0" + // 0x03B90313: 0x00001F30 - "\x03\xb9\x03\x14\x00\x00\x1f1" + // 0x03B90314: 0x00001F31 - "\x1f0\x03\x00\x00\x00\x1f2" + // 0x1F300300: 0x00001F32 - "\x1f1\x03\x00\x00\x00\x1f3" + // 0x1F310300: 0x00001F33 - "\x1f0\x03\x01\x00\x00\x1f4" + // 0x1F300301: 0x00001F34 - "\x1f1\x03\x01\x00\x00\x1f5" + // 0x1F310301: 0x00001F35 - "\x1f0\x03B\x00\x00\x1f6" + // 0x1F300342: 0x00001F36 - "\x1f1\x03B\x00\x00\x1f7" + // 0x1F310342: 0x00001F37 - "\x03\x99\x03\x13\x00\x00\x1f8" + // 0x03990313: 0x00001F38 - "\x03\x99\x03\x14\x00\x00\x1f9" + // 0x03990314: 0x00001F39 - "\x1f8\x03\x00\x00\x00\x1f:" + // 0x1F380300: 0x00001F3A - "\x1f9\x03\x00\x00\x00\x1f;" + // 0x1F390300: 0x00001F3B - "\x1f8\x03\x01\x00\x00\x1f<" + // 0x1F380301: 0x00001F3C - "\x1f9\x03\x01\x00\x00\x1f=" + // 0x1F390301: 0x00001F3D - "\x1f8\x03B\x00\x00\x1f>" + // 0x1F380342: 0x00001F3E - "\x1f9\x03B\x00\x00\x1f?" + // 0x1F390342: 0x00001F3F - "\x03\xbf\x03\x13\x00\x00\x1f@" + // 0x03BF0313: 0x00001F40 - "\x03\xbf\x03\x14\x00\x00\x1fA" + // 0x03BF0314: 0x00001F41 - "\x1f@\x03\x00\x00\x00\x1fB" + // 0x1F400300: 0x00001F42 - "\x1fA\x03\x00\x00\x00\x1fC" + // 0x1F410300: 0x00001F43 - "\x1f@\x03\x01\x00\x00\x1fD" + // 0x1F400301: 0x00001F44 - "\x1fA\x03\x01\x00\x00\x1fE" + // 0x1F410301: 0x00001F45 - "\x03\x9f\x03\x13\x00\x00\x1fH" + // 0x039F0313: 0x00001F48 - "\x03\x9f\x03\x14\x00\x00\x1fI" + // 0x039F0314: 0x00001F49 - "\x1fH\x03\x00\x00\x00\x1fJ" + // 0x1F480300: 0x00001F4A - "\x1fI\x03\x00\x00\x00\x1fK" + // 0x1F490300: 0x00001F4B - "\x1fH\x03\x01\x00\x00\x1fL" + // 0x1F480301: 0x00001F4C - "\x1fI\x03\x01\x00\x00\x1fM" + // 0x1F490301: 0x00001F4D - "\x03\xc5\x03\x13\x00\x00\x1fP" + // 0x03C50313: 0x00001F50 - "\x03\xc5\x03\x14\x00\x00\x1fQ" + // 0x03C50314: 0x00001F51 - "\x1fP\x03\x00\x00\x00\x1fR" + // 0x1F500300: 0x00001F52 - "\x1fQ\x03\x00\x00\x00\x1fS" + // 0x1F510300: 0x00001F53 - "\x1fP\x03\x01\x00\x00\x1fT" + // 0x1F500301: 0x00001F54 - "\x1fQ\x03\x01\x00\x00\x1fU" + // 0x1F510301: 0x00001F55 - "\x1fP\x03B\x00\x00\x1fV" + // 0x1F500342: 0x00001F56 - "\x1fQ\x03B\x00\x00\x1fW" + // 0x1F510342: 0x00001F57 - "\x03\xa5\x03\x14\x00\x00\x1fY" + // 0x03A50314: 0x00001F59 - "\x1fY\x03\x00\x00\x00\x1f[" + // 0x1F590300: 0x00001F5B - "\x1fY\x03\x01\x00\x00\x1f]" + // 0x1F590301: 0x00001F5D - "\x1fY\x03B\x00\x00\x1f_" + // 0x1F590342: 0x00001F5F - "\x03\xc9\x03\x13\x00\x00\x1f`" + // 0x03C90313: 0x00001F60 - "\x03\xc9\x03\x14\x00\x00\x1fa" + // 0x03C90314: 0x00001F61 - "\x1f`\x03\x00\x00\x00\x1fb" + // 0x1F600300: 0x00001F62 - "\x1fa\x03\x00\x00\x00\x1fc" + // 0x1F610300: 0x00001F63 - "\x1f`\x03\x01\x00\x00\x1fd" + // 0x1F600301: 0x00001F64 - "\x1fa\x03\x01\x00\x00\x1fe" + // 0x1F610301: 0x00001F65 - "\x1f`\x03B\x00\x00\x1ff" + // 0x1F600342: 0x00001F66 - "\x1fa\x03B\x00\x00\x1fg" + // 0x1F610342: 0x00001F67 - "\x03\xa9\x03\x13\x00\x00\x1fh" + // 0x03A90313: 0x00001F68 - "\x03\xa9\x03\x14\x00\x00\x1fi" + // 0x03A90314: 0x00001F69 - "\x1fh\x03\x00\x00\x00\x1fj" + // 0x1F680300: 0x00001F6A - "\x1fi\x03\x00\x00\x00\x1fk" + // 0x1F690300: 0x00001F6B - "\x1fh\x03\x01\x00\x00\x1fl" + // 0x1F680301: 0x00001F6C - "\x1fi\x03\x01\x00\x00\x1fm" + // 0x1F690301: 0x00001F6D - "\x1fh\x03B\x00\x00\x1fn" + // 0x1F680342: 0x00001F6E - "\x1fi\x03B\x00\x00\x1fo" + // 0x1F690342: 0x00001F6F - "\x03\xb1\x03\x00\x00\x00\x1fp" + // 0x03B10300: 0x00001F70 - "\x03\xb5\x03\x00\x00\x00\x1fr" + // 0x03B50300: 0x00001F72 - "\x03\xb7\x03\x00\x00\x00\x1ft" + // 0x03B70300: 0x00001F74 - "\x03\xb9\x03\x00\x00\x00\x1fv" + // 0x03B90300: 0x00001F76 - "\x03\xbf\x03\x00\x00\x00\x1fx" + // 0x03BF0300: 0x00001F78 - "\x03\xc5\x03\x00\x00\x00\x1fz" + // 0x03C50300: 0x00001F7A - "\x03\xc9\x03\x00\x00\x00\x1f|" + // 0x03C90300: 0x00001F7C - "\x1f\x00\x03E\x00\x00\x1f\x80" + // 0x1F000345: 0x00001F80 - "\x1f\x01\x03E\x00\x00\x1f\x81" + // 0x1F010345: 0x00001F81 - "\x1f\x02\x03E\x00\x00\x1f\x82" + // 0x1F020345: 0x00001F82 - "\x1f\x03\x03E\x00\x00\x1f\x83" + // 0x1F030345: 0x00001F83 - "\x1f\x04\x03E\x00\x00\x1f\x84" + // 0x1F040345: 0x00001F84 - "\x1f\x05\x03E\x00\x00\x1f\x85" + // 0x1F050345: 0x00001F85 - "\x1f\x06\x03E\x00\x00\x1f\x86" + // 0x1F060345: 0x00001F86 - "\x1f\a\x03E\x00\x00\x1f\x87" + // 0x1F070345: 0x00001F87 - "\x1f\b\x03E\x00\x00\x1f\x88" + // 0x1F080345: 0x00001F88 - "\x1f\t\x03E\x00\x00\x1f\x89" + // 0x1F090345: 0x00001F89 - "\x1f\n\x03E\x00\x00\x1f\x8a" + // 0x1F0A0345: 0x00001F8A - "\x1f\v\x03E\x00\x00\x1f\x8b" + // 0x1F0B0345: 0x00001F8B - "\x1f\f\x03E\x00\x00\x1f\x8c" + // 0x1F0C0345: 0x00001F8C - "\x1f\r\x03E\x00\x00\x1f\x8d" + // 0x1F0D0345: 0x00001F8D - "\x1f\x0e\x03E\x00\x00\x1f\x8e" + // 0x1F0E0345: 0x00001F8E - "\x1f\x0f\x03E\x00\x00\x1f\x8f" + // 0x1F0F0345: 0x00001F8F - "\x1f \x03E\x00\x00\x1f\x90" + // 0x1F200345: 0x00001F90 - "\x1f!\x03E\x00\x00\x1f\x91" + // 0x1F210345: 0x00001F91 - "\x1f\"\x03E\x00\x00\x1f\x92" + // 0x1F220345: 0x00001F92 - "\x1f#\x03E\x00\x00\x1f\x93" + // 0x1F230345: 0x00001F93 - "\x1f$\x03E\x00\x00\x1f\x94" + // 0x1F240345: 0x00001F94 - "\x1f%\x03E\x00\x00\x1f\x95" + // 0x1F250345: 0x00001F95 - "\x1f&\x03E\x00\x00\x1f\x96" + // 0x1F260345: 0x00001F96 - "\x1f'\x03E\x00\x00\x1f\x97" + // 0x1F270345: 0x00001F97 - "\x1f(\x03E\x00\x00\x1f\x98" + // 0x1F280345: 0x00001F98 - "\x1f)\x03E\x00\x00\x1f\x99" + // 0x1F290345: 0x00001F99 - "\x1f*\x03E\x00\x00\x1f\x9a" + // 0x1F2A0345: 0x00001F9A - "\x1f+\x03E\x00\x00\x1f\x9b" + // 0x1F2B0345: 0x00001F9B - "\x1f,\x03E\x00\x00\x1f\x9c" + // 0x1F2C0345: 0x00001F9C - "\x1f-\x03E\x00\x00\x1f\x9d" + // 0x1F2D0345: 0x00001F9D - "\x1f.\x03E\x00\x00\x1f\x9e" + // 0x1F2E0345: 0x00001F9E - "\x1f/\x03E\x00\x00\x1f\x9f" + // 0x1F2F0345: 0x00001F9F - "\x1f`\x03E\x00\x00\x1f\xa0" + // 0x1F600345: 0x00001FA0 - "\x1fa\x03E\x00\x00\x1f\xa1" + // 0x1F610345: 0x00001FA1 - "\x1fb\x03E\x00\x00\x1f\xa2" + // 0x1F620345: 0x00001FA2 - "\x1fc\x03E\x00\x00\x1f\xa3" + // 0x1F630345: 0x00001FA3 - "\x1fd\x03E\x00\x00\x1f\xa4" + // 0x1F640345: 0x00001FA4 - "\x1fe\x03E\x00\x00\x1f\xa5" + // 0x1F650345: 0x00001FA5 - "\x1ff\x03E\x00\x00\x1f\xa6" + // 0x1F660345: 0x00001FA6 - "\x1fg\x03E\x00\x00\x1f\xa7" + // 0x1F670345: 0x00001FA7 - "\x1fh\x03E\x00\x00\x1f\xa8" + // 0x1F680345: 0x00001FA8 - "\x1fi\x03E\x00\x00\x1f\xa9" + // 0x1F690345: 0x00001FA9 - "\x1fj\x03E\x00\x00\x1f\xaa" + // 0x1F6A0345: 0x00001FAA - "\x1fk\x03E\x00\x00\x1f\xab" + // 0x1F6B0345: 0x00001FAB - "\x1fl\x03E\x00\x00\x1f\xac" + // 0x1F6C0345: 0x00001FAC - "\x1fm\x03E\x00\x00\x1f\xad" + // 0x1F6D0345: 0x00001FAD - "\x1fn\x03E\x00\x00\x1f\xae" + // 0x1F6E0345: 0x00001FAE - "\x1fo\x03E\x00\x00\x1f\xaf" + // 0x1F6F0345: 0x00001FAF - "\x03\xb1\x03\x06\x00\x00\x1f\xb0" + // 0x03B10306: 0x00001FB0 - "\x03\xb1\x03\x04\x00\x00\x1f\xb1" + // 0x03B10304: 0x00001FB1 - "\x1fp\x03E\x00\x00\x1f\xb2" + // 0x1F700345: 0x00001FB2 - "\x03\xb1\x03E\x00\x00\x1f\xb3" + // 0x03B10345: 0x00001FB3 - "\x03\xac\x03E\x00\x00\x1f\xb4" + // 0x03AC0345: 0x00001FB4 - "\x03\xb1\x03B\x00\x00\x1f\xb6" + // 0x03B10342: 0x00001FB6 - "\x1f\xb6\x03E\x00\x00\x1f\xb7" + // 0x1FB60345: 0x00001FB7 - "\x03\x91\x03\x06\x00\x00\x1f\xb8" + // 0x03910306: 0x00001FB8 - "\x03\x91\x03\x04\x00\x00\x1f\xb9" + // 0x03910304: 0x00001FB9 - "\x03\x91\x03\x00\x00\x00\x1f\xba" + // 0x03910300: 0x00001FBA - "\x03\x91\x03E\x00\x00\x1f\xbc" + // 0x03910345: 0x00001FBC - "\x00\xa8\x03B\x00\x00\x1f\xc1" + // 0x00A80342: 0x00001FC1 - "\x1ft\x03E\x00\x00\x1f\xc2" + // 0x1F740345: 0x00001FC2 - "\x03\xb7\x03E\x00\x00\x1f\xc3" + // 0x03B70345: 0x00001FC3 - "\x03\xae\x03E\x00\x00\x1f\xc4" + // 0x03AE0345: 0x00001FC4 - "\x03\xb7\x03B\x00\x00\x1f\xc6" + // 0x03B70342: 0x00001FC6 - "\x1f\xc6\x03E\x00\x00\x1f\xc7" + // 0x1FC60345: 0x00001FC7 - "\x03\x95\x03\x00\x00\x00\x1f\xc8" + // 0x03950300: 0x00001FC8 - "\x03\x97\x03\x00\x00\x00\x1f\xca" + // 0x03970300: 0x00001FCA - "\x03\x97\x03E\x00\x00\x1f\xcc" + // 0x03970345: 0x00001FCC - "\x1f\xbf\x03\x00\x00\x00\x1f\xcd" + // 0x1FBF0300: 0x00001FCD - "\x1f\xbf\x03\x01\x00\x00\x1f\xce" + // 0x1FBF0301: 0x00001FCE - "\x1f\xbf\x03B\x00\x00\x1f\xcf" + // 0x1FBF0342: 0x00001FCF - "\x03\xb9\x03\x06\x00\x00\x1f\xd0" + // 0x03B90306: 0x00001FD0 - "\x03\xb9\x03\x04\x00\x00\x1f\xd1" + // 0x03B90304: 0x00001FD1 - "\x03\xca\x03\x00\x00\x00\x1f\xd2" + // 0x03CA0300: 0x00001FD2 - "\x03\xb9\x03B\x00\x00\x1f\xd6" + // 0x03B90342: 0x00001FD6 - "\x03\xca\x03B\x00\x00\x1f\xd7" + // 0x03CA0342: 0x00001FD7 - "\x03\x99\x03\x06\x00\x00\x1f\xd8" + // 0x03990306: 0x00001FD8 - "\x03\x99\x03\x04\x00\x00\x1f\xd9" + // 0x03990304: 0x00001FD9 - "\x03\x99\x03\x00\x00\x00\x1f\xda" + // 0x03990300: 0x00001FDA - "\x1f\xfe\x03\x00\x00\x00\x1f\xdd" + // 0x1FFE0300: 0x00001FDD - "\x1f\xfe\x03\x01\x00\x00\x1f\xde" + // 0x1FFE0301: 0x00001FDE - "\x1f\xfe\x03B\x00\x00\x1f\xdf" + // 0x1FFE0342: 0x00001FDF - "\x03\xc5\x03\x06\x00\x00\x1f\xe0" + // 0x03C50306: 0x00001FE0 - "\x03\xc5\x03\x04\x00\x00\x1f\xe1" + // 0x03C50304: 0x00001FE1 - "\x03\xcb\x03\x00\x00\x00\x1f\xe2" + // 0x03CB0300: 0x00001FE2 - "\x03\xc1\x03\x13\x00\x00\x1f\xe4" + // 0x03C10313: 0x00001FE4 - "\x03\xc1\x03\x14\x00\x00\x1f\xe5" + // 0x03C10314: 0x00001FE5 - "\x03\xc5\x03B\x00\x00\x1f\xe6" + // 0x03C50342: 0x00001FE6 - "\x03\xcb\x03B\x00\x00\x1f\xe7" + // 0x03CB0342: 0x00001FE7 - "\x03\xa5\x03\x06\x00\x00\x1f\xe8" + // 0x03A50306: 0x00001FE8 - "\x03\xa5\x03\x04\x00\x00\x1f\xe9" + // 0x03A50304: 0x00001FE9 - "\x03\xa5\x03\x00\x00\x00\x1f\xea" + // 0x03A50300: 0x00001FEA - "\x03\xa1\x03\x14\x00\x00\x1f\xec" + // 0x03A10314: 0x00001FEC - "\x00\xa8\x03\x00\x00\x00\x1f\xed" + // 0x00A80300: 0x00001FED - "\x1f|\x03E\x00\x00\x1f\xf2" + // 0x1F7C0345: 0x00001FF2 - "\x03\xc9\x03E\x00\x00\x1f\xf3" + // 0x03C90345: 0x00001FF3 - "\x03\xce\x03E\x00\x00\x1f\xf4" + // 0x03CE0345: 0x00001FF4 - "\x03\xc9\x03B\x00\x00\x1f\xf6" + // 0x03C90342: 0x00001FF6 - "\x1f\xf6\x03E\x00\x00\x1f\xf7" + // 0x1FF60345: 0x00001FF7 - "\x03\x9f\x03\x00\x00\x00\x1f\xf8" + // 0x039F0300: 0x00001FF8 - "\x03\xa9\x03\x00\x00\x00\x1f\xfa" + // 0x03A90300: 0x00001FFA - "\x03\xa9\x03E\x00\x00\x1f\xfc" + // 0x03A90345: 0x00001FFC - "!\x90\x038\x00\x00!\x9a" + // 0x21900338: 0x0000219A - "!\x92\x038\x00\x00!\x9b" + // 0x21920338: 0x0000219B - "!\x94\x038\x00\x00!\xae" + // 0x21940338: 0x000021AE - "!\xd0\x038\x00\x00!\xcd" + // 0x21D00338: 0x000021CD - "!\xd4\x038\x00\x00!\xce" + // 0x21D40338: 0x000021CE - "!\xd2\x038\x00\x00!\xcf" + // 0x21D20338: 0x000021CF - "\"\x03\x038\x00\x00\"\x04" + // 0x22030338: 0x00002204 - "\"\b\x038\x00\x00\"\t" + // 0x22080338: 0x00002209 - "\"\v\x038\x00\x00\"\f" + // 0x220B0338: 0x0000220C - "\"#\x038\x00\x00\"$" + // 0x22230338: 0x00002224 - "\"%\x038\x00\x00\"&" + // 0x22250338: 0x00002226 - "\"<\x038\x00\x00\"A" + // 0x223C0338: 0x00002241 - "\"C\x038\x00\x00\"D" + // 0x22430338: 0x00002244 - "\"E\x038\x00\x00\"G" + // 0x22450338: 0x00002247 - "\"H\x038\x00\x00\"I" + // 0x22480338: 0x00002249 - "\x00=\x038\x00\x00\"`" + // 0x003D0338: 0x00002260 - "\"a\x038\x00\x00\"b" + // 0x22610338: 0x00002262 - "\"M\x038\x00\x00\"m" + // 0x224D0338: 0x0000226D - "\x00<\x038\x00\x00\"n" + // 0x003C0338: 0x0000226E - "\x00>\x038\x00\x00\"o" + // 0x003E0338: 0x0000226F - "\"d\x038\x00\x00\"p" + // 0x22640338: 0x00002270 - "\"e\x038\x00\x00\"q" + // 0x22650338: 0x00002271 - "\"r\x038\x00\x00\"t" + // 0x22720338: 0x00002274 - "\"s\x038\x00\x00\"u" + // 0x22730338: 0x00002275 - "\"v\x038\x00\x00\"x" + // 0x22760338: 0x00002278 - "\"w\x038\x00\x00\"y" + // 0x22770338: 0x00002279 - "\"z\x038\x00\x00\"\x80" + // 0x227A0338: 0x00002280 - "\"{\x038\x00\x00\"\x81" + // 0x227B0338: 0x00002281 - "\"\x82\x038\x00\x00\"\x84" + // 0x22820338: 0x00002284 - "\"\x83\x038\x00\x00\"\x85" + // 0x22830338: 0x00002285 - "\"\x86\x038\x00\x00\"\x88" + // 0x22860338: 0x00002288 - "\"\x87\x038\x00\x00\"\x89" + // 0x22870338: 0x00002289 - "\"\xa2\x038\x00\x00\"\xac" + // 0x22A20338: 0x000022AC - "\"\xa8\x038\x00\x00\"\xad" + // 0x22A80338: 0x000022AD - "\"\xa9\x038\x00\x00\"\xae" + // 0x22A90338: 0x000022AE - "\"\xab\x038\x00\x00\"\xaf" + // 0x22AB0338: 0x000022AF - "\"|\x038\x00\x00\"\xe0" + // 0x227C0338: 0x000022E0 - "\"}\x038\x00\x00\"\xe1" + // 0x227D0338: 0x000022E1 - "\"\x91\x038\x00\x00\"\xe2" + // 0x22910338: 0x000022E2 - "\"\x92\x038\x00\x00\"\xe3" + // 0x22920338: 0x000022E3 - "\"\xb2\x038\x00\x00\"\xea" + // 0x22B20338: 0x000022EA - "\"\xb3\x038\x00\x00\"\xeb" + // 0x22B30338: 0x000022EB - "\"\xb4\x038\x00\x00\"\xec" + // 0x22B40338: 0x000022EC - "\"\xb5\x038\x00\x00\"\xed" + // 0x22B50338: 0x000022ED - "0K0\x99\x00\x000L" + // 0x304B3099: 0x0000304C - "0M0\x99\x00\x000N" + // 0x304D3099: 0x0000304E - "0O0\x99\x00\x000P" + // 0x304F3099: 0x00003050 - "0Q0\x99\x00\x000R" + // 0x30513099: 0x00003052 - "0S0\x99\x00\x000T" + // 0x30533099: 0x00003054 - "0U0\x99\x00\x000V" + // 0x30553099: 0x00003056 - "0W0\x99\x00\x000X" + // 0x30573099: 0x00003058 - "0Y0\x99\x00\x000Z" + // 0x30593099: 0x0000305A - "0[0\x99\x00\x000\\" + // 0x305B3099: 0x0000305C - "0]0\x99\x00\x000^" + // 0x305D3099: 0x0000305E - "0_0\x99\x00\x000`" + // 0x305F3099: 0x00003060 - "0a0\x99\x00\x000b" + // 0x30613099: 0x00003062 - "0d0\x99\x00\x000e" + // 0x30643099: 0x00003065 - "0f0\x99\x00\x000g" + // 0x30663099: 0x00003067 - "0h0\x99\x00\x000i" + // 0x30683099: 0x00003069 - "0o0\x99\x00\x000p" + // 0x306F3099: 0x00003070 - "0o0\x9a\x00\x000q" + // 0x306F309A: 0x00003071 - "0r0\x99\x00\x000s" + // 0x30723099: 0x00003073 - "0r0\x9a\x00\x000t" + // 0x3072309A: 0x00003074 - "0u0\x99\x00\x000v" + // 0x30753099: 0x00003076 - "0u0\x9a\x00\x000w" + // 0x3075309A: 0x00003077 - "0x0\x99\x00\x000y" + // 0x30783099: 0x00003079 - "0x0\x9a\x00\x000z" + // 0x3078309A: 0x0000307A - "0{0\x99\x00\x000|" + // 0x307B3099: 0x0000307C - "0{0\x9a\x00\x000}" + // 0x307B309A: 0x0000307D - "0F0\x99\x00\x000\x94" + // 0x30463099: 0x00003094 - "0\x9d0\x99\x00\x000\x9e" + // 0x309D3099: 0x0000309E - "0\xab0\x99\x00\x000\xac" + // 0x30AB3099: 0x000030AC - "0\xad0\x99\x00\x000\xae" + // 0x30AD3099: 0x000030AE - "0\xaf0\x99\x00\x000\xb0" + // 0x30AF3099: 0x000030B0 - "0\xb10\x99\x00\x000\xb2" + // 0x30B13099: 0x000030B2 - "0\xb30\x99\x00\x000\xb4" + // 0x30B33099: 0x000030B4 - "0\xb50\x99\x00\x000\xb6" + // 0x30B53099: 0x000030B6 - "0\xb70\x99\x00\x000\xb8" + // 0x30B73099: 0x000030B8 - "0\xb90\x99\x00\x000\xba" + // 0x30B93099: 0x000030BA - "0\xbb0\x99\x00\x000\xbc" + // 0x30BB3099: 0x000030BC - "0\xbd0\x99\x00\x000\xbe" + // 0x30BD3099: 0x000030BE - "0\xbf0\x99\x00\x000\xc0" + // 0x30BF3099: 0x000030C0 - "0\xc10\x99\x00\x000\xc2" + // 0x30C13099: 0x000030C2 - "0\xc40\x99\x00\x000\xc5" + // 0x30C43099: 0x000030C5 - "0\xc60\x99\x00\x000\xc7" + // 0x30C63099: 0x000030C7 - "0\xc80\x99\x00\x000\xc9" + // 0x30C83099: 0x000030C9 - "0\xcf0\x99\x00\x000\xd0" + // 0x30CF3099: 0x000030D0 - "0\xcf0\x9a\x00\x000\xd1" + // 0x30CF309A: 0x000030D1 - "0\xd20\x99\x00\x000\xd3" + // 0x30D23099: 0x000030D3 - "0\xd20\x9a\x00\x000\xd4" + // 0x30D2309A: 0x000030D4 - "0\xd50\x99\x00\x000\xd6" + // 0x30D53099: 0x000030D6 - "0\xd50\x9a\x00\x000\xd7" + // 0x30D5309A: 0x000030D7 - "0\xd80\x99\x00\x000\xd9" + // 0x30D83099: 0x000030D9 - "0\xd80\x9a\x00\x000\xda" + // 0x30D8309A: 0x000030DA - "0\xdb0\x99\x00\x000\xdc" + // 0x30DB3099: 0x000030DC - "0\xdb0\x9a\x00\x000\xdd" + // 0x30DB309A: 0x000030DD - "0\xa60\x99\x00\x000\xf4" + // 0x30A63099: 0x000030F4 - "0\xef0\x99\x00\x000\xf7" + // 0x30EF3099: 0x000030F7 - "0\xf00\x99\x00\x000\xf8" + // 0x30F03099: 0x000030F8 - "0\xf10\x99\x00\x000\xf9" + // 0x30F13099: 0x000030F9 - "0\xf20\x99\x00\x000\xfa" + // 0x30F23099: 0x000030FA - "0\xfd0\x99\x00\x000\xfe" + // 0x30FD3099: 0x000030FE - "\x05\xd2\x03\a\x00\x01\x05\xc9" + // 0x05D20307: 0x000105C9 - "\x05\xda\x03\a\x00\x01\x05\xe4" + // 0x05DA0307: 0x000105E4 - "\x10\x99\x10\xba\x00\x01\x10\x9a" + // 0x109910BA: 0x0001109A - "\x10\x9b\x10\xba\x00\x01\x10\x9c" + // 0x109B10BA: 0x0001109C - "\x10\xa5\x10\xba\x00\x01\x10\xab" + // 0x10A510BA: 0x000110AB - "\x111\x11'\x00\x01\x11." + // 0x11311127: 0x0001112E - "\x112\x11'\x00\x01\x11/" + // 0x11321127: 0x0001112F - "\x13G\x13>\x00\x01\x13K" + // 0x1347133E: 0x0001134B - "\x13G\x13W\x00\x01\x13L" + // 0x13471357: 0x0001134C - "\x13\x82\x13\xc9\x00\x01\x13\x83" + // 0x138213C9: 0x00011383 - "\x13\x84\x13\xbb\x00\x01\x13\x85" + // 0x138413BB: 0x00011385 - "\x13\x8b\x13\xc2\x00\x01\x13\x8e" + // 0x138B13C2: 0x0001138E - "\x13\x90\x13\xc9\x00\x01\x13\x91" + // 0x139013C9: 0x00011391 - "\x13\xc2\x13\xc2\x00\x01\x13\xc5" + // 0x13C213C2: 0x000113C5 - "\x13\xc2\x13\xb8\x00\x01\x13\xc7" + // 0x13C213B8: 0x000113C7 - "\x13\xc2\x13\xc9\x00\x01\x13\xc8" + // 0x13C213C9: 0x000113C8 - "\x14\xb9\x14\xba\x00\x01\x14\xbb" + // 0x14B914BA: 0x000114BB - "\x14\xb9\x14\xb0\x00\x01\x14\xbc" + // 0x14B914B0: 0x000114BC - "\x14\xb9\x14\xbd\x00\x01\x14\xbe" + // 0x14B914BD: 0x000114BE - "\x15\xb8\x15\xaf\x00\x01\x15\xba" + // 0x15B815AF: 0x000115BA - "\x15\xb9\x15\xaf\x00\x01\x15\xbb" + // 0x15B915AF: 0x000115BB - "\x195\x190\x00\x01\x198" + // 0x19351930: 0x00011938 - "a\x1ea\x1e\x00\x01a!" + // 0x611E611E: 0x00016121 - "a\x1ea)\x00\x01a\"" + // 0x611E6129: 0x00016122 - "a\x1ea\x1f\x00\x01a#" + // 0x611E611F: 0x00016123 - "a)a\x1f\x00\x01a$" + // 0x6129611F: 0x00016124 - "a\x1ea \x00\x01a%" + // 0x611E6120: 0x00016125 - "a!a\x1f\x00\x01a&" + // 0x6121611F: 0x00016126 - "a\"a\x1f\x00\x01a'" + // 0x6122611F: 0x00016127 - "a!a \x00\x01a(" + // 0x61216120: 0x00016128 - "mgmg\x00\x01mh" + // 0x6D676D67: 0x00016D68 - "mcmg\x00\x01mi" + // 0x6D636D67: 0x00016D69 - "mimg\x00\x01mj" + // 0x6D696D67: 0x00016D6A + "\x00\x01\x04\x00`\x00\x00\xc0" + // 0x00041 0x00300: 0x000C0 + "\x00\x01\x04\x00` \x00\xc1" + // 0x00041 0x00301: 0x000C1 + "\x00\x01\x04\x00`@\x00\xc2" + // 0x00041 0x00302: 0x000C2 + "\x00\x01\x04\x00``\x00\xc3" + // 0x00041 0x00303: 0x000C3 + "\x00\x01\x04\x00a\x00\x00\xc4" + // 0x00041 0x00308: 0x000C4 + "\x00\x01\x04\x00a@\x00\xc5" + // 0x00041 0x0030A: 0x000C5 + "\x00\x01\f\x00d\xe0\x00\xc7" + // 0x00043 0x00327: 0x000C7 + "\x00\x01\x14\x00`\x00\x00\xc8" + // 0x00045 0x00300: 0x000C8 + "\x00\x01\x14\x00` \x00\xc9" + // 0x00045 0x00301: 0x000C9 + "\x00\x01\x14\x00`@\x00\xca" + // 0x00045 0x00302: 0x000CA + "\x00\x01\x14\x00a\x00\x00\xcb" + // 0x00045 0x00308: 0x000CB + "\x00\x01$\x00`\x00\x00\xcc" + // 0x00049 0x00300: 0x000CC + "\x00\x01$\x00` \x00\xcd" + // 0x00049 0x00301: 0x000CD + "\x00\x01$\x00`@\x00\xce" + // 0x00049 0x00302: 0x000CE + "\x00\x01$\x00a\x00\x00\xcf" + // 0x00049 0x00308: 0x000CF + "\x00\x018\x00``\x00\xd1" + // 0x0004E 0x00303: 0x000D1 + "\x00\x01<\x00`\x00\x00\xd2" + // 0x0004F 0x00300: 0x000D2 + "\x00\x01<\x00` \x00\xd3" + // 0x0004F 0x00301: 0x000D3 + "\x00\x01<\x00`@\x00\xd4" + // 0x0004F 0x00302: 0x000D4 + "\x00\x01<\x00``\x00\xd5" + // 0x0004F 0x00303: 0x000D5 + "\x00\x01<\x00a\x00\x00\xd6" + // 0x0004F 0x00308: 0x000D6 + "\x00\x01T\x00`\x00\x00\xd9" + // 0x00055 0x00300: 0x000D9 + "\x00\x01T\x00` \x00\xda" + // 0x00055 0x00301: 0x000DA + "\x00\x01T\x00`@\x00\xdb" + // 0x00055 0x00302: 0x000DB + "\x00\x01T\x00a\x00\x00\xdc" + // 0x00055 0x00308: 0x000DC + "\x00\x01d\x00` \x00\xdd" + // 0x00059 0x00301: 0x000DD + "\x00\x01\x84\x00`\x00\x00\xe0" + // 0x00061 0x00300: 0x000E0 + "\x00\x01\x84\x00` \x00\xe1" + // 0x00061 0x00301: 0x000E1 + "\x00\x01\x84\x00`@\x00\xe2" + // 0x00061 0x00302: 0x000E2 + "\x00\x01\x84\x00``\x00\xe3" + // 0x00061 0x00303: 0x000E3 + "\x00\x01\x84\x00a\x00\x00\xe4" + // 0x00061 0x00308: 0x000E4 + "\x00\x01\x84\x00a@\x00\xe5" + // 0x00061 0x0030A: 0x000E5 + "\x00\x01\x8c\x00d\xe0\x00\xe7" + // 0x00063 0x00327: 0x000E7 + "\x00\x01\x94\x00`\x00\x00\xe8" + // 0x00065 0x00300: 0x000E8 + "\x00\x01\x94\x00` \x00\xe9" + // 0x00065 0x00301: 0x000E9 + "\x00\x01\x94\x00`@\x00\xea" + // 0x00065 0x00302: 0x000EA + "\x00\x01\x94\x00a\x00\x00\xeb" + // 0x00065 0x00308: 0x000EB + "\x00\x01\xa4\x00`\x00\x00\xec" + // 0x00069 0x00300: 0x000EC + "\x00\x01\xa4\x00` \x00\xed" + // 0x00069 0x00301: 0x000ED + "\x00\x01\xa4\x00`@\x00\xee" + // 0x00069 0x00302: 0x000EE + "\x00\x01\xa4\x00a\x00\x00\xef" + // 0x00069 0x00308: 0x000EF + "\x00\x01\xb8\x00``\x00\xf1" + // 0x0006E 0x00303: 0x000F1 + "\x00\x01\xbc\x00`\x00\x00\xf2" + // 0x0006F 0x00300: 0x000F2 + "\x00\x01\xbc\x00` \x00\xf3" + // 0x0006F 0x00301: 0x000F3 + "\x00\x01\xbc\x00`@\x00\xf4" + // 0x0006F 0x00302: 0x000F4 + "\x00\x01\xbc\x00``\x00\xf5" + // 0x0006F 0x00303: 0x000F5 + "\x00\x01\xbc\x00a\x00\x00\xf6" + // 0x0006F 0x00308: 0x000F6 + "\x00\x01\xd4\x00`\x00\x00\xf9" + // 0x00075 0x00300: 0x000F9 + "\x00\x01\xd4\x00` \x00\xfa" + // 0x00075 0x00301: 0x000FA + "\x00\x01\xd4\x00`@\x00\xfb" + // 0x00075 0x00302: 0x000FB + "\x00\x01\xd4\x00a\x00\x00\xfc" + // 0x00075 0x00308: 0x000FC + "\x00\x01\xe4\x00` \x00\xfd" + // 0x00079 0x00301: 0x000FD + "\x00\x01\xe4\x00a\x00\x00\xff" + // 0x00079 0x00308: 0x000FF + "\x00\x01\x04\x00`\x80\x01\x00" + // 0x00041 0x00304: 0x00100 + "\x00\x01\x84\x00`\x80\x01\x01" + // 0x00061 0x00304: 0x00101 + "\x00\x01\x04\x00`\xc0\x01\x02" + // 0x00041 0x00306: 0x00102 + "\x00\x01\x84\x00`\xc0\x01\x03" + // 0x00061 0x00306: 0x00103 + "\x00\x01\x04\x00e\x00\x01\x04" + // 0x00041 0x00328: 0x00104 + "\x00\x01\x84\x00e\x00\x01\x05" + // 0x00061 0x00328: 0x00105 + "\x00\x01\f\x00` \x01\x06" + // 0x00043 0x00301: 0x00106 + "\x00\x01\x8c\x00` \x01\a" + // 0x00063 0x00301: 0x00107 + "\x00\x01\f\x00`@\x01\b" + // 0x00043 0x00302: 0x00108 + "\x00\x01\x8c\x00`@\x01\t" + // 0x00063 0x00302: 0x00109 + "\x00\x01\f\x00`\xe0\x01\n" + // 0x00043 0x00307: 0x0010A + "\x00\x01\x8c\x00`\xe0\x01\v" + // 0x00063 0x00307: 0x0010B + "\x00\x01\f\x00a\x80\x01\f" + // 0x00043 0x0030C: 0x0010C + "\x00\x01\x8c\x00a\x80\x01\r" + // 0x00063 0x0030C: 0x0010D + "\x00\x01\x10\x00a\x80\x01\x0e" + // 0x00044 0x0030C: 0x0010E + "\x00\x01\x90\x00a\x80\x01\x0f" + // 0x00064 0x0030C: 0x0010F + "\x00\x01\x14\x00`\x80\x01\x12" + // 0x00045 0x00304: 0x00112 + "\x00\x01\x94\x00`\x80\x01\x13" + // 0x00065 0x00304: 0x00113 + "\x00\x01\x14\x00`\xc0\x01\x14" + // 0x00045 0x00306: 0x00114 + "\x00\x01\x94\x00`\xc0\x01\x15" + // 0x00065 0x00306: 0x00115 + "\x00\x01\x14\x00`\xe0\x01\x16" + // 0x00045 0x00307: 0x00116 + "\x00\x01\x94\x00`\xe0\x01\x17" + // 0x00065 0x00307: 0x00117 + "\x00\x01\x14\x00e\x00\x01\x18" + // 0x00045 0x00328: 0x00118 + "\x00\x01\x94\x00e\x00\x01\x19" + // 0x00065 0x00328: 0x00119 + "\x00\x01\x14\x00a\x80\x01\x1a" + // 0x00045 0x0030C: 0x0011A + "\x00\x01\x94\x00a\x80\x01\x1b" + // 0x00065 0x0030C: 0x0011B + "\x00\x01\x1c\x00`@\x01\x1c" + // 0x00047 0x00302: 0x0011C + "\x00\x01\x9c\x00`@\x01\x1d" + // 0x00067 0x00302: 0x0011D + "\x00\x01\x1c\x00`\xc0\x01\x1e" + // 0x00047 0x00306: 0x0011E + "\x00\x01\x9c\x00`\xc0\x01\x1f" + // 0x00067 0x00306: 0x0011F + "\x00\x01\x1c\x00`\xe0\x01 " + // 0x00047 0x00307: 0x00120 + "\x00\x01\x9c\x00`\xe0\x01!" + // 0x00067 0x00307: 0x00121 + "\x00\x01\x1c\x00d\xe0\x01\"" + // 0x00047 0x00327: 0x00122 + "\x00\x01\x9c\x00d\xe0\x01#" + // 0x00067 0x00327: 0x00123 + "\x00\x01 \x00`@\x01$" + // 0x00048 0x00302: 0x00124 + "\x00\x01\xa0\x00`@\x01%" + // 0x00068 0x00302: 0x00125 + "\x00\x01$\x00``\x01(" + // 0x00049 0x00303: 0x00128 + "\x00\x01\xa4\x00``\x01)" + // 0x00069 0x00303: 0x00129 + "\x00\x01$\x00`\x80\x01*" + // 0x00049 0x00304: 0x0012A + "\x00\x01\xa4\x00`\x80\x01+" + // 0x00069 0x00304: 0x0012B + "\x00\x01$\x00`\xc0\x01," + // 0x00049 0x00306: 0x0012C + "\x00\x01\xa4\x00`\xc0\x01-" + // 0x00069 0x00306: 0x0012D + "\x00\x01$\x00e\x00\x01." + // 0x00049 0x00328: 0x0012E + "\x00\x01\xa4\x00e\x00\x01/" + // 0x00069 0x00328: 0x0012F + "\x00\x01$\x00`\xe0\x010" + // 0x00049 0x00307: 0x00130 + "\x00\x01(\x00`@\x014" + // 0x0004A 0x00302: 0x00134 + "\x00\x01\xa8\x00`@\x015" + // 0x0006A 0x00302: 0x00135 + "\x00\x01,\x00d\xe0\x016" + // 0x0004B 0x00327: 0x00136 + "\x00\x01\xac\x00d\xe0\x017" + // 0x0006B 0x00327: 0x00137 + "\x00\x010\x00` \x019" + // 0x0004C 0x00301: 0x00139 + "\x00\x01\xb0\x00` \x01:" + // 0x0006C 0x00301: 0x0013A + "\x00\x010\x00d\xe0\x01;" + // 0x0004C 0x00327: 0x0013B + "\x00\x01\xb0\x00d\xe0\x01<" + // 0x0006C 0x00327: 0x0013C + "\x00\x010\x00a\x80\x01=" + // 0x0004C 0x0030C: 0x0013D + "\x00\x01\xb0\x00a\x80\x01>" + // 0x0006C 0x0030C: 0x0013E + "\x00\x018\x00` \x01C" + // 0x0004E 0x00301: 0x00143 + "\x00\x01\xb8\x00` \x01D" + // 0x0006E 0x00301: 0x00144 + "\x00\x018\x00d\xe0\x01E" + // 0x0004E 0x00327: 0x00145 + "\x00\x01\xb8\x00d\xe0\x01F" + // 0x0006E 0x00327: 0x00146 + "\x00\x018\x00a\x80\x01G" + // 0x0004E 0x0030C: 0x00147 + "\x00\x01\xb8\x00a\x80\x01H" + // 0x0006E 0x0030C: 0x00148 + "\x00\x01<\x00`\x80\x01L" + // 0x0004F 0x00304: 0x0014C + "\x00\x01\xbc\x00`\x80\x01M" + // 0x0006F 0x00304: 0x0014D + "\x00\x01<\x00`\xc0\x01N" + // 0x0004F 0x00306: 0x0014E + "\x00\x01\xbc\x00`\xc0\x01O" + // 0x0006F 0x00306: 0x0014F + "\x00\x01<\x00a`\x01P" + // 0x0004F 0x0030B: 0x00150 + "\x00\x01\xbc\x00a`\x01Q" + // 0x0006F 0x0030B: 0x00151 + "\x00\x01H\x00` \x01T" + // 0x00052 0x00301: 0x00154 + "\x00\x01\xc8\x00` \x01U" + // 0x00072 0x00301: 0x00155 + "\x00\x01H\x00d\xe0\x01V" + // 0x00052 0x00327: 0x00156 + "\x00\x01\xc8\x00d\xe0\x01W" + // 0x00072 0x00327: 0x00157 + "\x00\x01H\x00a\x80\x01X" + // 0x00052 0x0030C: 0x00158 + "\x00\x01\xc8\x00a\x80\x01Y" + // 0x00072 0x0030C: 0x00159 + "\x00\x01L\x00` \x01Z" + // 0x00053 0x00301: 0x0015A + "\x00\x01\xcc\x00` \x01[" + // 0x00073 0x00301: 0x0015B + "\x00\x01L\x00`@\x01\\" + // 0x00053 0x00302: 0x0015C + "\x00\x01\xcc\x00`@\x01]" + // 0x00073 0x00302: 0x0015D + "\x00\x01L\x00d\xe0\x01^" + // 0x00053 0x00327: 0x0015E + "\x00\x01\xcc\x00d\xe0\x01_" + // 0x00073 0x00327: 0x0015F + "\x00\x01L\x00a\x80\x01`" + // 0x00053 0x0030C: 0x00160 + "\x00\x01\xcc\x00a\x80\x01a" + // 0x00073 0x0030C: 0x00161 + "\x00\x01P\x00d\xe0\x01b" + // 0x00054 0x00327: 0x00162 + "\x00\x01\xd0\x00d\xe0\x01c" + // 0x00074 0x00327: 0x00163 + "\x00\x01P\x00a\x80\x01d" + // 0x00054 0x0030C: 0x00164 + "\x00\x01\xd0\x00a\x80\x01e" + // 0x00074 0x0030C: 0x00165 + "\x00\x01T\x00``\x01h" + // 0x00055 0x00303: 0x00168 + "\x00\x01\xd4\x00``\x01i" + // 0x00075 0x00303: 0x00169 + "\x00\x01T\x00`\x80\x01j" + // 0x00055 0x00304: 0x0016A + "\x00\x01\xd4\x00`\x80\x01k" + // 0x00075 0x00304: 0x0016B + "\x00\x01T\x00`\xc0\x01l" + // 0x00055 0x00306: 0x0016C + "\x00\x01\xd4\x00`\xc0\x01m" + // 0x00075 0x00306: 0x0016D + "\x00\x01T\x00a@\x01n" + // 0x00055 0x0030A: 0x0016E + "\x00\x01\xd4\x00a@\x01o" + // 0x00075 0x0030A: 0x0016F + "\x00\x01T\x00a`\x01p" + // 0x00055 0x0030B: 0x00170 + "\x00\x01\xd4\x00a`\x01q" + // 0x00075 0x0030B: 0x00171 + "\x00\x01T\x00e\x00\x01r" + // 0x00055 0x00328: 0x00172 + "\x00\x01\xd4\x00e\x00\x01s" + // 0x00075 0x00328: 0x00173 + "\x00\x01\\\x00`@\x01t" + // 0x00057 0x00302: 0x00174 + "\x00\x01\xdc\x00`@\x01u" + // 0x00077 0x00302: 0x00175 + "\x00\x01d\x00`@\x01v" + // 0x00059 0x00302: 0x00176 + "\x00\x01\xe4\x00`@\x01w" + // 0x00079 0x00302: 0x00177 + "\x00\x01d\x00a\x00\x01x" + // 0x00059 0x00308: 0x00178 + "\x00\x01h\x00` \x01y" + // 0x0005A 0x00301: 0x00179 + "\x00\x01\xe8\x00` \x01z" + // 0x0007A 0x00301: 0x0017A + "\x00\x01h\x00`\xe0\x01{" + // 0x0005A 0x00307: 0x0017B + "\x00\x01\xe8\x00`\xe0\x01|" + // 0x0007A 0x00307: 0x0017C + "\x00\x01h\x00a\x80\x01}" + // 0x0005A 0x0030C: 0x0017D + "\x00\x01\xe8\x00a\x80\x01~" + // 0x0007A 0x0030C: 0x0017E + "\x00\x01<\x00c`\x01\xa0" + // 0x0004F 0x0031B: 0x001A0 + "\x00\x01\xbc\x00c`\x01\xa1" + // 0x0006F 0x0031B: 0x001A1 + "\x00\x01T\x00c`\x01\xaf" + // 0x00055 0x0031B: 0x001AF + "\x00\x01\xd4\x00c`\x01\xb0" + // 0x00075 0x0031B: 0x001B0 + "\x00\x01\x04\x00a\x80\x01\xcd" + // 0x00041 0x0030C: 0x001CD + "\x00\x01\x84\x00a\x80\x01\xce" + // 0x00061 0x0030C: 0x001CE + "\x00\x01$\x00a\x80\x01\xcf" + // 0x00049 0x0030C: 0x001CF + "\x00\x01\xa4\x00a\x80\x01\xd0" + // 0x00069 0x0030C: 0x001D0 + "\x00\x01<\x00a\x80\x01\xd1" + // 0x0004F 0x0030C: 0x001D1 + "\x00\x01\xbc\x00a\x80\x01\xd2" + // 0x0006F 0x0030C: 0x001D2 + "\x00\x01T\x00a\x80\x01\xd3" + // 0x00055 0x0030C: 0x001D3 + "\x00\x01\xd4\x00a\x80\x01\xd4" + // 0x00075 0x0030C: 0x001D4 + "\x00\x03p\x00`\x80\x01\xd5" + // 0x000DC 0x00304: 0x001D5 + "\x00\x03\xf0\x00`\x80\x01\xd6" + // 0x000FC 0x00304: 0x001D6 + "\x00\x03p\x00` \x01\xd7" + // 0x000DC 0x00301: 0x001D7 + "\x00\x03\xf0\x00` \x01\xd8" + // 0x000FC 0x00301: 0x001D8 + "\x00\x03p\x00a\x80\x01\xd9" + // 0x000DC 0x0030C: 0x001D9 + "\x00\x03\xf0\x00a\x80\x01\xda" + // 0x000FC 0x0030C: 0x001DA + "\x00\x03p\x00`\x00\x01\xdb" + // 0x000DC 0x00300: 0x001DB + "\x00\x03\xf0\x00`\x00\x01\xdc" + // 0x000FC 0x00300: 0x001DC + "\x00\x03\x10\x00`\x80\x01\xde" + // 0x000C4 0x00304: 0x001DE + "\x00\x03\x90\x00`\x80\x01\xdf" + // 0x000E4 0x00304: 0x001DF + "\x00\b\x98\x00`\x80\x01\xe0" + // 0x00226 0x00304: 0x001E0 + "\x00\b\x9c\x00`\x80\x01\xe1" + // 0x00227 0x00304: 0x001E1 + "\x00\x03\x18\x00`\x80\x01\xe2" + // 0x000C6 0x00304: 0x001E2 + "\x00\x03\x98\x00`\x80\x01\xe3" + // 0x000E6 0x00304: 0x001E3 + "\x00\x01\x1c\x00a\x80\x01\xe6" + // 0x00047 0x0030C: 0x001E6 + "\x00\x01\x9c\x00a\x80\x01\xe7" + // 0x00067 0x0030C: 0x001E7 + "\x00\x01,\x00a\x80\x01\xe8" + // 0x0004B 0x0030C: 0x001E8 + "\x00\x01\xac\x00a\x80\x01\xe9" + // 0x0006B 0x0030C: 0x001E9 + "\x00\x01<\x00e\x00\x01\xea" + // 0x0004F 0x00328: 0x001EA + "\x00\x01\xbc\x00e\x00\x01\xeb" + // 0x0006F 0x00328: 0x001EB + "\x00\a\xa8\x00`\x80\x01\xec" + // 0x001EA 0x00304: 0x001EC + "\x00\a\xac\x00`\x80\x01\xed" + // 0x001EB 0x00304: 0x001ED + "\x00\x06\xdc\x00a\x80\x01\xee" + // 0x001B7 0x0030C: 0x001EE + "\x00\nH\x00a\x80\x01\xef" + // 0x00292 0x0030C: 0x001EF + "\x00\x01\xa8\x00a\x80\x01\xf0" + // 0x0006A 0x0030C: 0x001F0 + "\x00\x01\x1c\x00` \x01\xf4" + // 0x00047 0x00301: 0x001F4 + "\x00\x01\x9c\x00` \x01\xf5" + // 0x00067 0x00301: 0x001F5 + "\x00\x018\x00`\x00\x01\xf8" + // 0x0004E 0x00300: 0x001F8 + "\x00\x01\xb8\x00`\x00\x01\xf9" + // 0x0006E 0x00300: 0x001F9 + "\x00\x03\x14\x00` \x01\xfa" + // 0x000C5 0x00301: 0x001FA + "\x00\x03\x94\x00` \x01\xfb" + // 0x000E5 0x00301: 0x001FB + "\x00\x03\x18\x00` \x01\xfc" + // 0x000C6 0x00301: 0x001FC + "\x00\x03\x98\x00` \x01\xfd" + // 0x000E6 0x00301: 0x001FD + "\x00\x03`\x00` \x01\xfe" + // 0x000D8 0x00301: 0x001FE + "\x00\x03\xe0\x00` \x01\xff" + // 0x000F8 0x00301: 0x001FF + "\x00\x01\x04\x00a\xe0\x02\x00" + // 0x00041 0x0030F: 0x00200 + "\x00\x01\x84\x00a\xe0\x02\x01" + // 0x00061 0x0030F: 0x00201 + "\x00\x01\x04\x00b \x02\x02" + // 0x00041 0x00311: 0x00202 + "\x00\x01\x84\x00b \x02\x03" + // 0x00061 0x00311: 0x00203 + "\x00\x01\x14\x00a\xe0\x02\x04" + // 0x00045 0x0030F: 0x00204 + "\x00\x01\x94\x00a\xe0\x02\x05" + // 0x00065 0x0030F: 0x00205 + "\x00\x01\x14\x00b \x02\x06" + // 0x00045 0x00311: 0x00206 + "\x00\x01\x94\x00b \x02\a" + // 0x00065 0x00311: 0x00207 + "\x00\x01$\x00a\xe0\x02\b" + // 0x00049 0x0030F: 0x00208 + "\x00\x01\xa4\x00a\xe0\x02\t" + // 0x00069 0x0030F: 0x00209 + "\x00\x01$\x00b \x02\n" + // 0x00049 0x00311: 0x0020A + "\x00\x01\xa4\x00b \x02\v" + // 0x00069 0x00311: 0x0020B + "\x00\x01<\x00a\xe0\x02\f" + // 0x0004F 0x0030F: 0x0020C + "\x00\x01\xbc\x00a\xe0\x02\r" + // 0x0006F 0x0030F: 0x0020D + "\x00\x01<\x00b \x02\x0e" + // 0x0004F 0x00311: 0x0020E + "\x00\x01\xbc\x00b \x02\x0f" + // 0x0006F 0x00311: 0x0020F + "\x00\x01H\x00a\xe0\x02\x10" + // 0x00052 0x0030F: 0x00210 + "\x00\x01\xc8\x00a\xe0\x02\x11" + // 0x00072 0x0030F: 0x00211 + "\x00\x01H\x00b \x02\x12" + // 0x00052 0x00311: 0x00212 + "\x00\x01\xc8\x00b \x02\x13" + // 0x00072 0x00311: 0x00213 + "\x00\x01T\x00a\xe0\x02\x14" + // 0x00055 0x0030F: 0x00214 + "\x00\x01\xd4\x00a\xe0\x02\x15" + // 0x00075 0x0030F: 0x00215 + "\x00\x01T\x00b \x02\x16" + // 0x00055 0x00311: 0x00216 + "\x00\x01\xd4\x00b \x02\x17" + // 0x00075 0x00311: 0x00217 + "\x00\x01L\x00d\xc0\x02\x18" + // 0x00053 0x00326: 0x00218 + "\x00\x01\xcc\x00d\xc0\x02\x19" + // 0x00073 0x00326: 0x00219 + "\x00\x01P\x00d\xc0\x02\x1a" + // 0x00054 0x00326: 0x0021A + "\x00\x01\xd0\x00d\xc0\x02\x1b" + // 0x00074 0x00326: 0x0021B + "\x00\x01 \x00a\x80\x02\x1e" + // 0x00048 0x0030C: 0x0021E + "\x00\x01\xa0\x00a\x80\x02\x1f" + // 0x00068 0x0030C: 0x0021F + "\x00\x01\x04\x00`\xe0\x02&" + // 0x00041 0x00307: 0x00226 + "\x00\x01\x84\x00`\xe0\x02'" + // 0x00061 0x00307: 0x00227 + "\x00\x01\x14\x00d\xe0\x02(" + // 0x00045 0x00327: 0x00228 + "\x00\x01\x94\x00d\xe0\x02)" + // 0x00065 0x00327: 0x00229 + "\x00\x03X\x00`\x80\x02*" + // 0x000D6 0x00304: 0x0022A + "\x00\x03\xd8\x00`\x80\x02+" + // 0x000F6 0x00304: 0x0022B + "\x00\x03T\x00`\x80\x02," + // 0x000D5 0x00304: 0x0022C + "\x00\x03\xd4\x00`\x80\x02-" + // 0x000F5 0x00304: 0x0022D + "\x00\x01<\x00`\xe0\x02." + // 0x0004F 0x00307: 0x0022E + "\x00\x01\xbc\x00`\xe0\x02/" + // 0x0006F 0x00307: 0x0022F + "\x00\b\xb8\x00`\x80\x020" + // 0x0022E 0x00304: 0x00230 + "\x00\b\xbc\x00`\x80\x021" + // 0x0022F 0x00304: 0x00231 + "\x00\x01d\x00`\x80\x022" + // 0x00059 0x00304: 0x00232 + "\x00\x01\xe4\x00`\x80\x023" + // 0x00079 0x00304: 0x00233 + "\x00\x02\xa0\x00` \x03\x85" + // 0x000A8 0x00301: 0x00385 + "\x00\x0eD\x00` \x03\x86" + // 0x00391 0x00301: 0x00386 + "\x00\x0eT\x00` \x03\x88" + // 0x00395 0x00301: 0x00388 + "\x00\x0e\\\x00` \x03\x89" + // 0x00397 0x00301: 0x00389 + "\x00\x0ed\x00` \x03\x8a" + // 0x00399 0x00301: 0x0038A + "\x00\x0e|\x00` \x03\x8c" + // 0x0039F 0x00301: 0x0038C + "\x00\x0e\x94\x00` \x03\x8e" + // 0x003A5 0x00301: 0x0038E + "\x00\x0e\xa4\x00` \x03\x8f" + // 0x003A9 0x00301: 0x0038F + "\x00\x0f(\x00` \x03\x90" + // 0x003CA 0x00301: 0x00390 + "\x00\x0ed\x00a\x00\x03\xaa" + // 0x00399 0x00308: 0x003AA + "\x00\x0e\x94\x00a\x00\x03\xab" + // 0x003A5 0x00308: 0x003AB + "\x00\x0e\xc4\x00` \x03\xac" + // 0x003B1 0x00301: 0x003AC + "\x00\x0e\xd4\x00` \x03\xad" + // 0x003B5 0x00301: 0x003AD + "\x00\x0e\xdc\x00` \x03\xae" + // 0x003B7 0x00301: 0x003AE + "\x00\x0e\xe4\x00` \x03\xaf" + // 0x003B9 0x00301: 0x003AF + "\x00\x0f,\x00` \x03\xb0" + // 0x003CB 0x00301: 0x003B0 + "\x00\x0e\xe4\x00a\x00\x03\xca" + // 0x003B9 0x00308: 0x003CA + "\x00\x0f\x14\x00a\x00\x03\xcb" + // 0x003C5 0x00308: 0x003CB + "\x00\x0e\xfc\x00` \x03\xcc" + // 0x003BF 0x00301: 0x003CC + "\x00\x0f\x14\x00` \x03\xcd" + // 0x003C5 0x00301: 0x003CD + "\x00\x0f$\x00` \x03\xce" + // 0x003C9 0x00301: 0x003CE + "\x00\x0fH\x00` \x03\xd3" + // 0x003D2 0x00301: 0x003D3 + "\x00\x0fH\x00a\x00\x03\xd4" + // 0x003D2 0x00308: 0x003D4 + "\x00\x10T\x00`\x00\x04\x00" + // 0x00415 0x00300: 0x00400 + "\x00\x10T\x00a\x00\x04\x01" + // 0x00415 0x00308: 0x00401 + "\x00\x10L\x00` \x04\x03" + // 0x00413 0x00301: 0x00403 + "\x00\x10\x18\x00a\x00\x04\a" + // 0x00406 0x00308: 0x00407 + "\x00\x10h\x00` \x04\f" + // 0x0041A 0x00301: 0x0040C + "\x00\x10`\x00`\x00\x04\r" + // 0x00418 0x00300: 0x0040D + "\x00\x10\x8c\x00`\xc0\x04\x0e" + // 0x00423 0x00306: 0x0040E + "\x00\x10`\x00`\xc0\x04\x19" + // 0x00418 0x00306: 0x00419 + "\x00\x10\xe0\x00`\xc0\x049" + // 0x00438 0x00306: 0x00439 + "\x00\x10\xd4\x00`\x00\x04P" + // 0x00435 0x00300: 0x00450 + "\x00\x10\xd4\x00a\x00\x04Q" + // 0x00435 0x00308: 0x00451 + "\x00\x10\xcc\x00` \x04S" + // 0x00433 0x00301: 0x00453 + "\x00\x11X\x00a\x00\x04W" + // 0x00456 0x00308: 0x00457 + "\x00\x10\xe8\x00` \x04\\" + // 0x0043A 0x00301: 0x0045C + "\x00\x10\xe0\x00`\x00\x04]" + // 0x00438 0x00300: 0x0045D + "\x00\x11\f\x00`\xc0\x04^" + // 0x00443 0x00306: 0x0045E + "\x00\x11\xd0\x00a\xe0\x04v" + // 0x00474 0x0030F: 0x00476 + "\x00\x11\xd4\x00a\xe0\x04w" + // 0x00475 0x0030F: 0x00477 + "\x00\x10X\x00`\xc0\x04\xc1" + // 0x00416 0x00306: 0x004C1 + "\x00\x10\xd8\x00`\xc0\x04\xc2" + // 0x00436 0x00306: 0x004C2 + "\x00\x10@\x00`\xc0\x04\xd0" + // 0x00410 0x00306: 0x004D0 + "\x00\x10\xc0\x00`\xc0\x04\xd1" + // 0x00430 0x00306: 0x004D1 + "\x00\x10@\x00a\x00\x04\xd2" + // 0x00410 0x00308: 0x004D2 + "\x00\x10\xc0\x00a\x00\x04\xd3" + // 0x00430 0x00308: 0x004D3 + "\x00\x10T\x00`\xc0\x04\xd6" + // 0x00415 0x00306: 0x004D6 + "\x00\x10\xd4\x00`\xc0\x04\xd7" + // 0x00435 0x00306: 0x004D7 + "\x00\x13`\x00a\x00\x04\xda" + // 0x004D8 0x00308: 0x004DA + "\x00\x13d\x00a\x00\x04\xdb" + // 0x004D9 0x00308: 0x004DB + "\x00\x10X\x00a\x00\x04\xdc" + // 0x00416 0x00308: 0x004DC + "\x00\x10\xd8\x00a\x00\x04\xdd" + // 0x00436 0x00308: 0x004DD + "\x00\x10\\\x00a\x00\x04\xde" + // 0x00417 0x00308: 0x004DE + "\x00\x10\xdc\x00a\x00\x04\xdf" + // 0x00437 0x00308: 0x004DF + "\x00\x10`\x00`\x80\x04\xe2" + // 0x00418 0x00304: 0x004E2 + "\x00\x10\xe0\x00`\x80\x04\xe3" + // 0x00438 0x00304: 0x004E3 + "\x00\x10`\x00a\x00\x04\xe4" + // 0x00418 0x00308: 0x004E4 + "\x00\x10\xe0\x00a\x00\x04\xe5" + // 0x00438 0x00308: 0x004E5 + "\x00\x10x\x00a\x00\x04\xe6" + // 0x0041E 0x00308: 0x004E6 + "\x00\x10\xf8\x00a\x00\x04\xe7" + // 0x0043E 0x00308: 0x004E7 + "\x00\x13\xa0\x00a\x00\x04\xea" + // 0x004E8 0x00308: 0x004EA + "\x00\x13\xa4\x00a\x00\x04\xeb" + // 0x004E9 0x00308: 0x004EB + "\x00\x10\xb4\x00a\x00\x04\xec" + // 0x0042D 0x00308: 0x004EC + "\x00\x114\x00a\x00\x04\xed" + // 0x0044D 0x00308: 0x004ED + "\x00\x10\x8c\x00`\x80\x04\xee" + // 0x00423 0x00304: 0x004EE + "\x00\x11\f\x00`\x80\x04\xef" + // 0x00443 0x00304: 0x004EF + "\x00\x10\x8c\x00a\x00\x04\xf0" + // 0x00423 0x00308: 0x004F0 + "\x00\x11\f\x00a\x00\x04\xf1" + // 0x00443 0x00308: 0x004F1 + "\x00\x10\x8c\x00a`\x04\xf2" + // 0x00423 0x0030B: 0x004F2 + "\x00\x11\f\x00a`\x04\xf3" + // 0x00443 0x0030B: 0x004F3 + "\x00\x10\x9c\x00a\x00\x04\xf4" + // 0x00427 0x00308: 0x004F4 + "\x00\x11\x1c\x00a\x00\x04\xf5" + // 0x00447 0x00308: 0x004F5 + "\x00\x10\xac\x00a\x00\x04\xf8" + // 0x0042B 0x00308: 0x004F8 + "\x00\x11,\x00a\x00\x04\xf9" + // 0x0044B 0x00308: 0x004F9 + "\x00\x18\x9c\x00\xca`\x06\"" + // 0x00627 0x00653: 0x00622 + "\x00\x18\x9c\x00ʀ\x06#" + // 0x00627 0x00654: 0x00623 + "\x00\x19 \x00ʀ\x06$" + // 0x00648 0x00654: 0x00624 + "\x00\x18\x9c\x00ʠ\x06%" + // 0x00627 0x00655: 0x00625 + "\x00\x19(\x00ʀ\x06&" + // 0x0064A 0x00654: 0x00626 + "\x00\x1bT\x00ʀ\x06\xc0" + // 0x006D5 0x00654: 0x006C0 + "\x00\x1b\x04\x00ʀ\x06\xc2" + // 0x006C1 0x00654: 0x006C2 + "\x00\x1bH\x00ʀ\x06\xd3" + // 0x006D2 0x00654: 0x006D3 + "\x00$\xa0\x01'\x80\t)" + // 0x00928 0x0093C: 0x00929 + "\x00$\xc0\x01'\x80\t1" + // 0x00930 0x0093C: 0x00931 + "\x00$\xcc\x01'\x80\t4" + // 0x00933 0x0093C: 0x00934 + "\x00'\x1c\x017\xc0\t\xcb" + // 0x009C7 0x009BE: 0x009CB + "\x00'\x1c\x01:\xe0\t\xcc" + // 0x009C7 0x009D7: 0x009CC + "\x00-\x1c\x01j\xc0\vH" + // 0x00B47 0x00B56: 0x00B48 + "\x00-\x1c\x01g\xc0\vK" + // 0x00B47 0x00B3E: 0x00B4B + "\x00-\x1c\x01j\xe0\vL" + // 0x00B47 0x00B57: 0x00B4C + "\x00.H\x01z\xe0\v\x94" + // 0x00B92 0x00BD7: 0x00B94 + "\x00/\x18\x01w\xc0\v\xca" + // 0x00BC6 0x00BBE: 0x00BCA + "\x00/\x1c\x01w\xc0\v\xcb" + // 0x00BC7 0x00BBE: 0x00BCB + "\x00/\x18\x01z\xe0\v\xcc" + // 0x00BC6 0x00BD7: 0x00BCC + "\x001\x18\x01\x8a\xc0\fH" + // 0x00C46 0x00C56: 0x00C48 + "\x002\xfc\x01\x9a\xa0\f\xc0" + // 0x00CBF 0x00CD5: 0x00CC0 + "\x003\x18\x01\x9a\xa0\f\xc7" + // 0x00CC6 0x00CD5: 0x00CC7 + "\x003\x18\x01\x9a\xc0\f\xc8" + // 0x00CC6 0x00CD6: 0x00CC8 + "\x003\x18\x01\x98@\f\xca" + // 0x00CC6 0x00CC2: 0x00CCA + "\x003(\x01\x9a\xa0\f\xcb" + // 0x00CCA 0x00CD5: 0x00CCB + "\x005\x18\x01\xa7\xc0\rJ" + // 0x00D46 0x00D3E: 0x00D4A + "\x005\x1c\x01\xa7\xc0\rK" + // 0x00D47 0x00D3E: 0x00D4B + "\x005\x18\x01\xaa\xe0\rL" + // 0x00D46 0x00D57: 0x00D4C + "\x007d\x01\xb9@\r\xda" + // 0x00DD9 0x00DCA: 0x00DDA + "\x007d\x01\xb9\xe0\r\xdc" + // 0x00DD9 0x00DCF: 0x00DDC + "\x007p\x01\xb9@\r\xdd" + // 0x00DDC 0x00DCA: 0x00DDD + "\x007d\x01\xbb\xe0\r\xde" + // 0x00DD9 0x00DDF: 0x00DDE + "\x00@\x94\x02\x05\xc0\x10&" + // 0x01025 0x0102E: 0x01026 + "\x00l\x14\x03f\xa0\x1b\x06" + // 0x01B05 0x01B35: 0x01B06 + "\x00l\x1c\x03f\xa0\x1b\b" + // 0x01B07 0x01B35: 0x01B08 + "\x00l$\x03f\xa0\x1b\n" + // 0x01B09 0x01B35: 0x01B0A + "\x00l,\x03f\xa0\x1b\f" + // 0x01B0B 0x01B35: 0x01B0C + "\x00l4\x03f\xa0\x1b\x0e" + // 0x01B0D 0x01B35: 0x01B0E + "\x00lD\x03f\xa0\x1b\x12" + // 0x01B11 0x01B35: 0x01B12 + "\x00l\xe8\x03f\xa0\x1b;" + // 0x01B3A 0x01B35: 0x01B3B + "\x00l\xf0\x03f\xa0\x1b=" + // 0x01B3C 0x01B35: 0x01B3D + "\x00l\xf8\x03f\xa0\x1b@" + // 0x01B3E 0x01B35: 0x01B40 + "\x00l\xfc\x03f\xa0\x1bA" + // 0x01B3F 0x01B35: 0x01B41 + "\x00m\b\x03f\xa0\x1bC" + // 0x01B42 0x01B35: 0x01B43 + "\x00\x01\x04\x00d\xa0\x1e\x00" + // 0x00041 0x00325: 0x01E00 + "\x00\x01\x84\x00d\xa0\x1e\x01" + // 0x00061 0x00325: 0x01E01 + "\x00\x01\b\x00`\xe0\x1e\x02" + // 0x00042 0x00307: 0x01E02 + "\x00\x01\x88\x00`\xe0\x1e\x03" + // 0x00062 0x00307: 0x01E03 + "\x00\x01\b\x00d`\x1e\x04" + // 0x00042 0x00323: 0x01E04 + "\x00\x01\x88\x00d`\x1e\x05" + // 0x00062 0x00323: 0x01E05 + "\x00\x01\b\x00f \x1e\x06" + // 0x00042 0x00331: 0x01E06 + "\x00\x01\x88\x00f \x1e\a" + // 0x00062 0x00331: 0x01E07 + "\x00\x03\x1c\x00` \x1e\b" + // 0x000C7 0x00301: 0x01E08 + "\x00\x03\x9c\x00` \x1e\t" + // 0x000E7 0x00301: 0x01E09 + "\x00\x01\x10\x00`\xe0\x1e\n" + // 0x00044 0x00307: 0x01E0A + "\x00\x01\x90\x00`\xe0\x1e\v" + // 0x00064 0x00307: 0x01E0B + "\x00\x01\x10\x00d`\x1e\f" + // 0x00044 0x00323: 0x01E0C + "\x00\x01\x90\x00d`\x1e\r" + // 0x00064 0x00323: 0x01E0D + "\x00\x01\x10\x00f \x1e\x0e" + // 0x00044 0x00331: 0x01E0E + "\x00\x01\x90\x00f \x1e\x0f" + // 0x00064 0x00331: 0x01E0F + "\x00\x01\x10\x00d\xe0\x1e\x10" + // 0x00044 0x00327: 0x01E10 + "\x00\x01\x90\x00d\xe0\x1e\x11" + // 0x00064 0x00327: 0x01E11 + "\x00\x01\x10\x00e\xa0\x1e\x12" + // 0x00044 0x0032D: 0x01E12 + "\x00\x01\x90\x00e\xa0\x1e\x13" + // 0x00064 0x0032D: 0x01E13 + "\x00\x04H\x00`\x00\x1e\x14" + // 0x00112 0x00300: 0x01E14 + "\x00\x04L\x00`\x00\x1e\x15" + // 0x00113 0x00300: 0x01E15 + "\x00\x04H\x00` \x1e\x16" + // 0x00112 0x00301: 0x01E16 + "\x00\x04L\x00` \x1e\x17" + // 0x00113 0x00301: 0x01E17 + "\x00\x01\x14\x00e\xa0\x1e\x18" + // 0x00045 0x0032D: 0x01E18 + "\x00\x01\x94\x00e\xa0\x1e\x19" + // 0x00065 0x0032D: 0x01E19 + "\x00\x01\x14\x00f\x00\x1e\x1a" + // 0x00045 0x00330: 0x01E1A + "\x00\x01\x94\x00f\x00\x1e\x1b" + // 0x00065 0x00330: 0x01E1B + "\x00\b\xa0\x00`\xc0\x1e\x1c" + // 0x00228 0x00306: 0x01E1C + "\x00\b\xa4\x00`\xc0\x1e\x1d" + // 0x00229 0x00306: 0x01E1D + "\x00\x01\x18\x00`\xe0\x1e\x1e" + // 0x00046 0x00307: 0x01E1E + "\x00\x01\x98\x00`\xe0\x1e\x1f" + // 0x00066 0x00307: 0x01E1F + "\x00\x01\x1c\x00`\x80\x1e " + // 0x00047 0x00304: 0x01E20 + "\x00\x01\x9c\x00`\x80\x1e!" + // 0x00067 0x00304: 0x01E21 + "\x00\x01 \x00`\xe0\x1e\"" + // 0x00048 0x00307: 0x01E22 + "\x00\x01\xa0\x00`\xe0\x1e#" + // 0x00068 0x00307: 0x01E23 + "\x00\x01 \x00d`\x1e$" + // 0x00048 0x00323: 0x01E24 + "\x00\x01\xa0\x00d`\x1e%" + // 0x00068 0x00323: 0x01E25 + "\x00\x01 \x00a\x00\x1e&" + // 0x00048 0x00308: 0x01E26 + "\x00\x01\xa0\x00a\x00\x1e'" + // 0x00068 0x00308: 0x01E27 + "\x00\x01 \x00d\xe0\x1e(" + // 0x00048 0x00327: 0x01E28 + "\x00\x01\xa0\x00d\xe0\x1e)" + // 0x00068 0x00327: 0x01E29 + "\x00\x01 \x00e\xc0\x1e*" + // 0x00048 0x0032E: 0x01E2A + "\x00\x01\xa0\x00e\xc0\x1e+" + // 0x00068 0x0032E: 0x01E2B + "\x00\x01$\x00f\x00\x1e," + // 0x00049 0x00330: 0x01E2C + "\x00\x01\xa4\x00f\x00\x1e-" + // 0x00069 0x00330: 0x01E2D + "\x00\x03<\x00` \x1e." + // 0x000CF 0x00301: 0x01E2E + "\x00\x03\xbc\x00` \x1e/" + // 0x000EF 0x00301: 0x01E2F + "\x00\x01,\x00` \x1e0" + // 0x0004B 0x00301: 0x01E30 + "\x00\x01\xac\x00` \x1e1" + // 0x0006B 0x00301: 0x01E31 + "\x00\x01,\x00d`\x1e2" + // 0x0004B 0x00323: 0x01E32 + "\x00\x01\xac\x00d`\x1e3" + // 0x0006B 0x00323: 0x01E33 + "\x00\x01,\x00f \x1e4" + // 0x0004B 0x00331: 0x01E34 + "\x00\x01\xac\x00f \x1e5" + // 0x0006B 0x00331: 0x01E35 + "\x00\x010\x00d`\x1e6" + // 0x0004C 0x00323: 0x01E36 + "\x00\x01\xb0\x00d`\x1e7" + // 0x0006C 0x00323: 0x01E37 + "\x00x\xd8\x00`\x80\x1e8" + // 0x01E36 0x00304: 0x01E38 + "\x00x\xdc\x00`\x80\x1e9" + // 0x01E37 0x00304: 0x01E39 + "\x00\x010\x00f \x1e:" + // 0x0004C 0x00331: 0x01E3A + "\x00\x01\xb0\x00f \x1e;" + // 0x0006C 0x00331: 0x01E3B + "\x00\x010\x00e\xa0\x1e<" + // 0x0004C 0x0032D: 0x01E3C + "\x00\x01\xb0\x00e\xa0\x1e=" + // 0x0006C 0x0032D: 0x01E3D + "\x00\x014\x00` \x1e>" + // 0x0004D 0x00301: 0x01E3E + "\x00\x01\xb4\x00` \x1e?" + // 0x0006D 0x00301: 0x01E3F + "\x00\x014\x00`\xe0\x1e@" + // 0x0004D 0x00307: 0x01E40 + "\x00\x01\xb4\x00`\xe0\x1eA" + // 0x0006D 0x00307: 0x01E41 + "\x00\x014\x00d`\x1eB" + // 0x0004D 0x00323: 0x01E42 + "\x00\x01\xb4\x00d`\x1eC" + // 0x0006D 0x00323: 0x01E43 + "\x00\x018\x00`\xe0\x1eD" + // 0x0004E 0x00307: 0x01E44 + "\x00\x01\xb8\x00`\xe0\x1eE" + // 0x0006E 0x00307: 0x01E45 + "\x00\x018\x00d`\x1eF" + // 0x0004E 0x00323: 0x01E46 + "\x00\x01\xb8\x00d`\x1eG" + // 0x0006E 0x00323: 0x01E47 + "\x00\x018\x00f \x1eH" + // 0x0004E 0x00331: 0x01E48 + "\x00\x01\xb8\x00f \x1eI" + // 0x0006E 0x00331: 0x01E49 + "\x00\x018\x00e\xa0\x1eJ" + // 0x0004E 0x0032D: 0x01E4A + "\x00\x01\xb8\x00e\xa0\x1eK" + // 0x0006E 0x0032D: 0x01E4B + "\x00\x03T\x00` \x1eL" + // 0x000D5 0x00301: 0x01E4C + "\x00\x03\xd4\x00` \x1eM" + // 0x000F5 0x00301: 0x01E4D + "\x00\x03T\x00a\x00\x1eN" + // 0x000D5 0x00308: 0x01E4E + "\x00\x03\xd4\x00a\x00\x1eO" + // 0x000F5 0x00308: 0x01E4F + "\x00\x050\x00`\x00\x1eP" + // 0x0014C 0x00300: 0x01E50 + "\x00\x054\x00`\x00\x1eQ" + // 0x0014D 0x00300: 0x01E51 + "\x00\x050\x00` \x1eR" + // 0x0014C 0x00301: 0x01E52 + "\x00\x054\x00` \x1eS" + // 0x0014D 0x00301: 0x01E53 + "\x00\x01@\x00` \x1eT" + // 0x00050 0x00301: 0x01E54 + "\x00\x01\xc0\x00` \x1eU" + // 0x00070 0x00301: 0x01E55 + "\x00\x01@\x00`\xe0\x1eV" + // 0x00050 0x00307: 0x01E56 + "\x00\x01\xc0\x00`\xe0\x1eW" + // 0x00070 0x00307: 0x01E57 + "\x00\x01H\x00`\xe0\x1eX" + // 0x00052 0x00307: 0x01E58 + "\x00\x01\xc8\x00`\xe0\x1eY" + // 0x00072 0x00307: 0x01E59 + "\x00\x01H\x00d`\x1eZ" + // 0x00052 0x00323: 0x01E5A + "\x00\x01\xc8\x00d`\x1e[" + // 0x00072 0x00323: 0x01E5B + "\x00yh\x00`\x80\x1e\\" + // 0x01E5A 0x00304: 0x01E5C + "\x00yl\x00`\x80\x1e]" + // 0x01E5B 0x00304: 0x01E5D + "\x00\x01H\x00f \x1e^" + // 0x00052 0x00331: 0x01E5E + "\x00\x01\xc8\x00f \x1e_" + // 0x00072 0x00331: 0x01E5F + "\x00\x01L\x00`\xe0\x1e`" + // 0x00053 0x00307: 0x01E60 + "\x00\x01\xcc\x00`\xe0\x1ea" + // 0x00073 0x00307: 0x01E61 + "\x00\x01L\x00d`\x1eb" + // 0x00053 0x00323: 0x01E62 + "\x00\x01\xcc\x00d`\x1ec" + // 0x00073 0x00323: 0x01E63 + "\x00\x05h\x00`\xe0\x1ed" + // 0x0015A 0x00307: 0x01E64 + "\x00\x05l\x00`\xe0\x1ee" + // 0x0015B 0x00307: 0x01E65 + "\x00\x05\x80\x00`\xe0\x1ef" + // 0x00160 0x00307: 0x01E66 + "\x00\x05\x84\x00`\xe0\x1eg" + // 0x00161 0x00307: 0x01E67 + "\x00y\x88\x00`\xe0\x1eh" + // 0x01E62 0x00307: 0x01E68 + "\x00y\x8c\x00`\xe0\x1ei" + // 0x01E63 0x00307: 0x01E69 + "\x00\x01P\x00`\xe0\x1ej" + // 0x00054 0x00307: 0x01E6A + "\x00\x01\xd0\x00`\xe0\x1ek" + // 0x00074 0x00307: 0x01E6B + "\x00\x01P\x00d`\x1el" + // 0x00054 0x00323: 0x01E6C + "\x00\x01\xd0\x00d`\x1em" + // 0x00074 0x00323: 0x01E6D + "\x00\x01P\x00f \x1en" + // 0x00054 0x00331: 0x01E6E + "\x00\x01\xd0\x00f \x1eo" + // 0x00074 0x00331: 0x01E6F + "\x00\x01P\x00e\xa0\x1ep" + // 0x00054 0x0032D: 0x01E70 + "\x00\x01\xd0\x00e\xa0\x1eq" + // 0x00074 0x0032D: 0x01E71 + "\x00\x01T\x00d\x80\x1er" + // 0x00055 0x00324: 0x01E72 + "\x00\x01\xd4\x00d\x80\x1es" + // 0x00075 0x00324: 0x01E73 + "\x00\x01T\x00f\x00\x1et" + // 0x00055 0x00330: 0x01E74 + "\x00\x01\xd4\x00f\x00\x1eu" + // 0x00075 0x00330: 0x01E75 + "\x00\x01T\x00e\xa0\x1ev" + // 0x00055 0x0032D: 0x01E76 + "\x00\x01\xd4\x00e\xa0\x1ew" + // 0x00075 0x0032D: 0x01E77 + "\x00\x05\xa0\x00` \x1ex" + // 0x00168 0x00301: 0x01E78 + "\x00\x05\xa4\x00` \x1ey" + // 0x00169 0x00301: 0x01E79 + "\x00\x05\xa8\x00a\x00\x1ez" + // 0x0016A 0x00308: 0x01E7A + "\x00\x05\xac\x00a\x00\x1e{" + // 0x0016B 0x00308: 0x01E7B + "\x00\x01X\x00``\x1e|" + // 0x00056 0x00303: 0x01E7C + "\x00\x01\xd8\x00``\x1e}" + // 0x00076 0x00303: 0x01E7D + "\x00\x01X\x00d`\x1e~" + // 0x00056 0x00323: 0x01E7E + "\x00\x01\xd8\x00d`\x1e\x7f" + // 0x00076 0x00323: 0x01E7F + "\x00\x01\\\x00`\x00\x1e\x80" + // 0x00057 0x00300: 0x01E80 + "\x00\x01\xdc\x00`\x00\x1e\x81" + // 0x00077 0x00300: 0x01E81 + "\x00\x01\\\x00` \x1e\x82" + // 0x00057 0x00301: 0x01E82 + "\x00\x01\xdc\x00` \x1e\x83" + // 0x00077 0x00301: 0x01E83 + "\x00\x01\\\x00a\x00\x1e\x84" + // 0x00057 0x00308: 0x01E84 + "\x00\x01\xdc\x00a\x00\x1e\x85" + // 0x00077 0x00308: 0x01E85 + "\x00\x01\\\x00`\xe0\x1e\x86" + // 0x00057 0x00307: 0x01E86 + "\x00\x01\xdc\x00`\xe0\x1e\x87" + // 0x00077 0x00307: 0x01E87 + "\x00\x01\\\x00d`\x1e\x88" + // 0x00057 0x00323: 0x01E88 + "\x00\x01\xdc\x00d`\x1e\x89" + // 0x00077 0x00323: 0x01E89 + "\x00\x01`\x00`\xe0\x1e\x8a" + // 0x00058 0x00307: 0x01E8A + "\x00\x01\xe0\x00`\xe0\x1e\x8b" + // 0x00078 0x00307: 0x01E8B + "\x00\x01`\x00a\x00\x1e\x8c" + // 0x00058 0x00308: 0x01E8C + "\x00\x01\xe0\x00a\x00\x1e\x8d" + // 0x00078 0x00308: 0x01E8D + "\x00\x01d\x00`\xe0\x1e\x8e" + // 0x00059 0x00307: 0x01E8E + "\x00\x01\xe4\x00`\xe0\x1e\x8f" + // 0x00079 0x00307: 0x01E8F + "\x00\x01h\x00`@\x1e\x90" + // 0x0005A 0x00302: 0x01E90 + "\x00\x01\xe8\x00`@\x1e\x91" + // 0x0007A 0x00302: 0x01E91 + "\x00\x01h\x00d`\x1e\x92" + // 0x0005A 0x00323: 0x01E92 + "\x00\x01\xe8\x00d`\x1e\x93" + // 0x0007A 0x00323: 0x01E93 + "\x00\x01h\x00f \x1e\x94" + // 0x0005A 0x00331: 0x01E94 + "\x00\x01\xe8\x00f \x1e\x95" + // 0x0007A 0x00331: 0x01E95 + "\x00\x01\xa0\x00f \x1e\x96" + // 0x00068 0x00331: 0x01E96 + "\x00\x01\xd0\x00a\x00\x1e\x97" + // 0x00074 0x00308: 0x01E97 + "\x00\x01\xdc\x00a@\x1e\x98" + // 0x00077 0x0030A: 0x01E98 + "\x00\x01\xe4\x00a@\x1e\x99" + // 0x00079 0x0030A: 0x01E99 + "\x00\x05\xfc\x00`\xe0\x1e\x9b" + // 0x0017F 0x00307: 0x01E9B + "\x00\x01\x04\x00d`\x1e\xa0" + // 0x00041 0x00323: 0x01EA0 + "\x00\x01\x84\x00d`\x1e\xa1" + // 0x00061 0x00323: 0x01EA1 + "\x00\x01\x04\x00a \x1e\xa2" + // 0x00041 0x00309: 0x01EA2 + "\x00\x01\x84\x00a \x1e\xa3" + // 0x00061 0x00309: 0x01EA3 + "\x00\x03\b\x00` \x1e\xa4" + // 0x000C2 0x00301: 0x01EA4 + "\x00\x03\x88\x00` \x1e\xa5" + // 0x000E2 0x00301: 0x01EA5 + "\x00\x03\b\x00`\x00\x1e\xa6" + // 0x000C2 0x00300: 0x01EA6 + "\x00\x03\x88\x00`\x00\x1e\xa7" + // 0x000E2 0x00300: 0x01EA7 + "\x00\x03\b\x00a \x1e\xa8" + // 0x000C2 0x00309: 0x01EA8 + "\x00\x03\x88\x00a \x1e\xa9" + // 0x000E2 0x00309: 0x01EA9 + "\x00\x03\b\x00``\x1e\xaa" + // 0x000C2 0x00303: 0x01EAA + "\x00\x03\x88\x00``\x1e\xab" + // 0x000E2 0x00303: 0x01EAB + "\x00z\x80\x00`@\x1e\xac" + // 0x01EA0 0x00302: 0x01EAC + "\x00z\x84\x00`@\x1e\xad" + // 0x01EA1 0x00302: 0x01EAD + "\x00\x04\b\x00` \x1e\xae" + // 0x00102 0x00301: 0x01EAE + "\x00\x04\f\x00` \x1e\xaf" + // 0x00103 0x00301: 0x01EAF + "\x00\x04\b\x00`\x00\x1e\xb0" + // 0x00102 0x00300: 0x01EB0 + "\x00\x04\f\x00`\x00\x1e\xb1" + // 0x00103 0x00300: 0x01EB1 + "\x00\x04\b\x00a \x1e\xb2" + // 0x00102 0x00309: 0x01EB2 + "\x00\x04\f\x00a \x1e\xb3" + // 0x00103 0x00309: 0x01EB3 + "\x00\x04\b\x00``\x1e\xb4" + // 0x00102 0x00303: 0x01EB4 + "\x00\x04\f\x00``\x1e\xb5" + // 0x00103 0x00303: 0x01EB5 + "\x00z\x80\x00`\xc0\x1e\xb6" + // 0x01EA0 0x00306: 0x01EB6 + "\x00z\x84\x00`\xc0\x1e\xb7" + // 0x01EA1 0x00306: 0x01EB7 + "\x00\x01\x14\x00d`\x1e\xb8" + // 0x00045 0x00323: 0x01EB8 + "\x00\x01\x94\x00d`\x1e\xb9" + // 0x00065 0x00323: 0x01EB9 + "\x00\x01\x14\x00a \x1e\xba" + // 0x00045 0x00309: 0x01EBA + "\x00\x01\x94\x00a \x1e\xbb" + // 0x00065 0x00309: 0x01EBB + "\x00\x01\x14\x00``\x1e\xbc" + // 0x00045 0x00303: 0x01EBC + "\x00\x01\x94\x00``\x1e\xbd" + // 0x00065 0x00303: 0x01EBD + "\x00\x03(\x00` \x1e\xbe" + // 0x000CA 0x00301: 0x01EBE + "\x00\x03\xa8\x00` \x1e\xbf" + // 0x000EA 0x00301: 0x01EBF + "\x00\x03(\x00`\x00\x1e\xc0" + // 0x000CA 0x00300: 0x01EC0 + "\x00\x03\xa8\x00`\x00\x1e\xc1" + // 0x000EA 0x00300: 0x01EC1 + "\x00\x03(\x00a \x1e\xc2" + // 0x000CA 0x00309: 0x01EC2 + "\x00\x03\xa8\x00a \x1e\xc3" + // 0x000EA 0x00309: 0x01EC3 + "\x00\x03(\x00``\x1e\xc4" + // 0x000CA 0x00303: 0x01EC4 + "\x00\x03\xa8\x00``\x1e\xc5" + // 0x000EA 0x00303: 0x01EC5 + "\x00z\xe0\x00`@\x1e\xc6" + // 0x01EB8 0x00302: 0x01EC6 + "\x00z\xe4\x00`@\x1e\xc7" + // 0x01EB9 0x00302: 0x01EC7 + "\x00\x01$\x00a \x1e\xc8" + // 0x00049 0x00309: 0x01EC8 + "\x00\x01\xa4\x00a \x1e\xc9" + // 0x00069 0x00309: 0x01EC9 + "\x00\x01$\x00d`\x1e\xca" + // 0x00049 0x00323: 0x01ECA + "\x00\x01\xa4\x00d`\x1e\xcb" + // 0x00069 0x00323: 0x01ECB + "\x00\x01<\x00d`\x1e\xcc" + // 0x0004F 0x00323: 0x01ECC + "\x00\x01\xbc\x00d`\x1e\xcd" + // 0x0006F 0x00323: 0x01ECD + "\x00\x01<\x00a \x1e\xce" + // 0x0004F 0x00309: 0x01ECE + "\x00\x01\xbc\x00a \x1e\xcf" + // 0x0006F 0x00309: 0x01ECF + "\x00\x03P\x00` \x1e\xd0" + // 0x000D4 0x00301: 0x01ED0 + "\x00\x03\xd0\x00` \x1e\xd1" + // 0x000F4 0x00301: 0x01ED1 + "\x00\x03P\x00`\x00\x1e\xd2" + // 0x000D4 0x00300: 0x01ED2 + "\x00\x03\xd0\x00`\x00\x1e\xd3" + // 0x000F4 0x00300: 0x01ED3 + "\x00\x03P\x00a \x1e\xd4" + // 0x000D4 0x00309: 0x01ED4 + "\x00\x03\xd0\x00a \x1e\xd5" + // 0x000F4 0x00309: 0x01ED5 + "\x00\x03P\x00``\x1e\xd6" + // 0x000D4 0x00303: 0x01ED6 + "\x00\x03\xd0\x00``\x1e\xd7" + // 0x000F4 0x00303: 0x01ED7 + "\x00{0\x00`@\x1e\xd8" + // 0x01ECC 0x00302: 0x01ED8 + "\x00{4\x00`@\x1e\xd9" + // 0x01ECD 0x00302: 0x01ED9 + "\x00\x06\x80\x00` \x1e\xda" + // 0x001A0 0x00301: 0x01EDA + "\x00\x06\x84\x00` \x1e\xdb" + // 0x001A1 0x00301: 0x01EDB + "\x00\x06\x80\x00`\x00\x1e\xdc" + // 0x001A0 0x00300: 0x01EDC + "\x00\x06\x84\x00`\x00\x1e\xdd" + // 0x001A1 0x00300: 0x01EDD + "\x00\x06\x80\x00a \x1e\xde" + // 0x001A0 0x00309: 0x01EDE + "\x00\x06\x84\x00a \x1e\xdf" + // 0x001A1 0x00309: 0x01EDF + "\x00\x06\x80\x00``\x1e\xe0" + // 0x001A0 0x00303: 0x01EE0 + "\x00\x06\x84\x00``\x1e\xe1" + // 0x001A1 0x00303: 0x01EE1 + "\x00\x06\x80\x00d`\x1e\xe2" + // 0x001A0 0x00323: 0x01EE2 + "\x00\x06\x84\x00d`\x1e\xe3" + // 0x001A1 0x00323: 0x01EE3 + "\x00\x01T\x00d`\x1e\xe4" + // 0x00055 0x00323: 0x01EE4 + "\x00\x01\xd4\x00d`\x1e\xe5" + // 0x00075 0x00323: 0x01EE5 + "\x00\x01T\x00a \x1e\xe6" + // 0x00055 0x00309: 0x01EE6 + "\x00\x01\xd4\x00a \x1e\xe7" + // 0x00075 0x00309: 0x01EE7 + "\x00\x06\xbc\x00` \x1e\xe8" + // 0x001AF 0x00301: 0x01EE8 + "\x00\x06\xc0\x00` \x1e\xe9" + // 0x001B0 0x00301: 0x01EE9 + "\x00\x06\xbc\x00`\x00\x1e\xea" + // 0x001AF 0x00300: 0x01EEA + "\x00\x06\xc0\x00`\x00\x1e\xeb" + // 0x001B0 0x00300: 0x01EEB + "\x00\x06\xbc\x00a \x1e\xec" + // 0x001AF 0x00309: 0x01EEC + "\x00\x06\xc0\x00a \x1e\xed" + // 0x001B0 0x00309: 0x01EED + "\x00\x06\xbc\x00``\x1e\xee" + // 0x001AF 0x00303: 0x01EEE + "\x00\x06\xc0\x00``\x1e\xef" + // 0x001B0 0x00303: 0x01EEF + "\x00\x06\xbc\x00d`\x1e\xf0" + // 0x001AF 0x00323: 0x01EF0 + "\x00\x06\xc0\x00d`\x1e\xf1" + // 0x001B0 0x00323: 0x01EF1 + "\x00\x01d\x00`\x00\x1e\xf2" + // 0x00059 0x00300: 0x01EF2 + "\x00\x01\xe4\x00`\x00\x1e\xf3" + // 0x00079 0x00300: 0x01EF3 + "\x00\x01d\x00d`\x1e\xf4" + // 0x00059 0x00323: 0x01EF4 + "\x00\x01\xe4\x00d`\x1e\xf5" + // 0x00079 0x00323: 0x01EF5 + "\x00\x01d\x00a \x1e\xf6" + // 0x00059 0x00309: 0x01EF6 + "\x00\x01\xe4\x00a \x1e\xf7" + // 0x00079 0x00309: 0x01EF7 + "\x00\x01d\x00``\x1e\xf8" + // 0x00059 0x00303: 0x01EF8 + "\x00\x01\xe4\x00``\x1e\xf9" + // 0x00079 0x00303: 0x01EF9 + "\x00\x0e\xc4\x00b`\x1f\x00" + // 0x003B1 0x00313: 0x01F00 + "\x00\x0e\xc4\x00b\x80\x1f\x01" + // 0x003B1 0x00314: 0x01F01 + "\x00|\x00\x00`\x00\x1f\x02" + // 0x01F00 0x00300: 0x01F02 + "\x00|\x04\x00`\x00\x1f\x03" + // 0x01F01 0x00300: 0x01F03 + "\x00|\x00\x00` \x1f\x04" + // 0x01F00 0x00301: 0x01F04 + "\x00|\x04\x00` \x1f\x05" + // 0x01F01 0x00301: 0x01F05 + "\x00|\x00\x00h@\x1f\x06" + // 0x01F00 0x00342: 0x01F06 + "\x00|\x04\x00h@\x1f\a" + // 0x01F01 0x00342: 0x01F07 + "\x00\x0eD\x00b`\x1f\b" + // 0x00391 0x00313: 0x01F08 + "\x00\x0eD\x00b\x80\x1f\t" + // 0x00391 0x00314: 0x01F09 + "\x00| \x00`\x00\x1f\n" + // 0x01F08 0x00300: 0x01F0A + "\x00|$\x00`\x00\x1f\v" + // 0x01F09 0x00300: 0x01F0B + "\x00| \x00` \x1f\f" + // 0x01F08 0x00301: 0x01F0C + "\x00|$\x00` \x1f\r" + // 0x01F09 0x00301: 0x01F0D + "\x00| \x00h@\x1f\x0e" + // 0x01F08 0x00342: 0x01F0E + "\x00|$\x00h@\x1f\x0f" + // 0x01F09 0x00342: 0x01F0F + "\x00\x0e\xd4\x00b`\x1f\x10" + // 0x003B5 0x00313: 0x01F10 + "\x00\x0e\xd4\x00b\x80\x1f\x11" + // 0x003B5 0x00314: 0x01F11 + "\x00|@\x00`\x00\x1f\x12" + // 0x01F10 0x00300: 0x01F12 + "\x00|D\x00`\x00\x1f\x13" + // 0x01F11 0x00300: 0x01F13 + "\x00|@\x00` \x1f\x14" + // 0x01F10 0x00301: 0x01F14 + "\x00|D\x00` \x1f\x15" + // 0x01F11 0x00301: 0x01F15 + "\x00\x0eT\x00b`\x1f\x18" + // 0x00395 0x00313: 0x01F18 + "\x00\x0eT\x00b\x80\x1f\x19" + // 0x00395 0x00314: 0x01F19 + "\x00|`\x00`\x00\x1f\x1a" + // 0x01F18 0x00300: 0x01F1A + "\x00|d\x00`\x00\x1f\x1b" + // 0x01F19 0x00300: 0x01F1B + "\x00|`\x00` \x1f\x1c" + // 0x01F18 0x00301: 0x01F1C + "\x00|d\x00` \x1f\x1d" + // 0x01F19 0x00301: 0x01F1D + "\x00\x0e\xdc\x00b`\x1f " + // 0x003B7 0x00313: 0x01F20 + "\x00\x0e\xdc\x00b\x80\x1f!" + // 0x003B7 0x00314: 0x01F21 + "\x00|\x80\x00`\x00\x1f\"" + // 0x01F20 0x00300: 0x01F22 + "\x00|\x84\x00`\x00\x1f#" + // 0x01F21 0x00300: 0x01F23 + "\x00|\x80\x00` \x1f$" + // 0x01F20 0x00301: 0x01F24 + "\x00|\x84\x00` \x1f%" + // 0x01F21 0x00301: 0x01F25 + "\x00|\x80\x00h@\x1f&" + // 0x01F20 0x00342: 0x01F26 + "\x00|\x84\x00h@\x1f'" + // 0x01F21 0x00342: 0x01F27 + "\x00\x0e\\\x00b`\x1f(" + // 0x00397 0x00313: 0x01F28 + "\x00\x0e\\\x00b\x80\x1f)" + // 0x00397 0x00314: 0x01F29 + "\x00|\xa0\x00`\x00\x1f*" + // 0x01F28 0x00300: 0x01F2A + "\x00|\xa4\x00`\x00\x1f+" + // 0x01F29 0x00300: 0x01F2B + "\x00|\xa0\x00` \x1f," + // 0x01F28 0x00301: 0x01F2C + "\x00|\xa4\x00` \x1f-" + // 0x01F29 0x00301: 0x01F2D + "\x00|\xa0\x00h@\x1f." + // 0x01F28 0x00342: 0x01F2E + "\x00|\xa4\x00h@\x1f/" + // 0x01F29 0x00342: 0x01F2F + "\x00\x0e\xe4\x00b`\x1f0" + // 0x003B9 0x00313: 0x01F30 + "\x00\x0e\xe4\x00b\x80\x1f1" + // 0x003B9 0x00314: 0x01F31 + "\x00|\xc0\x00`\x00\x1f2" + // 0x01F30 0x00300: 0x01F32 + "\x00|\xc4\x00`\x00\x1f3" + // 0x01F31 0x00300: 0x01F33 + "\x00|\xc0\x00` \x1f4" + // 0x01F30 0x00301: 0x01F34 + "\x00|\xc4\x00` \x1f5" + // 0x01F31 0x00301: 0x01F35 + "\x00|\xc0\x00h@\x1f6" + // 0x01F30 0x00342: 0x01F36 + "\x00|\xc4\x00h@\x1f7" + // 0x01F31 0x00342: 0x01F37 + "\x00\x0ed\x00b`\x1f8" + // 0x00399 0x00313: 0x01F38 + "\x00\x0ed\x00b\x80\x1f9" + // 0x00399 0x00314: 0x01F39 + "\x00|\xe0\x00`\x00\x1f:" + // 0x01F38 0x00300: 0x01F3A + "\x00|\xe4\x00`\x00\x1f;" + // 0x01F39 0x00300: 0x01F3B + "\x00|\xe0\x00` \x1f<" + // 0x01F38 0x00301: 0x01F3C + "\x00|\xe4\x00` \x1f=" + // 0x01F39 0x00301: 0x01F3D + "\x00|\xe0\x00h@\x1f>" + // 0x01F38 0x00342: 0x01F3E + "\x00|\xe4\x00h@\x1f?" + // 0x01F39 0x00342: 0x01F3F + "\x00\x0e\xfc\x00b`\x1f@" + // 0x003BF 0x00313: 0x01F40 + "\x00\x0e\xfc\x00b\x80\x1fA" + // 0x003BF 0x00314: 0x01F41 + "\x00}\x00\x00`\x00\x1fB" + // 0x01F40 0x00300: 0x01F42 + "\x00}\x04\x00`\x00\x1fC" + // 0x01F41 0x00300: 0x01F43 + "\x00}\x00\x00` \x1fD" + // 0x01F40 0x00301: 0x01F44 + "\x00}\x04\x00` \x1fE" + // 0x01F41 0x00301: 0x01F45 + "\x00\x0e|\x00b`\x1fH" + // 0x0039F 0x00313: 0x01F48 + "\x00\x0e|\x00b\x80\x1fI" + // 0x0039F 0x00314: 0x01F49 + "\x00} \x00`\x00\x1fJ" + // 0x01F48 0x00300: 0x01F4A + "\x00}$\x00`\x00\x1fK" + // 0x01F49 0x00300: 0x01F4B + "\x00} \x00` \x1fL" + // 0x01F48 0x00301: 0x01F4C + "\x00}$\x00` \x1fM" + // 0x01F49 0x00301: 0x01F4D + "\x00\x0f\x14\x00b`\x1fP" + // 0x003C5 0x00313: 0x01F50 + "\x00\x0f\x14\x00b\x80\x1fQ" + // 0x003C5 0x00314: 0x01F51 + "\x00}@\x00`\x00\x1fR" + // 0x01F50 0x00300: 0x01F52 + "\x00}D\x00`\x00\x1fS" + // 0x01F51 0x00300: 0x01F53 + "\x00}@\x00` \x1fT" + // 0x01F50 0x00301: 0x01F54 + "\x00}D\x00` \x1fU" + // 0x01F51 0x00301: 0x01F55 + "\x00}@\x00h@\x1fV" + // 0x01F50 0x00342: 0x01F56 + "\x00}D\x00h@\x1fW" + // 0x01F51 0x00342: 0x01F57 + "\x00\x0e\x94\x00b\x80\x1fY" + // 0x003A5 0x00314: 0x01F59 + "\x00}d\x00`\x00\x1f[" + // 0x01F59 0x00300: 0x01F5B + "\x00}d\x00` \x1f]" + // 0x01F59 0x00301: 0x01F5D + "\x00}d\x00h@\x1f_" + // 0x01F59 0x00342: 0x01F5F + "\x00\x0f$\x00b`\x1f`" + // 0x003C9 0x00313: 0x01F60 + "\x00\x0f$\x00b\x80\x1fa" + // 0x003C9 0x00314: 0x01F61 + "\x00}\x80\x00`\x00\x1fb" + // 0x01F60 0x00300: 0x01F62 + "\x00}\x84\x00`\x00\x1fc" + // 0x01F61 0x00300: 0x01F63 + "\x00}\x80\x00` \x1fd" + // 0x01F60 0x00301: 0x01F64 + "\x00}\x84\x00` \x1fe" + // 0x01F61 0x00301: 0x01F65 + "\x00}\x80\x00h@\x1ff" + // 0x01F60 0x00342: 0x01F66 + "\x00}\x84\x00h@\x1fg" + // 0x01F61 0x00342: 0x01F67 + "\x00\x0e\xa4\x00b`\x1fh" + // 0x003A9 0x00313: 0x01F68 + "\x00\x0e\xa4\x00b\x80\x1fi" + // 0x003A9 0x00314: 0x01F69 + "\x00}\xa0\x00`\x00\x1fj" + // 0x01F68 0x00300: 0x01F6A + "\x00}\xa4\x00`\x00\x1fk" + // 0x01F69 0x00300: 0x01F6B + "\x00}\xa0\x00` \x1fl" + // 0x01F68 0x00301: 0x01F6C + "\x00}\xa4\x00` \x1fm" + // 0x01F69 0x00301: 0x01F6D + "\x00}\xa0\x00h@\x1fn" + // 0x01F68 0x00342: 0x01F6E + "\x00}\xa4\x00h@\x1fo" + // 0x01F69 0x00342: 0x01F6F + "\x00\x0e\xc4\x00`\x00\x1fp" + // 0x003B1 0x00300: 0x01F70 + "\x00\x0e\xd4\x00`\x00\x1fr" + // 0x003B5 0x00300: 0x01F72 + "\x00\x0e\xdc\x00`\x00\x1ft" + // 0x003B7 0x00300: 0x01F74 + "\x00\x0e\xe4\x00`\x00\x1fv" + // 0x003B9 0x00300: 0x01F76 + "\x00\x0e\xfc\x00`\x00\x1fx" + // 0x003BF 0x00300: 0x01F78 + "\x00\x0f\x14\x00`\x00\x1fz" + // 0x003C5 0x00300: 0x01F7A + "\x00\x0f$\x00`\x00\x1f|" + // 0x003C9 0x00300: 0x01F7C + "\x00|\x00\x00h\xa0\x1f\x80" + // 0x01F00 0x00345: 0x01F80 + "\x00|\x04\x00h\xa0\x1f\x81" + // 0x01F01 0x00345: 0x01F81 + "\x00|\b\x00h\xa0\x1f\x82" + // 0x01F02 0x00345: 0x01F82 + "\x00|\f\x00h\xa0\x1f\x83" + // 0x01F03 0x00345: 0x01F83 + "\x00|\x10\x00h\xa0\x1f\x84" + // 0x01F04 0x00345: 0x01F84 + "\x00|\x14\x00h\xa0\x1f\x85" + // 0x01F05 0x00345: 0x01F85 + "\x00|\x18\x00h\xa0\x1f\x86" + // 0x01F06 0x00345: 0x01F86 + "\x00|\x1c\x00h\xa0\x1f\x87" + // 0x01F07 0x00345: 0x01F87 + "\x00| \x00h\xa0\x1f\x88" + // 0x01F08 0x00345: 0x01F88 + "\x00|$\x00h\xa0\x1f\x89" + // 0x01F09 0x00345: 0x01F89 + "\x00|(\x00h\xa0\x1f\x8a" + // 0x01F0A 0x00345: 0x01F8A + "\x00|,\x00h\xa0\x1f\x8b" + // 0x01F0B 0x00345: 0x01F8B + "\x00|0\x00h\xa0\x1f\x8c" + // 0x01F0C 0x00345: 0x01F8C + "\x00|4\x00h\xa0\x1f\x8d" + // 0x01F0D 0x00345: 0x01F8D + "\x00|8\x00h\xa0\x1f\x8e" + // 0x01F0E 0x00345: 0x01F8E + "\x00|<\x00h\xa0\x1f\x8f" + // 0x01F0F 0x00345: 0x01F8F + "\x00|\x80\x00h\xa0\x1f\x90" + // 0x01F20 0x00345: 0x01F90 + "\x00|\x84\x00h\xa0\x1f\x91" + // 0x01F21 0x00345: 0x01F91 + "\x00|\x88\x00h\xa0\x1f\x92" + // 0x01F22 0x00345: 0x01F92 + "\x00|\x8c\x00h\xa0\x1f\x93" + // 0x01F23 0x00345: 0x01F93 + "\x00|\x90\x00h\xa0\x1f\x94" + // 0x01F24 0x00345: 0x01F94 + "\x00|\x94\x00h\xa0\x1f\x95" + // 0x01F25 0x00345: 0x01F95 + "\x00|\x98\x00h\xa0\x1f\x96" + // 0x01F26 0x00345: 0x01F96 + "\x00|\x9c\x00h\xa0\x1f\x97" + // 0x01F27 0x00345: 0x01F97 + "\x00|\xa0\x00h\xa0\x1f\x98" + // 0x01F28 0x00345: 0x01F98 + "\x00|\xa4\x00h\xa0\x1f\x99" + // 0x01F29 0x00345: 0x01F99 + "\x00|\xa8\x00h\xa0\x1f\x9a" + // 0x01F2A 0x00345: 0x01F9A + "\x00|\xac\x00h\xa0\x1f\x9b" + // 0x01F2B 0x00345: 0x01F9B + "\x00|\xb0\x00h\xa0\x1f\x9c" + // 0x01F2C 0x00345: 0x01F9C + "\x00|\xb4\x00h\xa0\x1f\x9d" + // 0x01F2D 0x00345: 0x01F9D + "\x00|\xb8\x00h\xa0\x1f\x9e" + // 0x01F2E 0x00345: 0x01F9E + "\x00|\xbc\x00h\xa0\x1f\x9f" + // 0x01F2F 0x00345: 0x01F9F + "\x00}\x80\x00h\xa0\x1f\xa0" + // 0x01F60 0x00345: 0x01FA0 + "\x00}\x84\x00h\xa0\x1f\xa1" + // 0x01F61 0x00345: 0x01FA1 + "\x00}\x88\x00h\xa0\x1f\xa2" + // 0x01F62 0x00345: 0x01FA2 + "\x00}\x8c\x00h\xa0\x1f\xa3" + // 0x01F63 0x00345: 0x01FA3 + "\x00}\x90\x00h\xa0\x1f\xa4" + // 0x01F64 0x00345: 0x01FA4 + "\x00}\x94\x00h\xa0\x1f\xa5" + // 0x01F65 0x00345: 0x01FA5 + "\x00}\x98\x00h\xa0\x1f\xa6" + // 0x01F66 0x00345: 0x01FA6 + "\x00}\x9c\x00h\xa0\x1f\xa7" + // 0x01F67 0x00345: 0x01FA7 + "\x00}\xa0\x00h\xa0\x1f\xa8" + // 0x01F68 0x00345: 0x01FA8 + "\x00}\xa4\x00h\xa0\x1f\xa9" + // 0x01F69 0x00345: 0x01FA9 + "\x00}\xa8\x00h\xa0\x1f\xaa" + // 0x01F6A 0x00345: 0x01FAA + "\x00}\xac\x00h\xa0\x1f\xab" + // 0x01F6B 0x00345: 0x01FAB + "\x00}\xb0\x00h\xa0\x1f\xac" + // 0x01F6C 0x00345: 0x01FAC + "\x00}\xb4\x00h\xa0\x1f\xad" + // 0x01F6D 0x00345: 0x01FAD + "\x00}\xb8\x00h\xa0\x1f\xae" + // 0x01F6E 0x00345: 0x01FAE + "\x00}\xbc\x00h\xa0\x1f\xaf" + // 0x01F6F 0x00345: 0x01FAF + "\x00\x0e\xc4\x00`\xc0\x1f\xb0" + // 0x003B1 0x00306: 0x01FB0 + "\x00\x0e\xc4\x00`\x80\x1f\xb1" + // 0x003B1 0x00304: 0x01FB1 + "\x00}\xc0\x00h\xa0\x1f\xb2" + // 0x01F70 0x00345: 0x01FB2 + "\x00\x0e\xc4\x00h\xa0\x1f\xb3" + // 0x003B1 0x00345: 0x01FB3 + "\x00\x0e\xb0\x00h\xa0\x1f\xb4" + // 0x003AC 0x00345: 0x01FB4 + "\x00\x0e\xc4\x00h@\x1f\xb6" + // 0x003B1 0x00342: 0x01FB6 + "\x00~\xd8\x00h\xa0\x1f\xb7" + // 0x01FB6 0x00345: 0x01FB7 + "\x00\x0eD\x00`\xc0\x1f\xb8" + // 0x00391 0x00306: 0x01FB8 + "\x00\x0eD\x00`\x80\x1f\xb9" + // 0x00391 0x00304: 0x01FB9 + "\x00\x0eD\x00`\x00\x1f\xba" + // 0x00391 0x00300: 0x01FBA + "\x00\x0eD\x00h\xa0\x1f\xbc" + // 0x00391 0x00345: 0x01FBC + "\x00\x02\xa0\x00h@\x1f\xc1" + // 0x000A8 0x00342: 0x01FC1 + "\x00}\xd0\x00h\xa0\x1f\xc2" + // 0x01F74 0x00345: 0x01FC2 + "\x00\x0e\xdc\x00h\xa0\x1f\xc3" + // 0x003B7 0x00345: 0x01FC3 + "\x00\x0e\xb8\x00h\xa0\x1f\xc4" + // 0x003AE 0x00345: 0x01FC4 + "\x00\x0e\xdc\x00h@\x1f\xc6" + // 0x003B7 0x00342: 0x01FC6 + "\x00\x7f\x18\x00h\xa0\x1f\xc7" + // 0x01FC6 0x00345: 0x01FC7 + "\x00\x0eT\x00`\x00\x1f\xc8" + // 0x00395 0x00300: 0x01FC8 + "\x00\x0e\\\x00`\x00\x1f\xca" + // 0x00397 0x00300: 0x01FCA + "\x00\x0e\\\x00h\xa0\x1f\xcc" + // 0x00397 0x00345: 0x01FCC + "\x00~\xfc\x00`\x00\x1f\xcd" + // 0x01FBF 0x00300: 0x01FCD + "\x00~\xfc\x00` \x1f\xce" + // 0x01FBF 0x00301: 0x01FCE + "\x00~\xfc\x00h@\x1f\xcf" + // 0x01FBF 0x00342: 0x01FCF + "\x00\x0e\xe4\x00`\xc0\x1f\xd0" + // 0x003B9 0x00306: 0x01FD0 + "\x00\x0e\xe4\x00`\x80\x1f\xd1" + // 0x003B9 0x00304: 0x01FD1 + "\x00\x0f(\x00`\x00\x1f\xd2" + // 0x003CA 0x00300: 0x01FD2 + "\x00\x0e\xe4\x00h@\x1f\xd6" + // 0x003B9 0x00342: 0x01FD6 + "\x00\x0f(\x00h@\x1f\xd7" + // 0x003CA 0x00342: 0x01FD7 + "\x00\x0ed\x00`\xc0\x1f\xd8" + // 0x00399 0x00306: 0x01FD8 + "\x00\x0ed\x00`\x80\x1f\xd9" + // 0x00399 0x00304: 0x01FD9 + "\x00\x0ed\x00`\x00\x1f\xda" + // 0x00399 0x00300: 0x01FDA + "\x00\x7f\xf8\x00`\x00\x1f\xdd" + // 0x01FFE 0x00300: 0x01FDD + "\x00\x7f\xf8\x00` \x1f\xde" + // 0x01FFE 0x00301: 0x01FDE + "\x00\x7f\xf8\x00h@\x1f\xdf" + // 0x01FFE 0x00342: 0x01FDF + "\x00\x0f\x14\x00`\xc0\x1f\xe0" + // 0x003C5 0x00306: 0x01FE0 + "\x00\x0f\x14\x00`\x80\x1f\xe1" + // 0x003C5 0x00304: 0x01FE1 + "\x00\x0f,\x00`\x00\x1f\xe2" + // 0x003CB 0x00300: 0x01FE2 + "\x00\x0f\x04\x00b`\x1f\xe4" + // 0x003C1 0x00313: 0x01FE4 + "\x00\x0f\x04\x00b\x80\x1f\xe5" + // 0x003C1 0x00314: 0x01FE5 + "\x00\x0f\x14\x00h@\x1f\xe6" + // 0x003C5 0x00342: 0x01FE6 + "\x00\x0f,\x00h@\x1f\xe7" + // 0x003CB 0x00342: 0x01FE7 + "\x00\x0e\x94\x00`\xc0\x1f\xe8" + // 0x003A5 0x00306: 0x01FE8 + "\x00\x0e\x94\x00`\x80\x1f\xe9" + // 0x003A5 0x00304: 0x01FE9 + "\x00\x0e\x94\x00`\x00\x1f\xea" + // 0x003A5 0x00300: 0x01FEA + "\x00\x0e\x84\x00b\x80\x1f\xec" + // 0x003A1 0x00314: 0x01FEC + "\x00\x02\xa0\x00`\x00\x1f\xed" + // 0x000A8 0x00300: 0x01FED + "\x00}\xf0\x00h\xa0\x1f\xf2" + // 0x01F7C 0x00345: 0x01FF2 + "\x00\x0f$\x00h\xa0\x1f\xf3" + // 0x003C9 0x00345: 0x01FF3 + "\x00\x0f8\x00h\xa0\x1f\xf4" + // 0x003CE 0x00345: 0x01FF4 + "\x00\x0f$\x00h@\x1f\xf6" + // 0x003C9 0x00342: 0x01FF6 + "\x00\x7f\xd8\x00h\xa0\x1f\xf7" + // 0x01FF6 0x00345: 0x01FF7 + "\x00\x0e|\x00`\x00\x1f\xf8" + // 0x0039F 0x00300: 0x01FF8 + "\x00\x0e\xa4\x00`\x00\x1f\xfa" + // 0x003A9 0x00300: 0x01FFA + "\x00\x0e\xa4\x00h\xa0\x1f\xfc" + // 0x003A9 0x00345: 0x01FFC + "\x00\x86@\x00g\x00!\x9a" + // 0x02190 0x00338: 0x0219A + "\x00\x86H\x00g\x00!\x9b" + // 0x02192 0x00338: 0x0219B + "\x00\x86P\x00g\x00!\xae" + // 0x02194 0x00338: 0x021AE + "\x00\x87@\x00g\x00!\xcd" + // 0x021D0 0x00338: 0x021CD + "\x00\x87P\x00g\x00!\xce" + // 0x021D4 0x00338: 0x021CE + "\x00\x87H\x00g\x00!\xcf" + // 0x021D2 0x00338: 0x021CF + "\x00\x88\f\x00g\x00\"\x04" + // 0x02203 0x00338: 0x02204 + "\x00\x88 \x00g\x00\"\t" + // 0x02208 0x00338: 0x02209 + "\x00\x88,\x00g\x00\"\f" + // 0x0220B 0x00338: 0x0220C + "\x00\x88\x8c\x00g\x00\"$" + // 0x02223 0x00338: 0x02224 + "\x00\x88\x94\x00g\x00\"&" + // 0x02225 0x00338: 0x02226 + "\x00\x88\xf0\x00g\x00\"A" + // 0x0223C 0x00338: 0x02241 + "\x00\x89\f\x00g\x00\"D" + // 0x02243 0x00338: 0x02244 + "\x00\x89\x14\x00g\x00\"G" + // 0x02245 0x00338: 0x02247 + "\x00\x89 \x00g\x00\"I" + // 0x02248 0x00338: 0x02249 + "\x00\x00\xf4\x00g\x00\"`" + // 0x0003D 0x00338: 0x02260 + "\x00\x89\x84\x00g\x00\"b" + // 0x02261 0x00338: 0x02262 + "\x00\x894\x00g\x00\"m" + // 0x0224D 0x00338: 0x0226D + "\x00\x00\xf0\x00g\x00\"n" + // 0x0003C 0x00338: 0x0226E + "\x00\x00\xf8\x00g\x00\"o" + // 0x0003E 0x00338: 0x0226F + "\x00\x89\x90\x00g\x00\"p" + // 0x02264 0x00338: 0x02270 + "\x00\x89\x94\x00g\x00\"q" + // 0x02265 0x00338: 0x02271 + "\x00\x89\xc8\x00g\x00\"t" + // 0x02272 0x00338: 0x02274 + "\x00\x89\xcc\x00g\x00\"u" + // 0x02273 0x00338: 0x02275 + "\x00\x89\xd8\x00g\x00\"x" + // 0x02276 0x00338: 0x02278 + "\x00\x89\xdc\x00g\x00\"y" + // 0x02277 0x00338: 0x02279 + "\x00\x89\xe8\x00g\x00\"\x80" + // 0x0227A 0x00338: 0x02280 + "\x00\x89\xec\x00g\x00\"\x81" + // 0x0227B 0x00338: 0x02281 + "\x00\x8a\b\x00g\x00\"\x84" + // 0x02282 0x00338: 0x02284 + "\x00\x8a\f\x00g\x00\"\x85" + // 0x02283 0x00338: 0x02285 + "\x00\x8a\x18\x00g\x00\"\x88" + // 0x02286 0x00338: 0x02288 + "\x00\x8a\x1c\x00g\x00\"\x89" + // 0x02287 0x00338: 0x02289 + "\x00\x8a\x88\x00g\x00\"\xac" + // 0x022A2 0x00338: 0x022AC + "\x00\x8a\xa0\x00g\x00\"\xad" + // 0x022A8 0x00338: 0x022AD + "\x00\x8a\xa4\x00g\x00\"\xae" + // 0x022A9 0x00338: 0x022AE + "\x00\x8a\xac\x00g\x00\"\xaf" + // 0x022AB 0x00338: 0x022AF + "\x00\x89\xf0\x00g\x00\"\xe0" + // 0x0227C 0x00338: 0x022E0 + "\x00\x89\xf4\x00g\x00\"\xe1" + // 0x0227D 0x00338: 0x022E1 + "\x00\x8aD\x00g\x00\"\xe2" + // 0x02291 0x00338: 0x022E2 + "\x00\x8aH\x00g\x00\"\xe3" + // 0x02292 0x00338: 0x022E3 + "\x00\x8a\xc8\x00g\x00\"\xea" + // 0x022B2 0x00338: 0x022EA + "\x00\x8a\xcc\x00g\x00\"\xeb" + // 0x022B3 0x00338: 0x022EB + "\x00\x8a\xd0\x00g\x00\"\xec" + // 0x022B4 0x00338: 0x022EC + "\x00\x8a\xd4\x00g\x00\"\xed" + // 0x022B5 0x00338: 0x022ED + "\x00\xc1,\x06\x13 0L" + // 0x0304B 0x03099: 0x0304C + "\x00\xc14\x06\x13 0N" + // 0x0304D 0x03099: 0x0304E + "\x00\xc1<\x06\x13 0P" + // 0x0304F 0x03099: 0x03050 + "\x00\xc1D\x06\x13 0R" + // 0x03051 0x03099: 0x03052 + "\x00\xc1L\x06\x13 0T" + // 0x03053 0x03099: 0x03054 + "\x00\xc1T\x06\x13 0V" + // 0x03055 0x03099: 0x03056 + "\x00\xc1\\\x06\x13 0X" + // 0x03057 0x03099: 0x03058 + "\x00\xc1d\x06\x13 0Z" + // 0x03059 0x03099: 0x0305A + "\x00\xc1l\x06\x13 0\\" + // 0x0305B 0x03099: 0x0305C + "\x00\xc1t\x06\x13 0^" + // 0x0305D 0x03099: 0x0305E + "\x00\xc1|\x06\x13 0`" + // 0x0305F 0x03099: 0x03060 + "\x00\xc1\x84\x06\x13 0b" + // 0x03061 0x03099: 0x03062 + "\x00\xc1\x90\x06\x13 0e" + // 0x03064 0x03099: 0x03065 + "\x00\xc1\x98\x06\x13 0g" + // 0x03066 0x03099: 0x03067 + "\x00\xc1\xa0\x06\x13 0i" + // 0x03068 0x03099: 0x03069 + "\x00\xc1\xbc\x06\x13 0p" + // 0x0306F 0x03099: 0x03070 + "\x00\xc1\xbc\x06\x13@0q" + // 0x0306F 0x0309A: 0x03071 + "\x00\xc1\xc8\x06\x13 0s" + // 0x03072 0x03099: 0x03073 + "\x00\xc1\xc8\x06\x13@0t" + // 0x03072 0x0309A: 0x03074 + "\x00\xc1\xd4\x06\x13 0v" + // 0x03075 0x03099: 0x03076 + "\x00\xc1\xd4\x06\x13@0w" + // 0x03075 0x0309A: 0x03077 + "\x00\xc1\xe0\x06\x13 0y" + // 0x03078 0x03099: 0x03079 + "\x00\xc1\xe0\x06\x13@0z" + // 0x03078 0x0309A: 0x0307A + "\x00\xc1\xec\x06\x13 0|" + // 0x0307B 0x03099: 0x0307C + "\x00\xc1\xec\x06\x13@0}" + // 0x0307B 0x0309A: 0x0307D + "\x00\xc1\x18\x06\x13 0\x94" + // 0x03046 0x03099: 0x03094 + "\x00\xc2t\x06\x13 0\x9e" + // 0x0309D 0x03099: 0x0309E + "\x00¬\x06\x13 0\xac" + // 0x030AB 0x03099: 0x030AC + "\x00´\x06\x13 0\xae" + // 0x030AD 0x03099: 0x030AE + "\x00¼\x06\x13 0\xb0" + // 0x030AF 0x03099: 0x030B0 + "\x00\xc2\xc4\x06\x13 0\xb2" + // 0x030B1 0x03099: 0x030B2 + "\x00\xc2\xcc\x06\x13 0\xb4" + // 0x030B3 0x03099: 0x030B4 + "\x00\xc2\xd4\x06\x13 0\xb6" + // 0x030B5 0x03099: 0x030B6 + "\x00\xc2\xdc\x06\x13 0\xb8" + // 0x030B7 0x03099: 0x030B8 + "\x00\xc2\xe4\x06\x13 0\xba" + // 0x030B9 0x03099: 0x030BA + "\x00\xc2\xec\x06\x13 0\xbc" + // 0x030BB 0x03099: 0x030BC + "\x00\xc2\xf4\x06\x13 0\xbe" + // 0x030BD 0x03099: 0x030BE + "\x00\xc2\xfc\x06\x13 0\xc0" + // 0x030BF 0x03099: 0x030C0 + "\x00\xc3\x04\x06\x13 0\xc2" + // 0x030C1 0x03099: 0x030C2 + "\x00\xc3\x10\x06\x13 0\xc5" + // 0x030C4 0x03099: 0x030C5 + "\x00\xc3\x18\x06\x13 0\xc7" + // 0x030C6 0x03099: 0x030C7 + "\x00\xc3 \x06\x13 0\xc9" + // 0x030C8 0x03099: 0x030C9 + "\x00\xc3<\x06\x13 0\xd0" + // 0x030CF 0x03099: 0x030D0 + "\x00\xc3<\x06\x13@0\xd1" + // 0x030CF 0x0309A: 0x030D1 + "\x00\xc3H\x06\x13 0\xd3" + // 0x030D2 0x03099: 0x030D3 + "\x00\xc3H\x06\x13@0\xd4" + // 0x030D2 0x0309A: 0x030D4 + "\x00\xc3T\x06\x13 0\xd6" + // 0x030D5 0x03099: 0x030D6 + "\x00\xc3T\x06\x13@0\xd7" + // 0x030D5 0x0309A: 0x030D7 + "\x00\xc3`\x06\x13 0\xd9" + // 0x030D8 0x03099: 0x030D9 + "\x00\xc3`\x06\x13@0\xda" + // 0x030D8 0x0309A: 0x030DA + "\x00\xc3l\x06\x13 0\xdc" + // 0x030DB 0x03099: 0x030DC + "\x00\xc3l\x06\x13@0\xdd" + // 0x030DB 0x0309A: 0x030DD + "\x00\u0098\x06\x13 0\xf4" + // 0x030A6 0x03099: 0x030F4 + "\x00ü\x06\x13 0\xf7" + // 0x030EF 0x03099: 0x030F7 + "\x00\xc3\xc0\x06\x13 0\xf8" + // 0x030F0 0x03099: 0x030F8 + "\x00\xc3\xc4\x06\x13 0\xf9" + // 0x030F1 0x03099: 0x030F9 + "\x00\xc3\xc8\x06\x13 0\xfa" + // 0x030F2 0x03099: 0x030FA + "\x00\xc3\xf4\x06\x13 0\xfe" + // 0x030FD 0x03099: 0x030FE + "\x04\x17H\x00`\xe1\x05\xc9" + // 0x105D2 0x00307: 0x105C9 + "\x04\x17h\x00`\xe1\x05\xe4" + // 0x105DA 0x00307: 0x105E4 + "\x04Bd\"\x17A\x10\x9a" + // 0x11099 0x110BA: 0x1109A + "\x04Bl\"\x17A\x10\x9c" + // 0x1109B 0x110BA: 0x1109C + "\x04B\x94\"\x17A\x10\xab" + // 0x110A5 0x110BA: 0x110AB + "\x04D\xc4\"$\xe1\x11." + // 0x11131 0x11127: 0x1112E + "\x04D\xc8\"$\xe1\x11/" + // 0x11132 0x11127: 0x1112F + "\x04M\x1c\"g\xc1\x13K" + // 0x11347 0x1133E: 0x1134B + "\x04M\x1c\"j\xe1\x13L" + // 0x11347 0x11357: 0x1134C + "\x04N\b\"y!\x13\x83" + // 0x11382 0x113C9: 0x11383 + "\x04N\x10\"wa\x13\x85" + // 0x11384 0x113BB: 0x11385 + "\x04N,\"xA\x13\x8e" + // 0x1138B 0x113C2: 0x1138E + "\x04N@\"y!\x13\x91" + // 0x11390 0x113C9: 0x11391 + "\x04O\b\"xA\x13\xc5" + // 0x113C2 0x113C2: 0x113C5 + "\x04O\b\"w\x01\x13\xc7" + // 0x113C2 0x113B8: 0x113C7 + "\x04O\b\"y!\x13\xc8" + // 0x113C2 0x113C9: 0x113C8 + "\x04R\xe4\"\x97A\x14\xbb" + // 0x114B9 0x114BA: 0x114BB + "\x04R\xe4\"\x96\x01\x14\xbc" + // 0x114B9 0x114B0: 0x114BC + "\x04R\xe4\"\x97\xa1\x14\xbe" + // 0x114B9 0x114BD: 0x114BE + "\x04V\xe0\"\xb5\xe1\x15\xba" + // 0x115B8 0x115AF: 0x115BA + "\x04V\xe4\"\xb5\xe1\x15\xbb" + // 0x115B9 0x115AF: 0x115BB + "\x04d\xd4#&\x01\x198" + // 0x11935 0x11930: 0x11938 + "\x05\x84x,#\xc1a!" + // 0x1611E 0x1611E: 0x16121 + "\x05\x84x,%!a\"" + // 0x1611E 0x16129: 0x16122 + "\x05\x84x,#\xe1a#" + // 0x1611E 0x1611F: 0x16123 + "\x05\x84\xa4,#\xe1a$" + // 0x16129 0x1611F: 0x16124 + "\x05\x84x,$\x01a%" + // 0x1611E 0x16120: 0x16125 + "\x05\x84\x84,#\xe1a&" + // 0x16121 0x1611F: 0x16126 + "\x05\x84\x88,#\xe1a'" + // 0x16122 0x1611F: 0x16127 + "\x05\x84\x84,$\x01a(" + // 0x16121 0x16120: 0x16128 + "\x05\xb5\x9c-\xac\xe1mh" + // 0x16D67 0x16D67: 0x16D68 + "\x05\xb5\x8c-\xac\xe1mi" + // 0x16D63 0x16D67: 0x16D69 + "\x05\xb5\xa4-\xac\xe1mj" + // 0x16D69 0x16D67: 0x16D6A "" // Total size of tables: 57KB (58086 bytes) diff --git a/vendor/golang.org/x/text/unicode/norm/transform.go b/vendor/golang.org/x/text/unicode/norm/transform.go index a1d366a..583230d 100644 --- a/vendor/golang.org/x/text/unicode/norm/transform.go +++ b/vendor/golang.org/x/text/unicode/norm/transform.go @@ -33,7 +33,7 @@ func (f Form) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) return nDst + n, nSrc + n, err } - if err == nil && n < len(src) && !atEOF { + if err == nil && n < len(src) { err = transform.ErrShortSrc } return n, n, err @@ -67,6 +67,7 @@ func (f Form) transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) nSrc = end // Next quickSpan. + var err error end = rb.nsrc eof := atEOF if n := nSrc + len(dst) - nDst; n < end { @@ -79,7 +80,7 @@ func (f Form) transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) nSrc += n nDst += n if ok { - if err == nil && n < rb.nsrc && !atEOF { + if err == nil && nSrc < rb.nsrc { err = transform.ErrShortSrc } return nDst, nSrc, err diff --git a/vendor/google.golang.org/grpc/CONTRIBUTING.md b/vendor/google.golang.org/grpc/CONTRIBUTING.md index 2079de7..bd80b1f 100644 --- a/vendor/google.golang.org/grpc/CONTRIBUTING.md +++ b/vendor/google.golang.org/grpc/CONTRIBUTING.md @@ -23,6 +23,29 @@ wanted"](https://github.com/grpc/grpc-go/issues?q=sort%3Aupdated-desc%20is%3Aiss are especially nice for first-time contributors, as they should be well-defined problems that already have agreed-upon solutions. +## Generative AI Policy + +AI tools have the ability to produce more code than is possible for the gRPC +team to read, understand, review, and accept into the repository. For this +reason, we request that all contributions adhere to the following rules: + +1. **No AI-Generated Interactions:** All communication in the repo must be + authored by a human. _Exception: AIs may be used for directed writing + assistance or translation._ Absolutely no automated agents are allowed to + directly publish to GitHub. + +2. **Author Ownership and Accountability:** Code contributions are expected to + be fully owned and understood by the human contributor. If the code was + produced by generative AI, the author is expected to have reviewed and + understood it in its entirety before submitting it for review. This includes + all content: production code, tests, examples, tools, etc. + +In addition to the above requirements, any AI-assisted contributions must also +comply with the [Linux Foundation Generative AI +Policy](https://www.linuxfoundation.org/legal/generative-ai). This includes +confirming that all contributions are legally allowed to be contributed to the +gRPC project under the applicable license terms. + ## Code Style We follow [Google's published Go style diff --git a/vendor/google.golang.org/grpc/balancer/endpointsharding/endpointsharding.go b/vendor/google.golang.org/grpc/balancer/endpointsharding/endpointsharding.go index 12479f6..22dbc52 100644 --- a/vendor/google.golang.org/grpc/balancer/endpointsharding/endpointsharding.go +++ b/vendor/google.golang.org/grpc/balancer/endpointsharding/endpointsharding.go @@ -39,27 +39,14 @@ import ( var randIntN = rand.IntN -// ChildState is the balancer state of a child along with the endpoint which -// identifies the child balancer. +// ChildState is the state of a child balancer. type ChildState struct { - Endpoint resolver.Endpoint - State balancer.State - - // Balancer exposes only the ExitIdler interface of the child LB policy. - // Other methods of the child policy are called only by endpointsharding. - Balancer ExitIdler + Endpoint resolver.Endpoint // Endpoint of the child balancer. + State balancer.State // State of the child balancer. + ExitIdle func() // Function to exit the child balancer from IDLE state. } -// ExitIdler provides access to only the ExitIdle method of the child balancer. -type ExitIdler interface { - // ExitIdle instructs the LB policy to reconnect to backends / exit the - // IDLE state, if appropriate and possible. Note that SubConns that enter - // the IDLE state will not reconnect until SubConn.Connect is called. - ExitIdle() -} - -// Options are the options to configure the behaviour of the -// endpointsharding balancer. +// Options configure the behaviour of the endpointsharding balancer. type Options struct { // DisableAutoReconnect allows the balancer to keep child balancer in the // IDLE state until they are explicitly triggered to exit using the @@ -77,14 +64,13 @@ type ChildBuilderFunc func(cc balancer.ClientConn, opts balancer.BuildOptions) b // policies each owning a single endpoint. The endpointsharding balancer // forwards the LoadBalancingConfig in ClientConn state updates to its children. func NewBalancer(cc balancer.ClientConn, opts balancer.BuildOptions, childBuilder ChildBuilderFunc, esOpts Options) balancer.Balancer { - es := &endpointSharding{ + return &endpointSharding{ cc: cc, bOpts: opts, esOpts: esOpts, childBuilder: childBuilder, + endpoints: resolver.NewEndpointMap[*endpointState](), } - es.children.Store(resolver.NewEndpointMap[*balancerWrapper]()) - return es } // endpointSharding is a balancer that wraps child balancers. It creates a child @@ -96,124 +82,129 @@ type endpointSharding struct { esOpts Options childBuilder ChildBuilderFunc - // childMu synchronizes calls to any single child. It must be held for all - // calls into a child. To avoid deadlocks, do not acquire childMu while - // holding mu. - childMu sync.Mutex - children atomic.Pointer[resolver.EndpointMap[*balancerWrapper]] - - // inhibitChildUpdates is set during UpdateClientConnState/ResolverError - // calls (calls to children will each produce an update, only want one - // update). - inhibitChildUpdates atomic.Bool - - // mu synchronizes access to the state stored in balancerWrappers in the - // children field. mu must not be held during calls into a child since - // synchronous calls back from the child may require taking mu, causing a - // deadlock. To avoid deadlocks, do not acquire childMu while holding mu. - mu sync.Mutex + // mu guards access to the below fields and guarantees mutual exclusion + // between top-down methods (like UpdateClientConnState, ResolverError etc, + // which are already serialized) and bottom-up methods (like UpdateState) + // that can be called concurrently. + // + // Lock ordering & deadlock prevention: + // Child callbacks (like UpdateState) acquire this mutex to push state updates + // to the parent. This establishes a strict lock ordering: + // [endpointState.childMu] -> [endpointSharding.mu] + // + // To prevent deadlocks, we must never invert this order. Therefore, we must + // never call any methods on a child balancer while holding this mutex. If we + // did, and that child balancer invoked UpdateState synchronously, it would + // attempt to re-acquire this mutex, causing a deadlock. + // + // Concurrency: + // Top-down operations need to iterate over all children. To ensure a + // single, clean aggregated update at the end of such operations, we inhibit + // intermediate updates from children. We grab this mutex briefly to set + // `inhibitChildUpdates = true` and immediately release it. This allows us + // to perform the potentially slow, top-down child updates without holding + // any parent locks. Once finished, we grab the mutex again to unset the + // flag and push the final aggregated state. An update from a child during + // this time will *only* update the child state, and will not access the + // endpoints map or push an aggregated state to the parent. + mu sync.Mutex + endpoints *resolver.EndpointMap[*endpointState] + inhibitChildUpdates bool } // rotateEndpoints returns a slice of all the input endpoints rotated a random // amount. func rotateEndpoints(es []resolver.Endpoint) []resolver.Endpoint { - les := len(es) - if les == 0 { + n := len(es) + if n == 0 { return es } - r := randIntN(les) + r := randIntN(n) + // Make a copy to avoid mutating data beyond the end of es. - ret := make([]resolver.Endpoint, les) + ret := make([]resolver.Endpoint, n) copy(ret, es[r:]) - copy(ret[les-r:], es[:r]) + copy(ret[n-r:], es[:r]) return ret } // UpdateClientConnState creates a child for new endpoints and deletes children // for endpoints that are no longer present. It also updates all the children, // and sends a single synchronous update of the childrens' aggregated state at -// the end of the UpdateClientConnState operation. If any endpoint has no -// addresses it will ignore that endpoint. Otherwise, returns first error found -// from a child, but fully processes the new update. +// the end of the UpdateClientConnState operation. +// +// Returns the first error found from a child, but fully processes the update. func (es *endpointSharding) UpdateClientConnState(state balancer.ClientConnState) error { - es.childMu.Lock() - defer es.childMu.Unlock() + es.inhibitUpdatesFromChildren() - es.inhibitChildUpdates.Store(true) - defer func() { - es.inhibitChildUpdates.Store(false) - es.updateState() - }() - var ret error - - children := es.children.Load() - newChildren := resolver.NewEndpointMap[*balancerWrapper]() - - // Update/Create new children. + // Update/create child balancers for each endpoint in the update. Note that we + // don't hold the mutex here, but this is fine because inhibitChildUpdates is + // true, and therefore UpdateState will not access es.endpoints. + var retErr error + newEndpoints := resolver.NewEndpointMap[*endpointState]() for _, endpoint := range rotateEndpoints(state.ResolverState.Endpoints) { - if _, ok := newChildren.Get(endpoint); ok { - // Endpoint child was already created, continue to avoid duplicate - // update. + if _, ok := newEndpoints.Get(endpoint); ok { + // Skip duplicate endpoints. continue } - childBalancer, ok := children.Get(endpoint) + epState, ok := es.endpoints.Get(endpoint) if ok { - // Endpoint attributes may have changed, update the stored endpoint. - es.mu.Lock() - childBalancer.childState.Endpoint = endpoint - es.mu.Unlock() + // Endpoint child already exists, update the stored endpoint. + epState.endpoint = endpoint } else { - childBalancer = &balancerWrapper{ - childState: ChildState{Endpoint: endpoint}, - ClientConn: es.cc, - es: es, + // Endpoint child does not exist, create a new one. + epState = &endpointState{ + ClientConn: es.cc, + parent: es, + endpoint: endpoint, + disableAutoReconnect: es.esOpts.DisableAutoReconnect, } - childBalancer.childState.Balancer = childBalancer - childBalancer.child = es.childBuilder(childBalancer, es.bOpts) + epState.childLB = es.childBuilder(epState, es.bOpts) } - newChildren.Set(endpoint, childBalancer) - if err := childBalancer.updateClientConnStateLocked(balancer.ClientConnState{ + // Update the endpoint state for the endpoint. + newEndpoints.Set(endpoint, epState) + + if err := epState.updateClientConnState(balancer.ClientConnState{ BalancerConfig: state.BalancerConfig, ResolverState: resolver.State{ Endpoints: []resolver.Endpoint{endpoint}, Attributes: state.ResolverState.Attributes, }, - }); err != nil && ret == nil { - // Return first error found, and always commit full processing of - // updating children. If desired to process more specific errors - // across all endpoints, caller should make these specific - // validations, this is a current limitation for simplicity sake. - ret = err + }); err != nil && retErr == nil { + // Keep the first error found from any child. + retErr = err } } + // Delete old children that are no longer present. - for e, child := range children.All() { - if _, ok := newChildren.Get(e); !ok { - child.closeLocked() + for e, child := range es.endpoints.All() { + if _, ok := newEndpoints.Get(e); !ok { + child.close() } } - es.children.Store(newChildren) - if newChildren.Len() == 0 { - return balancer.ErrBadResolverState + + if newEndpoints.Len() == 0 { + retErr = balancer.ErrBadResolverState } - return ret + + es.mu.Lock() + es.endpoints = newEndpoints + es.inhibitChildUpdates = false + es.updateStateLocked() + es.mu.Unlock() + + return retErr } // ResolverError forwards the resolver error to all of the endpointSharding's // children and sends a single synchronous update of the childStates at the end // of the ResolverError operation. func (es *endpointSharding) ResolverError(err error) { - es.childMu.Lock() - defer es.childMu.Unlock() - es.inhibitChildUpdates.Store(true) - defer func() { - es.inhibitChildUpdates.Store(false) - es.updateState() - }() - children := es.children.Load() - for _, child := range children.All() { - child.resolverErrorLocked(err) + es.inhibitUpdatesFromChildren() + for _, child := range es.endpoints.All() { + child.resolverError(err) } + es.allowUpdatesFromChildren() } func (es *endpointSharding) UpdateSubConnState(balancer.SubConn, balancer.SubConnState) { @@ -221,41 +212,49 @@ func (es *endpointSharding) UpdateSubConnState(balancer.SubConn, balancer.SubCon } func (es *endpointSharding) Close() { - es.childMu.Lock() - defer es.childMu.Unlock() - children := es.children.Load() - for _, child := range children.All() { - child.closeLocked() + es.inhibitUpdatesFromChildren() + for _, child := range es.endpoints.All() { + child.close() } } func (es *endpointSharding) ExitIdle() { - es.childMu.Lock() - defer es.childMu.Unlock() - for _, bw := range es.children.Load().All() { - if !bw.isClosed { - bw.child.ExitIdle() - } + es.inhibitUpdatesFromChildren() + for _, child := range es.endpoints.All() { + child.exitIdle() } + es.allowUpdatesFromChildren() } -// updateState updates this component's state. It sends the aggregated state, -// and a picker with round robin behavior with all the child states present if -// needed. -func (es *endpointSharding) updateState() { - if es.inhibitChildUpdates.Load() { - return - } +func (es *endpointSharding) inhibitUpdatesFromChildren() { + es.mu.Lock() + es.inhibitChildUpdates = true + es.mu.Unlock() +} + +func (es *endpointSharding) allowUpdatesFromChildren() { + es.mu.Lock() + es.inhibitChildUpdates = false + es.updateStateLocked() + es.mu.Unlock() +} + +// updateStateLocked updates this component's state. It sends the aggregated +// state, and a picker with round robin behavior with all the child states +// present if needed. This method must only be called when inhibitChildUpdates +// is false. +// +// Caller must hold es.mu. +func (es *endpointSharding) updateStateLocked() { var readyPickers, connectingPickers, idlePickers, transientFailurePickers []balancer.Picker - es.mu.Lock() - defer es.mu.Unlock() - - children := es.children.Load() - childStates := make([]ChildState, 0, children.Len()) - - for _, child := range children.All() { - childState := child.childState + childStates := make([]ChildState, 0, es.endpoints.Len()) + for _, epState := range es.endpoints.All() { + childState := ChildState{ + Endpoint: epState.endpoint, + State: epState.state, + ExitIdle: func() { go epState.exitIdle() }, + } childStates = append(childStates, childState) childPicker := childState.State.Picker switch childState.State.ConnectivityState { @@ -292,14 +291,14 @@ func (es *endpointSharding) updateState() { aggState = connectivity.TransientFailure pickers = []balancer.Picker{base.NewErrPicker(errors.New("no children to pick from"))} } // No children (resolver error before valid update). - p := &pickerWithChildStates{ - pickers: pickers, - childStates: childStates, - next: uint32(randIntN(len(pickers))), - } + es.cc.UpdateState(balancer.State{ ConnectivityState: aggState, - Picker: p, + Picker: &pickerWithChildStates{ + pickers: pickers, + childStates: childStates, + next: uint32(randIntN(len(pickers))), + }, }) } @@ -328,61 +327,59 @@ func ChildStatesFromPicker(picker balancer.Picker) []ChildState { return p.childStates } -// balancerWrapper is a wrapper of a balancer. It ID's a child balancer by -// endpoint, and persists recent child balancer state. -type balancerWrapper struct { - // The following fields are initialized at build time and read-only after - // that and therefore do not need to be guarded by a mutex. +// endpointState is the internal state maintained for each endpoint. +type endpointState struct { + balancer.ClientConn // Embedded to intercept UpdateState - // child contains the wrapped balancer. Access its methods only through - // methods on balancerWrapper to ensure proper synchronization - child balancer.Balancer - balancer.ClientConn // embed to intercept UpdateState, doesn't deal with SubConns + parent *endpointSharding // Parent endpointsharding balancer. + endpoint resolver.Endpoint // Endpoint of the child balancer. + state balancer.State // State of the child balancer. + disableAutoReconnect bool // Whether to disable auto reconnect for this child. - es *endpointSharding - - // Access to the following fields is guarded by es.mu. - - childState ChildState - isClosed bool + childMu sync.Mutex // Guarantees mutual exclusion for Balancer API calls to the child balancer. + childLB balancer.Balancer // Child balancer. + closed bool // Tracks closure of the child balancer to ensure ExitIdle is not called after Close(). } -func (bw *balancerWrapper) UpdateState(state balancer.State) { - bw.es.mu.Lock() - bw.childState.State = state - bw.es.mu.Unlock() - if state.ConnectivityState == connectivity.Idle && !bw.es.esOpts.DisableAutoReconnect { - bw.ExitIdle() +func (es *endpointState) UpdateState(state balancer.State) { + es.parent.mu.Lock() + es.state = state + if !es.parent.inhibitChildUpdates { + es.parent.updateStateLocked() + } + es.parent.mu.Unlock() + + if state.ConnectivityState == connectivity.Idle && !es.disableAutoReconnect { + go es.exitIdle() } - bw.es.updateState() } -// ExitIdle pings an IDLE child balancer to exit idle in a new goroutine to -// avoid deadlocks due to synchronous balancer state updates. -func (bw *balancerWrapper) ExitIdle() { - go func() { - bw.es.childMu.Lock() - if !bw.isClosed { - bw.child.ExitIdle() - } - bw.es.childMu.Unlock() - }() +func (es *endpointState) updateClientConnState(state balancer.ClientConnState) error { + es.childMu.Lock() + err := es.childLB.UpdateClientConnState(state) + es.childMu.Unlock() + return err } -// updateClientConnStateLocked delivers the ClientConnState to the child -// balancer. Callers must hold the child mutex of the parent endpointsharding -// balancer. -func (bw *balancerWrapper) updateClientConnStateLocked(ccs balancer.ClientConnState) error { - return bw.child.UpdateClientConnState(ccs) +func (es *endpointState) resolverError(err error) { + es.childMu.Lock() + es.childLB.ResolverError(err) + es.childMu.Unlock() } -// closeLocked closes the child balancer. Callers must hold the child mutext of -// the parent endpointsharding balancer. -func (bw *balancerWrapper) closeLocked() { - bw.child.Close() - bw.isClosed = true +func (es *endpointState) close() { + es.childMu.Lock() + if !es.closed { + es.closed = true + es.childLB.Close() + } + es.childMu.Unlock() } -func (bw *balancerWrapper) resolverErrorLocked(err error) { - bw.child.ResolverError(err) +func (es *endpointState) exitIdle() { + es.childMu.Lock() + if !es.closed { + es.childLB.ExitIdle() + } + es.childMu.Unlock() } diff --git a/vendor/google.golang.org/grpc/balancer/pickfirst/pickfirst.go b/vendor/google.golang.org/grpc/balancer/pickfirst/pickfirst.go index d48bc30..ddd08f5 100644 --- a/vendor/google.golang.org/grpc/balancer/pickfirst/pickfirst.go +++ b/vendor/google.golang.org/grpc/balancer/pickfirst/pickfirst.go @@ -36,7 +36,6 @@ import ( "google.golang.org/grpc/balancer/pickfirst/internal" "google.golang.org/grpc/connectivity" "google.golang.org/grpc/experimental/balancer/weight" - expstats "google.golang.org/grpc/experimental/stats" "google.golang.org/grpc/grpclog" "google.golang.org/grpc/internal/envconfig" internalgrpclog "google.golang.org/grpc/internal/grpclog" @@ -56,30 +55,7 @@ const Name = "pick_first" // attributes to indicate whether the health listener usage is enabled. type enableHealthListenerKeyType struct{} -var ( - logger = grpclog.Component("pick-first-leaf-lb") - disconnectionsMetric = expstats.RegisterInt64Count(expstats.MetricDescriptor{ - Name: "grpc.lb.pick_first.disconnections", - Description: "EXPERIMENTAL. Number of times the selected subchannel becomes disconnected.", - Unit: "{disconnection}", - Labels: []string{"grpc.target"}, - Default: false, - }) - connectionAttemptsSucceededMetric = expstats.RegisterInt64Count(expstats.MetricDescriptor{ - Name: "grpc.lb.pick_first.connection_attempts_succeeded", - Description: "EXPERIMENTAL. Number of successful connection attempts.", - Unit: "{attempt}", - Labels: []string{"grpc.target"}, - Default: false, - }) - connectionAttemptsFailedMetric = expstats.RegisterInt64Count(expstats.MetricDescriptor{ - Name: "grpc.lb.pick_first.connection_attempts_failed", - Description: "EXPERIMENTAL. Number of failed connection attempts.", - Unit: "{attempt}", - Labels: []string{"grpc.target"}, - Default: false, - }) -) +var logger = grpclog.Component("pick-first-leaf-lb") const ( // TODO: change to pick-first when this becomes the default pick_first policy. @@ -101,11 +77,9 @@ const ( type pickfirstBuilder struct{} -func (pickfirstBuilder) Build(cc balancer.ClientConn, bo balancer.BuildOptions) balancer.Balancer { +func (pickfirstBuilder) Build(cc balancer.ClientConn, _ balancer.BuildOptions) balancer.Balancer { b := &pickfirstBalancer{ - cc: cc, - target: bo.Target.String(), - metricsRecorder: cc.MetricsRecorder(), + cc: cc, subConns: resolver.NewAddressMapV2[*scData](), state: connectivity.Connecting, @@ -185,10 +159,8 @@ func (b *pickfirstBalancer) newSCData(addr resolver.Address) (*scData, error) { type pickfirstBalancer struct { // The following fields are initialized at build time and read-only after // that and therefore do not need to be guarded by a mutex. - logger *internalgrpclog.PrefixLogger - cc balancer.ClientConn - target string - metricsRecorder expstats.MetricsRecorder // guaranteed to be non nil + logger *internalgrpclog.PrefixLogger + cc balancer.ClientConn // The mutex is used to ensure synchronization of updates triggered // from the idle picker and the already serialized resolver, @@ -633,14 +605,11 @@ func (b *pickfirstBalancer) updateSubConnState(sd *scData, newState balancer.Sub return } - // Record a connection attempt when exiting CONNECTING. if newState.ConnectivityState == connectivity.TransientFailure { sd.connectionFailedInFirstPass = true - connectionAttemptsFailedMetric.Record(b.metricsRecorder, 1, b.target) } if newState.ConnectivityState == connectivity.Ready { - connectionAttemptsSucceededMetric.Record(b.metricsRecorder, 1, b.target) b.shutdownRemainingLocked(sd) if !b.addressList.seekTo(sd.addr) { // This should not fail as we should have only one SubConn after @@ -689,15 +658,6 @@ func (b *pickfirstBalancer) updateSubConnState(sd *scData, newState balancer.Sub // the first address when the picker is used. b.shutdownRemainingLocked(sd) sd.effectiveState = newState.ConnectivityState - // READY SubConn interspliced in between CONNECTING and IDLE, need to - // account for that. - if oldState == connectivity.Connecting { - // A known issue (https://github.com/grpc/grpc-go/issues/7862) - // causes a race that prevents the READY state change notification. - // This works around it. - connectionAttemptsSucceededMetric.Record(b.metricsRecorder, 1, b.target) - } - disconnectionsMetric.Record(b.metricsRecorder, 1, b.target) b.addressList.reset() b.updateBalancerState(balancer.State{ ConnectivityState: connectivity.Idle, diff --git a/vendor/google.golang.org/grpc/binarylog/grpc_binarylog_v1/binarylog.pb.go b/vendor/google.golang.org/grpc/binarylog/grpc_binarylog_v1/binarylog.pb.go index 296123e..d22d1c3 100644 --- a/vendor/google.golang.org/grpc/binarylog/grpc_binarylog_v1/binarylog.pb.go +++ b/vendor/google.golang.org/grpc/binarylog/grpc_binarylog_v1/binarylog.pb.go @@ -18,7 +18,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.36.11 +// protoc-gen-go v1.36.12 // protoc v5.27.1 // source: grpc/binlog/v1/binarylog.proto @@ -679,7 +679,7 @@ func (x *Message) GetData() []byte { // A list of metadata pairs, used in the payload of client header, // server header, and server trailer. // Implementations may omit some entries to honor the header limits -// of GRPC_BINARY_LOG_CONFIG. +// of GRPC_BINARY_LOG_FILTER. // // Header keys added by gRPC are omitted. To be more specific, // implementations will not log the following entries, and this is @@ -689,7 +689,9 @@ func (x *Message) GetData() []byte { // or keys like 'lb-token' // - transport specific entries, including but not limited to: // ':path', ':authority', 'content-encoding', 'user-agent', 'te', etc -// - entries added for call credentials +// - entries added for call credentials (on client side, excludes all +// such headers; on server side, excludes only the "authorization" +// header) // // Implementations must always log grpc-trace-bin if it is present. // Practically speaking it will only be visible on server side because diff --git a/vendor/google.golang.org/grpc/clientconn.go b/vendor/google.golang.org/grpc/clientconn.go index b27c7e8..7a25d25 100644 --- a/vendor/google.golang.org/grpc/clientconn.go +++ b/vendor/google.golang.org/grpc/clientconn.go @@ -1211,6 +1211,12 @@ func (cc *ClientConn) Close() error { cc.mu.Unlock() cc.resolverWrapper.close() + // Swap in a default ConfigSelector so the resolver-provided one (which may + // transitively retain resolver-owned state such as parsed service configs + // and cluster maps) is released once in-flight RPCs finish selecting on + // it. Done after the resolver has closed so no further UpdateState calls + // race with this swap. + cc.safeConfigSelector.UpdateConfigSelector(&defaultConfigSelector{nil}) // The order of closing matters here since the balancer wrapper assumes the // picker is closed before it is closed. cc.pickerWrapper.close() diff --git a/vendor/google.golang.org/grpc/health/grpc_health_v1/health.pb.go b/vendor/google.golang.org/grpc/health/grpc_health_v1/health.pb.go index dcb98cd..35d4c83 100644 --- a/vendor/google.golang.org/grpc/health/grpc_health_v1/health.pb.go +++ b/vendor/google.golang.org/grpc/health/grpc_health_v1/health.pb.go @@ -17,7 +17,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.36.11 +// protoc-gen-go v1.36.12 // protoc v5.27.1 // source: grpc/health/v1/health.proto diff --git a/vendor/google.golang.org/grpc/internal/binarylog/method_logger.go b/vendor/google.golang.org/grpc/internal/binarylog/method_logger.go index 9669328..ca0e586 100644 --- a/vendor/google.golang.org/grpc/internal/binarylog/method_logger.go +++ b/vendor/google.golang.org/grpc/internal/binarylog/method_logger.go @@ -395,7 +395,7 @@ func (c *Cancel) toProto() *binlogpb.GrpcLogEntry { // omitted. func metadataKeyOmit(key string) bool { switch key { - case "lb-token", ":path", ":authority", "content-encoding", "content-type", "user-agent", "te": + case "lb-token", ":path", ":authority", "content-encoding", "content-type", "user-agent", "te", "authorization": return true case "grpc-trace-bin": // grpc-trace-bin is special because it's visible to users. return false diff --git a/vendor/google.golang.org/grpc/internal/buffer/unbounded.go b/vendor/google.golang.org/grpc/internal/buffer/unbounded.go index 467392b..d1f4b63 100644 --- a/vendor/google.golang.org/grpc/internal/buffer/unbounded.go +++ b/vendor/google.golang.org/grpc/internal/buffer/unbounded.go @@ -27,32 +27,29 @@ import ( // extra goroutines. This is typically used for passing updates from one entity // to another within gRPC. // +// To avoid extra memory allocations and type assertions, using any on +// performance-critical code paths is discouraged. Use concrete types wherever +// possible when instantiating Unbounded. +// // All methods on this type are thread-safe and don't block on anything except // the underlying mutex used for synchronization. -// -// Unbounded supports values of any type to be stored in it by using a channel -// of `any`. This means that a call to Put() incurs an extra memory allocation, -// and also that users need a type assertion while reading. For performance -// critical code paths, using Unbounded is strongly discouraged and defining a -// new type specific implementation of this buffer is preferred. See -// internal/transport/transport.go for an example of this. -type Unbounded struct { - c chan any +type Unbounded[T any] struct { + c chan T closed bool closing bool mu sync.Mutex - backlog []any + backlog []T } // NewUnbounded returns a new instance of Unbounded. -func NewUnbounded() *Unbounded { - return &Unbounded{c: make(chan any, 1)} +func NewUnbounded[T any]() *Unbounded[T] { + return &Unbounded[T]{c: make(chan T, 1)} } var errBufferClosed = errors.New("Put called on closed buffer.Unbounded") // Put adds t to the unbounded buffer. -func (b *Unbounded) Put(t any) error { +func (b *Unbounded[T]) Put(t T) error { b.mu.Lock() defer b.mu.Unlock() if b.closing { @@ -72,13 +69,14 @@ func (b *Unbounded) Put(t any) error { // Load sends the earliest buffered data, if any, onto the read channel returned // by Get(). Users are expected to call this every time they successfully read a // value from the read channel. -func (b *Unbounded) Load() { +func (b *Unbounded[T]) Load() { b.mu.Lock() defer b.mu.Unlock() if len(b.backlog) > 0 { select { case b.c <- b.backlog[0]: - b.backlog[0] = nil + var zero T + b.backlog[0] = zero b.backlog = b.backlog[1:] default: } @@ -96,14 +94,14 @@ func (b *Unbounded) Load() { // // If the unbounded buffer is closed, the read channel returned by this method // is closed after all data is drained. -func (b *Unbounded) Get() <-chan any { +func (b *Unbounded[T]) Get() <-chan T { return b.c } // Close closes the unbounded buffer. No subsequent data may be Put(), and the // channel returned from Get() will be closed after all the data is read and // Load() is called for the final time. -func (b *Unbounded) Close() { +func (b *Unbounded[T]) Close() { b.mu.Lock() defer b.mu.Unlock() if b.closing { diff --git a/vendor/google.golang.org/grpc/internal/envconfig/envconfig.go b/vendor/google.golang.org/grpc/internal/envconfig/envconfig.go index 3334481..2f4ae2f 100644 --- a/vendor/google.golang.org/grpc/internal/envconfig/envconfig.go +++ b/vendor/google.golang.org/grpc/internal/envconfig/envconfig.go @@ -144,14 +144,21 @@ var ( // ControlBufferThrottleLimit is the maximum number of control frames that can // be queued in the control buffer before throttling is applied. The value - // must be between 1 and 10,000, and is set to 100 by default. + // must be between 1 and 100,000, and is set to 10,000 by default. // // This environment variable serves as an escape hatch to increase the // throttling limit if unforeseen issues arise, and it will be removed in a // future release. // - // TODO: Remove this env var once v1.83.0 is released. - ControlBufferThrottleLimit = uint64FromEnv("GRPC_GO_EXPERIMENTAL_CONTROL_BUFFER_THROTTLE_LIMIT", 100, 1, 10000) + // TODO: Remove this env var once v1.86.0 is released. + ControlBufferThrottleLimit = uint64FromEnv("GRPC_GO_EXPERIMENTAL_CONTROL_BUFFER_THROTTLE_LIMIT", 10000, 1, 100000) + + // ALTSMaxFrameSize is the maximum frame size for ALTS in bytes. + // This can be overridden by setting the environment variable + // "GRPC_GO_EXPERIMENTAL_ALTS_MAX_FRAME_SIZE" (min: 4096, max: 512*1024, capped at + // 512KiB to match altsWriteBufferMaxSize in + // credentials/alts/internal/conn/record.go). + ALTSMaxFrameSize = uint64FromEnv("GRPC_GO_EXPERIMENTAL_ALTS_MAX_FRAME_SIZE", 4096, 4096, 512*1024) // EnableReceiveBufferCompaction enables the compaction of data buffers // to reduce the number of buffers in the receive buffer. diff --git a/vendor/google.golang.org/grpc/internal/envconfig/xds.go b/vendor/google.golang.org/grpc/internal/envconfig/xds.go index e4b6919..5ec39bd 100644 --- a/vendor/google.golang.org/grpc/internal/envconfig/xds.go +++ b/vendor/google.golang.org/grpc/internal/envconfig/xds.go @@ -98,4 +98,9 @@ var ( // filter. For more details, see: // https://github.com/grpc/proposal/blob/master/A83-xds-gcp-authn-filter.md GCPAuthenticationFilterEnabled = boolFromEnv("GRPC_EXPERIMENTAL_XDS_GCP_AUTHENTICATION_FILTER", false) + + // XDSClientExtAuthzEnabled indicates whether the external authorization + // filter is enabled on the client side. For more details, see: + // https://github.com/grpc/proposal/blob/master/A92-xds-ext-authz.md + XDSClientExtAuthzEnabled = boolFromEnv("GRPC_EXPERIMENTAL_XDS_EXT_AUTHZ_ON_CLIENT", false) ) diff --git a/vendor/google.golang.org/grpc/internal/grpcsync/callback_serializer.go b/vendor/google.golang.org/grpc/internal/grpcsync/callback_serializer.go index d4999fc..caa9dd6 100644 --- a/vendor/google.golang.org/grpc/internal/grpcsync/callback_serializer.go +++ b/vendor/google.golang.org/grpc/internal/grpcsync/callback_serializer.go @@ -41,7 +41,7 @@ type CallbackSerializer struct { // its resources. done chan struct{} - callbacks *buffer.Unbounded + callbacks *buffer.Unbounded[func(context.Context)] } // NewCallbackSerializer returns a new CallbackSerializer instance. The provided @@ -52,7 +52,7 @@ type CallbackSerializer struct { func NewCallbackSerializer(ctx context.Context) *CallbackSerializer { cs := &CallbackSerializer{ done: make(chan struct{}), - callbacks: buffer.NewUnbounded(), + callbacks: buffer.NewUnbounded[func(context.Context)](), } go cs.run(ctx) return cs @@ -113,7 +113,7 @@ func (cs *CallbackSerializer) run(ctx context.Context) { // Run all callbacks. for cb := range cs.callbacks.Get() { cs.callbacks.Load() - cb.(func(context.Context))(ctx) + cb(ctx) } } diff --git a/vendor/google.golang.org/grpc/internal/grpcsync/refcounted.go b/vendor/google.golang.org/grpc/internal/grpcsync/refcounted.go new file mode 100644 index 0000000..bca9b83 --- /dev/null +++ b/vendor/google.golang.org/grpc/internal/grpcsync/refcounted.go @@ -0,0 +1,109 @@ +/* + * + * Copyright 2026 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package grpcsync + +import ( + "sync/atomic" + + "google.golang.org/grpc/grpclog" +) + +var logger = grpclog.Component("grpcsync") + +// RefCounted is a reference counted wrapper of type T. It tracks the number of +// active references and runs a cleanup when the last reference is released. +type RefCounted[T any] struct { + val T + refCount atomic.Int32 + onZero func() +} + +// NewRefCounted creates a new RefCounted instance wrapping the given value with +// initial refcount of one. +// +// The value should typically be a pointer, interface, or handle rather than a +// plain value type (such as a struct or primitive value). +// +// The provided onZero callback must not be nil, and is executed exactly once +// when the reference count drops to zero. Panics if onZero is nil. +// +// WARNING: onZero runs synchronously inside Decrement; it must not acquire +// locks held by Decrement callers. +func NewRefCounted[T any](val T, onZero func()) *RefCounted[T] { + if onZero == nil { + panic("grpcsync: onZero callback cannot be nil") + } + rc := &RefCounted[T]{ + val: val, + onZero: onZero, + } + rc.refCount.Store(1) + return rc +} + +// Value returns the encapsulated resource. +func (rc *RefCounted[T]) Value() T { + return rc.val +} + +// TryIncrement attempts to increment the reference count, returning true if +// successful. It returns false if the count has already reached 0, indicating +// the resource has been cleaned up and cannot be resurrected. +// +// WARNING: Avoid calling TryIncrement on hot paths when an active reference is +// already guaranteed by the caller; use Increment instead to bypass the +// CompareAndSwap loop overhead. TryIncrement should be reserved for speculative +// lookups (such as fetching from a cache or map) where the resource might be +// dead. +func (rc *RefCounted[T]) TryIncrement() bool { + // Utilize a CompareAndSwap loop to prevent race conditions where a concurrent + // decrement could drop the count to zero between the read and the increment + // operation, which would otherwise inadvertently resurrect a closed resource. + for { + count := rc.refCount.Load() + if count <= 0 { + return false // Already dead or dying + } + if rc.refCount.CompareAndSwap(count, count+1) { + return true + } + } +} + +// Increment increments the reference count. +// +// WARNING: Call Increment only when there is a guarantee that an active +// reference is already present, ensuring the resource is not dead. If there is +// a possibility that the resource is dead or its reference count might have +// reached zero, call TryIncrement instead. +func (rc *RefCounted[T]) Increment() { + if rc.refCount.Add(1) <= 1 { + logger.Errorf("Resource already closed or dead") + } +} + +// Decrement decrements the reference count. If it drops to zero, the onZero +// callback is executed synchronously before this method returns. +func (rc *RefCounted[T]) Decrement() { + if v := rc.refCount.Add(-1); v < 0 { + logger.Errorf("Refcount cannot be negative") + } else if v == 0 { + rc.onZero() + } +} diff --git a/vendor/google.golang.org/grpc/internal/internal.go b/vendor/google.golang.org/grpc/internal/internal.go index 4b3d563..2b7fa6b 100644 --- a/vendor/google.golang.org/grpc/internal/internal.go +++ b/vendor/google.golang.org/grpc/internal/internal.go @@ -245,6 +245,10 @@ var ( AsyncReporterCleanupDelegate = func(cleanup func()) func() { return cleanup } + + // XDSFilterWrapperOption returns a ServerOption that sets the internal + // stream wrapper used for server-side xDS HTTP filters. + XDSFilterWrapperOption any // func(func(grpc.ServerStream) (grpc.ServerStream, error)) grpc.ServerOption ) // HealthChecker defines the signature of the client-side LB channel health diff --git a/vendor/google.golang.org/grpc/internal/resolver/config_selector.go b/vendor/google.golang.org/grpc/internal/resolver/config_selector.go index 238950b..ead6dda 100644 --- a/vendor/google.golang.org/grpc/internal/resolver/config_selector.go +++ b/vendor/google.golang.org/grpc/internal/resolver/config_selector.go @@ -42,6 +42,10 @@ type RPCInfo struct { // efficiency reasons. SelectConfig should not be blocking. Context context.Context Method string // i.e. "/Service/Method" + // Authority is the target authority (host) name of the RPC. This is required + // for HTTP filters (such as external processing) to populate request + // attributes. + Authority string } // RPCConfig describes the configuration to use for each RPC. @@ -54,17 +58,6 @@ type RPCConfig struct { Interceptor any } -// ServerInterceptor is an interceptor for incoming RPC's on gRPC server side. -type ServerInterceptor interface { - // AllowRPC checks if an incoming RPC is allowed to proceed based on - // information about connection RPC was received on, and HTTP Headers. This - // information will be piped into context. - AllowRPC(ctx context.Context) error // TODO: Make this a real interceptor for filters such as rate limiting. - // Close closes the interceptor. Once called, no new calls to NewStream are - // accepted. Ongoing calls to NewStream are allowed to complete. - Close() -} - type csKeyType string const csKey = csKeyType("grpc.internal.resolver.configSelector") diff --git a/vendor/google.golang.org/grpc/internal/transport/bdp_estimator.go b/vendor/google.golang.org/grpc/internal/transport/bdp_estimator.go index 070680e..4718576 100644 --- a/vendor/google.golang.org/grpc/internal/transport/bdp_estimator.go +++ b/vendor/google.golang.org/grpc/internal/transport/bdp_estimator.go @@ -47,10 +47,9 @@ const ( var bdpPing = &ping{data: [8]byte{2, 4, 16, 16, 9, 14, 7, 7}} type bdpEstimator struct { + mu sync.Mutex // sentAt is the time when the ping was sent. sentAt time.Time - - mu sync.Mutex // bdp is the current bdp estimate. bdp uint32 // sample is the number of bytes received in one measurement cycle. @@ -75,7 +74,9 @@ func (b *bdpEstimator) timesnap(d [8]byte) { if bdpPing.data != d { return } + b.mu.Lock() b.sentAt = time.Now() + b.mu.Unlock() } // add adds bytes to the current sample for calculating bdp. diff --git a/vendor/google.golang.org/grpc/internal/transport/controlbuf.go b/vendor/google.golang.org/grpc/internal/transport/controlbuf.go index b9bae02..e33ac3a 100644 --- a/vendor/google.golang.org/grpc/internal/transport/controlbuf.go +++ b/vendor/google.golang.org/grpc/internal/transport/controlbuf.go @@ -26,6 +26,7 @@ import ( "runtime" "sync" "sync/atomic" + "time" "golang.org/x/net/http2" "golang.org/x/net/http2/hpack" @@ -97,22 +98,35 @@ func (il *itemList) isEmpty() bool { return il.head == nil } -// maxQueuedControlBufferItems is the maximum number of frames (other than -// HEADERS and DATA) that we will buffer before preventing new reads from -// occurring on the transport. These are control frames sent in response to -// client requests, or frames that result in work being scheduled, such as -// RST_STREAM due to bad headers or settings acks. -var maxQueuedControlBufferItems = int(envconfig.ControlBufferThrottleLimit) +// maxQueuedTransportResponseFrames is the maximum number of "transport +// response" frames that we will buffer before preventing new reads from +// occurring on the transport. See cbItem.isTransportResponseFrame for the +// items that count towards this limit. +var maxQueuedTransportResponseFrames = int(envconfig.ControlBufferThrottleLimit) type cbItem interface { - isThrottled() bool + // isTransportResponseFrame reports whether the item counts against the + // maxQueuedTransportResponseFrames limit, when queued in the + // controlBuffer of a transport on the given side. + // + // Items that the peer can make the transport queue in unbounded + // numbers, for example by sending PING or SETTINGS frames, must be + // counted, so that the transport stops reading from a peer that sends + // such frames without reading what the transport writes. Items whose + // number grows with the local application's load (for example, one + // per stream it creates) must not be counted. Otherwise, under high + // concurrency, both peers could stop reading at the same time and + // deadlock (see https://github.com/grpc/grpc-go/issues/9330). + isTransportResponseFrame(s side) bool } -// throttledItem represents every item in the controlBuffer to which the overall -// throttling limit applies, other than outgoing HEADERS and DATA frames. -type throttledItem struct{} +// nonTransportResponseFrame represents items in the controlBuffer that are not +// queued in response to peer control/reset frames (for example, +// locally-initiated or flow-controlled items). These items are not counted +// against the maxQueuedTransportResponseFrames limit. +type nonTransportResponseFrame struct{} -func (throttledItem) isThrottled() bool { return true } +func (nonTransportResponseFrame) isTransportResponseFrame(side) bool { return false } // The following defines various control items which could flow through // the control buffer of transport. They represent different aspects of @@ -120,12 +134,13 @@ func (throttledItem) isThrottled() bool { return true } // registerStream is used to register an incoming stream with loopy writer. type registerStream struct { - throttledItem + nonTransportResponseFrame streamID uint32 wq *writeQuota } type clientHeaders struct { + nonTransportResponseFrame streamID uint32 hf []hpack.HeaderField initStream func(uint32) error @@ -134,9 +149,8 @@ type clientHeaders struct { onOrphaned func(error) } -func (*clientHeaders) isThrottled() bool { return false } - type serverHeaders struct { + nonTransportResponseFrame streamID uint32 hf []hpack.HeaderField endStream bool @@ -144,24 +158,37 @@ type serverHeaders struct { cleanup *cleanupStream } -func (h *serverHeaders) isThrottled() bool { return false } - type cleanupStream struct { - throttledItem streamID uint32 rst bool rstCode http2.ErrCode onWrite func() } +// isTransportResponseFrame returns true on the server since cleanupStream +// either results in a RST_STREAM frame being sent on the wire or in +// non-trivial work being performed when under a Rapid Reset attack. +// +// It returns false on the client, where a cleanupStream is queued at most once +// per stream, and the number of streams is controlled by the client and not by +// the server. Counting them on the client makes the client stop reading under +// high concurrency, which deadlocks with a server that has also stopped +// reading (see https://github.com/grpc/grpc-go/issues/9330). +func (*cleanupStream) isTransportResponseFrame(s side) bool { return s == serverSide } + type earlyAbortStream struct { - throttledItem streamID uint32 rst bool hf []hpack.HeaderField // Pre-built header fields } +// isTransportResponseFrame returns true on the server since earlyAbortStream +// results in a HEADERS frame being sent on the wire, and possibly a RST_STREAM +// frame. It is never queued on the client. +func (*earlyAbortStream) isTransportResponseFrame(s side) bool { return s == serverSide } + type dataFrame struct { + nonTransportResponseFrame streamID uint32 endStream bool h []byte @@ -172,36 +199,40 @@ type dataFrame struct { onEachWrite func() } -func (*dataFrame) isThrottled() bool { return false } - type incomingWindowUpdate struct { - throttledItem streamID uint32 increment uint32 } +// isTransportResponseFrame returns true to protect against a WINDOW_UPDATE +// flood attack from the peer. +func (*incomingWindowUpdate) isTransportResponseFrame(side) bool { return true } + type outgoingWindowUpdate struct { - throttledItem + nonTransportResponseFrame streamID uint32 increment uint32 } type incomingSettings struct { - throttledItem ss []http2.Setting } +// isTransportResponseFrame returns true since incomingSettings results in a +// SETTINGS ACK frame being sent on the wire. +func (*incomingSettings) isTransportResponseFrame(side) bool { return true } + type outgoingSettings struct { - throttledItem + nonTransportResponseFrame ss []http2.Setting } type incomingGoAway struct { - throttledItem + nonTransportResponseFrame } type goAway struct { - throttledItem + nonTransportResponseFrame code http2.ErrCode debugData []byte headsUp bool @@ -209,22 +240,43 @@ type goAway struct { } type ping struct { - throttledItem ack bool data [8]byte } +// isTransportResponseFrame returns true for all pings, and not only for ping +// acks sent in response to pings from the peer. This is because a BDP ping is +// queued in response to a DATA frame (of any size) from the peer, whenever +// there is no BDP ping outstanding. And since the BDP ping's payload is fixed, +// the peer can make it look like the BDP ping was acked at any time, by +// sending a ping ack with that payload. A peer alternating between empty DATA +// frames and such ping acks would otherwise be able to queue an unbounded +// number of BDP pings. Pings initiated locally (keepalive and BDP) are rare +// enough to not cause throttling of well-behaved peers. +func (*ping) isTransportResponseFrame(side) bool { return true } + type outFlowControlSizeRequest struct { - throttledItem + nonTransportResponseFrame resp chan uint32 } +// outStreamRequestForTesting is used by tests to retrieve a pointer to an outStream +// safely inside the loopyWriter goroutine without racing on loopyWriter.estdStreams. +// By holding the *outStream pointer while streams and transports close down, tests +// can inspect settled accounting values (such as bytesOutStanding) after loopyWriter +// has run to completion without any data races. +type outStreamRequestForTesting struct { + nonTransportResponseFrame + streamID uint32 + resp chan *outStream +} + // closeConnection is an instruction to tell the loopy writer to flush the // framer and exit, which will cause the transport's connection to be closed // (by the client or server). The transport itself will close after the reader // encounters the EOF caused by the connection closure. type closeConnection struct { - throttledItem + nonTransportResponseFrame } type outStreamState int @@ -305,8 +357,9 @@ func (l *outStreamList) dequeue() *outStream { // shouldn't be confused with an HTTP2 frame, although some of the control // frames like dataFrame and headerFrame do go out on wire as HTTP2 frames. type controlBuffer struct { - wakeupCh chan struct{} // Unblocks readers waiting for something to read. + wakeupCh chan struct{} // Unblocks readers waiting for new items. done <-chan struct{} // Closed when the transport is done. + side side // Side of the transport owning this buffer. // Mutex guards all the fields below, except trfChan which can be read // atomically without holding mu. @@ -315,26 +368,30 @@ type controlBuffer struct { closed bool // True when the controlbuf is finished. list *itemList // List of queued control frames. - // transportResponseFrames counts the number of queued items that represent - // the response of an action initiated by the peer. trfChan is created - // when transportResponseFrames >= maxQueuedTransportResponseFrames and is - // closed and nilled when transportResponseFrames drops below the - // threshold. Both fields are protected by mu. + // transportResponseFrames counts the number of queued items that + // represent the response of an action initiated by the peer (as + // determined by cbItem.isTransportResponseFrame for this side). + // trfChan is created when transportResponseFrames >= + // maxQueuedTransportResponseFrames and is closed and nilled when + // transportResponseFrames drops below the threshold. Both fields are + // protected by mu. transportResponseFrames int trfChan atomic.Pointer[chan struct{}] } -func newControlBuffer(done <-chan struct{}) *controlBuffer { +func newControlBuffer(done <-chan struct{}, s side) *controlBuffer { return &controlBuffer{ wakeupCh: make(chan struct{}, 1), list: &itemList{}, done: done, + side: s, } } -// throttle blocks if there are too many frames in the control buf that -// represent the response of an action initiated by the peer, like -// incomingSettings cleanupStreams etc. +// throttle blocks if there are too many items in the control buffer that count +// towards the maxQueuedTransportResponseFrames limit (see +// cbItem.isTransportResponseFrame), until their number drops below the limit, +// the control buffer is finished, or the transport is done. func (c *controlBuffer) throttle() { if ch := c.trfChan.Load(); ch != nil { select { @@ -344,6 +401,25 @@ func (c *controlBuffer) throttle() { } } +// throttleWithTimeout is like throttle, but it stops waiting and returns an +// error if the control buffer is still throttled after the given duration. +func (c *controlBuffer) throttleWithTimeout(timeout time.Duration) error { + ch := c.trfChan.Load() + if ch == nil { + return nil + } + timer := time.NewTimer(timeout) + defer timer.Stop() + select { + case <-(*ch): + return nil + case <-c.done: + return nil + case <-timer.C: + return fmt.Errorf("still throttled after %v, with at least %d queued frames", timeout, maxQueuedTransportResponseFrames) + } +} + // put adds an item to the controlbuf. func (c *controlBuffer) put(it cbItem) error { _, err := c.executeAndPut(nil, it) @@ -379,9 +455,9 @@ func (c *controlBuffer) executeAndPut(f func() bool, it cbItem) (bool, error) { c.consumerWaiting = false } c.list.enqueue(it) - if it.isThrottled() { + if it.isTransportResponseFrame(c.side) { c.transportResponseFrames++ - if c.transportResponseFrames == maxQueuedControlBufferItems { + if c.transportResponseFrames == maxQueuedTransportResponseFrames { // We are adding the frame that puts us over the threshold; create // a throttling channel. ch := make(chan struct{}) @@ -436,8 +512,8 @@ func (c *controlBuffer) getOnceLocked() (any, error) { return nil, nil } h := c.list.dequeue().(cbItem) - if h.isThrottled() { - if c.transportResponseFrames == maxQueuedControlBufferItems { + if h.isTransportResponseFrame(c.side) { + if c.transportResponseFrames == maxQueuedTransportResponseFrames { // We are removing the frame that put us over the // threshold; close and clear the throttling channel. ch := c.trfChan.Swap(nil) @@ -473,9 +549,10 @@ func (c *controlBuffer) finish() { } } - // In case throttle() is currently in flight, it needs to be unblocked. - // Otherwise, the transport may not close, since the transport is closed by - // the reader encountering the connection error. + // In case throttle() or throttleWithTimeout() is currently in flight, + // it needs to be unblocked. Otherwise, the transport may not close, + // since the transport is closed by the reader encountering the + // connection error. ch := c.trfChan.Swap(nil) if ch != nil { close(*ch) @@ -799,6 +876,10 @@ func (l *loopyWriter) outFlowControlSizeRequestHandler(o *outFlowControlSizeRequ o.resp <- l.sendQuota } +func (l *loopyWriter) outStreamRequestHandler(o *outStreamRequestForTesting) { + o.resp <- l.estdStreams[o.streamID] +} + func (l *loopyWriter) cleanupStreamHandler(c *cleanupStream) error { c.onWrite() if str, ok := l.estdStreams[c.streamID]; ok { @@ -896,6 +977,8 @@ func (l *loopyWriter) handle(i any) error { return l.goAwayHandler(i) case *outFlowControlSizeRequest: l.outFlowControlSizeRequestHandler(i) + case *outStreamRequestForTesting: + l.outStreamRequestHandler(i) case closeConnection: // Just return a non-I/O error and run() will flush and close the // connection. diff --git a/vendor/google.golang.org/grpc/internal/transport/handler_server.go b/vendor/google.golang.org/grpc/internal/transport/handler_server.go index 9cd8d28..a701522 100644 --- a/vendor/google.golang.org/grpc/internal/transport/handler_server.go +++ b/vendor/google.golang.org/grpc/internal/transport/handler_server.go @@ -268,7 +268,7 @@ func (ht *serverHandlerTransport) writeStatus(s *ServerStream, st *status.Status for _, v := range vv { // http2 ResponseWriter mechanism to send undeclared Trailers after // the headers have possibly been written. - h.Add(http2.TrailerPrefix+k, encodeMetadataHeader(k, v)) + h.Add(http.TrailerPrefix+k, encodeMetadataHeader(k, v)) } } } @@ -494,7 +494,8 @@ func mapRecvMsgError(err error) error { if err == io.EOF || err == io.ErrUnexpectedEOF { return err } - if se, ok := err.(http2.StreamError); ok { + var se http2.StreamError + if errors.As(err, &se) { if code, ok := http2ErrConvTab[se.Code]; ok { return status.Error(code, se.Error()) } diff --git a/vendor/google.golang.org/grpc/internal/transport/http2_client.go b/vendor/google.golang.org/grpc/internal/transport/http2_client.go index 10d1977..a198baf 100644 --- a/vendor/google.golang.org/grpc/internal/transport/http2_client.go +++ b/vendor/google.golang.org/grpc/internal/transport/http2_client.go @@ -65,6 +65,13 @@ var clientConnectionCounter uint64 var goAwayLoopyWriterTimeout = 5 * time.Second +// clientThrottleTimeout is the maximum amount of time for which the client +// stops reading from the connection because too many frames queued in +// response to the server (see maxQueuedTransportResponseFrames) are waiting +// to be written. After that, the client closes the connection instead of +// waiting forever, since the server is most likely not reading. +var clientThrottleTimeout = 10 * time.Second + var metadataFromOutgoingContextRaw = internal.FromOutgoingContextRaw.(func(context.Context) (metadata.MD, [][]string, bool)) // http2Client implements the ClientTransport interface with HTTP2. @@ -107,6 +114,12 @@ type http2Client struct { kp keepalive.ClientParameters keepaliveEnabled bool + // throttleTimeout is the maximum amount of time for which reads can + // stay throttled before the connection is closed. It is copied from + // clientThrottleTimeout on creation, so that tests can override the + // latter without racing with the readers of other transports. + throttleTimeout time.Duration + statsHandler stats.Handler initialWindowSize int32 @@ -359,6 +372,7 @@ func NewHTTP2Client(connectCtx, ctx context.Context, addr resolver.Address, opts streamQuota: defaultMaxStreamsClient, streamsQuotaAvailable: make(chan struct{}, 1), keepaliveEnabled: keepaliveEnabled, + throttleTimeout: clientThrottleTimeout, bufferPool: opts.BufferPool, onClose: onClose, } @@ -386,7 +400,7 @@ func NewHTTP2Client(connectCtx, ctx context.Context, addr resolver.Address, opts } else if md := imetadata.Get(addr); md != nil { t.md = md } - t.controlBuf = newControlBuffer(t.ctxDone) + t.controlBuf = newControlBuffer(t.ctxDone, clientSide) if opts.InitialWindowSize >= defaultWindowSize { t.initialWindowSize = opts.InitialWindowSize } @@ -554,8 +568,6 @@ func (t *http2Client) createHeaderFields(ctx context.Context, callHdr *CallHdr) if err != nil { return nil, err } - // TODO(mmukhi): Benchmark if the performance gets better if count the metadata and other header fields - // first and create a slice of that exact size. // Make the slice of certain predictable size to reduce allocations made by append. hfLen := 7 // :method, :scheme, :path, :authority, content-type, user-agent, te hfLen += len(authData) + len(callAuthData) @@ -575,6 +587,21 @@ func (t *http2Client) createHeaderFields(ctx context.Context, callHdr *CallHdr) if _, ok := ctx.Deadline(); ok { hfLen++ } + // Count the metadata header fields as well so the slice is not reallocated + // while they are appended below. Reserved headers are dropped when writing, + // so this may slightly over-count, which is preferable to growing the slice. + md, added, mdOK := metadataFromOutgoingContextRaw(ctx) + if mdOK { + for _, vv := range md { + hfLen += len(vv) + } + for _, vv := range added { + hfLen += len(vv) / 2 + } + } + for _, vv := range t.md { + hfLen += len(vv) + } headerFields := make([]hpack.HeaderField, 0, hfLen) headerFields = append(headerFields, hpack.HeaderField{Name: ":method", Value: "POST"}) headerFields = append(headerFields, hpack.HeaderField{Name: ":scheme", Value: t.scheme}) @@ -619,7 +646,7 @@ func (t *http2Client) createHeaderFields(ctx context.Context, callHdr *CallHdr) headerFields = append(headerFields, hpack.HeaderField{Name: k, Value: encodeMetadataHeader(k, v)}) } - if md, added, ok := metadataFromOutgoingContextRaw(ctx); ok { + if mdOK { var k string for k, vv := range md { // HTTP doesn't allow you to set pseudoheaders after non pseudoheaders were set. @@ -648,6 +675,9 @@ func (t *http2Client) createHeaderFields(ctx context.Context, callHdr *CallHdr) if isReservedHeader(k) { continue } + if err := imetadata.ValidatePair(k, vv...); err != nil { + return nil, status.Error(codes.Internal, err.Error()) + } for _, v := range vv { headerFields = append(headerFields, hpack.HeaderField{Name: k, Value: encodeMetadataHeader(k, v)}) } @@ -691,6 +721,9 @@ func (t *http2Client) getTrAuthData(ctx context.Context, audience string) (map[s for k, v := range data { // Capital header names are illegal in HTTP/2. k = strings.ToLower(k) + if err := imetadata.ValidatePair(k, v); err != nil { + return nil, status.Error(codes.Internal, err.Error()) + } authData[k] = v } } @@ -724,6 +757,9 @@ func (t *http2Client) getCallAuthData(ctx context.Context, audience string, call for k, v := range data { // Capital header names are illegal in HTTP/2 k = strings.ToLower(k) + if err := imetadata.ValidatePair(k, v); err != nil { + return nil, status.Error(codes.Internal, err.Error()) + } callAuthData[k] = v } } @@ -930,6 +966,7 @@ func (t *http2Client) NewStream(ctx context.Context, callHdr *CallHdr, handler s LocalAddr: t.localAddr, Compression: callHdr.SendCompress, Header: header, + Authority: callHdr.Host, }) } if transportDrainRequired { @@ -1226,23 +1263,26 @@ func (t *http2Client) handleData(f *parsedDataFrame) { t.closeStream(s, io.EOF, true, http2.ErrCodeFlowControl, status.New(codes.Internal, err.Error()), nil, false) return } + } - if s.nonGRPCStatus != nil { - // The frame should be handled as a non-gRPC response body - st := s.handleNonGRPCData(f) - if st != nil { - t.closeStream(s, st.Err(), true, http2.ErrCodeProtocol, st, nil, true) - return - } - if w := s.fc.onRead(size); w > 0 { - t.controlBuf.put(&outgoingWindowUpdate{ - streamID: s.id, - increment: w, - }) - } + if s.nonGRPCStatus != nil { + // The frame should be handled as a non-gRPC response body. A non-nil + // status also covers END_STREAM, so no separate handling is needed below. + st := s.handleNonGRPCData(f) + if st != nil { + t.closeStream(s, st.Err(), true, http2.ErrCodeProtocol, st, nil, true) return } + if w := s.fc.onRead(size); w > 0 { + t.controlBuf.put(&outgoingWindowUpdate{ + streamID: s.id, + increment: w, + }) + } + return + } + if size > 0 { dataLen := f.data.Len() if f.Header().Flags.Has(http2.FlagDataPadded) { if w := s.fc.onRead(size - uint32(dataLen)); w > 0 { @@ -1701,9 +1741,19 @@ func (t *http2Client) reader(errCh chan<- error) { atomic.StoreInt64(&t.lastRead, time.Now().UnixNano()) } - // loop to keep reading incoming messages on this transport. + // Loop to keep reading incoming messages on this transport. for { - t.controlBuf.throttle() + // Stop reading while too many items that the server can make + // the client queue (see cbItem.isTransportResponseFrame) are + // waiting to be written, to bound the memory that a server + // can make the client use by flooding it without reading. If + // reads stay throttled for t.throttleTimeout, close the + // connection instead of waiting forever. + if err := t.controlBuf.throttleWithTimeout(t.throttleTimeout); err != nil { + t.logger.Warningf("Closing connection since the server is not reading: %v", err) + errClose = connectionErrorf(true, err, "closing connection since the server is not reading: %v", err) + return + } frame, err := t.framer.readFrame() if t.keepaliveEnabled { atomic.StoreInt64(&t.lastRead, time.Now().UnixNano()) diff --git a/vendor/google.golang.org/grpc/internal/transport/http2_server.go b/vendor/google.golang.org/grpc/internal/transport/http2_server.go index 82e13e6..5c3fc76 100644 --- a/vendor/google.golang.org/grpc/internal/transport/http2_server.go +++ b/vendor/google.golang.org/grpc/internal/transport/http2_server.go @@ -297,7 +297,7 @@ func NewServerTransport(conn net.Conn, config *ServerConfig) (_ ServerTransport, ) t.logger = prefixLoggerForServerTransport(t) - t.controlBuf = newControlBuffer(t.done) + t.controlBuf = newControlBuffer(t.done, serverSide) if !config.StaticWindowSize { t.bdpEst = &bdpEstimator{ bdp: initialWindowSize, @@ -380,6 +380,11 @@ func (t *http2Server) operateHeaders(ctx context.Context, frame *http2.MetaHeade defer t.maxStreamMu.Unlock() streamID := frame.Header().StreamID + if streamID%2 != 1 || streamID <= t.maxStreamID { + // illegal gRPC stream id. + return fmt.Errorf("received an illegal stream id: %v. headers frame: %+v", streamID, frame) + } + t.maxStreamID = streamID // frame.Truncated is set to true when framer detects that the current header // list size hits MaxHeaderListSize limit. @@ -393,12 +398,6 @@ func (t *http2Server) operateHeaders(ctx context.Context, frame *http2.MetaHeade return nil } - if streamID%2 != 1 || streamID <= t.maxStreamID { - // illegal gRPC stream id. - return fmt.Errorf("received an illegal stream id: %v. headers frame: %+v", streamID, frame) - } - t.maxStreamID = streamID - s := &ServerStream{ Stream: Stream{ id: streamID, @@ -531,6 +530,7 @@ func (t *http2Server) operateHeaders(ctx context.Context, frame *http2.MetaHeade if frame.StreamEnded() { // s is just created by the caller. No lock needed. s.state = streamReadDone + s.write(recvMsg{err: io.EOF}) } if timeoutSet { s.ctx, s.cancel = context.WithTimeout(ctx, timeout) @@ -1013,7 +1013,17 @@ func (t *http2Server) streamContextErr(s *ServerStream) error { return ErrConnClosing default: } - return ContextErr(s.ctx.Err()) + err := s.ctx.Err() + if err == nil { + // In closeStream and finishStream, the stream state is transitioned to + // streamDone before s.cancel() is invoked so that concurrent operations + // immediately observe the terminal state. A concurrent caller (such as + // write or writeHeader) can see streamDone and invoke streamContextErr + // before s.cancel() runs or propagates to s.ctx. Default to + // context.Canceled rather than passing nil to ContextErr. + err = context.Canceled + } + return ContextErr(err) } // WriteHeader sends the header metadata md back to the client. @@ -1335,10 +1345,6 @@ func (t *http2Server) deleteStream(s *ServerStream, eosReceived bool) { // finishStream closes the stream and puts the trailing headerFrame into controlbuf. func (t *http2Server) finishStream(s *ServerStream, rst bool, rstCode http2.ErrCode, hdr *serverHeaders, eosReceived bool) { - // In case stream sending and receiving are invoked in separate - // goroutines (e.g., bi-directional streaming), cancel needs to be - // called to interrupt the potential blocking on other goroutines. - s.cancel() oldState := s.swapState(streamDone) if oldState == streamDone { @@ -1346,6 +1352,11 @@ func (t *http2Server) finishStream(s *ServerStream, rst bool, rstCode http2.ErrC return } + // In case stream sending and receiving are invoked in separate + // goroutines (e.g., bi-directional streaming), cancel needs to be + // called to interrupt the potential blocking on other goroutines. + s.cancel() + hdr.cleanup = &cleanupStream{ streamID: s.id, rst: rst, @@ -1359,15 +1370,16 @@ func (t *http2Server) finishStream(s *ServerStream, rst bool, rstCode http2.ErrC // closeStream clears the footprint of a stream when the stream is not needed any more. func (t *http2Server) closeStream(s *ServerStream, rst bool, rstCode http2.ErrCode, eosReceived bool) { + // We can't return early even if the stream's state is "done" as the state + // might have been set by the `finishStream` method. Deleting the stream via + // `finishStream` can get blocked on flow control. + s.swapState(streamDone) + // In case stream sending and receiving are invoked in separate // goroutines (e.g., bi-directional streaming), cancel needs to be // called to interrupt the potential blocking on other goroutines. s.cancel() - // We can't return early even if the stream's state is "done" as the state - // might have been set by the `finishStream` method. Deleting the stream via - // `finishStream` can get blocked on flow control. - s.swapState(streamDone) t.deleteStream(s, eosReceived) t.controlBuf.put(&cleanupStream{ diff --git a/vendor/google.golang.org/grpc/internal/transport/http_util.go b/vendor/google.golang.org/grpc/internal/transport/http_util.go index c34975f..faa42f8 100644 --- a/vendor/google.golang.org/grpc/internal/transport/http_util.go +++ b/vendor/google.golang.org/grpc/internal/transport/http_util.go @@ -300,24 +300,29 @@ func decodeGrpcMessageUnchecked(msg string) string { type bufWriter struct { pool *imem.SimpleBufferPool - buf []byte + bufHandle *[]byte offset int batchSize int conn io.Writer err error } +// unsharedBufWriter keeps the unshared slice header in the writer allocation. +type unsharedBufWriter struct { + bufWriter + buf []byte +} + func newBufWriter(conn io.Writer, batchSize int, pool *imem.SimpleBufferPool) *bufWriter { - w := &bufWriter{ - batchSize: batchSize, - conn: conn, - pool: pool, + if pool == nil && batchSize > 0 { + w := &unsharedBufWriter{ + bufWriter: bufWriter{batchSize: batchSize, conn: conn}, + buf: make([]byte, batchSize), + } + w.bufHandle = &w.buf + return &w.bufWriter } - // this indicates that we should use non shared buf - if pool == nil { - w.buf = make([]byte, batchSize) - } - return w + return &bufWriter{batchSize: batchSize, conn: conn, pool: pool} } func (w *bufWriter) Write(b []byte) (int, error) { @@ -328,13 +333,13 @@ func (w *bufWriter) Write(b []byte) (int, error) { n, err := w.conn.Write(b) return n, toIOError(err) } - if w.buf == nil { - b := w.pool.Get(w.batchSize) - w.buf = *b + if w.bufHandle == nil { + w.bufHandle = w.pool.Get(w.batchSize) } + buf := *w.bufHandle written := 0 for len(b) > 0 { - copied := copy(w.buf[w.offset:], b) + copied := copy(buf[w.offset:], b) b = b[copied:] written += copied w.offset += copied @@ -350,15 +355,17 @@ func (w *bufWriter) Write(b []byte) (int, error) { func (w *bufWriter) Flush() error { err := w.flushKeepBuffer() - // Only release the buffer if we are in a "shared" mode - if w.buf != nil && w.pool != nil { - b := w.buf - w.pool.Put(&b) - w.buf = nil - } + w.releaseBuffer() return err } +func (w *bufWriter) releaseBuffer() { + if w.pool != nil && w.bufHandle != nil { + w.pool.Put(w.bufHandle) + w.bufHandle = nil + } +} + func (w *bufWriter) flushKeepBuffer() error { if w.err != nil { return w.err @@ -366,9 +373,13 @@ func (w *bufWriter) flushKeepBuffer() error { if w.offset == 0 { return nil } - _, w.err = w.conn.Write(w.buf[:w.offset]) + buf := *w.bufHandle + _, w.err = w.conn.Write(buf[:w.offset]) w.err = toIOError(w.err) w.offset = 0 + if w.err != nil { + w.releaseBuffer() + } return w.err } diff --git a/vendor/google.golang.org/grpc/internal/transport/transport.go b/vendor/google.golang.org/grpc/internal/transport/transport.go index 5fc901e..f627adf 100644 --- a/vendor/google.golang.org/grpc/internal/transport/transport.go +++ b/vendor/google.golang.org/grpc/internal/transport/transport.go @@ -89,10 +89,10 @@ type recvMsg struct { // recvBuffer is an unbounded channel of recvMsg structs. // -// Note: recvBuffer differs from buffer.Unbounded only in the fact that it -// holds a channel of recvMsg structs instead of objects implementing "item" -// interface. recvBuffer is written to much more often and using strict recvMsg -// structs helps avoid allocation in "recvBuffer.put" +// Note: recvBuffer differs from buffer.Unbounded in that it provides in-place +// value initialization (via init) to avoid struct pointer allocations on +// streams, and automatically frees pooled mem.Buffer payloads when stream +// errors occur. type recvBuffer struct { c chan recvMsg mu sync.Mutex @@ -121,7 +121,9 @@ func (b *recvBuffer) put(r recvMsg) { if b.err != nil { // drop the buffer on the floor. Since b.err is not nil, any subsequent reads // will always return an error, making this buffer inaccessible. - r.buffer.Free() + if r.buffer != nil { + r.buffer.Free() + } // An error had occurred earlier, don't accept more // data or errors. return @@ -466,15 +468,18 @@ func (s *Stream) ReadMessageHeader(header []byte) (err error) { return er } s.readRequester.requestRead(len(header)) + bytesRead := 0 for len(header) != 0 { n, err := s.trReader.ReadMessageHeader(header) + bytesRead += n header = header[n:] if len(header) == 0 { err = nil } if err != nil { - if n > 0 && err == io.EOF { + if bytesRead > 0 && err == io.EOF { err = io.ErrUnexpectedEOF + s.trReader.er = err } return err } @@ -505,19 +510,22 @@ func (s *Stream) read(n int) (data mem.BufferSlice, err error) { allocCap := min(ceil(n, http2MaxFrameLen), 128) data = make(mem.BufferSlice, 0, allocCap) s.readRequester.requestRead(n) + bytesRead := 0 for n != 0 { buf, err := s.trReader.Read(n) var bufLen int if buf != nil { bufLen = buf.Len() } + bytesRead += bufLen n -= bufLen if n == 0 { err = nil } if err != nil { - if bufLen > 0 && err == io.EOF { + if bytesRead > 0 && err == io.EOF { err = io.ErrUnexpectedEOF + s.trReader.er = err } data.Free() return nil, err diff --git a/vendor/google.golang.org/grpc/metadata/metadata.go b/vendor/google.golang.org/grpc/metadata/metadata.go index d2e1525..a3090ff 100644 --- a/vendor/google.golang.org/grpc/metadata/metadata.go +++ b/vendor/google.golang.org/grpc/metadata/metadata.go @@ -24,6 +24,7 @@ package metadata // import "google.golang.org/grpc/metadata" import ( "context" "fmt" + "sort" "strings" "google.golang.org/grpc/internal" @@ -90,6 +91,76 @@ func Pairs(kv ...string) MD { return md } +// loggableMetadataKeys is the set of metadata keys whose values are known not +// to carry credentials or other sensitive data, and are therefore safe to print +// verbatim in String. Values for any key not in this set are redacted. Keys are +// in metadata's canonical lowercase form. +// +// The list is intentionally restricted to standardized gRPC and HTTP/2 protocol +// headers. Everything else, including all application-defined keys, is +// censored. +// Note that this list might change as we add/remove support for +// metadata types. +var loggableMetadataKeys = map[string]bool{ + "content-type": true, + "te": true, + "user-agent": true, + "grpc-encoding": true, + "grpc-accept-encoding": true, + "grpc-timeout": true, + "grpc-status": true, + "grpc-message-type": true, + "grpc-previous-rpc-attempts": true, + "grpc-retry-pushback-ms": true, +} + +// String implements fmt.Stringer to allow metadata to be printed when stored in +// a context. +// +// To avoid accidentally leaking credentials or other sensitive data (for +// example via log(md), or by logging a value that happens to contain metadata), +// String reports only keys on an allowlist of standardized, non-sensitive +// protocol headers (see loggableMetadataKeys). Every other key is omitted +// entirely, along with its values, because a key name may itself be sensitive; +// only the number of omitted keys is reported, as "". This is a +// best-effort guard against accidents, not a security boundary: a caller that +// genuinely wants the full contents can still print map[string][]string(md) +// directly. +// +// Note that this only affects verbs that use the Stringer, such as %v and %s. +// The %#v verb prints the underlying map with all values and is not redacted. +// Users should not rely on the output of this method to be stable +// # Experimental +// +// Notice: This API is EXPERIMENTAL and may be changed or removed in a later +// release. +func (md MD) String() string { + keys := make([]string, 0, len(md)) + for k := range md { + if loggableMetadataKeys[strings.ToLower(k)] { + keys = append(keys, k) + } + } + sort.Strings(keys) + + var sb strings.Builder + sb.WriteString("map[") + for i, k := range keys { + if i > 0 { + sb.WriteByte(' ') + } + fmt.Fprintf(&sb, "%s:%v", k, md[k]) + } + if redacted := len(md) - len(keys); redacted > 0 { + if len(keys) > 0 { + sb.WriteByte(' ') + } + fmt.Fprintf(&sb, "<%d redacted>", redacted) + } + sb.WriteByte(']') + return sb.String() +} + // Len returns the number of items in md. func (md MD) Len() int { return len(md) @@ -289,6 +360,66 @@ func FromOutgoingContext(ctx context.Context) (MD, bool) { return out, ok } +// ValueFromOutgoingContext returns the metadata value corresponding to the +// metadata key from the outgoing metadata if it exists. Keys are matched in a +// case-insensitive manner. +// +// Unlike FromOutgoingContext, this does not copy the entire outgoing metadata. +func ValueFromOutgoingContext(ctx context.Context, key string) []string { + raw, ok := ctx.Value(mdOutgoingKey{}).(rawMD) + if !ok { + return nil + } + + key = strings.ToLower(key) + // Unlike ValueFromIncomingContext, this can't return as soon as raw.md is + // checked: raw.added still needs to be walked and accumulated regardless. + // The else below prevents that from overwriting an exact match with an + // unrelated case-insensitive one. + var matchedMD []string + if v, ok := raw.md[key]; ok { + matchedMD = v + } else { + for k, v := range raw.md { + // Case insensitive comparison: MD is a map, and there's no + // guarantee that the MD attached to the context is created using + // our helper functions. + if strings.EqualFold(k, key) { + matchedMD = v + break + } + } + } + + // Defer allocating vals until raw.added actually has a match, so a match + // found only in raw.md doesn't pay for both a copyOf and a growing + // append. + var vals []string + for _, added := range raw.added { + if len(added)%2 == 1 { + panic(fmt.Sprintf("metadata: ValueFromOutgoingContext got an odd number of input pairs for metadata: %d", len(added))) + } + + // Case insensitive, like FromOutgoingContext: added isn't guaranteed + // lowercase, though AppendToOutgoingContext already lowercases it in + // practice, so try the cheap exact match first. + for i := 0; i < len(added); i += 2 { + if added[i] == key || strings.EqualFold(added[i], key) { + if vals == nil { + vals = make([]string, 0, len(matchedMD)+1) + vals = append(vals, matchedMD...) + } + vals = append(vals, added[i+1]) + } + } + } + + if vals == nil && matchedMD != nil { + return copyOf(matchedMD) + } + return vals +} + type rawMD struct { md MD added [][]string diff --git a/vendor/google.golang.org/grpc/resolver_wrapper.go b/vendor/google.golang.org/grpc/resolver_wrapper.go index 6e61376..f8b0fd3 100644 --- a/vendor/google.golang.org/grpc/resolver_wrapper.go +++ b/vendor/google.golang.org/grpc/resolver_wrapper.go @@ -188,7 +188,7 @@ func (ccr *ccResolverWrapper) ParseServiceConfig(scJSON string) *serviceconfig.P // addChannelzTraceEvent adds a channelz trace event containing the new // state received from resolver implementations. func (ccr *ccResolverWrapper) addChannelzTraceEvent(s resolver.State) { - if !logger.V(0) && !channelz.IsOn() { + if !logger.V(2) && !channelz.IsOn() { return } var updates []string diff --git a/vendor/google.golang.org/grpc/rpc_util.go b/vendor/google.golang.org/grpc/rpc_util.go index 52f4ea5..6f1bb2e 100644 --- a/vendor/google.golang.org/grpc/rpc_util.go +++ b/vendor/google.golang.org/grpc/rpc_util.go @@ -179,7 +179,6 @@ type callInfo struct { contentSubtype string codec baseCodec maxRetryRPCBufferSize int - onFinish []func(err error) authority string acceptedResponseCompressors []string } @@ -394,8 +393,7 @@ type OnFinishCallOption struct { OnFinish func(error) } -func (o OnFinishCallOption) before(c *callInfo) error { - c.onFinish = append(c.onFinish, o.OnFinish) +func (o OnFinishCallOption) before(*callInfo) error { return nil } diff --git a/vendor/google.golang.org/grpc/server.go b/vendor/google.golang.org/grpc/server.go index cf0a206..5c16597 100644 --- a/vendor/google.golang.org/grpc/server.go +++ b/vendor/google.golang.org/grpc/server.go @@ -89,6 +89,7 @@ func init() { internal.MetricsRecorderForServer = func(srv *Server) estats.MetricsRecorder { return istats.NewMetricsRecorderList(srv.opts.statsHandlers) } + internal.XDSFilterWrapperOption = xdsFilterWrapperOption } var statusOK = status.New(codes.OK, "") @@ -117,10 +118,8 @@ type ServiceDesc struct { // serviceInfo wraps information about a service. It is very similar to // ServiceDesc and is constructed from it for internal purposes. type serviceInfo struct { - // Contains the implementation for the methods in this service. - serviceImpl any - methods map[string]*MethodDesc - streams map[string]*StreamDesc + serviceImpl any // Implementation for the methods in this service. + streams map[string]*StreamDesc // Streaming descriptors and wrapped unary descriptors for this service. mdata any } @@ -183,6 +182,7 @@ type serverOptions struct { bufferPool mem.BufferPool waitForHandlers bool staticWindowSize bool + streamWrapper func(ServerStream) (ServerStream, error) } var defaultServerOptions = serverOptions{ @@ -663,6 +663,14 @@ func bufferPool(bufferPool mem.BufferPool) ServerOption { }) } +// xdsFilterWrapperOption returns a ServerOption that sets the server-level +// stream wrapper (used internally by xDS server filters). +func xdsFilterWrapperOption(w func(ServerStream) (ServerStream, error)) ServerOption { + return newFuncServerOption(func(o *serverOptions) { + o.streamWrapper = w + }) +} + // serverWorkerResetThreshold defines how often the stack must be reset. Every // N requests, by spawning a new goroutine in its place, a worker can reset its // stack so that large stacks don't live in memory forever. 2^16 should allow @@ -790,18 +798,22 @@ func (s *Server) register(sd *ServiceDesc, ss any) { } info := &serviceInfo{ serviceImpl: ss, - methods: make(map[string]*MethodDesc), streams: make(map[string]*StreamDesc), mdata: sd.Metadata, } - for i := range sd.Methods { - d := &sd.Methods[i] - info.methods[d.MethodName] = d - } for i := range sd.Streams { d := &sd.Streams[i] info.streams[d.StreamName] = d } + for i := range sd.Methods { + d := &sd.Methods[i] + info.streams[d.MethodName] = &StreamDesc{ + StreamName: d.MethodName, + Handler: s.wrapUnaryHandler(d), + ServerStreams: false, + ClientStreams: false, + } + } s.services[sd.ServiceName] = info } @@ -827,20 +839,26 @@ type ServiceInfo struct { func (s *Server) GetServiceInfo() map[string]ServiceInfo { ret := make(map[string]ServiceInfo) for n, srv := range s.services { - methods := make([]MethodInfo, 0, len(srv.methods)+len(srv.streams)) - for m := range srv.methods { - methods = append(methods, MethodInfo{ - Name: m, - IsClientStream: false, - IsServerStream: false, - }) - } + methods := make([]MethodInfo, 0, len(srv.streams)) + // Iterate over unary methods first to maintain backward compatibility of order. for m, d := range srv.streams { - methods = append(methods, MethodInfo{ - Name: m, - IsClientStream: d.ClientStreams, - IsServerStream: d.ServerStreams, - }) + if !d.ClientStreams && !d.ServerStreams { + methods = append(methods, MethodInfo{ + Name: m, + IsClientStream: false, + IsServerStream: false, + }) + } + } + // Iterate over streaming methods. + for m, d := range srv.streams { + if d.ClientStreams || d.ServerStreams { + methods = append(methods, MethodInfo{ + Name: m, + IsClientStream: d.ClientStreams, + IsServerStream: d.ServerStreams, + }) + } } ret[n] = ServiceInfo{ @@ -1185,42 +1203,6 @@ func (s *Server) incrCallsFailed() { s.channelz.ServerMetrics.CallsFailed.Add(1) } -func (s *Server) sendResponse(ctx context.Context, stream *transport.ServerStream, msg any, cp Compressor, opts *transport.WriteOptions, comp encoding.Compressor) error { - data, err := encode(s.getCodec(stream.ContentSubtype()), msg) - if err != nil { - channelz.Error(logger, s.channelz, "grpc: server failed to encode response: ", err) - return err - } - - compData, pf, err := compress(data, cp, comp, s.opts.bufferPool) - if err != nil { - data.Free() - channelz.Error(logger, s.channelz, "grpc: server failed to compress response: ", err) - return err - } - - hdr, payload := msgHeader(data, compData, pf) - - defer func() { - compData.Free() - data.Free() - // payload does not need to be freed here, it is either data or compData, both of - // which are already freed. - }() - - dataLen := data.Len() - payloadLen := payload.Len() - // TODO(dfawley): should we be checking len(data) instead? - if payloadLen > s.opts.maxSendMessageSize { - return status.Errorf(codes.ResourceExhausted, "grpc: trying to send message larger than max (%d vs. %d)", payloadLen, s.opts.maxSendMessageSize) - } - err = stream.Write(hdr, payload, opts) - if err == nil && s.statsHandler != nil { - s.statsHandler.HandleRPC(ctx, outPayload(false, msg, dataLen, payloadLen, time.Now())) - } - return err -} - // chainUnaryServerInterceptors chains all unary server interceptors into one. func chainUnaryServerInterceptors(s *Server) { // Prepend opts.unaryInt to the chaining interceptors if it exists, since unaryInt will @@ -1257,300 +1239,6 @@ func getChainUnaryHandler(interceptors []UnaryServerInterceptor, curr int, info } } -func (s *Server) processUnaryRPC(ctx context.Context, stream *transport.ServerStream, info *serviceInfo, md *MethodDesc, trInfo *traceInfo) (err error) { - sh := s.statsHandler - if sh != nil || trInfo != nil || channelz.IsOn() { - if channelz.IsOn() { - s.incrCallsStarted() - } - var statsBegin *stats.Begin - if sh != nil { - statsBegin = &stats.Begin{ - BeginTime: time.Now(), - IsClientStream: false, - IsServerStream: false, - } - sh.HandleRPC(ctx, statsBegin) - } - if trInfo != nil { - trInfo.tr.LazyLog(&trInfo.firstLine, false) - } - // The deferred error handling for tracing, stats handler and channelz are - // combined into one function to reduce stack usage -- a defer takes ~56-64 - // bytes on the stack, so overflowing the stack will require a stack - // re-allocation, which is expensive. - // - // To maintain behavior similar to separate deferred statements, statements - // should be executed in the reverse order. That is, tracing first, stats - // handler second, and channelz last. Note that panics *within* defers will - // lead to different behavior, but that's an acceptable compromise; that - // would be undefined behavior territory anyway. - defer func() { - if trInfo != nil { - if err != nil && err != io.EOF { - trInfo.tr.LazyLog(&fmtStringer{"%v", []any{err}}, true) - trInfo.tr.SetError() - } - trInfo.tr.Finish() - } - - if sh != nil { - end := &stats.End{ - BeginTime: statsBegin.BeginTime, - EndTime: time.Now(), - } - if err != nil && err != io.EOF { - end.Error = toRPCErr(err) - } - sh.HandleRPC(ctx, end) - } - - if channelz.IsOn() { - if err != nil && err != io.EOF { - s.incrCallsFailed() - } else { - s.incrCallsSucceeded() - } - } - }() - } - var binlogs []binarylog.MethodLogger - if ml := binarylog.GetMethodLogger(stream.Method()); ml != nil { - binlogs = append(binlogs, ml) - } - if s.opts.binaryLogger != nil { - if ml := s.opts.binaryLogger.GetMethodLogger(stream.Method()); ml != nil { - binlogs = append(binlogs, ml) - } - } - if len(binlogs) != 0 { - md, _ := metadata.FromIncomingContext(ctx) - logEntry := &binarylog.ClientHeader{ - Header: md, - MethodName: stream.Method(), - PeerAddr: nil, - } - if deadline, ok := ctx.Deadline(); ok { - logEntry.Timeout = time.Until(deadline) - if logEntry.Timeout < 0 { - logEntry.Timeout = 0 - } - } - if a := md[":authority"]; len(a) > 0 { - logEntry.Authority = a[0] - } - if peer, ok := peer.FromContext(ctx); ok { - logEntry.PeerAddr = peer.Addr - } - for _, binlog := range binlogs { - binlog.Log(ctx, logEntry) - } - } - - // comp and cp are used for compression. decomp and dc are used for - // decompression. If comp and decomp are both set, they are the same; - // however they are kept separate to ensure that at most one of the - // compressor/decompressor variable pairs are set for use later. - var comp, decomp encoding.Compressor - var cp Compressor - var dc Decompressor - var sendCompressorName string - - // If dc is set and matches the stream's compression, use it. Otherwise, try - // to find a matching registered compressor for decomp. - if rc := stream.RecvCompress(); s.opts.dc != nil && s.opts.dc.Type() == rc { - dc = s.opts.dc - } else if rc != "" && rc != encoding.Identity { - decomp = encoding.GetCompressor(rc) - if decomp == nil { - st := status.Newf(codes.Unimplemented, "grpc: Decompressor is not installed for grpc-encoding %q", rc) - stream.WriteStatus(st) - return st.Err() - } - } - - // If cp is set, use it. Otherwise, attempt to compress the response using - // the incoming message compression method. - // - // NOTE: this needs to be ahead of all handling, https://github.com/grpc/grpc-go/issues/686. - if s.opts.cp != nil { - cp = s.opts.cp - sendCompressorName = cp.Type() - } else if rc := stream.RecvCompress(); rc != "" && rc != encoding.Identity { - // Legacy compressor not specified; attempt to respond with same encoding. - comp = encoding.GetCompressor(rc) - if comp != nil { - sendCompressorName = comp.Name() - } - } - - if sendCompressorName != "" { - if err := stream.SetSendCompress(sendCompressorName); err != nil { - return status.Errorf(codes.Internal, "grpc: failed to set send compressor: %v", err) - } - } - - var payInfo *payloadInfo - if sh != nil || len(binlogs) != 0 { - payInfo = &payloadInfo{} - defer payInfo.free() - } - - d, err := recvAndDecompress(&parser{r: stream, bufferPool: s.opts.bufferPool}, stream, dc, s.opts.maxReceiveMessageSize, payInfo, decomp, true) - if err != nil { - if e := stream.WriteStatus(status.Convert(err)); e != nil { - channelz.Warningf(logger, s.channelz, "grpc: Server.processUnaryRPC failed to write status: %v", e) - } - return err - } - freed := false - dataFree := func() { - if !freed { - d.Free() - freed = true - } - } - defer dataFree() - df := func(v any) error { - defer dataFree() - if err := s.getCodec(stream.ContentSubtype()).Unmarshal(d, v); err != nil { - return status.Errorf(codes.Internal, "grpc: error unmarshalling request: %v", err) - } - - if sh != nil { - sh.HandleRPC(ctx, &stats.InPayload{ - RecvTime: time.Now(), - Payload: v, - Length: d.Len(), - WireLength: payInfo.compressedLength + headerLen, - CompressedLength: payInfo.compressedLength, - }) - } - if len(binlogs) != 0 { - cm := &binarylog.ClientMessage{ - Message: d.Materialize(), - } - for _, binlog := range binlogs { - binlog.Log(ctx, cm) - } - } - if trInfo != nil { - trInfo.tr.LazyLog(&payload{sent: false, msg: v}, true) - } - return nil - } - ctx = NewContextWithServerTransportStream(ctx, stream) - reply, appErr := md.Handler(info.serviceImpl, ctx, df, s.opts.unaryInt) - if appErr != nil { - appStatus, ok := status.FromError(appErr) - if !ok { - // Convert non-status application error to a status error with code - // Unknown, but handle context errors specifically. - appStatus = status.FromContextError(appErr) - appErr = appStatus.Err() - } - if trInfo != nil { - trInfo.tr.LazyLog(stringer(appStatus.Message()), true) - trInfo.tr.SetError() - } - if e := stream.WriteStatus(appStatus); e != nil { - channelz.Warningf(logger, s.channelz, "grpc: Server.processUnaryRPC failed to write status: %v", e) - } - if len(binlogs) != 0 { - if h, _ := stream.Header(); h.Len() > 0 { - // Only log serverHeader if there was header. Otherwise it can - // be trailer only. - sh := &binarylog.ServerHeader{ - Header: h, - } - for _, binlog := range binlogs { - binlog.Log(ctx, sh) - } - } - st := &binarylog.ServerTrailer{ - Trailer: stream.Trailer(), - Err: appErr, - } - for _, binlog := range binlogs { - binlog.Log(ctx, st) - } - } - return appErr - } - if trInfo != nil { - trInfo.tr.LazyLog(stringer("OK"), false) - } - opts := &transport.WriteOptions{Last: true} - - // Server handler could have set new compressor by calling SetSendCompressor. - // In case it is set, we need to use it for compressing outbound message. - if stream.SendCompress() != sendCompressorName { - comp = encoding.GetCompressor(stream.SendCompress()) - } - if err := s.sendResponse(ctx, stream, reply, cp, opts, comp); err != nil { - if err == io.EOF { - // The entire stream is done (for unary RPC only). - return err - } - if sts, ok := status.FromError(err); ok { - if e := stream.WriteStatus(sts); e != nil { - channelz.Warningf(logger, s.channelz, "grpc: Server.processUnaryRPC failed to write status: %v", e) - } - } else { - switch st := err.(type) { - case transport.ConnectionError: - // Nothing to do here. - default: - panic(fmt.Sprintf("grpc: Unexpected error (%T) from sendResponse: %v", st, st)) - } - } - if len(binlogs) != 0 { - h, _ := stream.Header() - sh := &binarylog.ServerHeader{ - Header: h, - } - st := &binarylog.ServerTrailer{ - Trailer: stream.Trailer(), - Err: appErr, - } - for _, binlog := range binlogs { - binlog.Log(ctx, sh) - binlog.Log(ctx, st) - } - } - return err - } - if len(binlogs) != 0 { - h, _ := stream.Header() - sh := &binarylog.ServerHeader{ - Header: h, - } - sm := &binarylog.ServerMessage{ - Message: reply, - } - for _, binlog := range binlogs { - binlog.Log(ctx, sh) - binlog.Log(ctx, sm) - } - } - if trInfo != nil { - trInfo.tr.LazyLog(&payload{sent: true, msg: reply}, true) - } - // TODO: Should we be logging if writing status failed here, like above? - // Should the logging be in WriteStatus? Should we ignore the WriteStatus - // error or allow the stats handler to see it? - if len(binlogs) != 0 { - st := &binarylog.ServerTrailer{ - Trailer: stream.Trailer(), - Err: appErr, - } - for _, binlog := range binlogs { - binlog.Log(ctx, st) - } - } - return stream.WriteStatus(statusOK) -} - // chainStreamServerInterceptors chains all stream server interceptors into one. func chainStreamServerInterceptors(s *Server) { // Prepend opts.streamInt to the chaining interceptors if it exists, since streamInt will @@ -1587,7 +1275,21 @@ func getChainStreamHandler(interceptors []StreamServerInterceptor, curr int, inf } } -func (s *Server) processStreamingRPC(ctx context.Context, stream *transport.ServerStream, info *serviceInfo, sd *StreamDesc, trInfo *traceInfo) (err error) { +// wrapUnaryHandler converts a standard Unary Method Descriptor into a +// StreamHandler, allowing Unary RPCs to be processed via the same unified +// pipeline as Streaming RPCs. +func (s *Server) wrapUnaryHandler(md *MethodDesc) StreamHandler { + return func(srv any, stream ServerStream) error { + df := func(v any) error { return stream.RecvMsg(v) } + reply, err := md.Handler(srv, stream.Context(), df, s.opts.unaryInt) + if err != nil { + return err + } + return stream.SendMsg(reply) + } +} + +func (s *Server) processRPC(ctx context.Context, stream *transport.ServerStream, info *serviceInfo, sd *StreamDesc, trInfo *traceInfo) (err error) { if channelz.IsOn() { s.incrCallsStarted() } @@ -1615,7 +1317,16 @@ func (s *Server) processStreamingRPC(ctx context.Context, stream *transport.Serv } if sh != nil || trInfo != nil || channelz.IsOn() { - // See comment in processUnaryRPC on defers. + // The deferred error handling for tracing, stats handler and channelz are + // combined into one function to reduce stack usage -- a defer takes ~56-64 + // bytes on the stack, so overflowing the stack will require a stack + // re-allocation, which is expensive. + // + // To maintain behavior similar to separate deferred statements, statements + // should be executed in the reverse order. That is, tracing first, stats + // handler second, and channelz last. Note that panics *within* defers will + // lead to different behavior, but that's an acceptable compromise; that + // would be undefined behavior territory anyway. defer func() { if trInfo != nil { ss.mu.Lock() @@ -1717,23 +1428,34 @@ func (s *Server) processStreamingRPC(ctx context.Context, stream *transport.Serv ss.ctx = newContextWithRPCInfo(ss.ctx, false, ss.codec, ss.compressorV0, ss.compressorV1) - if trInfo != nil { - trInfo.tr.LazyLog(&trInfo.firstLine, false) - } + // Execute the xDS HTTP filter interceptors. var appErr error - var server any - if info != nil { - server = info.serviceImpl + var wrappedStream ServerStream = ss + if s.opts.streamWrapper != nil { + wrappedStream, appErr = s.opts.streamWrapper(ss) } - if s.opts.streamInt == nil { - appErr = sd.Handler(server, ss) - } else { - info := &StreamServerInfo{ - FullMethod: stream.Method(), - IsClientStream: sd.ClientStreams, - IsServerStream: sd.ServerStreams, + + if appErr == nil { + if trInfo != nil { + trInfo.tr.LazyLog(&trInfo.firstLine, false) + } + var server any + if info != nil { + server = info.serviceImpl + } + if s.opts.streamInt == nil || (!sd.ClientStreams && !sd.ServerStreams) { + // If there is no stream interceptor, or if this is a unary RPC, call + // the handler directly. The wrapped unary handler will call the unary + // interceptor if it exists. + appErr = sd.Handler(server, wrappedStream) + } else { + info := &StreamServerInfo{ + FullMethod: stream.Method(), + IsClientStream: sd.ClientStreams, + IsServerStream: sd.ServerStreams, + } + appErr = s.opts.streamInt(server, wrappedStream, info, sd.Handler) } - appErr = s.opts.streamInt(server, ss, info, sd.Handler) } if appErr != nil { appStatus, ok := status.FromError(appErr) @@ -1750,6 +1472,17 @@ func (s *Server) processStreamingRPC(ctx context.Context, stream *transport.Serv ss.mu.Unlock() } if len(ss.binlogs) != 0 { + if !ss.serverHeaderBinlogged { + if h, _ := ss.s.Header(); h.Len() > 0 { + sh := &binarylog.ServerHeader{ + Header: h, + } + ss.serverHeaderBinlogged = true + for _, binlog := range ss.binlogs { + binlog.Log(ctx, sh) + } + } + } st := &binarylog.ServerTrailer{ Trailer: ss.s.Trailer(), Err: appErr, @@ -1758,8 +1491,9 @@ func (s *Server) processStreamingRPC(ctx context.Context, stream *transport.Serv binlog.Log(ctx, st) } } - ss.s.WriteStatus(appStatus) - // TODO: Should we log an error from WriteStatus here and below? + if err := ss.s.WriteStatus(appStatus); err != nil { + channelz.Warningf(logger, s.channelz, "grpc: Server.processRPC failed to write status: %v", err) + } return appErr } if trInfo != nil { @@ -1776,7 +1510,10 @@ func (s *Server) processStreamingRPC(ctx context.Context, stream *transport.Serv binlog.Log(ctx, st) } } - return ss.s.WriteStatus(statusOK) + if err := ss.s.WriteStatus(statusOK); err != nil { + channelz.Warningf(logger, s.channelz, "grpc: Server.processRPC failed to write status: %v", err) + } + return err } func (s *Server) handleMalformedMethodName(stream *transport.ServerStream, ti *traceInfo) { @@ -1854,18 +1591,14 @@ func (s *Server) handleStream(t transport.ServerTransport, stream *transport.Ser srv, knownService := s.services[service] if knownService { - if md, ok := srv.methods[method]; ok { - s.processUnaryRPC(ctx, stream, srv, md, ti) - return - } if sd, ok := srv.streams[method]; ok { - s.processStreamingRPC(ctx, stream, srv, sd, ti) + s.processRPC(ctx, stream, srv, sd, ti) return } } // Unknown service, or known server unknown method. if unknownDesc := s.opts.unknownStreamDesc; unknownDesc != nil { - s.processStreamingRPC(ctx, stream, nil, unknownDesc, ti) + s.processRPC(ctx, stream, nil, unknownDesc, ti) return } var errDesc string @@ -1986,7 +1719,13 @@ func (s *Server) stop(graceful bool) { } if graceful || s.opts.waitForHandlers { + // Release the lock while waiting for handlers to finish. Holding it + // here would deadlock a concurrent Stop() (the recommended way to abort + // a GracefulStop that is taking too long), because Stop() must acquire + // s.mu before it can force the server to shut down. + s.mu.Unlock() s.handlersWG.Wait() + s.mu.Lock() } if s.events != nil { @@ -2069,9 +1808,6 @@ func (s *Server) isRegisteredMethod(serviceMethod string) bool { method := serviceMethod[pos+1:] srv, knownService := s.services[service] if knownService { - if _, ok := srv.methods[method]; ok { - return true - } if _, ok := srv.streams[method]; ok { return true } diff --git a/vendor/google.golang.org/grpc/stats/stats.go b/vendor/google.golang.org/grpc/stats/stats.go index 10bf998..c699672 100644 --- a/vendor/google.golang.org/grpc/stats/stats.go +++ b/vendor/google.golang.org/grpc/stats/stats.go @@ -190,6 +190,9 @@ type OutHeader struct { Compression string // Header contains the header metadata sent. Header metadata.MD + // Authority is the :authority pseudo-header sent for the RPC. + // It is valid only if Client is true. + Authority string // The following fields are valid only if Client is true. // FullMethod is the full RPC method string, i.e., /package.service/method. diff --git a/vendor/google.golang.org/grpc/stream.go b/vendor/google.golang.org/grpc/stream.go index 51aff85..9fd628b 100644 --- a/vendor/google.golang.org/grpc/stream.go +++ b/vendor/google.golang.org/grpc/stream.go @@ -28,6 +28,7 @@ import ( "strconv" "strings" "sync" + "sync/atomic" "time" "google.golang.org/grpc/balancer" @@ -148,6 +149,81 @@ type ClientStream interface { RecvMsg(m any) error } +// clientStreamWrapper wraps a ClientStream and handles SendMsg, CloseSend, and +// RecvMsg parities based on the nature of stream. +type clientStreamWrapper struct { + ClientStream + desc *StreamDesc + closeSendCalled atomic.Bool +} + +// CloseSend closes the send direction of the stream. The implementation ensures +// that CloseSend is only called once on the underlying ClientStream, even if +// CloseSend is called multiple times on the wrapper. +func (w *clientStreamWrapper) CloseSend() error { + if w.closeSendCalled.Swap(true) { + return nil + } + return w.ClientStream.CloseSend() +} + +// SendMsg sends message m across the stream. For RPCs where client can call +// SendMsg only once, i.e. only server-streaming RPCs, it converts io.EOF to nil +// and immediately calls CloseSend to trigger any interceptor hooks. +func (w *clientStreamWrapper) SendMsg(m any) error { + err := w.ClientStream.SendMsg(m) + // If the RPC is a client-streaming RPC, the client can send multiple + // messages. In this case, the client should handle any type of + // error,including io.EOF and call CloseSend once it is done sending messages. + if w.desc.ClientStreams { + return err + } + + if err == io.EOF { + // For non-client-streaming RPCs, we return nil instead of EOF on error + // because the generated code requires it. finish is not called; RecvMsg() + // will call it with the stream's status independently. + return nil + } + if err != nil { + return err + } + // In some scenarios (e.g., xDS), the same interceptors process both unary and + // streaming RPCs, relying on CloseSend to signal that no more messages are on + // the way. Although protobuf-generated stubs already invoke CloseSend for + // server-streaming RPCs, it is explicitly called here to ensure downstream + // interceptors are also notified when callers interact with the ClientStream + // API directly. + if err := w.CloseSend(); err != nil && err != io.EOF { + return err + } + return nil + +} + +// RecvMsg receives message m from the stream. For non-server-streaming RPCs +// (unary and client-streaming), it calls the underlying RecvMsg a second time +// after receiving the first message to get the trailers. +func (w *clientStreamWrapper) RecvMsg(m any) error { + err := w.ClientStream.RecvMsg(m) + if err != nil { + return err + } + if w.desc.ServerStreams { + return nil + } + // Call RecvMsg again for non-server streaming RPCs to get the trailers and + // ensure RPC has completed successfully. + err = w.ClientStream.RecvMsg(m) + if err == io.EOF { + return nil + } + if err == nil { + return status.Error(codes.Internal, "cardinality violation: expected for non server-streaming RPCs, but received another message") + } + return err +} + // NewStream creates a new Stream for the client side. This is typically // called by generated code. ctx is used for the lifetime of the stream. // @@ -253,14 +329,11 @@ func newClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, meth mc := &emptyMethodConfig var onCommit func() - newStream := func(ctx context.Context, filterOpts ...CallOption) (ClientStream, error) { - if filterOpts != nil { - opts = combine(opts, filterOpts) - } + newStream := func(ctx context.Context, opts ...CallOption) (ClientStream, error) { return newClientStreamWithParams(ctx, desc, cc, method, mc, onCommit, nameResolutionDelayed, opts...) } - rpcInfo := iresolver.RPCInfo{Context: ctx, Method: method} + rpcInfo := iresolver.RPCInfo{Context: ctx, Method: method, Authority: cc.authority} rpcConfig, err := cc.safeConfigSelector.SelectConfig(rpcInfo) if err != nil { if st, ok := status.FromError(err); ok { @@ -278,13 +351,23 @@ func newClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, meth ctx = rpcConfig.Context } mc = &rpcConfig.MethodConfig - onCommit = rpcConfig.OnCommitted + + if rpcConfig.OnCommitted != nil { + onCommit = rpcConfig.OnCommitted + // Register an OnFinish CallOption with the OnCommitted callback to + // ensure it is invoked on stream termination, even if the stream + // fails early before committing. Implementations of OnCommitted are + // expected to be idempotent (e.g., guarded by sync.Once), since both + // onCommit and OnFinish may run for a single RPC. + opts = append(opts, OnFinish(func(error) { rpcConfig.OnCommitted() })) + } + if rpcConfig.Interceptor != nil { rpcInfo.Context = nil ns := newStream if interceptor, ok := rpcConfig.Interceptor.(clientInterceptor); ok { - newStream = func(ctx context.Context, filterOpts ...CallOption) (ClientStream, error) { - cs, err := interceptor.NewStream(ctx, rpcInfo, ns, filterOpts...) + newStream = func(ctx context.Context, opts ...CallOption) (ClientStream, error) { + cs, err := interceptor.NewStream(ctx, rpcInfo, ns, opts...) if err != nil { return nil, toRPCErr(err) } @@ -296,7 +379,11 @@ func newClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, meth } } - return newStream(ctx) + cs, err := newStream(ctx, opts...) + if err != nil { + return nil, err + } + return &clientStreamWrapper{ClientStream: cs, desc: desc}, nil } func newClientStreamWithParams(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, mc *serviceconfig.MethodConfig, onCommit func(), nameResolutionDelayed bool, opts ...CallOption) (_ ClientStream, err error) { @@ -536,13 +623,21 @@ func (a *csAttempt) getTransport() error { func (a *csAttempt) newStream() error { cs := a.cs - cs.callHdr.PreviousAttempts = cs.numRetries + // The header is copied because the fields set below, notably the authority + // override taken from the pick result, describe the endpoint picked for + // this attempt only. Mutating the clientStream's header would carry them + // into a later attempt. + callHdr := *cs.callHdr + callHdr.PreviousAttempts = cs.numRetries // Merge metadata stored in PickResult, if any, with existing call metadata. // It is safe to overwrite the csAttempt's context here, since all state // maintained in it are local to the attempt. When the attempt has to be // retried, a new instance of csAttempt will be created. if a.pickResult.Metadata != nil { + if err := imetadata.Validate(a.pickResult.Metadata); err != nil { + return status.Error(codes.Internal, err.Error()) + } // We currently do not have a function it the metadata package which // merges given metadata with existing metadata in a context. Existing // function `AppendToOutgoingContext()` takes a variadic argument of key @@ -560,11 +655,11 @@ func (a *csAttempt) newStream() error { // apply it, as specified in gRFC A81. if cs.callInfo.authority == "" { if authMD := a.pickResult.Metadata.Get(":authority"); len(authMD) > 0 { - cs.callHdr.Authority = authMD[0] + callHdr.Authority = authMD[0] } } } - s, err := a.transport.NewStream(a.ctx, cs.callHdr, a.statsHandler) + s, err := a.transport.NewStream(a.ctx, &callHdr, a.statsHandler) if err != nil { nse, ok := err.(*transport.NewStreamError) if !ok { @@ -599,10 +694,6 @@ type clientStream struct { cancel context.CancelFunc // cancels all attempts - sentLast bool // sent an end stream - - receivedFirstMsg bool // set after the first message is received - methodConfig *MethodConfig ctx context.Context // the application's context, wrapped by stats/tracing @@ -610,19 +701,10 @@ type clientStream struct { retryThrottler *retryThrottler // The throttler active when the RPC began. binlogs []binarylog.MethodLogger - // serverHeaderBinlogged is a boolean for whether server header has been - // logged. Server header will be logged when the first time one of those - // happens: stream.Header(), stream.Recv(). - // - // It's only read and used by Recv() and Header(), so it doesn't need to be - // synchronized. - serverHeaderBinlogged bool mu sync.Mutex - firstAttempt bool // if true, transparent retry is valid - numRetries int // exclusive of transparent retry attempt(s) - numRetriesSincePushback int // retries since pushback; to reset backoff - finished bool // TODO: replace with atomic cmpxchg or sync.Once? + numRetries int // exclusive of transparent retry attempt(s) + numRetriesSincePushback int // retries since pushback; to reset backoff // attempt is the active client stream attempt. // The only place where it is written is the newAttemptLocked method and this method never writes nil. // So, attempt can be nil only inside newClientStream function when clientStream is first created. @@ -632,13 +714,33 @@ type clientStream struct { // place where we need to check if the attempt is nil. attempt *csAttempt // TODO(hedging): hedging will have multiple attempts simultaneously. - committed bool // active attempt committed for retry? onCommit func() replayBuffer []replayOp // operations to replay on retry replayBufferSize int // current size of replayBuffer + + // Bool fields are grouped at the tail to eliminate the alignment padding + // that would otherwise follow each bool when the next field is pointer- or + // int-sized. See https://github.com/grpc/grpc-go/issues/9280 for benchmarks. + // Add new bool fields here, not inline above. + + // Not guarded by mu. + sentLast bool // sent an end stream + receivedFirstMsg bool // set after the first message is received + // serverHeaderBinlogged is a boolean for whether server header has been + // logged. Server header will be logged when the first time one of those + // happens: stream.Header(), stream.Recv(). + // + // It's only read and used by Recv() and Header(), so it doesn't need to be + // synchronized. + serverHeaderBinlogged bool // nameResolutionDelay indicates if there was a delay in the name resolution. // This field is only valid on client side, it's always false on server side. nameResolutionDelay bool + + // Guarded by mu. + firstAttempt bool // if true, transparent retry is valid + finished bool // TODO: replace with atomic cmpxchg or sync.Once? + committed bool // active attempt committed for retry? } type replayOp struct { @@ -656,10 +758,8 @@ type csAttempt struct { parser parser pickResult balancer.PickResult - finished bool - decompressorV0 Decompressor - decompressorV1 encoding.Compressor - decompressorSet bool + decompressorV0 Decompressor + decompressorV1 encoding.Compressor mu sync.Mutex // guards trInfo.tr // trInfo may be nil (if EnableTracing is false). @@ -670,10 +770,18 @@ type csAttempt struct { statsHandler stats.Handler beginTime time.Time - // set for newStream errors that may be transparently retried - allowTransparentRetry bool - // set for pick errors that are returned as a status - drop bool + // Bool fields are grouped at the tail to eliminate the alignment padding + // that would otherwise follow each bool when the next field is pointer- or + // int-sized. See https://github.com/grpc/grpc-go/issues/9347 for benchmarks. + // Add new bool fields here, not inline above. + + // Not guarded by mu. + decompressorSet bool + allowTransparentRetry bool // set for newStream errors that may be transparently retried + drop bool // set for pick errors that are returned as a status + + // Guarded by mu. + finished bool } func (cs *clientStream) commitAttemptLocked() { @@ -1044,8 +1152,8 @@ func (cs *clientStream) RecvMsg(m any) error { binlog.Log(cs.ctx, sm) } } - if err != nil || !cs.desc.ServerStreams { - // err != nil or non-server-streaming indicates end of stream. + if err != nil { + // err != nil indicates end of stream. cs.finish(err) } return err @@ -1093,7 +1201,8 @@ func (cs *clientStream) finish(err error) { } cs.finished = true cs.commitAttemptLocked() - if cs.attempt != nil { + attemptCreated := cs.attempt != nil + if attemptCreated { cs.attempt.finish(err) // after functions all rely upon having a stream. if cs.attempt.transportStream != nil { @@ -1131,7 +1240,13 @@ func (cs *clientStream) finish(err error) { if err == nil { cs.retryThrottler.successfulRPC() } - endOfClientStream(cs.cc, err, cs.opts...) + // If no attempt was ever created, stream creation has failed, and the + // cleanup is left to newClientStream, whose deferred cleanup invokes + // endOfClientStream if the call fails. Invoking it here as well would + // run the cleanup twice for the same call. + if attemptCreated { + endOfClientStream(cs.cc, err, cs.opts...) + } cs.cancel() } @@ -1145,12 +1260,6 @@ func (a *csAttempt) sendMsg(m any, hdr []byte, payld mem.BufferSlice, dataLength a.mu.Unlock() } if err := a.transportStream.Write(hdr, payld, &transport.WriteOptions{Last: !cs.desc.ClientStreams}); err != nil { - if !cs.desc.ClientStreams { - // For non-client-streaming RPCs, we return nil instead of EOF on error - // because the generated code requires it. finish is not called; RecvMsg() - // will call it with the stream's status independently. - return nil - } return io.EOF } if a.statsHandler != nil { @@ -1218,18 +1327,7 @@ func (a *csAttempt) recvMsg(m any, payInfo *payloadInfo) (err error) { Length: payInfo.uncompressedBytes.Len(), }) } - if cs.desc.ServerStreams { - // Subsequent messages should be received by subsequent RecvMsg calls. - return nil - } - // Special handling for non-server-stream rpcs. - // This recv expects EOF or errors, so we don't collect inPayload. - if err := recv(&a.parser, cs.codec, a.transportStream, a.decompressorV0, m, *cs.callInfo.maxReceiveMessageSize, nil, a.decompressorV1, false); err == io.EOF { - return a.transportStream.Status().Err() // non-server streaming Recv returns nil on success - } else if err != nil { - return toRPCErr(err) - } - return status.Error(codes.Internal, "cardinality violation: expected for non server-streaming RPCs, but received another message") + return nil } func (a *csAttempt) finish(err error) { @@ -1399,7 +1497,7 @@ func newNonRetryClientStream(ctx context.Context, desc *StreamDesc, method strin } }() } - return as, nil + return &clientStreamWrapper{ClientStream: as, desc: desc}, nil } type addrConnStream struct { @@ -1411,20 +1509,28 @@ type addrConnStream struct { callInfo *callInfo transport transport.ClientTransport ctx context.Context - sentLast bool - receivedFirstMsg bool desc *StreamDesc codec baseCodec sendCompressorV0 Compressor sendCompressorV1 encoding.Compressor - decompressorSet bool decompressorV0 Decompressor decompressorV1 encoding.Compressor - parser parser // mu guards finished and is held for the entire finish method. - mu sync.Mutex - finished bool + mu sync.Mutex + parser parser + + // Bool fields are grouped at the tail to eliminate the alignment padding + // that would otherwise follow each bool when the next field is pointer- or + // int-sized. See https://github.com/grpc/grpc-go/issues/9348 for benchmarks. + // Add new bool fields here, not inline above. + + // Not guarded by mu. + sentLast bool + receivedFirstMsg bool + decompressorSet bool + + finished bool // guarded by mu } func (as *addrConnStream) Header() (metadata.MD, error) { @@ -1497,12 +1603,6 @@ func (as *addrConnStream) SendMsg(m any) (err error) { } if err := as.transportStream.Write(hdr, payload, &transport.WriteOptions{Last: !as.desc.ClientStreams}); err != nil { - if !as.desc.ClientStreams { - // For non-client-streaming RPCs, we return nil instead of EOF on error - // because the generated code requires it. finish is not called; RecvMsg() - // will call it with the stream's status independently. - return nil - } return io.EOF } @@ -1511,8 +1611,8 @@ func (as *addrConnStream) SendMsg(m any) (err error) { func (as *addrConnStream) RecvMsg(m any) (err error) { defer func() { - if err != nil || !as.desc.ServerStreams { - // err != nil or non-server-streaming indicates end of stream. + if err != nil { + // err != nil indicates end of stream. as.finish(err) } }() @@ -1551,20 +1651,7 @@ func (as *addrConnStream) RecvMsg(m any) (err error) { return toRPCErr(err) } as.receivedFirstMsg = true - - if as.desc.ServerStreams { - // Subsequent messages should be received by subsequent RecvMsg calls. - return nil - } - - // Special handling for non-server-stream rpcs. - // This recv expects EOF or errors, so we don't collect inPayload. - if err := recv(&as.parser, as.codec, as.transportStream, as.decompressorV0, m, *as.callInfo.maxReceiveMessageSize, nil, as.decompressorV1, false); err == io.EOF { - return as.transportStream.Status().Err() // non-server streaming Recv returns nil on success - } else if err != nil { - return toRPCErr(err) - } - return status.Error(codes.Internal, "cardinality violation: expected for non server-streaming RPCs, but received another message") + return nil } func (as *addrConnStream) finish(err error) { @@ -1658,15 +1745,23 @@ type serverStream struct { sendCompressorName string - recvFirstMsg bool // set after the first message is received - maxReceiveMessageSize int maxSendMessageSize int - trInfo *traceInfo + + // mu guards trInfo.tr after the service handler runs. + mu sync.Mutex + trInfo *traceInfo statsHandler stats.Handler binlogs []binarylog.MethodLogger + + // Bool fields are grouped at the tail to eliminate the alignment padding + // that would otherwise follow each bool when the next field is pointer- or + // int-sized. See https://github.com/grpc/grpc-go/issues/9349 for benchmarks. + // Add new bool fields here, not inline above. + + recvFirstMsg bool // set after the first message is received // serverHeaderBinlogged indicates whether server header has been logged. It // will happen when one of the following two happens: stream.SendHeader(), // stream.Send(). @@ -1674,8 +1769,6 @@ type serverStream struct { // It's only checked in send and sendHeader, doesn't need to be // synchronized. serverHeaderBinlogged bool - - mu sync.Mutex // protects trInfo.tr after the service handler runs. } func (ss *serverStream) Context() context.Context { diff --git a/vendor/google.golang.org/grpc/version.go b/vendor/google.golang.org/grpc/version.go index 835dc07..d41341b 100644 --- a/vendor/google.golang.org/grpc/version.go +++ b/vendor/google.golang.org/grpc/version.go @@ -19,4 +19,4 @@ package grpc // Version is the current grpc version. -const Version = "1.83.2" +const Version = "1.85.0" diff --git a/vendor/google.golang.org/protobuf/types/known/emptypb/empty.pb.go b/vendor/google.golang.org/protobuf/types/known/emptypb/empty.pb.go new file mode 100644 index 0000000..1d7ee3b --- /dev/null +++ b/vendor/google.golang.org/protobuf/types/known/emptypb/empty.pb.go @@ -0,0 +1,142 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Code generated by protoc-gen-go. DO NOT EDIT. +// source: google/protobuf/empty.proto + +package emptypb + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" + unsafe "unsafe" +) + +// A generic empty message that you can re-use to avoid defining duplicated +// empty messages in your APIs. A typical example is to use it as the request +// or the response type of an API method. For instance: +// +// service Foo { +// rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); +// } +type Empty struct { + state protoimpl.MessageState `protogen:"open.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *Empty) Reset() { + *x = Empty{} + mi := &file_google_protobuf_empty_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *Empty) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Empty) ProtoMessage() {} + +func (x *Empty) ProtoReflect() protoreflect.Message { + mi := &file_google_protobuf_empty_proto_msgTypes[0] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use Empty.ProtoReflect.Descriptor instead. +func (*Empty) Descriptor() ([]byte, []int) { + return file_google_protobuf_empty_proto_rawDescGZIP(), []int{0} +} + +var File_google_protobuf_empty_proto protoreflect.FileDescriptor + +const file_google_protobuf_empty_proto_rawDesc = "" + + "\n" + + "\x1bgoogle/protobuf/empty.proto\x12\x0fgoogle.protobuf\"\a\n" + + "\x05EmptyB}\n" + + "\x13com.google.protobufB\n" + + "EmptyProtoP\x01Z.google.golang.org/protobuf/types/known/emptypb\xf8\x01\x01\xa2\x02\x03GPB\xaa\x02\x1eGoogle.Protobuf.WellKnownTypesb\x06proto3" + +var ( + file_google_protobuf_empty_proto_rawDescOnce sync.Once + file_google_protobuf_empty_proto_rawDescData []byte +) + +func file_google_protobuf_empty_proto_rawDescGZIP() []byte { + file_google_protobuf_empty_proto_rawDescOnce.Do(func() { + file_google_protobuf_empty_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_google_protobuf_empty_proto_rawDesc), len(file_google_protobuf_empty_proto_rawDesc))) + }) + return file_google_protobuf_empty_proto_rawDescData +} + +var file_google_protobuf_empty_proto_msgTypes = make([]protoimpl.MessageInfo, 1) +var file_google_protobuf_empty_proto_goTypes = []any{ + (*Empty)(nil), // 0: google.protobuf.Empty +} +var file_google_protobuf_empty_proto_depIdxs = []int32{ + 0, // [0:0] is the sub-list for method output_type + 0, // [0:0] is the sub-list for method input_type + 0, // [0:0] is the sub-list for extension type_name + 0, // [0:0] is the sub-list for extension extendee + 0, // [0:0] is the sub-list for field type_name +} + +func init() { file_google_protobuf_empty_proto_init() } +func file_google_protobuf_empty_proto_init() { + if File_google_protobuf_empty_proto != nil { + return + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: unsafe.Slice(unsafe.StringData(file_google_protobuf_empty_proto_rawDesc), len(file_google_protobuf_empty_proto_rawDesc)), + NumEnums: 0, + NumMessages: 1, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_google_protobuf_empty_proto_goTypes, + DependencyIndexes: file_google_protobuf_empty_proto_depIdxs, + MessageInfos: file_google_protobuf_empty_proto_msgTypes, + }.Build() + File_google_protobuf_empty_proto = out.File + file_google_protobuf_empty_proto_goTypes = nil + file_google_protobuf_empty_proto_depIdxs = nil +} diff --git a/vendor/modules.txt b/vendor/modules.txt index 50ed72a..f38f8bb 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -23,8 +23,8 @@ github.com/coder/websocket/internal/bpool github.com/coder/websocket/internal/errd github.com/coder/websocket/internal/util github.com/coder/websocket/internal/wsjs -# github.com/gabriel-vasile/mimetype v1.4.15 -## explicit; go 1.21 +# github.com/gabriel-vasile/mimetype v1.4.16 +## explicit; go 1.24 github.com/gabriel-vasile/mimetype github.com/gabriel-vasile/mimetype/internal/cdf github.com/gabriel-vasile/mimetype/internal/charset @@ -34,7 +34,7 @@ github.com/gabriel-vasile/mimetype/internal/magic github.com/gabriel-vasile/mimetype/internal/markup github.com/gabriel-vasile/mimetype/internal/mp3 github.com/gabriel-vasile/mimetype/internal/scan -# github.com/getsentry/sentry-go v0.49.0 +# github.com/getsentry/sentry-go v0.50.0 ## explicit; go 1.25.0 github.com/getsentry/sentry-go github.com/getsentry/sentry-go/attribute @@ -49,7 +49,7 @@ github.com/getsentry/sentry-go/internal/ratelimit github.com/getsentry/sentry-go/internal/telemetry github.com/getsentry/sentry-go/internal/util github.com/getsentry/sentry-go/report -# github.com/go-faker/faker/v4 v4.11.0 +# github.com/go-faker/faker/v4 v4.12.0 ## explicit; go 1.26.0 github.com/go-faker/faker/v4 github.com/go-faker/faker/v4/pkg/errors @@ -63,19 +63,19 @@ github.com/go-logr/logr/funcr # github.com/go-logr/stdr v1.2.2 ## explicit; go 1.16 github.com/go-logr/stdr -# github.com/go-playground/locales v0.14.1 +# github.com/go-playground/locales v0.14.2 ## explicit; go 1.17 github.com/go-playground/locales github.com/go-playground/locales/currency github.com/go-playground/locales/en -# github.com/go-playground/universal-translator v0.18.1 -## explicit; go 1.18 +# github.com/go-playground/universal-translator v0.18.2 +## explicit; go 1.26 github.com/go-playground/universal-translator # github.com/google/uuid v1.6.0 ## explicit github.com/google/uuid -# github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0 -## explicit; go 1.25.0 +# github.com/grpc-ecosystem/grpc-gateway/v2 v2.34.0 +## explicit; go 1.26.0 github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule github.com/grpc-ecosystem/grpc-gateway/v2/runtime github.com/grpc-ecosystem/grpc-gateway/v2/utilities @@ -88,10 +88,11 @@ github.com/jackc/pgpassfile # github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 ## explicit; go 1.14 github.com/jackc/pgservicefile -# github.com/jackc/pgx/v5 v5.10.0 +# github.com/jackc/pgx/v5 v5.13.0 ## explicit; go 1.25.0 github.com/jackc/pgx/v5 github.com/jackc/pgx/v5/internal/iobufpool +github.com/jackc/pgx/v5/internal/pgdatetime github.com/jackc/pgx/v5/internal/pgio github.com/jackc/pgx/v5/internal/sanitize github.com/jackc/pgx/v5/internal/stmtcache @@ -102,7 +103,7 @@ github.com/jackc/pgx/v5/pgproto3 github.com/jackc/pgx/v5/pgtype github.com/jackc/pgx/v5/pgxpool github.com/jackc/pgx/v5/stdlib -# github.com/jackc/puddle/v2 v2.2.2 +# github.com/jackc/puddle/v2 v2.2.4 ## explicit; go 1.19 github.com/jackc/puddle/v2 github.com/jackc/puddle/v2/internal/genstack @@ -113,13 +114,14 @@ github.com/jmoiron/sqlx/reflectx # github.com/json-iterator/go v1.1.12 ## explicit; go 1.12 github.com/json-iterator/go -# github.com/klauspost/compress v1.19.2 -## explicit; go 1.24 +# github.com/klauspost/compress v1.20.4 +## explicit; go 1.25 github.com/klauspost/compress github.com/klauspost/compress/fse github.com/klauspost/compress/huff0 github.com/klauspost/compress/internal/cpuinfo github.com/klauspost/compress/internal/le +github.com/klauspost/compress/internal/regmask github.com/klauspost/compress/internal/snapref github.com/klauspost/compress/zstd github.com/klauspost/compress/zstd/internal/xxhash @@ -137,8 +139,8 @@ github.com/leodido/go-urn/scim/schema ## explicit; go 1.20 github.com/mailru/easyjson/buffer github.com/mailru/easyjson/jwriter -# github.com/mfridman/interpolate v0.0.2 -## explicit; go 1.19 +# github.com/mfridman/interpolate v0.2.0 +## explicit; go 1.25.0 github.com/mfridman/interpolate # github.com/mitchellh/mapstructure v1.5.0 ## explicit; go 1.14 @@ -152,8 +154,11 @@ github.com/modern-go/reflect2 # github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 ## explicit github.com/munnerz/goautoneg -# github.com/pressly/goose/v3 v3.27.3 -## explicit; go 1.25.7 +# github.com/pandatix/go-abnf v0.5.5 +## explicit; go 1.26.0 +github.com/pandatix/go-abnf +# github.com/pressly/goose/v3 v3.30.1 +## explicit; go 1.26.0 github.com/pressly/goose/v3 github.com/pressly/goose/v3/database github.com/pressly/goose/v3/database/dialect @@ -165,8 +170,8 @@ github.com/pressly/goose/v3/internal/sqlparser github.com/pressly/goose/v3/lock github.com/pressly/goose/v3/lock/internal/store github.com/pressly/goose/v3/lock/internal/table -# github.com/prometheus/client_golang v1.24.1 -## explicit; go 1.25.0 +# github.com/prometheus/client_golang v1.25.0 +## explicit; go 1.26.0 github.com/prometheus/client_golang/internal/github.com/golang/gddo/httputil github.com/prometheus/client_golang/internal/github.com/golang/gddo/httputil/header github.com/prometheus/client_golang/prometheus @@ -174,22 +179,22 @@ github.com/prometheus/client_golang/prometheus/collectors github.com/prometheus/client_golang/prometheus/internal github.com/prometheus/client_golang/prometheus/promhttp github.com/prometheus/client_golang/prometheus/promhttp/internal -# github.com/prometheus/client_model v0.6.2 -## explicit; go 1.22.0 +# github.com/prometheus/client_model v0.6.3 +## explicit; go 1.23 github.com/prometheus/client_model/go -# github.com/prometheus/common v0.70.1 -## explicit; go 1.25.0 +# github.com/prometheus/common v0.74.0 +## explicit; go 1.26.0 github.com/prometheus/common/expfmt github.com/prometheus/common/model -# github.com/prometheus/procfs v0.21.1 -## explicit; go 1.25.0 +# github.com/prometheus/procfs v0.23.0 +## explicit; go 1.26.0 github.com/prometheus/procfs github.com/prometheus/procfs/internal/fs -github.com/prometheus/procfs/internal/util +github.com/prometheus/procfs/internal/parsers # github.com/robfig/cron/v3 v3.0.1 ## explicit; go 1.12 github.com/robfig/cron/v3 -# github.com/sethvargo/go-retry v0.4.0 +# github.com/sethvargo/go-retry v0.5.0 ## explicit; go 1.25 github.com/sethvargo/go-retry # github.com/stretchr/testify v1.12.1 @@ -213,8 +218,8 @@ github.com/txix-open/etp/v4/bpool github.com/txix-open/etp/v4/internal github.com/txix-open/etp/v4/msg github.com/txix-open/etp/v4/store -# github.com/txix-open/isp-kit v1.74.1 -## explicit; go 1.26.0 +# github.com/txix-open/isp-kit v1.76.0 +## explicit; go 1.27 github.com/txix-open/isp-kit/app github.com/txix-open/isp-kit/bgjobx github.com/txix-open/isp-kit/bgjobx/handler @@ -274,8 +279,8 @@ github.com/txix-open/isp-kit/validator # github.com/txix-open/jsonschema v1.3.0 ## explicit; go 1.18 github.com/txix-open/jsonschema -# github.com/txix-open/validator/v10 v10.0.0-20250506161033-f8ce404fffdb -## explicit; go 1.20 +# github.com/txix-open/validator/v10 v10.0.0-20261027072444-85f3391fc5c3 +## explicit; go 1.26.0 github.com/txix-open/validator/v10 github.com/txix-open/validator/v10/translations/en # github.com/wk8/go-ordered-map/v2 v2.1.8 @@ -294,12 +299,12 @@ github.com/xeipuuv/gojsonschema ## explicit; go 1.24.0 go.opentelemetry.io/auto/sdk go.opentelemetry.io/auto/sdk/internal/telemetry -# go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.71.0 -## explicit; go 1.25.0 +# go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.72.0 +## explicit; go 1.26.0 go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace/internal/semconv -# go.opentelemetry.io/otel v1.46.0 -## explicit; go 1.25.0 +# go.opentelemetry.io/otel v1.47.0 +## explicit; go 1.26.0 go.opentelemetry.io/otel go.opentelemetry.io/otel/attribute go.opentelemetry.io/otel/attribute/internal @@ -310,6 +315,7 @@ go.opentelemetry.io/otel/internal/baggage go.opentelemetry.io/otel/internal/errorhandler go.opentelemetry.io/otel/internal/global go.opentelemetry.io/otel/propagation +go.opentelemetry.io/otel/propagation/internal/hextable go.opentelemetry.io/otel/semconv/internal/metricpool go.opentelemetry.io/otel/semconv/v1.17.0 go.opentelemetry.io/otel/semconv/v1.21.0 @@ -317,12 +323,12 @@ go.opentelemetry.io/otel/semconv/v1.37.0 go.opentelemetry.io/otel/semconv/v1.43.0 go.opentelemetry.io/otel/semconv/v1.43.0/httpconv go.opentelemetry.io/otel/semconv/v1.43.0/otelconv -# go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.46.0 -## explicit; go 1.25.0 +# go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0 +## explicit; go 1.26.0 go.opentelemetry.io/otel/exporters/otlp/otlptrace go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform -# go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.46.0 -## explicit; go 1.25.0 +# go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0 +## explicit; go 1.26.0 go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/internal go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/internal/counter @@ -332,13 +338,17 @@ go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/internal/otlpcon go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/internal/otlpjson go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/internal/retry go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/internal/x -# go.opentelemetry.io/otel/metric v1.46.0 -## explicit; go 1.25.0 +# go.opentelemetry.io/otel/log v1.47.0 +## explicit; go 1.26.0 +go.opentelemetry.io/otel/log +go.opentelemetry.io/otel/log/embedded +# go.opentelemetry.io/otel/metric v1.47.0 +## explicit; go 1.26.0 go.opentelemetry.io/otel/metric go.opentelemetry.io/otel/metric/embedded go.opentelemetry.io/otel/metric/noop -# go.opentelemetry.io/otel/sdk v1.46.0 -## explicit; go 1.25.0 +# go.opentelemetry.io/otel/sdk v1.47.0 +## explicit; go 1.26.0 go.opentelemetry.io/otel/sdk go.opentelemetry.io/otel/sdk/instrumentation go.opentelemetry.io/otel/sdk/internal/attrnorm @@ -347,14 +357,14 @@ go.opentelemetry.io/otel/sdk/resource go.opentelemetry.io/otel/sdk/trace go.opentelemetry.io/otel/sdk/trace/internal/env go.opentelemetry.io/otel/sdk/trace/internal/observ -# go.opentelemetry.io/otel/trace v1.46.0 -## explicit; go 1.25.0 +# go.opentelemetry.io/otel/trace v1.47.0 +## explicit; go 1.26.0 go.opentelemetry.io/otel/trace go.opentelemetry.io/otel/trace/embedded go.opentelemetry.io/otel/trace/internal/telemetry go.opentelemetry.io/otel/trace/noop -# go.opentelemetry.io/proto/otlp v1.11.0 -## explicit; go 1.25.0 +# go.opentelemetry.io/proto/otlp v1.11.1 +## explicit; go 1.26.0 go.opentelemetry.io/proto/otlp/collector/trace/v1 go.opentelemetry.io/proto/otlp/common/v1 go.opentelemetry.io/proto/otlp/resource/v1 @@ -373,16 +383,16 @@ go.uber.org/zap/internal/exit go.uber.org/zap/internal/pool go.uber.org/zap/internal/stacktrace go.uber.org/zap/zapcore -# go.yaml.in/yaml/v3 v3.0.5 +# go.yaml.in/yaml/v3 v3.0.6 ## explicit; go 1.16 go.yaml.in/yaml/v3 -# golang.org/x/crypto v0.55.0 -## explicit; go 1.25.0 +# golang.org/x/crypto v0.59.0 +## explicit; go 1.26.0 golang.org/x/crypto/bcrypt golang.org/x/crypto/blowfish golang.org/x/crypto/sha3 -# golang.org/x/net v0.58.0 -## explicit; go 1.25.0 +# golang.org/x/net v0.63.0 +## explicit; go 1.26.0 golang.org/x/net/http/httpguts golang.org/x/net/http2 golang.org/x/net/http2/hpack @@ -391,19 +401,19 @@ golang.org/x/net/internal/httpcommon golang.org/x/net/internal/httpsfv golang.org/x/net/internal/timeseries golang.org/x/net/trace -# golang.org/x/sync v0.22.0 -## explicit; go 1.25.0 +# golang.org/x/sync v0.25.0 +## explicit; go 1.26.0 golang.org/x/sync/errgroup golang.org/x/sync/semaphore -# golang.org/x/sys v0.47.0 -## explicit; go 1.25.0 +# golang.org/x/sys v0.50.0 +## explicit; go 1.26.0 golang.org/x/sys/cpu golang.org/x/sys/execabs golang.org/x/sys/unix golang.org/x/sys/windows golang.org/x/sys/windows/registry -# golang.org/x/text v0.41.0 -## explicit; go 1.25.0 +# golang.org/x/text v0.44.0 +## explicit; go 1.26.0 golang.org/x/text/cases golang.org/x/text/internal golang.org/x/text/internal/language @@ -417,14 +427,14 @@ golang.org/x/text/transform golang.org/x/text/unicode/bidi golang.org/x/text/unicode/norm golang.org/x/text/width -# google.golang.org/genproto/googleapis/api v0.0.0-20260825221802-da73d73af1c5 -## explicit; go 1.25.0 +# google.golang.org/genproto/googleapis/api v0.0.0-20261118221215-c8830f628b3f +## explicit; go 1.26.0 google.golang.org/genproto/googleapis/api/httpbody -# google.golang.org/genproto/googleapis/rpc v0.0.0-20260825221802-da73d73af1c5 -## explicit; go 1.25.0 +# google.golang.org/genproto/googleapis/rpc v0.0.0-20261118221215-c8830f628b3f +## explicit; go 1.26.0 google.golang.org/genproto/googleapis/rpc/status -# google.golang.org/grpc v1.83.2 -## explicit; go 1.25.0 +# google.golang.org/grpc v1.85.0 +## explicit; go 1.26.0 google.golang.org/grpc google.golang.org/grpc/attributes google.golang.org/grpc/backoff @@ -527,6 +537,7 @@ google.golang.org/protobuf/runtime/protoiface google.golang.org/protobuf/runtime/protoimpl google.golang.org/protobuf/types/known/anypb google.golang.org/protobuf/types/known/durationpb +google.golang.org/protobuf/types/known/emptypb google.golang.org/protobuf/types/known/fieldmaskpb google.golang.org/protobuf/types/known/structpb google.golang.org/protobuf/types/known/timestamppb