text
stringlengths 2
1.1M
| id
stringlengths 11
117
| metadata
dict | __index_level_0__
int64 0
885
|
---|---|---|---|
// Copyright 2020 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 boringcrypto
// Package boring exposes functions that are only available when building with
// Go+BoringCrypto. This package is available on all targets as long as the
// Go+BoringCrypto toolchain is used. Use the Enabled function to determine
// whether the BoringCrypto core is actually in use.
//
// Any time the Go+BoringCrypto toolchain is used, the "boringcrypto" build tag
// is satisfied, so that applications can tag files that use this package.
package boring
import "crypto/internal/boring"
// Enabled reports whether BoringCrypto handles supported crypto operations.
func Enabled() bool {
return boring.Enabled
}
| go/src/crypto/boring/boring.go/0 | {
"file_path": "go/src/crypto/boring/boring.go",
"repo_id": "go",
"token_count": 203
} | 204 |
// Copyright 2021 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 ppc64le
package cipher_test
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"testing"
"time"
)
var cbcAESFuzzTests = []struct {
name string
key []byte
}{
{
"CBC-AES128",
commonKey128,
},
{
"CBC-AES192",
commonKey192,
},
{
"CBC-AES256",
commonKey256,
},
}
var timeout *time.Timer
const datalen = 1024
func TestFuzz(t *testing.T) {
for _, ft := range cbcAESFuzzTests {
c, _ := aes.NewCipher(ft.key)
cbcAsm := cipher.NewCBCEncrypter(c, commonIV)
cbcGeneric := cipher.NewCBCGenericEncrypter(c, commonIV)
if testing.Short() {
timeout = time.NewTimer(10 * time.Millisecond)
} else {
timeout = time.NewTimer(2 * time.Second)
}
indata := make([]byte, datalen)
outgeneric := make([]byte, datalen)
outdata := make([]byte, datalen)
fuzzencrypt:
for {
select {
case <-timeout.C:
break fuzzencrypt
default:
}
rand.Read(indata[:])
cbcGeneric.CryptBlocks(indata, outgeneric)
cbcAsm.CryptBlocks(indata, outdata)
if !bytes.Equal(outdata, outgeneric) {
t.Fatalf("AES-CBC encryption does not match reference result: %x and %x, please report this error to security@golang.org", outdata, outgeneric)
}
}
cbcAsm = cipher.NewCBCDecrypter(c, commonIV)
cbcGeneric = cipher.NewCBCGenericDecrypter(c, commonIV)
if testing.Short() {
timeout = time.NewTimer(10 * time.Millisecond)
} else {
timeout = time.NewTimer(2 * time.Second)
}
fuzzdecrypt:
for {
select {
case <-timeout.C:
break fuzzdecrypt
default:
}
rand.Read(indata[:])
cbcGeneric.CryptBlocks(indata, outgeneric)
cbcAsm.CryptBlocks(indata, outdata)
if !bytes.Equal(outdata, outgeneric) {
t.Fatalf("AES-CBC decryption does not match reference result: %x and %x, please report this error to security@golang.org", outdata, outgeneric)
}
}
}
}
| go/src/crypto/cipher/fuzz_test.go/0 | {
"file_path": "go/src/crypto/cipher/fuzz_test.go",
"repo_id": "go",
"token_count": 849
} | 205 |
// Copyright 2022 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package ecdh_test
import (
"bytes"
"crypto"
"crypto/cipher"
"crypto/ecdh"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"fmt"
"internal/testenv"
"io"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"testing"
"golang.org/x/crypto/chacha20"
)
// Check that PublicKey and PrivateKey implement the interfaces documented in
// crypto.PublicKey and crypto.PrivateKey.
var _ interface {
Equal(x crypto.PublicKey) bool
} = &ecdh.PublicKey{}
var _ interface {
Public() crypto.PublicKey
Equal(x crypto.PrivateKey) bool
} = &ecdh.PrivateKey{}
func TestECDH(t *testing.T) {
testAllCurves(t, func(t *testing.T, curve ecdh.Curve) {
aliceKey, err := curve.GenerateKey(rand.Reader)
if err != nil {
t.Fatal(err)
}
bobKey, err := curve.GenerateKey(rand.Reader)
if err != nil {
t.Fatal(err)
}
alicePubKey, err := curve.NewPublicKey(aliceKey.PublicKey().Bytes())
if err != nil {
t.Error(err)
}
if !bytes.Equal(aliceKey.PublicKey().Bytes(), alicePubKey.Bytes()) {
t.Error("encoded and decoded public keys are different")
}
if !aliceKey.PublicKey().Equal(alicePubKey) {
t.Error("encoded and decoded public keys are different")
}
alicePrivKey, err := curve.NewPrivateKey(aliceKey.Bytes())
if err != nil {
t.Error(err)
}
if !bytes.Equal(aliceKey.Bytes(), alicePrivKey.Bytes()) {
t.Error("encoded and decoded private keys are different")
}
if !aliceKey.Equal(alicePrivKey) {
t.Error("encoded and decoded private keys are different")
}
bobSecret, err := bobKey.ECDH(aliceKey.PublicKey())
if err != nil {
t.Fatal(err)
}
aliceSecret, err := aliceKey.ECDH(bobKey.PublicKey())
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(bobSecret, aliceSecret) {
t.Error("two ECDH computations came out different")
}
})
}
type countingReader struct {
r io.Reader
n int
}
func (r *countingReader) Read(p []byte) (int, error) {
n, err := r.r.Read(p)
r.n += n
return n, err
}
func TestGenerateKey(t *testing.T) {
testAllCurves(t, func(t *testing.T, curve ecdh.Curve) {
r := &countingReader{r: rand.Reader}
k, err := curve.GenerateKey(r)
if err != nil {
t.Fatal(err)
}
// GenerateKey does rejection sampling. If the masking works correctly,
// the probability of a rejection is 1-ord(G)/2^ceil(log2(ord(G))),
// which for all curves is small enough (at most 2^-32, for P-256) that
// a bit flip is more likely to make this test fail than bad luck.
// Account for the extra MaybeReadByte byte, too.
if got, expected := r.n, len(k.Bytes())+1; got > expected {
t.Errorf("expected GenerateKey to consume at most %v bytes, got %v", expected, got)
}
})
}
var vectors = map[ecdh.Curve]struct {
PrivateKey, PublicKey string
PeerPublicKey string
SharedSecret string
}{
// NIST vectors from CAVS 14.1, ECC CDH Primitive (SP800-56A).
ecdh.P256(): {
PrivateKey: "7d7dc5f71eb29ddaf80d6214632eeae03d9058af1fb6d22ed80badb62bc1a534",
PublicKey: "04ead218590119e8876b29146ff89ca61770c4edbbf97d38ce385ed281d8a6b230" +
"28af61281fd35e2fa7002523acc85a429cb06ee6648325389f59edfce1405141",
PeerPublicKey: "04700c48f77f56584c5cc632ca65640db91b6bacce3a4df6b42ce7cc838833d287" +
"db71e509e3fd9b060ddb20ba5c51dcc5948d46fbf640dfe0441782cab85fa4ac",
SharedSecret: "46fc62106420ff012e54a434fbdd2d25ccc5852060561e68040dd7778997bd7b",
},
ecdh.P384(): {
PrivateKey: "3cc3122a68f0d95027ad38c067916ba0eb8c38894d22e1b15618b6818a661774ad463b205da88cf699ab4d43c9cf98a1",
PublicKey: "049803807f2f6d2fd966cdd0290bd410c0190352fbec7ff6247de1302df86f25d34fe4a97bef60cff548355c015dbb3e5f" +
"ba26ca69ec2f5b5d9dad20cc9da711383a9dbe34ea3fa5a2af75b46502629ad54dd8b7d73a8abb06a3a3be47d650cc99",
PeerPublicKey: "04a7c76b970c3b5fe8b05d2838ae04ab47697b9eaf52e764592efda27fe7513272734466b400091adbf2d68c58e0c50066" +
"ac68f19f2e1cb879aed43a9969b91a0839c4c38a49749b661efedf243451915ed0905a32b060992b468c64766fc8437a",
SharedSecret: "5f9d29dc5e31a163060356213669c8ce132e22f57c9a04f40ba7fcead493b457e5621e766c40a2e3d4d6a04b25e533f1",
},
// For some reason all field elements in the test vector (both scalars and
// base field elements), but not the shared secret output, have two extra
// leading zero bytes (which in big-endian are irrelevant). Removed here.
ecdh.P521(): {
PrivateKey: "017eecc07ab4b329068fba65e56a1f8890aa935e57134ae0ffcce802735151f4eac6564f6ee9974c5e6887a1fefee5743ae2241bfeb95d5ce31ddcb6f9edb4d6fc47",
PublicKey: "0400602f9d0cf9e526b29e22381c203c48a886c2b0673033366314f1ffbcba240ba42f4ef38a76174635f91e6b4ed34275eb01c8467d05ca80315bf1a7bbd945f550a5" +
"01b7c85f26f5d4b2d7355cf6b02117659943762b6d1db5ab4f1dbc44ce7b2946eb6c7de342962893fd387d1b73d7a8672d1f236961170b7eb3579953ee5cdc88cd2d",
PeerPublicKey: "0400685a48e86c79f0f0875f7bc18d25eb5fc8c0b07e5da4f4370f3a9490340854334b1e1b87fa395464c60626124a4e70d0f785601d37c09870ebf176666877a2046d" +
"01ba52c56fc8776d9e8f5db4f0cc27636d0b741bbe05400697942e80b739884a83bde99e0f6716939e632bc8986fa18dccd443a348b6c3e522497955a4f3c302f676",
SharedSecret: "005fc70477c3e63bc3954bd0df3ea0d1f41ee21746ed95fc5e1fdf90930d5e136672d72cc770742d1711c3c3a4c334a0ad9759436a4d3c5bf6e74b9578fac148c831",
},
// X25519 test vector from RFC 7748, Section 6.1.
ecdh.X25519(): {
PrivateKey: "77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a",
PublicKey: "8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a",
PeerPublicKey: "de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f",
SharedSecret: "4a5d9d5ba4ce2de1728e3bf480350f25e07e21c947d19e3376f09b3c1e161742",
},
}
func TestVectors(t *testing.T) {
testAllCurves(t, func(t *testing.T, curve ecdh.Curve) {
v := vectors[curve]
key, err := curve.NewPrivateKey(hexDecode(t, v.PrivateKey))
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(key.PublicKey().Bytes(), hexDecode(t, v.PublicKey)) {
t.Error("public key derived from the private key does not match")
}
peer, err := curve.NewPublicKey(hexDecode(t, v.PeerPublicKey))
if err != nil {
t.Fatal(err)
}
secret, err := key.ECDH(peer)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(secret, hexDecode(t, v.SharedSecret)) {
t.Errorf("shared secret does not match: %x %x %s %x", secret, sha256.Sum256(secret), v.SharedSecret,
sha256.Sum256(hexDecode(t, v.SharedSecret)))
}
})
}
func hexDecode(t *testing.T, s string) []byte {
b, err := hex.DecodeString(s)
if err != nil {
t.Fatal("invalid hex string:", s)
}
return b
}
func TestString(t *testing.T) {
testAllCurves(t, func(t *testing.T, curve ecdh.Curve) {
s := fmt.Sprintf("%s", curve)
if s[:1] != "P" && s[:1] != "X" {
t.Errorf("unexpected Curve string encoding: %q", s)
}
})
}
func TestX25519Failure(t *testing.T) {
identity := hexDecode(t, "0000000000000000000000000000000000000000000000000000000000000000")
lowOrderPoint := hexDecode(t, "e0eb7a7c3b41b8ae1656e3faf19fc46ada098deb9c32b1fd866205165f49b800")
randomScalar := make([]byte, 32)
rand.Read(randomScalar)
t.Run("identity point", func(t *testing.T) { testX25519Failure(t, randomScalar, identity) })
t.Run("low order point", func(t *testing.T) { testX25519Failure(t, randomScalar, lowOrderPoint) })
}
func testX25519Failure(t *testing.T, private, public []byte) {
priv, err := ecdh.X25519().NewPrivateKey(private)
if err != nil {
t.Fatal(err)
}
pub, err := ecdh.X25519().NewPublicKey(public)
if err != nil {
t.Fatal(err)
}
secret, err := priv.ECDH(pub)
if err == nil {
t.Error("expected ECDH error")
}
if secret != nil {
t.Errorf("unexpected ECDH output: %x", secret)
}
}
var invalidPrivateKeys = map[ecdh.Curve][]string{
ecdh.P256(): {
// Bad lengths.
"",
"01",
"01010101010101010101010101010101010101010101010101010101010101",
"000101010101010101010101010101010101010101010101010101010101010101",
strings.Repeat("01", 200),
// Zero.
"0000000000000000000000000000000000000000000000000000000000000000",
// Order of the curve and above.
"ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551",
"ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632552",
"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
},
ecdh.P384(): {
// Bad lengths.
"",
"01",
"0101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101",
"00010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101",
strings.Repeat("01", 200),
// Zero.
"000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
// Order of the curve and above.
"ffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973",
"ffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52974",
"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
},
ecdh.P521(): {
// Bad lengths.
"",
"01",
"0101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101",
"00010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101",
strings.Repeat("01", 200),
// Zero.
"000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
// Order of the curve and above.
"01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409",
"01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e9138640a",
"11fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409",
"03fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff4a30d0f077e5f2cd6ff980291ee134ba0776b937113388f5d76df6e3d2270c812",
},
ecdh.X25519(): {
// X25519 only rejects bad lengths.
"",
"01",
"01010101010101010101010101010101010101010101010101010101010101",
"000101010101010101010101010101010101010101010101010101010101010101",
strings.Repeat("01", 200),
},
}
func TestNewPrivateKey(t *testing.T) {
testAllCurves(t, func(t *testing.T, curve ecdh.Curve) {
for _, input := range invalidPrivateKeys[curve] {
k, err := curve.NewPrivateKey(hexDecode(t, input))
if err == nil {
t.Errorf("unexpectedly accepted %q", input)
} else if k != nil {
t.Error("PrivateKey was not nil on error")
} else if strings.Contains(err.Error(), "boringcrypto") {
t.Errorf("boringcrypto error leaked out: %v", err)
}
}
})
}
var invalidPublicKeys = map[ecdh.Curve][]string{
ecdh.P256(): {
// Bad lengths.
"",
"04",
strings.Repeat("04", 200),
// Infinity.
"00",
// Compressed encodings.
"036b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296",
"02e2534a3532d08fbba02dde659ee62bd0031fe2db785596ef509302446b030852",
// Points not on the curve.
"046b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c2964fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f6",
"0400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
},
ecdh.P384(): {
// Bad lengths.
"",
"04",
strings.Repeat("04", 200),
// Infinity.
"00",
// Compressed encodings.
"03aa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7",
"0208d999057ba3d2d969260045c55b97f089025959a6f434d651d207d19fb96e9e4fe0e86ebe0e64f85b96a9c75295df61",
// Points not on the curve.
"04aa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab73617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e60",
"04000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
},
ecdh.P521(): {
// Bad lengths.
"",
"04",
strings.Repeat("04", 200),
// Infinity.
"00",
// Compressed encodings.
"030035b5df64ae2ac204c354b483487c9070cdc61c891c5ff39afc06c5d55541d3ceac8659e24afe3d0750e8b88e9f078af066a1d5025b08e5a5e2fbc87412871902f3",
"0200c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66",
// Points not on the curve.
"0400c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16651",
"04000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
},
ecdh.X25519(): {},
}
func TestNewPublicKey(t *testing.T) {
testAllCurves(t, func(t *testing.T, curve ecdh.Curve) {
for _, input := range invalidPublicKeys[curve] {
k, err := curve.NewPublicKey(hexDecode(t, input))
if err == nil {
t.Errorf("unexpectedly accepted %q", input)
} else if k != nil {
t.Error("PublicKey was not nil on error")
} else if strings.Contains(err.Error(), "boringcrypto") {
t.Errorf("boringcrypto error leaked out: %v", err)
}
}
})
}
func testAllCurves(t *testing.T, f func(t *testing.T, curve ecdh.Curve)) {
t.Run("P256", func(t *testing.T) { f(t, ecdh.P256()) })
t.Run("P384", func(t *testing.T) { f(t, ecdh.P384()) })
t.Run("P521", func(t *testing.T) { f(t, ecdh.P521()) })
t.Run("X25519", func(t *testing.T) { f(t, ecdh.X25519()) })
}
func BenchmarkECDH(b *testing.B) {
benchmarkAllCurves(b, func(b *testing.B, curve ecdh.Curve) {
c, err := chacha20.NewUnauthenticatedCipher(make([]byte, 32), make([]byte, 12))
if err != nil {
b.Fatal(err)
}
rand := cipher.StreamReader{
S: c, R: zeroReader,
}
peerKey, err := curve.GenerateKey(rand)
if err != nil {
b.Fatal(err)
}
peerShare := peerKey.PublicKey().Bytes()
b.ResetTimer()
b.ReportAllocs()
var allocationsSink byte
for i := 0; i < b.N; i++ {
key, err := curve.GenerateKey(rand)
if err != nil {
b.Fatal(err)
}
share := key.PublicKey().Bytes()
peerPubKey, err := curve.NewPublicKey(peerShare)
if err != nil {
b.Fatal(err)
}
secret, err := key.ECDH(peerPubKey)
if err != nil {
b.Fatal(err)
}
allocationsSink ^= secret[0] ^ share[0]
}
})
}
func benchmarkAllCurves(b *testing.B, f func(b *testing.B, curve ecdh.Curve)) {
b.Run("P256", func(b *testing.B) { f(b, ecdh.P256()) })
b.Run("P384", func(b *testing.B) { f(b, ecdh.P384()) })
b.Run("P521", func(b *testing.B) { f(b, ecdh.P521()) })
b.Run("X25519", func(b *testing.B) { f(b, ecdh.X25519()) })
}
type zr struct{}
// Read replaces the contents of dst with zeros. It is safe for concurrent use.
func (zr) Read(dst []byte) (n int, err error) {
clear(dst)
return len(dst), nil
}
var zeroReader = zr{}
const linkerTestProgram = `
package main
import "crypto/ecdh"
import "crypto/rand"
func main() {
curve := ecdh.P384()
key, err := curve.GenerateKey(rand.Reader)
if err != nil { panic(err) }
_, err = curve.NewPublicKey(key.PublicKey().Bytes())
if err != nil { panic(err) }
_, err = curve.NewPrivateKey(key.Bytes())
if err != nil { panic(err) }
_, err = key.ECDH(key.PublicKey())
if err != nil { panic(err) }
println("OK")
}
`
// TestLinker ensures that using one curve does not bring all other
// implementations into the binary. This also guarantees that govulncheck can
// avoid warning about a curve-specific vulnerability if that curve is not used.
func TestLinker(t *testing.T) {
if testing.Short() {
t.Skip("test requires running 'go build'")
}
testenv.MustHaveGoBuild(t)
dir := t.TempDir()
hello := filepath.Join(dir, "hello.go")
err := os.WriteFile(hello, []byte(linkerTestProgram), 0664)
if err != nil {
t.Fatal(err)
}
run := func(args ...string) string {
cmd := exec.Command(args[0], args[1:]...)
cmd.Dir = dir
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("%v: %v\n%s", args, err, string(out))
}
return string(out)
}
goBin := testenv.GoToolPath(t)
run(goBin, "build", "-o", "hello.exe", "hello.go")
if out := run("./hello.exe"); out != "OK\n" {
t.Error("unexpected output:", out)
}
// List all text symbols under crypto/... and make sure there are some for
// P384, but none for the other curves.
var consistent bool
nm := run(goBin, "tool", "nm", "hello.exe")
for _, match := range regexp.MustCompile(`(?m)T (crypto/.*)$`).FindAllStringSubmatch(nm, -1) {
symbol := strings.ToLower(match[1])
if strings.Contains(symbol, "p384") {
consistent = true
}
if strings.Contains(symbol, "p224") || strings.Contains(symbol, "p256") || strings.Contains(symbol, "p521") {
t.Errorf("unexpected symbol in program using only ecdh.P384: %s", match[1])
}
}
if !consistent {
t.Error("no P384 symbols found in program using ecdh.P384, test is broken")
}
}
func TestMismatchedCurves(t *testing.T) {
curves := []struct {
name string
curve ecdh.Curve
}{
{"P256", ecdh.P256()},
{"P384", ecdh.P384()},
{"P521", ecdh.P521()},
{"X25519", ecdh.X25519()},
}
for _, privCurve := range curves {
priv, err := privCurve.curve.GenerateKey(rand.Reader)
if err != nil {
t.Fatalf("failed to generate test key: %s", err)
}
for _, pubCurve := range curves {
if privCurve == pubCurve {
continue
}
t.Run(fmt.Sprintf("%s/%s", privCurve.name, pubCurve.name), func(t *testing.T) {
pub, err := pubCurve.curve.GenerateKey(rand.Reader)
if err != nil {
t.Fatalf("failed to generate test key: %s", err)
}
expected := "crypto/ecdh: private key and public key curves do not match"
_, err = priv.ECDH(pub.PublicKey())
if err.Error() != expected {
t.Fatalf("unexpected error: want %q, got %q", expected, err)
}
})
}
}
}
| go/src/crypto/ecdh/ecdh_test.go/0 | {
"file_path": "go/src/crypto/ecdh/ecdh_test.go",
"repo_id": "go",
"token_count": 8151
} | 206 |
// Copyright 2016 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 ed25519
import (
"bufio"
"bytes"
"compress/gzip"
"crypto"
"crypto/internal/boring"
"crypto/rand"
"crypto/sha512"
"encoding/hex"
"internal/testenv"
"log"
"os"
"strings"
"testing"
)
func Example_ed25519ctx() {
pub, priv, err := GenerateKey(nil)
if err != nil {
log.Fatal(err)
}
msg := []byte("The quick brown fox jumps over the lazy dog")
sig, err := priv.Sign(nil, msg, &Options{
Context: "Example_ed25519ctx",
})
if err != nil {
log.Fatal(err)
}
if err := VerifyWithOptions(pub, msg, sig, &Options{
Context: "Example_ed25519ctx",
}); err != nil {
log.Fatal("invalid signature")
}
}
type zeroReader struct{}
func (zeroReader) Read(buf []byte) (int, error) {
clear(buf)
return len(buf), nil
}
func TestSignVerify(t *testing.T) {
var zero zeroReader
public, private, _ := GenerateKey(zero)
message := []byte("test message")
sig := Sign(private, message)
if !Verify(public, message, sig) {
t.Errorf("valid signature rejected")
}
wrongMessage := []byte("wrong message")
if Verify(public, wrongMessage, sig) {
t.Errorf("signature of different message accepted")
}
}
func TestSignVerifyHashed(t *testing.T) {
// From RFC 8032, Section 7.3
key, _ := hex.DecodeString("833fe62409237b9d62ec77587520911e9a759cec1d19755b7da901b96dca3d42ec172b93ad5e563bf4932c70e1245034c35467ef2efd4d64ebf819683467e2bf")
expectedSig, _ := hex.DecodeString("98a70222f0b8121aa9d30f813d683f809e462b469c7ff87639499bb94e6dae4131f85042463c2a355a2003d062adf5aaa10b8c61e636062aaad11c2a26083406")
message, _ := hex.DecodeString("616263")
private := PrivateKey(key)
public := private.Public().(PublicKey)
hash := sha512.Sum512(message)
sig, err := private.Sign(nil, hash[:], crypto.SHA512)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(sig, expectedSig) {
t.Error("signature doesn't match test vector")
}
sig, err = private.Sign(nil, hash[:], &Options{Hash: crypto.SHA512})
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(sig, expectedSig) {
t.Error("signature doesn't match test vector")
}
if err := VerifyWithOptions(public, hash[:], sig, &Options{Hash: crypto.SHA512}); err != nil {
t.Errorf("valid signature rejected: %v", err)
}
if err := VerifyWithOptions(public, hash[:], sig, &Options{Hash: crypto.SHA256}); err == nil {
t.Errorf("expected error for wrong hash")
}
wrongHash := sha512.Sum512([]byte("wrong message"))
if VerifyWithOptions(public, wrongHash[:], sig, &Options{Hash: crypto.SHA512}) == nil {
t.Errorf("signature of different message accepted")
}
sig[0] ^= 0xff
if VerifyWithOptions(public, hash[:], sig, &Options{Hash: crypto.SHA512}) == nil {
t.Errorf("invalid signature accepted")
}
sig[0] ^= 0xff
sig[SignatureSize-1] ^= 0xff
if VerifyWithOptions(public, hash[:], sig, &Options{Hash: crypto.SHA512}) == nil {
t.Errorf("invalid signature accepted")
}
// The RFC provides no test vectors for Ed25519ph with context, so just sign
// and verify something.
sig, err = private.Sign(nil, hash[:], &Options{Hash: crypto.SHA512, Context: "123"})
if err != nil {
t.Fatal(err)
}
if err := VerifyWithOptions(public, hash[:], sig, &Options{Hash: crypto.SHA512, Context: "123"}); err != nil {
t.Errorf("valid signature rejected: %v", err)
}
if err := VerifyWithOptions(public, hash[:], sig, &Options{Hash: crypto.SHA512, Context: "321"}); err == nil {
t.Errorf("expected error for wrong context")
}
if err := VerifyWithOptions(public, hash[:], sig, &Options{Hash: crypto.SHA256, Context: "123"}); err == nil {
t.Errorf("expected error for wrong hash")
}
}
func TestSignVerifyContext(t *testing.T) {
// From RFC 8032, Section 7.2
key, _ := hex.DecodeString("0305334e381af78f141cb666f6199f57bc3495335a256a95bd2a55bf546663f6dfc9425e4f968f7f0c29f0259cf5f9aed6851c2bb4ad8bfb860cfee0ab248292")
expectedSig, _ := hex.DecodeString("55a4cc2f70a54e04288c5f4cd1e45a7bb520b36292911876cada7323198dd87a8b36950b95130022907a7fb7c4e9b2d5f6cca685a587b4b21f4b888e4e7edb0d")
message, _ := hex.DecodeString("f726936d19c800494e3fdaff20b276a8")
context := "foo"
private := PrivateKey(key)
public := private.Public().(PublicKey)
sig, err := private.Sign(nil, message, &Options{Context: context})
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(sig, expectedSig) {
t.Error("signature doesn't match test vector")
}
if err := VerifyWithOptions(public, message, sig, &Options{Context: context}); err != nil {
t.Errorf("valid signature rejected: %v", err)
}
if VerifyWithOptions(public, []byte("bar"), sig, &Options{Context: context}) == nil {
t.Errorf("signature of different message accepted")
}
if VerifyWithOptions(public, message, sig, &Options{Context: "bar"}) == nil {
t.Errorf("signature with different context accepted")
}
sig[0] ^= 0xff
if VerifyWithOptions(public, message, sig, &Options{Context: context}) == nil {
t.Errorf("invalid signature accepted")
}
sig[0] ^= 0xff
sig[SignatureSize-1] ^= 0xff
if VerifyWithOptions(public, message, sig, &Options{Context: context}) == nil {
t.Errorf("invalid signature accepted")
}
}
func TestCryptoSigner(t *testing.T) {
var zero zeroReader
public, private, _ := GenerateKey(zero)
signer := crypto.Signer(private)
publicInterface := signer.Public()
public2, ok := publicInterface.(PublicKey)
if !ok {
t.Fatalf("expected PublicKey from Public() but got %T", publicInterface)
}
if !bytes.Equal(public, public2) {
t.Errorf("public keys do not match: original:%x vs Public():%x", public, public2)
}
message := []byte("message")
var noHash crypto.Hash
signature, err := signer.Sign(zero, message, noHash)
if err != nil {
t.Fatalf("error from Sign(): %s", err)
}
signature2, err := signer.Sign(zero, message, &Options{Hash: noHash})
if err != nil {
t.Fatalf("error from Sign(): %s", err)
}
if !bytes.Equal(signature, signature2) {
t.Errorf("signatures keys do not match")
}
if !Verify(public, message, signature) {
t.Errorf("Verify failed on signature from Sign()")
}
}
func TestEqual(t *testing.T) {
public, private, _ := GenerateKey(rand.Reader)
if !public.Equal(public) {
t.Errorf("public key is not equal to itself: %q", public)
}
if !public.Equal(crypto.Signer(private).Public()) {
t.Errorf("private.Public() is not Equal to public: %q", public)
}
if !private.Equal(private) {
t.Errorf("private key is not equal to itself: %q", private)
}
otherPub, otherPriv, _ := GenerateKey(rand.Reader)
if public.Equal(otherPub) {
t.Errorf("different public keys are Equal")
}
if private.Equal(otherPriv) {
t.Errorf("different private keys are Equal")
}
}
func TestGolden(t *testing.T) {
// sign.input.gz is a selection of test cases from
// https://ed25519.cr.yp.to/python/sign.input
testDataZ, err := os.Open("testdata/sign.input.gz")
if err != nil {
t.Fatal(err)
}
defer testDataZ.Close()
testData, err := gzip.NewReader(testDataZ)
if err != nil {
t.Fatal(err)
}
defer testData.Close()
scanner := bufio.NewScanner(testData)
lineNo := 0
for scanner.Scan() {
lineNo++
line := scanner.Text()
parts := strings.Split(line, ":")
if len(parts) != 5 {
t.Fatalf("bad number of parts on line %d", lineNo)
}
privBytes, _ := hex.DecodeString(parts[0])
pubKey, _ := hex.DecodeString(parts[1])
msg, _ := hex.DecodeString(parts[2])
sig, _ := hex.DecodeString(parts[3])
// The signatures in the test vectors also include the message
// at the end, but we just want R and S.
sig = sig[:SignatureSize]
if l := len(pubKey); l != PublicKeySize {
t.Fatalf("bad public key length on line %d: got %d bytes", lineNo, l)
}
var priv [PrivateKeySize]byte
copy(priv[:], privBytes)
copy(priv[32:], pubKey)
sig2 := Sign(priv[:], msg)
if !bytes.Equal(sig, sig2[:]) {
t.Errorf("different signature result on line %d: %x vs %x", lineNo, sig, sig2)
}
if !Verify(pubKey, msg, sig2) {
t.Errorf("signature failed to verify on line %d", lineNo)
}
priv2 := NewKeyFromSeed(priv[:32])
if !bytes.Equal(priv[:], priv2) {
t.Errorf("recreating key pair gave different private key on line %d: %x vs %x", lineNo, priv[:], priv2)
}
if pubKey2 := priv2.Public().(PublicKey); !bytes.Equal(pubKey, pubKey2) {
t.Errorf("recreating key pair gave different public key on line %d: %x vs %x", lineNo, pubKey, pubKey2)
}
if seed := priv2.Seed(); !bytes.Equal(priv[:32], seed) {
t.Errorf("recreating key pair gave different seed on line %d: %x vs %x", lineNo, priv[:32], seed)
}
}
if err := scanner.Err(); err != nil {
t.Fatalf("error reading test data: %s", err)
}
}
func TestMalleability(t *testing.T) {
// https://tools.ietf.org/html/rfc8032#section-5.1.7 adds an additional test
// that s be in [0, order). This prevents someone from adding a multiple of
// order to s and obtaining a second valid signature for the same message.
msg := []byte{0x54, 0x65, 0x73, 0x74}
sig := []byte{
0x7c, 0x38, 0xe0, 0x26, 0xf2, 0x9e, 0x14, 0xaa, 0xbd, 0x05, 0x9a,
0x0f, 0x2d, 0xb8, 0xb0, 0xcd, 0x78, 0x30, 0x40, 0x60, 0x9a, 0x8b,
0xe6, 0x84, 0xdb, 0x12, 0xf8, 0x2a, 0x27, 0x77, 0x4a, 0xb0, 0x67,
0x65, 0x4b, 0xce, 0x38, 0x32, 0xc2, 0xd7, 0x6f, 0x8f, 0x6f, 0x5d,
0xaf, 0xc0, 0x8d, 0x93, 0x39, 0xd4, 0xee, 0xf6, 0x76, 0x57, 0x33,
0x36, 0xa5, 0xc5, 0x1e, 0xb6, 0xf9, 0x46, 0xb3, 0x1d,
}
publicKey := []byte{
0x7d, 0x4d, 0x0e, 0x7f, 0x61, 0x53, 0xa6, 0x9b, 0x62, 0x42, 0xb5,
0x22, 0xab, 0xbe, 0xe6, 0x85, 0xfd, 0xa4, 0x42, 0x0f, 0x88, 0x34,
0xb1, 0x08, 0xc3, 0xbd, 0xae, 0x36, 0x9e, 0xf5, 0x49, 0xfa,
}
if Verify(publicKey, msg, sig) {
t.Fatal("non-canonical signature accepted")
}
}
func TestAllocations(t *testing.T) {
if boring.Enabled {
t.Skip("skipping allocations test with BoringCrypto")
}
testenv.SkipIfOptimizationOff(t)
if allocs := testing.AllocsPerRun(100, func() {
seed := make([]byte, SeedSize)
message := []byte("Hello, world!")
priv := NewKeyFromSeed(seed)
pub := priv.Public().(PublicKey)
signature := Sign(priv, message)
if !Verify(pub, message, signature) {
t.Fatal("signature didn't verify")
}
}); allocs > 0 {
t.Errorf("expected zero allocations, got %0.1f", allocs)
}
}
func BenchmarkKeyGeneration(b *testing.B) {
var zero zeroReader
for i := 0; i < b.N; i++ {
if _, _, err := GenerateKey(zero); err != nil {
b.Fatal(err)
}
}
}
func BenchmarkNewKeyFromSeed(b *testing.B) {
seed := make([]byte, SeedSize)
for i := 0; i < b.N; i++ {
_ = NewKeyFromSeed(seed)
}
}
func BenchmarkSigning(b *testing.B) {
var zero zeroReader
_, priv, err := GenerateKey(zero)
if err != nil {
b.Fatal(err)
}
message := []byte("Hello, world!")
b.ResetTimer()
for i := 0; i < b.N; i++ {
Sign(priv, message)
}
}
func BenchmarkVerification(b *testing.B) {
var zero zeroReader
pub, priv, err := GenerateKey(zero)
if err != nil {
b.Fatal(err)
}
message := []byte("Hello, world!")
signature := Sign(priv, message)
b.ResetTimer()
for i := 0; i < b.N; i++ {
Verify(pub, message, signature)
}
}
| go/src/crypto/ed25519/ed25519_test.go/0 | {
"file_path": "go/src/crypto/ed25519/ed25519_test.go",
"repo_id": "go",
"token_count": 4564
} | 207 |
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"strconv"
. "github.com/mmcloughlin/avo/build"
. "github.com/mmcloughlin/avo/operand"
. "github.com/mmcloughlin/avo/reg"
)
//go:generate go run . -out ../nat_amd64.s -pkg bigmod
func main() {
Package("crypto/internal/bigmod")
ConstraintExpr("!purego")
addMulVVW(1024)
addMulVVW(1536)
addMulVVW(2048)
Generate()
}
func addMulVVW(bits int) {
if bits%64 != 0 {
panic("bit size unsupported")
}
Implement("addMulVVW" + strconv.Itoa(bits))
CMPB(Mem{Symbol: Symbol{Name: "·supportADX"}, Base: StaticBase}, Imm(1))
JEQ(LabelRef("adx"))
z := Mem{Base: Load(Param("z"), GP64())}
x := Mem{Base: Load(Param("x"), GP64())}
y := Load(Param("y"), GP64())
carry := GP64()
XORQ(carry, carry) // zero out carry
for i := 0; i < bits/64; i++ {
Comment("Iteration " + strconv.Itoa(i))
hi, lo := RDX, RAX // implicit MULQ inputs and outputs
MOVQ(x.Offset(i*8), lo)
MULQ(y)
ADDQ(z.Offset(i*8), lo)
ADCQ(Imm(0), hi)
ADDQ(carry, lo)
ADCQ(Imm(0), hi)
MOVQ(hi, carry)
MOVQ(lo, z.Offset(i*8))
}
Store(carry, ReturnIndex(0))
RET()
Label("adx")
// The ADX strategy implements the following function, where c1 and c2 are
// the overflow and the carry flag respectively.
//
// func addMulVVW(z, x []uint, y uint) (carry uint) {
// var c1, c2 uint
// for i := range z {
// hi, lo := bits.Mul(x[i], y)
// lo, c1 = bits.Add(lo, z[i], c1)
// z[i], c2 = bits.Add(lo, carry, c2)
// carry = hi
// }
// return carry + c1 + c2
// }
//
// The loop is fully unrolled and the hi / carry registers are alternated
// instead of introducing a MOV.
z = Mem{Base: Load(Param("z"), GP64())}
x = Mem{Base: Load(Param("x"), GP64())}
Load(Param("y"), RDX) // implicit source of MULXQ
carry = GP64()
XORQ(carry, carry) // zero out carry
z0 := GP64()
XORQ(z0, z0) // unset flags and zero out z0
for i := 0; i < bits/64; i++ {
hi, lo := GP64(), GP64()
Comment("Iteration " + strconv.Itoa(i))
MULXQ(x.Offset(i*8), lo, hi)
ADCXQ(carry, lo)
ADOXQ(z.Offset(i*8), lo)
MOVQ(lo, z.Offset(i*8))
i++
Comment("Iteration " + strconv.Itoa(i))
MULXQ(x.Offset(i*8), lo, carry)
ADCXQ(hi, lo)
ADOXQ(z.Offset(i*8), lo)
MOVQ(lo, z.Offset(i*8))
}
Comment("Add back carry flags and return")
ADCXQ(z0, carry)
ADOXQ(z0, carry)
Store(carry, ReturnIndex(0))
RET()
}
| go/src/crypto/internal/bigmod/_asm/nat_amd64_asm.go/0 | {
"file_path": "go/src/crypto/internal/bigmod/_asm/nat_amd64_asm.go",
"repo_id": "go",
"token_count": 1183
} | 208 |
// Copyright 2022 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package bbig
import (
"crypto/internal/boring"
"math/big"
"unsafe"
)
func Enc(b *big.Int) boring.BigInt {
if b == nil {
return nil
}
x := b.Bits()
if len(x) == 0 {
return boring.BigInt{}
}
return unsafe.Slice((*uint)(&x[0]), len(x))
}
func Dec(b boring.BigInt) *big.Int {
if b == nil {
return nil
}
if len(b) == 0 {
return new(big.Int)
}
x := unsafe.Slice((*big.Word)(&b[0]), len(b))
return new(big.Int).SetBits(x)
}
| go/src/crypto/internal/boring/bbig/big.go/0 | {
"file_path": "go/src/crypto/internal/boring/bbig/big.go",
"repo_id": "go",
"token_count": 254
} | 209 |
// Copyright 2017 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 boringcrypto && linux && (amd64 || arm64) && !android && !msan
package boring
// #include "goboringcrypto.h"
import "C"
import (
"bytes"
"crypto"
"hash"
"runtime"
"unsafe"
)
// hashToMD converts a hash.Hash implementation from this package
// to a BoringCrypto *C.GO_EVP_MD.
func hashToMD(h hash.Hash) *C.GO_EVP_MD {
switch h.(type) {
case *sha1Hash:
return C._goboringcrypto_EVP_sha1()
case *sha224Hash:
return C._goboringcrypto_EVP_sha224()
case *sha256Hash:
return C._goboringcrypto_EVP_sha256()
case *sha384Hash:
return C._goboringcrypto_EVP_sha384()
case *sha512Hash:
return C._goboringcrypto_EVP_sha512()
}
return nil
}
// cryptoHashToMD converts a crypto.Hash
// to a BoringCrypto *C.GO_EVP_MD.
func cryptoHashToMD(ch crypto.Hash) *C.GO_EVP_MD {
switch ch {
case crypto.MD5:
return C._goboringcrypto_EVP_md5()
case crypto.MD5SHA1:
return C._goboringcrypto_EVP_md5_sha1()
case crypto.SHA1:
return C._goboringcrypto_EVP_sha1()
case crypto.SHA224:
return C._goboringcrypto_EVP_sha224()
case crypto.SHA256:
return C._goboringcrypto_EVP_sha256()
case crypto.SHA384:
return C._goboringcrypto_EVP_sha384()
case crypto.SHA512:
return C._goboringcrypto_EVP_sha512()
}
return nil
}
// NewHMAC returns a new HMAC using BoringCrypto.
// The function h must return a hash implemented by
// BoringCrypto (for example, h could be boring.NewSHA256).
// If h is not recognized, NewHMAC returns nil.
func NewHMAC(h func() hash.Hash, key []byte) hash.Hash {
ch := h()
md := hashToMD(ch)
if md == nil {
return nil
}
// Note: Could hash down long keys here using EVP_Digest.
hkey := bytes.Clone(key)
hmac := &boringHMAC{
md: md,
size: ch.Size(),
blockSize: ch.BlockSize(),
key: hkey,
}
hmac.Reset()
return hmac
}
type boringHMAC struct {
md *C.GO_EVP_MD
ctx C.GO_HMAC_CTX
ctx2 C.GO_HMAC_CTX
size int
blockSize int
key []byte
sum []byte
needCleanup bool
}
func (h *boringHMAC) Reset() {
if h.needCleanup {
C._goboringcrypto_HMAC_CTX_cleanup(&h.ctx)
} else {
h.needCleanup = true
// Note: Because of the finalizer, any time h.ctx is passed to cgo,
// that call must be followed by a call to runtime.KeepAlive(h),
// to make sure h is not collected (and finalized) before the cgo
// call returns.
runtime.SetFinalizer(h, (*boringHMAC).finalize)
}
C._goboringcrypto_HMAC_CTX_init(&h.ctx)
if C._goboringcrypto_HMAC_Init(&h.ctx, unsafe.Pointer(base(h.key)), C.int(len(h.key)), h.md) == 0 {
panic("boringcrypto: HMAC_Init failed")
}
if int(C._goboringcrypto_HMAC_size(&h.ctx)) != h.size {
println("boringcrypto: HMAC size:", C._goboringcrypto_HMAC_size(&h.ctx), "!=", h.size)
panic("boringcrypto: HMAC size mismatch")
}
runtime.KeepAlive(h) // Next line will keep h alive too; just making doubly sure.
h.sum = nil
}
func (h *boringHMAC) finalize() {
C._goboringcrypto_HMAC_CTX_cleanup(&h.ctx)
}
func (h *boringHMAC) Write(p []byte) (int, error) {
if len(p) > 0 {
C._goboringcrypto_HMAC_Update(&h.ctx, (*C.uint8_t)(unsafe.Pointer(&p[0])), C.size_t(len(p)))
}
runtime.KeepAlive(h)
return len(p), nil
}
func (h *boringHMAC) Size() int {
return h.size
}
func (h *boringHMAC) BlockSize() int {
return h.blockSize
}
func (h *boringHMAC) Sum(in []byte) []byte {
if h.sum == nil {
size := h.Size()
h.sum = make([]byte, size)
}
// Make copy of context because Go hash.Hash mandates
// that Sum has no effect on the underlying stream.
// In particular it is OK to Sum, then Write more, then Sum again,
// and the second Sum acts as if the first didn't happen.
C._goboringcrypto_HMAC_CTX_init(&h.ctx2)
if C._goboringcrypto_HMAC_CTX_copy_ex(&h.ctx2, &h.ctx) == 0 {
panic("boringcrypto: HMAC_CTX_copy_ex failed")
}
C._goboringcrypto_HMAC_Final(&h.ctx2, (*C.uint8_t)(unsafe.Pointer(&h.sum[0])), nil)
C._goboringcrypto_HMAC_CTX_cleanup(&h.ctx2)
return append(in, h.sum...)
}
| go/src/crypto/internal/boring/hmac.go/0 | {
"file_path": "go/src/crypto/internal/boring/hmac.go",
"repo_id": "go",
"token_count": 1730
} | 210 |
// Copyright (c) 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package edwards25519
import (
"bytes"
"encoding/hex"
"math/big"
mathrand "math/rand"
"reflect"
"testing"
"testing/quick"
)
// quickCheckConfig returns a quick.Config that scales the max count by the
// given factor if the -short flag is not set.
func quickCheckConfig(slowScale int) *quick.Config {
cfg := new(quick.Config)
if !testing.Short() {
cfg.MaxCountScale = float64(slowScale)
}
return cfg
}
var scOneBytes = [32]byte{1}
var scOne, _ = new(Scalar).SetCanonicalBytes(scOneBytes[:])
var scMinusOne, _ = new(Scalar).SetCanonicalBytes(scalarMinusOneBytes[:])
// Generate returns a valid (reduced modulo l) Scalar with a distribution
// weighted towards high, low, and edge values.
func (Scalar) Generate(rand *mathrand.Rand, size int) reflect.Value {
var s [32]byte
diceRoll := rand.Intn(100)
switch {
case diceRoll == 0:
case diceRoll == 1:
s = scOneBytes
case diceRoll == 2:
s = scalarMinusOneBytes
case diceRoll < 5:
// Generate a low scalar in [0, 2^125).
rand.Read(s[:16])
s[15] &= (1 << 5) - 1
case diceRoll < 10:
// Generate a high scalar in [2^252, 2^252 + 2^124).
s[31] = 1 << 4
rand.Read(s[:16])
s[15] &= (1 << 4) - 1
default:
// Generate a valid scalar in [0, l) by returning [0, 2^252) which has a
// negligibly different distribution (the former has a 2^-127.6 chance
// of being out of the latter range).
rand.Read(s[:])
s[31] &= (1 << 4) - 1
}
val := Scalar{}
fiatScalarFromBytes((*[4]uint64)(&val.s), &s)
fiatScalarToMontgomery(&val.s, (*fiatScalarNonMontgomeryDomainFieldElement)(&val.s))
return reflect.ValueOf(val)
}
func TestScalarGenerate(t *testing.T) {
f := func(sc Scalar) bool {
return isReduced(sc.Bytes())
}
if err := quick.Check(f, quickCheckConfig(1024)); err != nil {
t.Errorf("generated unreduced scalar: %v", err)
}
}
func TestScalarSetCanonicalBytes(t *testing.T) {
f1 := func(in [32]byte, sc Scalar) bool {
// Mask out top 4 bits to guarantee value falls in [0, l).
in[len(in)-1] &= (1 << 4) - 1
if _, err := sc.SetCanonicalBytes(in[:]); err != nil {
return false
}
repr := sc.Bytes()
return bytes.Equal(in[:], repr) && isReduced(repr)
}
if err := quick.Check(f1, quickCheckConfig(1024)); err != nil {
t.Errorf("failed bytes->scalar->bytes round-trip: %v", err)
}
f2 := func(sc1, sc2 Scalar) bool {
if _, err := sc2.SetCanonicalBytes(sc1.Bytes()); err != nil {
return false
}
return sc1 == sc2
}
if err := quick.Check(f2, quickCheckConfig(1024)); err != nil {
t.Errorf("failed scalar->bytes->scalar round-trip: %v", err)
}
b := scalarMinusOneBytes
b[31] += 1
s := scOne
if out, err := s.SetCanonicalBytes(b[:]); err == nil {
t.Errorf("SetCanonicalBytes worked on a non-canonical value")
} else if s != scOne {
t.Errorf("SetCanonicalBytes modified its receiver")
} else if out != nil {
t.Errorf("SetCanonicalBytes did not return nil with an error")
}
}
func TestScalarSetUniformBytes(t *testing.T) {
mod, _ := new(big.Int).SetString("27742317777372353535851937790883648493", 10)
mod.Add(mod, new(big.Int).Lsh(big.NewInt(1), 252))
f := func(in [64]byte, sc Scalar) bool {
sc.SetUniformBytes(in[:])
repr := sc.Bytes()
if !isReduced(repr) {
return false
}
scBig := bigIntFromLittleEndianBytes(repr[:])
inBig := bigIntFromLittleEndianBytes(in[:])
return inBig.Mod(inBig, mod).Cmp(scBig) == 0
}
if err := quick.Check(f, quickCheckConfig(1024)); err != nil {
t.Error(err)
}
}
func TestScalarSetBytesWithClamping(t *testing.T) {
// Generated with libsodium.js 1.0.18 crypto_scalarmult_ed25519_base.
random := "633d368491364dc9cd4c1bf891b1d59460face1644813240a313e61f2c88216e"
s, _ := new(Scalar).SetBytesWithClamping(decodeHex(random))
p := new(Point).ScalarBaseMult(s)
want := "1d87a9026fd0126a5736fe1628c95dd419172b5b618457e041c9c861b2494a94"
if got := hex.EncodeToString(p.Bytes()); got != want {
t.Errorf("random: got %q, want %q", got, want)
}
zero := "0000000000000000000000000000000000000000000000000000000000000000"
s, _ = new(Scalar).SetBytesWithClamping(decodeHex(zero))
p = new(Point).ScalarBaseMult(s)
want = "693e47972caf527c7883ad1b39822f026f47db2ab0e1919955b8993aa04411d1"
if got := hex.EncodeToString(p.Bytes()); got != want {
t.Errorf("zero: got %q, want %q", got, want)
}
one := "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
s, _ = new(Scalar).SetBytesWithClamping(decodeHex(one))
p = new(Point).ScalarBaseMult(s)
want = "12e9a68b73fd5aacdbcaf3e88c46fea6ebedb1aa84eed1842f07f8edab65e3a7"
if got := hex.EncodeToString(p.Bytes()); got != want {
t.Errorf("one: got %q, want %q", got, want)
}
}
func bigIntFromLittleEndianBytes(b []byte) *big.Int {
bb := make([]byte, len(b))
for i := range b {
bb[i] = b[len(b)-i-1]
}
return new(big.Int).SetBytes(bb)
}
func TestScalarMultiplyDistributesOverAdd(t *testing.T) {
multiplyDistributesOverAdd := func(x, y, z Scalar) bool {
// Compute t1 = (x+y)*z
var t1 Scalar
t1.Add(&x, &y)
t1.Multiply(&t1, &z)
// Compute t2 = x*z + y*z
var t2 Scalar
var t3 Scalar
t2.Multiply(&x, &z)
t3.Multiply(&y, &z)
t2.Add(&t2, &t3)
reprT1, reprT2 := t1.Bytes(), t2.Bytes()
return t1 == t2 && isReduced(reprT1) && isReduced(reprT2)
}
if err := quick.Check(multiplyDistributesOverAdd, quickCheckConfig(1024)); err != nil {
t.Error(err)
}
}
func TestScalarAddLikeSubNeg(t *testing.T) {
addLikeSubNeg := func(x, y Scalar) bool {
// Compute t1 = x - y
var t1 Scalar
t1.Subtract(&x, &y)
// Compute t2 = -y + x
var t2 Scalar
t2.Negate(&y)
t2.Add(&t2, &x)
return t1 == t2 && isReduced(t1.Bytes())
}
if err := quick.Check(addLikeSubNeg, quickCheckConfig(1024)); err != nil {
t.Error(err)
}
}
func TestScalarNonAdjacentForm(t *testing.T) {
s, _ := (&Scalar{}).SetCanonicalBytes([]byte{
0x1a, 0x0e, 0x97, 0x8a, 0x90, 0xf6, 0x62, 0x2d,
0x37, 0x47, 0x02, 0x3f, 0x8a, 0xd8, 0x26, 0x4d,
0xa7, 0x58, 0xaa, 0x1b, 0x88, 0xe0, 0x40, 0xd1,
0x58, 0x9e, 0x7b, 0x7f, 0x23, 0x76, 0xef, 0x09,
})
expectedNaf := [256]int8{
0, 13, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, -9, 0, 0, 0, 0, -11, 0, 0, 0, 0, 3, 0, 0, 0, 0, 1,
0, 0, 0, 0, 9, 0, 0, 0, 0, -5, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 11, 0, 0, 0, 0, 11, 0, 0, 0, 0, 0,
-9, 0, 0, 0, 0, 0, -3, 0, 0, 0, 0, 9, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 9, 0,
0, 0, 0, -15, 0, 0, 0, 0, -7, 0, 0, 0, 0, -9, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 13, 0, 0, 0, 0, 0, -3, 0,
0, 0, 0, -11, 0, 0, 0, 0, -7, 0, 0, 0, 0, -13, 0, 0, 0, 0, 11, 0, 0, 0, 0, -9, 0, 0, 0, 0, 0, 1, 0, 0,
0, 0, 0, -15, 0, 0, 0, 0, 1, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 13, 0, 0, 0,
0, 0, 0, 11, 0, 0, 0, 0, 0, 15, 0, 0, 0, 0, 0, -9, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 7,
0, 0, 0, 0, 0, -15, 0, 0, 0, 0, 0, 15, 0, 0, 0, 0, 15, 0, 0, 0, 0, 15, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0,
}
sNaf := s.nonAdjacentForm(5)
for i := 0; i < 256; i++ {
if expectedNaf[i] != sNaf[i] {
t.Errorf("Wrong digit at position %d, got %d, expected %d", i, sNaf[i], expectedNaf[i])
}
}
}
type notZeroScalar Scalar
func (notZeroScalar) Generate(rand *mathrand.Rand, size int) reflect.Value {
var s Scalar
var isNonZero uint64
for isNonZero == 0 {
s = Scalar{}.Generate(rand, size).Interface().(Scalar)
fiatScalarNonzero(&isNonZero, (*[4]uint64)(&s.s))
}
return reflect.ValueOf(notZeroScalar(s))
}
func TestScalarEqual(t *testing.T) {
if scOne.Equal(scMinusOne) == 1 {
t.Errorf("scOne.Equal(&scMinusOne) is true")
}
if scMinusOne.Equal(scMinusOne) == 0 {
t.Errorf("scMinusOne.Equal(&scMinusOne) is false")
}
}
| go/src/crypto/internal/edwards25519/scalar_test.go/0 | {
"file_path": "go/src/crypto/internal/edwards25519/scalar_test.go",
"repo_id": "go",
"token_count": 3599
} | 211 |
// Copyright 2021 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.
// Code generated by addchain. DO NOT EDIT.
package fiat
// Invert sets e = 1/x, and returns e.
//
// If x == 0, Invert returns e = 0.
func (e *P224Element) Invert(x *P224Element) *P224Element {
// Inversion is implemented as exponentiation with exponent p − 2.
// The sequence of 11 multiplications and 223 squarings is derived from the
// following addition chain generated with github.com/mmcloughlin/addchain v0.4.0.
//
// _10 = 2*1
// _11 = 1 + _10
// _110 = 2*_11
// _111 = 1 + _110
// _111000 = _111 << 3
// _111111 = _111 + _111000
// x12 = _111111 << 6 + _111111
// x14 = x12 << 2 + _11
// x17 = x14 << 3 + _111
// x31 = x17 << 14 + x14
// x48 = x31 << 17 + x17
// x96 = x48 << 48 + x48
// x127 = x96 << 31 + x31
// return x127 << 97 + x96
//
var z = new(P224Element).Set(e)
var t0 = new(P224Element)
var t1 = new(P224Element)
var t2 = new(P224Element)
z.Square(x)
t0.Mul(x, z)
z.Square(t0)
z.Mul(x, z)
t1.Square(z)
for s := 1; s < 3; s++ {
t1.Square(t1)
}
t1.Mul(z, t1)
t2.Square(t1)
for s := 1; s < 6; s++ {
t2.Square(t2)
}
t1.Mul(t1, t2)
for s := 0; s < 2; s++ {
t1.Square(t1)
}
t0.Mul(t0, t1)
t1.Square(t0)
for s := 1; s < 3; s++ {
t1.Square(t1)
}
z.Mul(z, t1)
t1.Square(z)
for s := 1; s < 14; s++ {
t1.Square(t1)
}
t0.Mul(t0, t1)
t1.Square(t0)
for s := 1; s < 17; s++ {
t1.Square(t1)
}
z.Mul(z, t1)
t1.Square(z)
for s := 1; s < 48; s++ {
t1.Square(t1)
}
z.Mul(z, t1)
t1.Square(z)
for s := 1; s < 31; s++ {
t1.Square(t1)
}
t0.Mul(t0, t1)
for s := 0; s < 97; s++ {
t0.Square(t0)
}
z.Mul(z, t0)
return e.Set(z)
}
| go/src/crypto/internal/nistec/fiat/p224_invert.go/0 | {
"file_path": "go/src/crypto/internal/nistec/fiat/p224_invert.go",
"repo_id": "go",
"token_count": 940
} | 212 |
// Copyright 2015 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.
// This file contains the Go wrapper for the constant-time, 64-bit assembly
// implementation of P256. The optimizations performed here are described in
// detail in:
// S.Gueron and V.Krasnov, "Fast prime field elliptic-curve cryptography with
// 256-bit primes"
// https://link.springer.com/article/10.1007%2Fs13389-014-0090-x
// https://eprint.iacr.org/2013/816.pdf
//go:build (amd64 || arm64 || ppc64le || s390x) && !purego
package nistec
import (
_ "embed"
"errors"
"internal/byteorder"
"math/bits"
"runtime"
"unsafe"
)
// p256Element is a P-256 base field element in [0, P-1] in the Montgomery
// domain (with R 2²⁵⁶) as four limbs in little-endian order value.
type p256Element [4]uint64
// p256One is one in the Montgomery domain.
var p256One = p256Element{0x0000000000000001, 0xffffffff00000000,
0xffffffffffffffff, 0x00000000fffffffe}
var p256Zero = p256Element{}
// p256P is 2²⁵⁶ - 2²²⁴ + 2¹⁹² + 2⁹⁶ - 1 in the Montgomery domain.
var p256P = p256Element{0xffffffffffffffff, 0x00000000ffffffff,
0x0000000000000000, 0xffffffff00000001}
// P256Point is a P-256 point. The zero value should not be assumed to be valid
// (although it is in this implementation).
type P256Point struct {
// (X:Y:Z) are Jacobian coordinates where x = X/Z² and y = Y/Z³. The point
// at infinity can be represented by any set of coordinates with Z = 0.
x, y, z p256Element
}
// NewP256Point returns a new P256Point representing the point at infinity.
func NewP256Point() *P256Point {
return &P256Point{
x: p256One, y: p256One, z: p256Zero,
}
}
// SetGenerator sets p to the canonical generator and returns p.
func (p *P256Point) SetGenerator() *P256Point {
p.x = p256Element{0x79e730d418a9143c, 0x75ba95fc5fedb601,
0x79fb732b77622510, 0x18905f76a53755c6}
p.y = p256Element{0xddf25357ce95560a, 0x8b4ab8e4ba19e45c,
0xd2e88688dd21f325, 0x8571ff1825885d85}
p.z = p256One
return p
}
// Set sets p = q and returns p.
func (p *P256Point) Set(q *P256Point) *P256Point {
p.x, p.y, p.z = q.x, q.y, q.z
return p
}
const p256ElementLength = 32
const p256UncompressedLength = 1 + 2*p256ElementLength
const p256CompressedLength = 1 + p256ElementLength
// SetBytes sets p to the compressed, uncompressed, or infinity value encoded in
// b, as specified in SEC 1, Version 2.0, Section 2.3.4. If the point is not on
// the curve, it returns nil and an error, and the receiver is unchanged.
// Otherwise, it returns p.
func (p *P256Point) SetBytes(b []byte) (*P256Point, error) {
// p256Mul operates in the Montgomery domain with R = 2²⁵⁶ mod p. Thus rr
// here is R in the Montgomery domain, or R×R mod p. See comment in
// P256OrdInverse about how this is used.
rr := p256Element{0x0000000000000003, 0xfffffffbffffffff,
0xfffffffffffffffe, 0x00000004fffffffd}
switch {
// Point at infinity.
case len(b) == 1 && b[0] == 0:
return p.Set(NewP256Point()), nil
// Uncompressed form.
case len(b) == p256UncompressedLength && b[0] == 4:
var r P256Point
p256BigToLittle(&r.x, (*[32]byte)(b[1:33]))
p256BigToLittle(&r.y, (*[32]byte)(b[33:65]))
if p256LessThanP(&r.x) == 0 || p256LessThanP(&r.y) == 0 {
return nil, errors.New("invalid P256 element encoding")
}
p256Mul(&r.x, &r.x, &rr)
p256Mul(&r.y, &r.y, &rr)
if err := p256CheckOnCurve(&r.x, &r.y); err != nil {
return nil, err
}
r.z = p256One
return p.Set(&r), nil
// Compressed form.
case len(b) == p256CompressedLength && (b[0] == 2 || b[0] == 3):
var r P256Point
p256BigToLittle(&r.x, (*[32]byte)(b[1:33]))
if p256LessThanP(&r.x) == 0 {
return nil, errors.New("invalid P256 element encoding")
}
p256Mul(&r.x, &r.x, &rr)
// y² = x³ - 3x + b
p256Polynomial(&r.y, &r.x)
if !p256Sqrt(&r.y, &r.y) {
return nil, errors.New("invalid P256 compressed point encoding")
}
// Select the positive or negative root, as indicated by the least
// significant bit, based on the encoding type byte.
yy := new(p256Element)
p256FromMont(yy, &r.y)
cond := int(yy[0]&1) ^ int(b[0]&1)
p256NegCond(&r.y, cond)
r.z = p256One
return p.Set(&r), nil
default:
return nil, errors.New("invalid P256 point encoding")
}
}
// p256Polynomial sets y2 to x³ - 3x + b, and returns y2.
func p256Polynomial(y2, x *p256Element) *p256Element {
x3 := new(p256Element)
p256Sqr(x3, x, 1)
p256Mul(x3, x3, x)
threeX := new(p256Element)
p256Add(threeX, x, x)
p256Add(threeX, threeX, x)
p256NegCond(threeX, 1)
p256B := &p256Element{0xd89cdf6229c4bddf, 0xacf005cd78843090,
0xe5a220abf7212ed6, 0xdc30061d04874834}
p256Add(x3, x3, threeX)
p256Add(x3, x3, p256B)
*y2 = *x3
return y2
}
func p256CheckOnCurve(x, y *p256Element) error {
// y² = x³ - 3x + b
rhs := p256Polynomial(new(p256Element), x)
lhs := new(p256Element)
p256Sqr(lhs, y, 1)
if p256Equal(lhs, rhs) != 1 {
return errors.New("P256 point not on curve")
}
return nil
}
// p256LessThanP returns 1 if x < p, and 0 otherwise. Note that a p256Element is
// not allowed to be equal to or greater than p, so if this function returns 0
// then x is invalid.
func p256LessThanP(x *p256Element) int {
var b uint64
_, b = bits.Sub64(x[0], p256P[0], b)
_, b = bits.Sub64(x[1], p256P[1], b)
_, b = bits.Sub64(x[2], p256P[2], b)
_, b = bits.Sub64(x[3], p256P[3], b)
return int(b)
}
// p256Add sets res = x + y.
func p256Add(res, x, y *p256Element) {
var c, b uint64
t1 := make([]uint64, 4)
t1[0], c = bits.Add64(x[0], y[0], 0)
t1[1], c = bits.Add64(x[1], y[1], c)
t1[2], c = bits.Add64(x[2], y[2], c)
t1[3], c = bits.Add64(x[3], y[3], c)
t2 := make([]uint64, 4)
t2[0], b = bits.Sub64(t1[0], p256P[0], 0)
t2[1], b = bits.Sub64(t1[1], p256P[1], b)
t2[2], b = bits.Sub64(t1[2], p256P[2], b)
t2[3], b = bits.Sub64(t1[3], p256P[3], b)
// Three options:
// - a+b < p
// then c is 0, b is 1, and t1 is correct
// - p <= a+b < 2^256
// then c is 0, b is 0, and t2 is correct
// - 2^256 <= a+b
// then c is 1, b is 1, and t2 is correct
t2Mask := (c ^ b) - 1
res[0] = (t1[0] & ^t2Mask) | (t2[0] & t2Mask)
res[1] = (t1[1] & ^t2Mask) | (t2[1] & t2Mask)
res[2] = (t1[2] & ^t2Mask) | (t2[2] & t2Mask)
res[3] = (t1[3] & ^t2Mask) | (t2[3] & t2Mask)
}
// p256Sqrt sets e to a square root of x. If x is not a square, p256Sqrt returns
// false and e is unchanged. e and x can overlap.
func p256Sqrt(e, x *p256Element) (isSquare bool) {
t0, t1 := new(p256Element), new(p256Element)
// Since p = 3 mod 4, exponentiation by (p + 1) / 4 yields a square root candidate.
//
// The sequence of 7 multiplications and 253 squarings is derived from the
// following addition chain generated with github.com/mmcloughlin/addchain v0.4.0.
//
// _10 = 2*1
// _11 = 1 + _10
// _1100 = _11 << 2
// _1111 = _11 + _1100
// _11110000 = _1111 << 4
// _11111111 = _1111 + _11110000
// x16 = _11111111 << 8 + _11111111
// x32 = x16 << 16 + x16
// return ((x32 << 32 + 1) << 96 + 1) << 94
//
p256Sqr(t0, x, 1)
p256Mul(t0, x, t0)
p256Sqr(t1, t0, 2)
p256Mul(t0, t0, t1)
p256Sqr(t1, t0, 4)
p256Mul(t0, t0, t1)
p256Sqr(t1, t0, 8)
p256Mul(t0, t0, t1)
p256Sqr(t1, t0, 16)
p256Mul(t0, t0, t1)
p256Sqr(t0, t0, 32)
p256Mul(t0, x, t0)
p256Sqr(t0, t0, 96)
p256Mul(t0, x, t0)
p256Sqr(t0, t0, 94)
p256Sqr(t1, t0, 1)
if p256Equal(t1, x) != 1 {
return false
}
*e = *t0
return true
}
// The following assembly functions are implemented in p256_asm_*.s
// Montgomery multiplication. Sets res = in1 * in2 * R⁻¹ mod p.
//
//go:noescape
func p256Mul(res, in1, in2 *p256Element)
// Montgomery square, repeated n times (n >= 1).
//
//go:noescape
func p256Sqr(res, in *p256Element, n int)
// Montgomery multiplication by R⁻¹, or 1 outside the domain.
// Sets res = in * R⁻¹, bringing res out of the Montgomery domain.
//
//go:noescape
func p256FromMont(res, in *p256Element)
// If cond is not 0, sets val = -val mod p.
//
//go:noescape
func p256NegCond(val *p256Element, cond int)
// If cond is 0, sets res = b, otherwise sets res = a.
//
//go:noescape
func p256MovCond(res, a, b *P256Point, cond int)
//go:noescape
func p256BigToLittle(res *p256Element, in *[32]byte)
//go:noescape
func p256LittleToBig(res *[32]byte, in *p256Element)
//go:noescape
func p256OrdBigToLittle(res *p256OrdElement, in *[32]byte)
//go:noescape
func p256OrdLittleToBig(res *[32]byte, in *p256OrdElement)
// p256Table is a table of the first 16 multiples of a point. Points are stored
// at an index offset of -1 so [8]P is at index 7, P is at 0, and [16]P is at 15.
// [0]P is the point at infinity and it's not stored.
type p256Table [16]P256Point
// p256Select sets res to the point at index idx in the table.
// idx must be in [0, 15]. It executes in constant time.
//
//go:noescape
func p256Select(res *P256Point, table *p256Table, idx int)
// p256AffinePoint is a point in affine coordinates (x, y). x and y are still
// Montgomery domain elements. The point can't be the point at infinity.
type p256AffinePoint struct {
x, y p256Element
}
// p256AffineTable is a table of the first 32 multiples of a point. Points are
// stored at an index offset of -1 like in p256Table, and [0]P is not stored.
type p256AffineTable [32]p256AffinePoint
// p256Precomputed is a series of precomputed multiples of G, the canonical
// generator. The first p256AffineTable contains multiples of G. The second one
// multiples of [2⁶]G, the third one of [2¹²]G, and so on, where each successive
// table is the previous table doubled six times. Six is the width of the
// sliding window used in p256ScalarMult, and having each table already
// pre-doubled lets us avoid the doublings between windows entirely. This table
// MUST NOT be modified, as it aliases into p256PrecomputedEmbed below.
var p256Precomputed *[43]p256AffineTable
//go:embed p256_asm_table.bin
var p256PrecomputedEmbed string
func init() {
p256PrecomputedPtr := (*unsafe.Pointer)(unsafe.Pointer(&p256PrecomputedEmbed))
if runtime.GOARCH == "s390x" {
var newTable [43 * 32 * 2 * 4]uint64
for i, x := range (*[43 * 32 * 2 * 4][8]byte)(*p256PrecomputedPtr) {
newTable[i] = byteorder.LeUint64(x[:])
}
newTablePtr := unsafe.Pointer(&newTable)
p256PrecomputedPtr = &newTablePtr
}
p256Precomputed = (*[43]p256AffineTable)(*p256PrecomputedPtr)
}
// p256SelectAffine sets res to the point at index idx in the table.
// idx must be in [0, 31]. It executes in constant time.
//
//go:noescape
func p256SelectAffine(res *p256AffinePoint, table *p256AffineTable, idx int)
// Point addition with an affine point and constant time conditions.
// If zero is 0, sets res = in2. If sel is 0, sets res = in1.
// If sign is not 0, sets res = in1 + -in2. Otherwise, sets res = in1 + in2
//
//go:noescape
func p256PointAddAffineAsm(res, in1 *P256Point, in2 *p256AffinePoint, sign, sel, zero int)
// Point addition. Sets res = in1 + in2. Returns one if the two input points
// were equal and zero otherwise. If in1 or in2 are the point at infinity, res
// and the return value are undefined.
//
//go:noescape
func p256PointAddAsm(res, in1, in2 *P256Point) int
// Point doubling. Sets res = in + in. in can be the point at infinity.
//
//go:noescape
func p256PointDoubleAsm(res, in *P256Point)
// p256OrdElement is a P-256 scalar field element in [0, ord(G)-1] in the
// Montgomery domain (with R 2²⁵⁶) as four uint64 limbs in little-endian order.
type p256OrdElement [4]uint64
// p256OrdReduce ensures s is in the range [0, ord(G)-1].
func p256OrdReduce(s *p256OrdElement) {
// Since 2 * ord(G) > 2²⁵⁶, we can just conditionally subtract ord(G),
// keeping the result if it doesn't underflow.
t0, b := bits.Sub64(s[0], 0xf3b9cac2fc632551, 0)
t1, b := bits.Sub64(s[1], 0xbce6faada7179e84, b)
t2, b := bits.Sub64(s[2], 0xffffffffffffffff, b)
t3, b := bits.Sub64(s[3], 0xffffffff00000000, b)
tMask := b - 1 // zero if subtraction underflowed
s[0] ^= (t0 ^ s[0]) & tMask
s[1] ^= (t1 ^ s[1]) & tMask
s[2] ^= (t2 ^ s[2]) & tMask
s[3] ^= (t3 ^ s[3]) & tMask
}
// Add sets q = p1 + p2, and returns q. The points may overlap.
func (q *P256Point) Add(r1, r2 *P256Point) *P256Point {
var sum, double P256Point
r1IsInfinity := r1.isInfinity()
r2IsInfinity := r2.isInfinity()
pointsEqual := p256PointAddAsm(&sum, r1, r2)
p256PointDoubleAsm(&double, r1)
p256MovCond(&sum, &double, &sum, pointsEqual)
p256MovCond(&sum, r1, &sum, r2IsInfinity)
p256MovCond(&sum, r2, &sum, r1IsInfinity)
return q.Set(&sum)
}
// Double sets q = p + p, and returns q. The points may overlap.
func (q *P256Point) Double(p *P256Point) *P256Point {
var double P256Point
p256PointDoubleAsm(&double, p)
return q.Set(&double)
}
// ScalarBaseMult sets r = scalar * generator, where scalar is a 32-byte big
// endian value, and returns r. If scalar is not 32 bytes long, ScalarBaseMult
// returns an error and the receiver is unchanged.
func (r *P256Point) ScalarBaseMult(scalar []byte) (*P256Point, error) {
if len(scalar) != 32 {
return nil, errors.New("invalid scalar length")
}
scalarReversed := new(p256OrdElement)
p256OrdBigToLittle(scalarReversed, (*[32]byte)(scalar))
p256OrdReduce(scalarReversed)
r.p256BaseMult(scalarReversed)
return r, nil
}
// ScalarMult sets r = scalar * q, where scalar is a 32-byte big endian value,
// and returns r. If scalar is not 32 bytes long, ScalarBaseMult returns an
// error and the receiver is unchanged.
func (r *P256Point) ScalarMult(q *P256Point, scalar []byte) (*P256Point, error) {
if len(scalar) != 32 {
return nil, errors.New("invalid scalar length")
}
scalarReversed := new(p256OrdElement)
p256OrdBigToLittle(scalarReversed, (*[32]byte)(scalar))
p256OrdReduce(scalarReversed)
r.Set(q).p256ScalarMult(scalarReversed)
return r, nil
}
// uint64IsZero returns 1 if x is zero and zero otherwise.
func uint64IsZero(x uint64) int {
x = ^x
x &= x >> 32
x &= x >> 16
x &= x >> 8
x &= x >> 4
x &= x >> 2
x &= x >> 1
return int(x & 1)
}
// p256Equal returns 1 if a and b are equal and 0 otherwise.
func p256Equal(a, b *p256Element) int {
var acc uint64
for i := range a {
acc |= a[i] ^ b[i]
}
return uint64IsZero(acc)
}
// isInfinity returns 1 if p is the point at infinity and 0 otherwise.
func (p *P256Point) isInfinity() int {
return p256Equal(&p.z, &p256Zero)
}
// Bytes returns the uncompressed or infinity encoding of p, as specified in
// SEC 1, Version 2.0, Section 2.3.3. Note that the encoding of the point at
// infinity is shorter than all other encodings.
func (p *P256Point) Bytes() []byte {
// This function is outlined to make the allocations inline in the caller
// rather than happen on the heap.
var out [p256UncompressedLength]byte
return p.bytes(&out)
}
func (p *P256Point) bytes(out *[p256UncompressedLength]byte) []byte {
// The proper representation of the point at infinity is a single zero byte.
if p.isInfinity() == 1 {
return append(out[:0], 0)
}
x, y := new(p256Element), new(p256Element)
p.affineFromMont(x, y)
out[0] = 4 // Uncompressed form.
p256LittleToBig((*[32]byte)(out[1:33]), x)
p256LittleToBig((*[32]byte)(out[33:65]), y)
return out[:]
}
// affineFromMont sets (x, y) to the affine coordinates of p, converted out of the
// Montgomery domain.
func (p *P256Point) affineFromMont(x, y *p256Element) {
p256Inverse(y, &p.z)
p256Sqr(x, y, 1)
p256Mul(y, y, x)
p256Mul(x, &p.x, x)
p256Mul(y, &p.y, y)
p256FromMont(x, x)
p256FromMont(y, y)
}
// BytesX returns the encoding of the x-coordinate of p, as specified in SEC 1,
// Version 2.0, Section 2.3.5, or an error if p is the point at infinity.
func (p *P256Point) BytesX() ([]byte, error) {
// This function is outlined to make the allocations inline in the caller
// rather than happen on the heap.
var out [p256ElementLength]byte
return p.bytesX(&out)
}
func (p *P256Point) bytesX(out *[p256ElementLength]byte) ([]byte, error) {
if p.isInfinity() == 1 {
return nil, errors.New("P256 point is the point at infinity")
}
x := new(p256Element)
p256Inverse(x, &p.z)
p256Sqr(x, x, 1)
p256Mul(x, &p.x, x)
p256FromMont(x, x)
p256LittleToBig((*[32]byte)(out[:]), x)
return out[:], nil
}
// BytesCompressed returns the compressed or infinity encoding of p, as
// specified in SEC 1, Version 2.0, Section 2.3.3. Note that the encoding of the
// point at infinity is shorter than all other encodings.
func (p *P256Point) BytesCompressed() []byte {
// This function is outlined to make the allocations inline in the caller
// rather than happen on the heap.
var out [p256CompressedLength]byte
return p.bytesCompressed(&out)
}
func (p *P256Point) bytesCompressed(out *[p256CompressedLength]byte) []byte {
if p.isInfinity() == 1 {
return append(out[:0], 0)
}
x, y := new(p256Element), new(p256Element)
p.affineFromMont(x, y)
out[0] = 2 | byte(y[0]&1)
p256LittleToBig((*[32]byte)(out[1:33]), x)
return out[:]
}
// Select sets q to p1 if cond == 1, and to p2 if cond == 0.
func (q *P256Point) Select(p1, p2 *P256Point, cond int) *P256Point {
p256MovCond(q, p1, p2, cond)
return q
}
// p256Inverse sets out to in⁻¹ mod p. If in is zero, out will be zero.
func p256Inverse(out, in *p256Element) {
// Inversion is calculated through exponentiation by p - 2, per Fermat's
// little theorem.
//
// The sequence of 12 multiplications and 255 squarings is derived from the
// following addition chain generated with github.com/mmcloughlin/addchain
// v0.4.0.
//
// _10 = 2*1
// _11 = 1 + _10
// _110 = 2*_11
// _111 = 1 + _110
// _111000 = _111 << 3
// _111111 = _111 + _111000
// x12 = _111111 << 6 + _111111
// x15 = x12 << 3 + _111
// x16 = 2*x15 + 1
// x32 = x16 << 16 + x16
// i53 = x32 << 15
// x47 = x15 + i53
// i263 = ((i53 << 17 + 1) << 143 + x47) << 47
// return (x47 + i263) << 2 + 1
//
var z = new(p256Element)
var t0 = new(p256Element)
var t1 = new(p256Element)
p256Sqr(z, in, 1)
p256Mul(z, in, z)
p256Sqr(z, z, 1)
p256Mul(z, in, z)
p256Sqr(t0, z, 3)
p256Mul(t0, z, t0)
p256Sqr(t1, t0, 6)
p256Mul(t0, t0, t1)
p256Sqr(t0, t0, 3)
p256Mul(z, z, t0)
p256Sqr(t0, z, 1)
p256Mul(t0, in, t0)
p256Sqr(t1, t0, 16)
p256Mul(t0, t0, t1)
p256Sqr(t0, t0, 15)
p256Mul(z, z, t0)
p256Sqr(t0, t0, 17)
p256Mul(t0, in, t0)
p256Sqr(t0, t0, 143)
p256Mul(t0, z, t0)
p256Sqr(t0, t0, 47)
p256Mul(z, z, t0)
p256Sqr(z, z, 2)
p256Mul(out, in, z)
}
func boothW5(in uint) (int, int) {
var s uint = ^((in >> 5) - 1)
var d uint = (1 << 6) - in - 1
d = (d & s) | (in & (^s))
d = (d >> 1) + (d & 1)
return int(d), int(s & 1)
}
func boothW6(in uint) (int, int) {
var s uint = ^((in >> 6) - 1)
var d uint = (1 << 7) - in - 1
d = (d & s) | (in & (^s))
d = (d >> 1) + (d & 1)
return int(d), int(s & 1)
}
func (p *P256Point) p256BaseMult(scalar *p256OrdElement) {
var t0 p256AffinePoint
wvalue := (scalar[0] << 1) & 0x7f
sel, sign := boothW6(uint(wvalue))
p256SelectAffine(&t0, &p256Precomputed[0], sel)
p.x, p.y, p.z = t0.x, t0.y, p256One
p256NegCond(&p.y, sign)
index := uint(5)
zero := sel
for i := 1; i < 43; i++ {
if index < 192 {
wvalue = ((scalar[index/64] >> (index % 64)) + (scalar[index/64+1] << (64 - (index % 64)))) & 0x7f
} else {
wvalue = (scalar[index/64] >> (index % 64)) & 0x7f
}
index += 6
sel, sign = boothW6(uint(wvalue))
p256SelectAffine(&t0, &p256Precomputed[i], sel)
p256PointAddAffineAsm(p, p, &t0, sign, sel, zero)
zero |= sel
}
// If the whole scalar was zero, set to the point at infinity.
p256MovCond(p, p, NewP256Point(), zero)
}
func (p *P256Point) p256ScalarMult(scalar *p256OrdElement) {
// precomp is a table of precomputed points that stores powers of p
// from p^1 to p^16.
var precomp p256Table
var t0, t1, t2, t3 P256Point
// Prepare the table
precomp[0] = *p // 1
p256PointDoubleAsm(&t0, p)
p256PointDoubleAsm(&t1, &t0)
p256PointDoubleAsm(&t2, &t1)
p256PointDoubleAsm(&t3, &t2)
precomp[1] = t0 // 2
precomp[3] = t1 // 4
precomp[7] = t2 // 8
precomp[15] = t3 // 16
p256PointAddAsm(&t0, &t0, p)
p256PointAddAsm(&t1, &t1, p)
p256PointAddAsm(&t2, &t2, p)
precomp[2] = t0 // 3
precomp[4] = t1 // 5
precomp[8] = t2 // 9
p256PointDoubleAsm(&t0, &t0)
p256PointDoubleAsm(&t1, &t1)
precomp[5] = t0 // 6
precomp[9] = t1 // 10
p256PointAddAsm(&t2, &t0, p)
p256PointAddAsm(&t1, &t1, p)
precomp[6] = t2 // 7
precomp[10] = t1 // 11
p256PointDoubleAsm(&t0, &t0)
p256PointDoubleAsm(&t2, &t2)
precomp[11] = t0 // 12
precomp[13] = t2 // 14
p256PointAddAsm(&t0, &t0, p)
p256PointAddAsm(&t2, &t2, p)
precomp[12] = t0 // 13
precomp[14] = t2 // 15
// Start scanning the window from top bit
index := uint(254)
var sel, sign int
wvalue := (scalar[index/64] >> (index % 64)) & 0x3f
sel, _ = boothW5(uint(wvalue))
p256Select(p, &precomp, sel)
zero := sel
for index > 4 {
index -= 5
p256PointDoubleAsm(p, p)
p256PointDoubleAsm(p, p)
p256PointDoubleAsm(p, p)
p256PointDoubleAsm(p, p)
p256PointDoubleAsm(p, p)
if index < 192 {
wvalue = ((scalar[index/64] >> (index % 64)) + (scalar[index/64+1] << (64 - (index % 64)))) & 0x3f
} else {
wvalue = (scalar[index/64] >> (index % 64)) & 0x3f
}
sel, sign = boothW5(uint(wvalue))
p256Select(&t0, &precomp, sel)
p256NegCond(&t0.y, sign)
p256PointAddAsm(&t1, p, &t0)
p256MovCond(&t1, &t1, p, sel)
p256MovCond(p, &t1, &t0, zero)
zero |= sel
}
p256PointDoubleAsm(p, p)
p256PointDoubleAsm(p, p)
p256PointDoubleAsm(p, p)
p256PointDoubleAsm(p, p)
p256PointDoubleAsm(p, p)
wvalue = (scalar[0] << 1) & 0x3f
sel, sign = boothW5(uint(wvalue))
p256Select(&t0, &precomp, sel)
p256NegCond(&t0.y, sign)
p256PointAddAsm(&t1, p, &t0)
p256MovCond(&t1, &t1, p, sel)
p256MovCond(p, &t1, &t0, zero)
}
| go/src/crypto/internal/nistec/p256_asm.go/0 | {
"file_path": "go/src/crypto/internal/nistec/p256_asm.go",
"repo_id": "go",
"token_count": 9475
} | 213 |
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:generate go run gen.go -output md5block.go
// Package md5 implements the MD5 hash algorithm as defined in RFC 1321.
//
// MD5 is cryptographically broken and should not be used for secure
// applications.
package md5
import (
"crypto"
"errors"
"hash"
"internal/byteorder"
)
func init() {
crypto.RegisterHash(crypto.MD5, New)
}
// The size of an MD5 checksum in bytes.
const Size = 16
// The blocksize of MD5 in bytes.
const BlockSize = 64
const (
init0 = 0x67452301
init1 = 0xEFCDAB89
init2 = 0x98BADCFE
init3 = 0x10325476
)
// digest represents the partial evaluation of a checksum.
type digest struct {
s [4]uint32
x [BlockSize]byte
nx int
len uint64
}
func (d *digest) Reset() {
d.s[0] = init0
d.s[1] = init1
d.s[2] = init2
d.s[3] = init3
d.nx = 0
d.len = 0
}
const (
magic = "md5\x01"
marshaledSize = len(magic) + 4*4 + BlockSize + 8
)
func (d *digest) MarshalBinary() ([]byte, error) {
b := make([]byte, 0, marshaledSize)
b = append(b, magic...)
b = byteorder.BeAppendUint32(b, d.s[0])
b = byteorder.BeAppendUint32(b, d.s[1])
b = byteorder.BeAppendUint32(b, d.s[2])
b = byteorder.BeAppendUint32(b, d.s[3])
b = append(b, d.x[:d.nx]...)
b = b[:len(b)+len(d.x)-d.nx] // already zero
b = byteorder.BeAppendUint64(b, d.len)
return b, nil
}
func (d *digest) UnmarshalBinary(b []byte) error {
if len(b) < len(magic) || string(b[:len(magic)]) != magic {
return errors.New("crypto/md5: invalid hash state identifier")
}
if len(b) != marshaledSize {
return errors.New("crypto/md5: invalid hash state size")
}
b = b[len(magic):]
b, d.s[0] = consumeUint32(b)
b, d.s[1] = consumeUint32(b)
b, d.s[2] = consumeUint32(b)
b, d.s[3] = consumeUint32(b)
b = b[copy(d.x[:], b):]
b, d.len = consumeUint64(b)
d.nx = int(d.len % BlockSize)
return nil
}
func consumeUint64(b []byte) ([]byte, uint64) {
return b[8:], byteorder.BeUint64(b[0:8])
}
func consumeUint32(b []byte) ([]byte, uint32) {
return b[4:], byteorder.BeUint32(b[0:4])
}
// New returns a new hash.Hash computing the MD5 checksum. The Hash also
// implements [encoding.BinaryMarshaler] and [encoding.BinaryUnmarshaler] to
// marshal and unmarshal the internal state of the hash.
func New() hash.Hash {
d := new(digest)
d.Reset()
return d
}
func (d *digest) Size() int { return Size }
func (d *digest) BlockSize() int { return BlockSize }
func (d *digest) Write(p []byte) (nn int, err error) {
// Note that we currently call block or blockGeneric
// directly (guarded using haveAsm) because this allows
// escape analysis to see that p and d don't escape.
nn = len(p)
d.len += uint64(nn)
if d.nx > 0 {
n := copy(d.x[d.nx:], p)
d.nx += n
if d.nx == BlockSize {
if haveAsm {
block(d, d.x[:])
} else {
blockGeneric(d, d.x[:])
}
d.nx = 0
}
p = p[n:]
}
if len(p) >= BlockSize {
n := len(p) &^ (BlockSize - 1)
if haveAsm {
block(d, p[:n])
} else {
blockGeneric(d, p[:n])
}
p = p[n:]
}
if len(p) > 0 {
d.nx = copy(d.x[:], p)
}
return
}
func (d *digest) Sum(in []byte) []byte {
// Make a copy of d so that caller can keep writing and summing.
d0 := *d
hash := d0.checkSum()
return append(in, hash[:]...)
}
func (d *digest) checkSum() [Size]byte {
// Append 0x80 to the end of the message and then append zeros
// until the length is a multiple of 56 bytes. Finally append
// 8 bytes representing the message length in bits.
//
// 1 byte end marker :: 0-63 padding bytes :: 8 byte length
tmp := [1 + 63 + 8]byte{0x80}
pad := (55 - d.len) % 64 // calculate number of padding bytes
byteorder.LePutUint64(tmp[1+pad:], d.len<<3) // append length in bits
d.Write(tmp[:1+pad+8])
// The previous write ensures that a whole number of
// blocks (i.e. a multiple of 64 bytes) have been hashed.
if d.nx != 0 {
panic("d.nx != 0")
}
var digest [Size]byte
byteorder.LePutUint32(digest[0:], d.s[0])
byteorder.LePutUint32(digest[4:], d.s[1])
byteorder.LePutUint32(digest[8:], d.s[2])
byteorder.LePutUint32(digest[12:], d.s[3])
return digest
}
// Sum returns the MD5 checksum of the data.
func Sum(data []byte) [Size]byte {
var d digest
d.Reset()
d.Write(data)
return d.checkSum()
}
| go/src/crypto/md5/md5.go/0 | {
"file_path": "go/src/crypto/md5/md5.go",
"repo_id": "go",
"token_count": 1874
} | 214 |
// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build openbsd || netbsd
package rand
import "internal/syscall/unix"
func init() {
// getentropy(2) returns a maximum of 256 bytes per call.
altGetRandom = batched(unix.GetEntropy, 256)
}
| go/src/crypto/rand/rand_getentropy.go/0 | {
"file_path": "go/src/crypto/rand/rand_getentropy.go",
"repo_id": "go",
"token_count": 113
} | 215 |
// Copyright 2022 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build !boringcrypto
package rsa
import "crypto/internal/boring"
func boringPublicKey(*PublicKey) (*boring.PublicKeyRSA, error) {
panic("boringcrypto: not available")
}
func boringPrivateKey(*PrivateKey) (*boring.PrivateKeyRSA, error) {
panic("boringcrypto: not available")
}
| go/src/crypto/rsa/notboring.go/0 | {
"file_path": "go/src/crypto/rsa/notboring.go",
"repo_id": "go",
"token_count": 139
} | 216 |
// Copyright 2016 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 !purego
package sha1
import "internal/cpu"
//go:noescape
func blockAVX2(dig *digest, p []byte)
//go:noescape
func blockAMD64(dig *digest, p []byte)
var useAVX2 = cpu.X86.HasAVX2 && cpu.X86.HasBMI1 && cpu.X86.HasBMI2
func block(dig *digest, p []byte) {
if useAVX2 && len(p) >= 256 {
// blockAVX2 calculates sha1 for 2 block per iteration
// it also interleaves precalculation for next block.
// So it may read up-to 192 bytes past end of p
// We may add checks inside blockAVX2, but this will
// just turn it into a copy of blockAMD64,
// so call it directly, instead.
safeLen := len(p) - 128
if safeLen%128 != 0 {
safeLen -= 64
}
blockAVX2(dig, p[:safeLen])
blockAMD64(dig, p[safeLen:])
} else {
blockAMD64(dig, p)
}
}
| go/src/crypto/sha1/sha1block_amd64.go/0 | {
"file_path": "go/src/crypto/sha1/sha1block_amd64.go",
"repo_id": "go",
"token_count": 357
} | 217 |
// Copyright 2013 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 !purego
#include "textflag.h"
// SHA256 block routine. See sha256block.go for Go equivalent.
//
// The algorithm is detailed in FIPS 180-4:
//
// https://csrc.nist.gov/publications/fips/fips180-4/fips-180-4.pdf
// The avx2-version is described in an Intel White-Paper:
// "Fast SHA-256 Implementations on Intel Architecture Processors"
// To find it, surf to http://www.intel.com/p/en_US/embedded
// and search for that title.
// AVX2 version by Intel, same algorithm as code in Linux kernel:
// https://github.com/torvalds/linux/blob/master/arch/x86/crypto/sha256-avx2-asm.S
// by
// James Guilford <james.guilford@intel.com>
// Kirk Yap <kirk.s.yap@intel.com>
// Tim Chen <tim.c.chen@linux.intel.com>
// Wt = Mt; for 0 <= t <= 15
// Wt = SIGMA1(Wt-2) + SIGMA0(Wt-15) + Wt-16; for 16 <= t <= 63
//
// a = H0
// b = H1
// c = H2
// d = H3
// e = H4
// f = H5
// g = H6
// h = H7
//
// for t = 0 to 63 {
// T1 = h + BIGSIGMA1(e) + Ch(e,f,g) + Kt + Wt
// T2 = BIGSIGMA0(a) + Maj(a,b,c)
// h = g
// g = f
// f = e
// e = d + T1
// d = c
// c = b
// b = a
// a = T1 + T2
// }
//
// H0 = a + H0
// H1 = b + H1
// H2 = c + H2
// H3 = d + H3
// H4 = e + H4
// H5 = f + H5
// H6 = g + H6
// H7 = h + H7
// Wt = Mt; for 0 <= t <= 15
#define MSGSCHEDULE0(index) \
MOVL (index*4)(SI), AX; \
BSWAPL AX; \
MOVL AX, (index*4)(BP)
// Wt = SIGMA1(Wt-2) + Wt-7 + SIGMA0(Wt-15) + Wt-16; for 16 <= t <= 63
// SIGMA0(x) = ROTR(7,x) XOR ROTR(18,x) XOR SHR(3,x)
// SIGMA1(x) = ROTR(17,x) XOR ROTR(19,x) XOR SHR(10,x)
#define MSGSCHEDULE1(index) \
MOVL ((index-2)*4)(BP), AX; \
MOVL AX, CX; \
RORL $17, AX; \
MOVL CX, DX; \
RORL $19, CX; \
SHRL $10, DX; \
MOVL ((index-15)*4)(BP), BX; \
XORL CX, AX; \
MOVL BX, CX; \
XORL DX, AX; \
RORL $7, BX; \
MOVL CX, DX; \
SHRL $3, DX; \
RORL $18, CX; \
ADDL ((index-7)*4)(BP), AX; \
XORL CX, BX; \
XORL DX, BX; \
ADDL ((index-16)*4)(BP), BX; \
ADDL BX, AX; \
MOVL AX, ((index)*4)(BP)
// Calculate T1 in AX - uses AX, CX and DX registers.
// h is also used as an accumulator. Wt is passed in AX.
// T1 = h + BIGSIGMA1(e) + Ch(e, f, g) + Kt + Wt
// BIGSIGMA1(x) = ROTR(6,x) XOR ROTR(11,x) XOR ROTR(25,x)
// Ch(x, y, z) = (x AND y) XOR (NOT x AND z)
#define SHA256T1(const, e, f, g, h) \
ADDL AX, h; \
MOVL e, AX; \
ADDL $const, h; \
MOVL e, CX; \
RORL $6, AX; \
MOVL e, DX; \
RORL $11, CX; \
XORL CX, AX; \
MOVL e, CX; \
RORL $25, DX; \
ANDL f, CX; \
XORL AX, DX; \
MOVL e, AX; \
NOTL AX; \
ADDL DX, h; \
ANDL g, AX; \
XORL CX, AX; \
ADDL h, AX
// Calculate T2 in BX - uses BX, CX, DX and DI registers.
// T2 = BIGSIGMA0(a) + Maj(a, b, c)
// BIGSIGMA0(x) = ROTR(2,x) XOR ROTR(13,x) XOR ROTR(22,x)
// Maj(x, y, z) = (x AND y) XOR (x AND z) XOR (y AND z)
#define SHA256T2(a, b, c) \
MOVL a, DI; \
MOVL c, BX; \
RORL $2, DI; \
MOVL a, DX; \
ANDL b, BX; \
RORL $13, DX; \
MOVL a, CX; \
ANDL c, CX; \
XORL DX, DI; \
XORL CX, BX; \
MOVL a, DX; \
MOVL b, CX; \
RORL $22, DX; \
ANDL a, CX; \
XORL CX, BX; \
XORL DX, DI; \
ADDL DI, BX
// Calculate T1 and T2, then e = d + T1 and a = T1 + T2.
// The values for e and a are stored in d and h, ready for rotation.
#define SHA256ROUND(index, const, a, b, c, d, e, f, g, h) \
SHA256T1(const, e, f, g, h); \
SHA256T2(a, b, c); \
MOVL BX, h; \
ADDL AX, d; \
ADDL AX, h
#define SHA256ROUND0(index, const, a, b, c, d, e, f, g, h) \
MSGSCHEDULE0(index); \
SHA256ROUND(index, const, a, b, c, d, e, f, g, h)
#define SHA256ROUND1(index, const, a, b, c, d, e, f, g, h) \
MSGSCHEDULE1(index); \
SHA256ROUND(index, const, a, b, c, d, e, f, g, h)
// Definitions for AVX2 version
// addm (mem), reg
// Add reg to mem using reg-mem add and store
#define addm(P1, P2) \
ADDL P2, P1; \
MOVL P1, P2
#define XDWORD0 Y4
#define XDWORD1 Y5
#define XDWORD2 Y6
#define XDWORD3 Y7
#define XWORD0 X4
#define XWORD1 X5
#define XWORD2 X6
#define XWORD3 X7
#define XTMP0 Y0
#define XTMP1 Y1
#define XTMP2 Y2
#define XTMP3 Y3
#define XTMP4 Y8
#define XTMP5 Y11
#define XFER Y9
#define BYTE_FLIP_MASK Y13 // mask to convert LE -> BE
#define X_BYTE_FLIP_MASK X13
#define NUM_BYTES DX
#define INP DI
#define CTX SI // Beginning of digest in memory (a, b, c, ... , h)
#define a AX
#define b BX
#define c CX
#define d R8
#define e DX
#define f R9
#define g R10
#define h R11
#define old_h R11
#define TBL BP
#define SRND SI // SRND is same register as CTX
#define T1 R12
#define y0 R13
#define y1 R14
#define y2 R15
#define y3 DI
// Offsets
#define XFER_SIZE 2*64*4
#define INP_END_SIZE 8
#define INP_SIZE 8
#define _XFER 0
#define _INP_END _XFER + XFER_SIZE
#define _INP _INP_END + INP_END_SIZE
#define STACK_SIZE _INP + INP_SIZE
#define ROUND_AND_SCHED_N_0(disp, a, b, c, d, e, f, g, h, XDWORD0, XDWORD1, XDWORD2, XDWORD3) \
; \ // ############################# RND N + 0 ############################//
MOVL a, y3; \ // y3 = a // MAJA
RORXL $25, e, y0; \ // y0 = e >> 25 // S1A
RORXL $11, e, y1; \ // y1 = e >> 11 // S1B
; \
ADDL (disp + 0*4)(SP)(SRND*1), h; \ // h = k + w + h // disp = k + w
ORL c, y3; \ // y3 = a|c // MAJA
VPALIGNR $4, XDWORD2, XDWORD3, XTMP0; \ // XTMP0 = W[-7]
MOVL f, y2; \ // y2 = f // CH
RORXL $13, a, T1; \ // T1 = a >> 13 // S0B
; \
XORL y1, y0; \ // y0 = (e>>25) ^ (e>>11) // S1
XORL g, y2; \ // y2 = f^g // CH
VPADDD XDWORD0, XTMP0, XTMP0; \ // XTMP0 = W[-7] + W[-16] // y1 = (e >> 6) // S1
RORXL $6, e, y1; \ // y1 = (e >> 6) // S1
; \
ANDL e, y2; \ // y2 = (f^g)&e // CH
XORL y1, y0; \ // y0 = (e>>25) ^ (e>>11) ^ (e>>6) // S1
RORXL $22, a, y1; \ // y1 = a >> 22 // S0A
ADDL h, d; \ // d = k + w + h + d // --
; \
ANDL b, y3; \ // y3 = (a|c)&b // MAJA
VPALIGNR $4, XDWORD0, XDWORD1, XTMP1; \ // XTMP1 = W[-15]
XORL T1, y1; \ // y1 = (a>>22) ^ (a>>13) // S0
RORXL $2, a, T1; \ // T1 = (a >> 2) // S0
; \
XORL g, y2; \ // y2 = CH = ((f^g)&e)^g // CH
VPSRLD $7, XTMP1, XTMP2; \
XORL T1, y1; \ // y1 = (a>>22) ^ (a>>13) ^ (a>>2) // S0
MOVL a, T1; \ // T1 = a // MAJB
ANDL c, T1; \ // T1 = a&c // MAJB
; \
ADDL y0, y2; \ // y2 = S1 + CH // --
VPSLLD $(32-7), XTMP1, XTMP3; \
ORL T1, y3; \ // y3 = MAJ = (a|c)&b)|(a&c) // MAJ
ADDL y1, h; \ // h = k + w + h + S0 // --
; \
ADDL y2, d; \ // d = k + w + h + d + S1 + CH = d + t1 // --
VPOR XTMP2, XTMP3, XTMP3; \ // XTMP3 = W[-15] ror 7
; \
VPSRLD $18, XTMP1, XTMP2; \
ADDL y2, h; \ // h = k + w + h + S0 + S1 + CH = t1 + S0// --
ADDL y3, h // h = t1 + S0 + MAJ // --
#define ROUND_AND_SCHED_N_1(disp, a, b, c, d, e, f, g, h, XDWORD0, XDWORD1, XDWORD2, XDWORD3) \
; \ // ################################### RND N + 1 ############################
; \
MOVL a, y3; \ // y3 = a // MAJA
RORXL $25, e, y0; \ // y0 = e >> 25 // S1A
RORXL $11, e, y1; \ // y1 = e >> 11 // S1B
ADDL (disp + 1*4)(SP)(SRND*1), h; \ // h = k + w + h // --
ORL c, y3; \ // y3 = a|c // MAJA
; \
VPSRLD $3, XTMP1, XTMP4; \ // XTMP4 = W[-15] >> 3
MOVL f, y2; \ // y2 = f // CH
RORXL $13, a, T1; \ // T1 = a >> 13 // S0B
XORL y1, y0; \ // y0 = (e>>25) ^ (e>>11) // S1
XORL g, y2; \ // y2 = f^g // CH
; \
RORXL $6, e, y1; \ // y1 = (e >> 6) // S1
XORL y1, y0; \ // y0 = (e>>25) ^ (e>>11) ^ (e>>6) // S1
RORXL $22, a, y1; \ // y1 = a >> 22 // S0A
ANDL e, y2; \ // y2 = (f^g)&e // CH
ADDL h, d; \ // d = k + w + h + d // --
; \
VPSLLD $(32-18), XTMP1, XTMP1; \
ANDL b, y3; \ // y3 = (a|c)&b // MAJA
XORL T1, y1; \ // y1 = (a>>22) ^ (a>>13) // S0
; \
VPXOR XTMP1, XTMP3, XTMP3; \
RORXL $2, a, T1; \ // T1 = (a >> 2) // S0
XORL g, y2; \ // y2 = CH = ((f^g)&e)^g // CH
; \
VPXOR XTMP2, XTMP3, XTMP3; \ // XTMP3 = W[-15] ror 7 ^ W[-15] ror 18
XORL T1, y1; \ // y1 = (a>>22) ^ (a>>13) ^ (a>>2) // S0
MOVL a, T1; \ // T1 = a // MAJB
ANDL c, T1; \ // T1 = a&c // MAJB
ADDL y0, y2; \ // y2 = S1 + CH // --
; \
VPXOR XTMP4, XTMP3, XTMP1; \ // XTMP1 = s0
VPSHUFD $0xFA, XDWORD3, XTMP2; \ // XTMP2 = W[-2] {BBAA}
ORL T1, y3; \ // y3 = MAJ = (a|c)&b)|(a&c) // MAJ
ADDL y1, h; \ // h = k + w + h + S0 // --
; \
VPADDD XTMP1, XTMP0, XTMP0; \ // XTMP0 = W[-16] + W[-7] + s0
ADDL y2, d; \ // d = k + w + h + d + S1 + CH = d + t1 // --
ADDL y2, h; \ // h = k + w + h + S0 + S1 + CH = t1 + S0// --
ADDL y3, h; \ // h = t1 + S0 + MAJ // --
; \
VPSRLD $10, XTMP2, XTMP4 // XTMP4 = W[-2] >> 10 {BBAA}
#define ROUND_AND_SCHED_N_2(disp, a, b, c, d, e, f, g, h, XDWORD0, XDWORD1, XDWORD2, XDWORD3) \
; \ // ################################### RND N + 2 ############################
; \
MOVL a, y3; \ // y3 = a // MAJA
RORXL $25, e, y0; \ // y0 = e >> 25 // S1A
ADDL (disp + 2*4)(SP)(SRND*1), h; \ // h = k + w + h // --
; \
VPSRLQ $19, XTMP2, XTMP3; \ // XTMP3 = W[-2] ror 19 {xBxA}
RORXL $11, e, y1; \ // y1 = e >> 11 // S1B
ORL c, y3; \ // y3 = a|c // MAJA
MOVL f, y2; \ // y2 = f // CH
XORL g, y2; \ // y2 = f^g // CH
; \
RORXL $13, a, T1; \ // T1 = a >> 13 // S0B
XORL y1, y0; \ // y0 = (e>>25) ^ (e>>11) // S1
VPSRLQ $17, XTMP2, XTMP2; \ // XTMP2 = W[-2] ror 17 {xBxA}
ANDL e, y2; \ // y2 = (f^g)&e // CH
; \
RORXL $6, e, y1; \ // y1 = (e >> 6) // S1
VPXOR XTMP3, XTMP2, XTMP2; \
ADDL h, d; \ // d = k + w + h + d // --
ANDL b, y3; \ // y3 = (a|c)&b // MAJA
; \
XORL y1, y0; \ // y0 = (e>>25) ^ (e>>11) ^ (e>>6) // S1
RORXL $22, a, y1; \ // y1 = a >> 22 // S0A
VPXOR XTMP2, XTMP4, XTMP4; \ // XTMP4 = s1 {xBxA}
XORL g, y2; \ // y2 = CH = ((f^g)&e)^g // CH
; \
VPSHUFB shuff_00BA<>(SB), XTMP4, XTMP4;\ // XTMP4 = s1 {00BA}
; \
XORL T1, y1; \ // y1 = (a>>22) ^ (a>>13) // S0
RORXL $2, a, T1; \ // T1 = (a >> 2) // S0
VPADDD XTMP4, XTMP0, XTMP0; \ // XTMP0 = {..., ..., W[1], W[0]}
; \
XORL T1, y1; \ // y1 = (a>>22) ^ (a>>13) ^ (a>>2) // S0
MOVL a, T1; \ // T1 = a // MAJB
ANDL c, T1; \ // T1 = a&c // MAJB
ADDL y0, y2; \ // y2 = S1 + CH // --
VPSHUFD $80, XTMP0, XTMP2; \ // XTMP2 = W[-2] {DDCC}
; \
ORL T1, y3; \ // y3 = MAJ = (a|c)&b)|(a&c) // MAJ
ADDL y1, h; \ // h = k + w + h + S0 // --
ADDL y2, d; \ // d = k + w + h + d + S1 + CH = d + t1 // --
ADDL y2, h; \ // h = k + w + h + S0 + S1 + CH = t1 + S0// --
; \
ADDL y3, h // h = t1 + S0 + MAJ // --
#define ROUND_AND_SCHED_N_3(disp, a, b, c, d, e, f, g, h, XDWORD0, XDWORD1, XDWORD2, XDWORD3) \
; \ // ################################### RND N + 3 ############################
; \
MOVL a, y3; \ // y3 = a // MAJA
RORXL $25, e, y0; \ // y0 = e >> 25 // S1A
RORXL $11, e, y1; \ // y1 = e >> 11 // S1B
ADDL (disp + 3*4)(SP)(SRND*1), h; \ // h = k + w + h // --
ORL c, y3; \ // y3 = a|c // MAJA
; \
VPSRLD $10, XTMP2, XTMP5; \ // XTMP5 = W[-2] >> 10 {DDCC}
MOVL f, y2; \ // y2 = f // CH
RORXL $13, a, T1; \ // T1 = a >> 13 // S0B
XORL y1, y0; \ // y0 = (e>>25) ^ (e>>11) // S1
XORL g, y2; \ // y2 = f^g // CH
; \
VPSRLQ $19, XTMP2, XTMP3; \ // XTMP3 = W[-2] ror 19 {xDxC}
RORXL $6, e, y1; \ // y1 = (e >> 6) // S1
ANDL e, y2; \ // y2 = (f^g)&e // CH
ADDL h, d; \ // d = k + w + h + d // --
ANDL b, y3; \ // y3 = (a|c)&b // MAJA
; \
VPSRLQ $17, XTMP2, XTMP2; \ // XTMP2 = W[-2] ror 17 {xDxC}
XORL y1, y0; \ // y0 = (e>>25) ^ (e>>11) ^ (e>>6) // S1
XORL g, y2; \ // y2 = CH = ((f^g)&e)^g // CH
; \
VPXOR XTMP3, XTMP2, XTMP2; \
RORXL $22, a, y1; \ // y1 = a >> 22 // S0A
ADDL y0, y2; \ // y2 = S1 + CH // --
; \
VPXOR XTMP2, XTMP5, XTMP5; \ // XTMP5 = s1 {xDxC}
XORL T1, y1; \ // y1 = (a>>22) ^ (a>>13) // S0
ADDL y2, d; \ // d = k + w + h + d + S1 + CH = d + t1 // --
; \
RORXL $2, a, T1; \ // T1 = (a >> 2) // S0
; \
VPSHUFB shuff_DC00<>(SB), XTMP5, XTMP5;\ // XTMP5 = s1 {DC00}
; \
VPADDD XTMP0, XTMP5, XDWORD0; \ // XDWORD0 = {W[3], W[2], W[1], W[0]}
XORL T1, y1; \ // y1 = (a>>22) ^ (a>>13) ^ (a>>2) // S0
MOVL a, T1; \ // T1 = a // MAJB
ANDL c, T1; \ // T1 = a&c // MAJB
ORL T1, y3; \ // y3 = MAJ = (a|c)&b)|(a&c) // MAJ
; \
ADDL y1, h; \ // h = k + w + h + S0 // --
ADDL y2, h; \ // h = k + w + h + S0 + S1 + CH = t1 + S0// --
ADDL y3, h // h = t1 + S0 + MAJ // --
#define DO_ROUND_N_0(disp, a, b, c, d, e, f, g, h, old_h) \
; \ // ################################### RND N + 0 ###########################
MOVL f, y2; \ // y2 = f // CH
RORXL $25, e, y0; \ // y0 = e >> 25 // S1A
RORXL $11, e, y1; \ // y1 = e >> 11 // S1B
XORL g, y2; \ // y2 = f^g // CH
; \
XORL y1, y0; \ // y0 = (e>>25) ^ (e>>11) // S1
RORXL $6, e, y1; \ // y1 = (e >> 6) // S1
ANDL e, y2; \ // y2 = (f^g)&e // CH
; \
XORL y1, y0; \ // y0 = (e>>25) ^ (e>>11) ^ (e>>6) // S1
RORXL $13, a, T1; \ // T1 = a >> 13 // S0B
XORL g, y2; \ // y2 = CH = ((f^g)&e)^g // CH
RORXL $22, a, y1; \ // y1 = a >> 22 // S0A
MOVL a, y3; \ // y3 = a // MAJA
; \
XORL T1, y1; \ // y1 = (a>>22) ^ (a>>13) // S0
RORXL $2, a, T1; \ // T1 = (a >> 2) // S0
ADDL (disp + 0*4)(SP)(SRND*1), h; \ // h = k + w + h // --
ORL c, y3; \ // y3 = a|c // MAJA
; \
XORL T1, y1; \ // y1 = (a>>22) ^ (a>>13) ^ (a>>2) // S0
MOVL a, T1; \ // T1 = a // MAJB
ANDL b, y3; \ // y3 = (a|c)&b // MAJA
ANDL c, T1; \ // T1 = a&c // MAJB
ADDL y0, y2; \ // y2 = S1 + CH // --
; \
ADDL h, d; \ // d = k + w + h + d // --
ORL T1, y3; \ // y3 = MAJ = (a|c)&b)|(a&c) // MAJ
ADDL y1, h; \ // h = k + w + h + S0 // --
ADDL y2, d // d = k + w + h + d + S1 + CH = d + t1 // --
#define DO_ROUND_N_1(disp, a, b, c, d, e, f, g, h, old_h) \
; \ // ################################### RND N + 1 ###########################
ADDL y2, old_h; \ // h = k + w + h + S0 + S1 + CH = t1 + S0 // --
MOVL f, y2; \ // y2 = f // CH
RORXL $25, e, y0; \ // y0 = e >> 25 // S1A
RORXL $11, e, y1; \ // y1 = e >> 11 // S1B
XORL g, y2; \ // y2 = f^g // CH
; \
XORL y1, y0; \ // y0 = (e>>25) ^ (e>>11) // S1
RORXL $6, e, y1; \ // y1 = (e >> 6) // S1
ANDL e, y2; \ // y2 = (f^g)&e // CH
ADDL y3, old_h; \ // h = t1 + S0 + MAJ // --
; \
XORL y1, y0; \ // y0 = (e>>25) ^ (e>>11) ^ (e>>6) // S1
RORXL $13, a, T1; \ // T1 = a >> 13 // S0B
XORL g, y2; \ // y2 = CH = ((f^g)&e)^g // CH
RORXL $22, a, y1; \ // y1 = a >> 22 // S0A
MOVL a, y3; \ // y3 = a // MAJA
; \
XORL T1, y1; \ // y1 = (a>>22) ^ (a>>13) // S0
RORXL $2, a, T1; \ // T1 = (a >> 2) // S0
ADDL (disp + 1*4)(SP)(SRND*1), h; \ // h = k + w + h // --
ORL c, y3; \ // y3 = a|c // MAJA
; \
XORL T1, y1; \ // y1 = (a>>22) ^ (a>>13) ^ (a>>2) // S0
MOVL a, T1; \ // T1 = a // MAJB
ANDL b, y3; \ // y3 = (a|c)&b // MAJA
ANDL c, T1; \ // T1 = a&c // MAJB
ADDL y0, y2; \ // y2 = S1 + CH // --
; \
ADDL h, d; \ // d = k + w + h + d // --
ORL T1, y3; \ // y3 = MAJ = (a|c)&b)|(a&c) // MAJ
ADDL y1, h; \ // h = k + w + h + S0 // --
; \
ADDL y2, d // d = k + w + h + d + S1 + CH = d + t1 // --
#define DO_ROUND_N_2(disp, a, b, c, d, e, f, g, h, old_h) \
; \ // ################################### RND N + 2 ##############################
ADDL y2, old_h; \ // h = k + w + h + S0 + S1 + CH = t1 + S0// --
MOVL f, y2; \ // y2 = f // CH
RORXL $25, e, y0; \ // y0 = e >> 25 // S1A
RORXL $11, e, y1; \ // y1 = e >> 11 // S1B
XORL g, y2; \ // y2 = f^g // CH
; \
XORL y1, y0; \ // y0 = (e>>25) ^ (e>>11) // S1
RORXL $6, e, y1; \ // y1 = (e >> 6) // S1
ANDL e, y2; \ // y2 = (f^g)&e // CH
ADDL y3, old_h; \ // h = t1 + S0 + MAJ // --
; \
XORL y1, y0; \ // y0 = (e>>25) ^ (e>>11) ^ (e>>6) // S1
RORXL $13, a, T1; \ // T1 = a >> 13 // S0B
XORL g, y2; \ // y2 = CH = ((f^g)&e)^g // CH
RORXL $22, a, y1; \ // y1 = a >> 22 // S0A
MOVL a, y3; \ // y3 = a // MAJA
; \
XORL T1, y1; \ // y1 = (a>>22) ^ (a>>13) // S0
RORXL $2, a, T1; \ // T1 = (a >> 2) // S0
ADDL (disp + 2*4)(SP)(SRND*1), h; \ // h = k + w + h // --
ORL c, y3; \ // y3 = a|c // MAJA
; \
XORL T1, y1; \ // y1 = (a>>22) ^ (a>>13) ^ (a>>2) // S0
MOVL a, T1; \ // T1 = a // MAJB
ANDL b, y3; \ // y3 = (a|c)&b // MAJA
ANDL c, T1; \ // T1 = a&c // MAJB
ADDL y0, y2; \ // y2 = S1 + CH // --
; \
ADDL h, d; \ // d = k + w + h + d // --
ORL T1, y3; \ // y3 = MAJ = (a|c)&b)|(a&c) // MAJ
ADDL y1, h; \ // h = k + w + h + S0 // --
; \
ADDL y2, d // d = k + w + h + d + S1 + CH = d + t1 // --
#define DO_ROUND_N_3(disp, a, b, c, d, e, f, g, h, old_h) \
; \ // ################################### RND N + 3 ###########################
ADDL y2, old_h; \ // h = k + w + h + S0 + S1 + CH = t1 + S0// --
MOVL f, y2; \ // y2 = f // CH
RORXL $25, e, y0; \ // y0 = e >> 25 // S1A
RORXL $11, e, y1; \ // y1 = e >> 11 // S1B
XORL g, y2; \ // y2 = f^g // CH
; \
XORL y1, y0; \ // y0 = (e>>25) ^ (e>>11) // S1
RORXL $6, e, y1; \ // y1 = (e >> 6) // S1
ANDL e, y2; \ // y2 = (f^g)&e // CH
ADDL y3, old_h; \ // h = t1 + S0 + MAJ // --
; \
XORL y1, y0; \ // y0 = (e>>25) ^ (e>>11) ^ (e>>6) // S1
RORXL $13, a, T1; \ // T1 = a >> 13 // S0B
XORL g, y2; \ // y2 = CH = ((f^g)&e)^g // CH
RORXL $22, a, y1; \ // y1 = a >> 22 // S0A
MOVL a, y3; \ // y3 = a // MAJA
; \
XORL T1, y1; \ // y1 = (a>>22) ^ (a>>13) // S0
RORXL $2, a, T1; \ // T1 = (a >> 2) // S0
ADDL (disp + 3*4)(SP)(SRND*1), h; \ // h = k + w + h // --
ORL c, y3; \ // y3 = a|c // MAJA
; \
XORL T1, y1; \ // y1 = (a>>22) ^ (a>>13) ^ (a>>2) // S0
MOVL a, T1; \ // T1 = a // MAJB
ANDL b, y3; \ // y3 = (a|c)&b // MAJA
ANDL c, T1; \ // T1 = a&c // MAJB
ADDL y0, y2; \ // y2 = S1 + CH // --
; \
ADDL h, d; \ // d = k + w + h + d // --
ORL T1, y3; \ // y3 = MAJ = (a|c)&b)|(a&c) // MAJ
ADDL y1, h; \ // h = k + w + h + S0 // --
; \
ADDL y2, d; \ // d = k + w + h + d + S1 + CH = d + t1 // --
; \
ADDL y2, h; \ // h = k + w + h + S0 + S1 + CH = t1 + S0// --
; \
ADDL y3, h // h = t1 + S0 + MAJ // --
// Definitions for sha-ni version
//
// The sha-ni implementation uses Intel(R) SHA extensions SHA256RNDS2, SHA256MSG1, SHA256MSG2
// It also reuses portions of the flip_mask (half) and K256 table (stride 32) from the avx2 version
//
// Reference
// S. Gulley, et al, "New Instructions Supporting the Secure Hash
// Algorithm on Intel® Architecture Processors", July 2013
// https://www.intel.com/content/www/us/en/developer/articles/technical/intel-sha-extensions.html
//
#define digestPtr DI // input/output, base pointer to digest hash vector H0, H1, ..., H7
#define dataPtr SI // input, base pointer to first input data block
#define numBytes DX // input, number of input bytes to be processed
#define sha256Constants AX // round contents from K256 table, indexed by round number x 32
#define msg X0 // input data
#define state0 X1 // round intermediates and outputs
#define state1 X2
#define m0 X3 // m0, m1,... m4 -- round message temps
#define m1 X4
#define m2 X5
#define m3 X6
#define m4 X7
#define shufMask X8 // input data endian conversion control mask
#define abefSave X9 // digest hash vector inter-block buffer abef
#define cdghSave X10 // digest hash vector inter-block buffer cdgh
#define nop(m,a) // nop instead of final SHA256MSG1 for first and last few rounds
#define sha256msg1(m,a) \ // final SHA256MSG1 for middle rounds that require it
SHA256MSG1 m, a
#define vmov(a,b) \ // msg copy for all but rounds 12-15
VMOVDQA a, b
#define vmovrev(a,b) \ // reverse copy for rounds 12-15
VMOVDQA b, a
// sha rounds 0 to 11
// identical with the exception of the final msg op
// which is replaced with a nop for rounds where it is not needed
// refer to Gulley, et al for more information
#define rounds0to11(m,a,c,sha256Msg1) \
VMOVDQU c*16(dataPtr), msg \
PSHUFB shufMask, msg \
VMOVDQA msg, m \
PADDD (c*32)(sha256Constants), msg \
SHA256RNDS2 msg, state0, state1 \
PSHUFD $0x0e, msg, msg \
SHA256RNDS2 msg, state1, state0 \
sha256Msg1 (m,a)
// sha rounds 12 to 59
// identical with the exception of the final msg op
// and the reverse copy(m,msg) in round 12 which is required
// after the last data load
// refer to Gulley, et al for more information
#define rounds12to59(m,c,a,t,sha256Msg1,movop) \
movop (m,msg) \
PADDD (c*32)(sha256Constants), msg \
SHA256RNDS2 msg, state0, state1 \
VMOVDQA m, m4 \
PALIGNR $4, a, m4 \
PADDD m4, t \
SHA256MSG2 m, t \
PSHUFD $0x0e, msg, msg \
SHA256RNDS2 msg, state1, state0 \
sha256Msg1 (m,a)
TEXT ·block(SB), 0, $536-32
CMPB ·useSHA(SB), $1
JE sha_ni
CMPB ·useAVX2(SB), $1
JE avx2
MOVQ p_base+8(FP), SI
MOVQ p_len+16(FP), DX
SHRQ $6, DX
SHLQ $6, DX
LEAQ (SI)(DX*1), DI
MOVQ DI, 256(SP)
CMPQ SI, DI
JEQ end
MOVQ dig+0(FP), BP
MOVL (0*4)(BP), R8 // a = H0
MOVL (1*4)(BP), R9 // b = H1
MOVL (2*4)(BP), R10 // c = H2
MOVL (3*4)(BP), R11 // d = H3
MOVL (4*4)(BP), R12 // e = H4
MOVL (5*4)(BP), R13 // f = H5
MOVL (6*4)(BP), R14 // g = H6
MOVL (7*4)(BP), R15 // h = H7
loop:
MOVQ SP, BP
SHA256ROUND0(0, 0x428a2f98, R8, R9, R10, R11, R12, R13, R14, R15)
SHA256ROUND0(1, 0x71374491, R15, R8, R9, R10, R11, R12, R13, R14)
SHA256ROUND0(2, 0xb5c0fbcf, R14, R15, R8, R9, R10, R11, R12, R13)
SHA256ROUND0(3, 0xe9b5dba5, R13, R14, R15, R8, R9, R10, R11, R12)
SHA256ROUND0(4, 0x3956c25b, R12, R13, R14, R15, R8, R9, R10, R11)
SHA256ROUND0(5, 0x59f111f1, R11, R12, R13, R14, R15, R8, R9, R10)
SHA256ROUND0(6, 0x923f82a4, R10, R11, R12, R13, R14, R15, R8, R9)
SHA256ROUND0(7, 0xab1c5ed5, R9, R10, R11, R12, R13, R14, R15, R8)
SHA256ROUND0(8, 0xd807aa98, R8, R9, R10, R11, R12, R13, R14, R15)
SHA256ROUND0(9, 0x12835b01, R15, R8, R9, R10, R11, R12, R13, R14)
SHA256ROUND0(10, 0x243185be, R14, R15, R8, R9, R10, R11, R12, R13)
SHA256ROUND0(11, 0x550c7dc3, R13, R14, R15, R8, R9, R10, R11, R12)
SHA256ROUND0(12, 0x72be5d74, R12, R13, R14, R15, R8, R9, R10, R11)
SHA256ROUND0(13, 0x80deb1fe, R11, R12, R13, R14, R15, R8, R9, R10)
SHA256ROUND0(14, 0x9bdc06a7, R10, R11, R12, R13, R14, R15, R8, R9)
SHA256ROUND0(15, 0xc19bf174, R9, R10, R11, R12, R13, R14, R15, R8)
SHA256ROUND1(16, 0xe49b69c1, R8, R9, R10, R11, R12, R13, R14, R15)
SHA256ROUND1(17, 0xefbe4786, R15, R8, R9, R10, R11, R12, R13, R14)
SHA256ROUND1(18, 0x0fc19dc6, R14, R15, R8, R9, R10, R11, R12, R13)
SHA256ROUND1(19, 0x240ca1cc, R13, R14, R15, R8, R9, R10, R11, R12)
SHA256ROUND1(20, 0x2de92c6f, R12, R13, R14, R15, R8, R9, R10, R11)
SHA256ROUND1(21, 0x4a7484aa, R11, R12, R13, R14, R15, R8, R9, R10)
SHA256ROUND1(22, 0x5cb0a9dc, R10, R11, R12, R13, R14, R15, R8, R9)
SHA256ROUND1(23, 0x76f988da, R9, R10, R11, R12, R13, R14, R15, R8)
SHA256ROUND1(24, 0x983e5152, R8, R9, R10, R11, R12, R13, R14, R15)
SHA256ROUND1(25, 0xa831c66d, R15, R8, R9, R10, R11, R12, R13, R14)
SHA256ROUND1(26, 0xb00327c8, R14, R15, R8, R9, R10, R11, R12, R13)
SHA256ROUND1(27, 0xbf597fc7, R13, R14, R15, R8, R9, R10, R11, R12)
SHA256ROUND1(28, 0xc6e00bf3, R12, R13, R14, R15, R8, R9, R10, R11)
SHA256ROUND1(29, 0xd5a79147, R11, R12, R13, R14, R15, R8, R9, R10)
SHA256ROUND1(30, 0x06ca6351, R10, R11, R12, R13, R14, R15, R8, R9)
SHA256ROUND1(31, 0x14292967, R9, R10, R11, R12, R13, R14, R15, R8)
SHA256ROUND1(32, 0x27b70a85, R8, R9, R10, R11, R12, R13, R14, R15)
SHA256ROUND1(33, 0x2e1b2138, R15, R8, R9, R10, R11, R12, R13, R14)
SHA256ROUND1(34, 0x4d2c6dfc, R14, R15, R8, R9, R10, R11, R12, R13)
SHA256ROUND1(35, 0x53380d13, R13, R14, R15, R8, R9, R10, R11, R12)
SHA256ROUND1(36, 0x650a7354, R12, R13, R14, R15, R8, R9, R10, R11)
SHA256ROUND1(37, 0x766a0abb, R11, R12, R13, R14, R15, R8, R9, R10)
SHA256ROUND1(38, 0x81c2c92e, R10, R11, R12, R13, R14, R15, R8, R9)
SHA256ROUND1(39, 0x92722c85, R9, R10, R11, R12, R13, R14, R15, R8)
SHA256ROUND1(40, 0xa2bfe8a1, R8, R9, R10, R11, R12, R13, R14, R15)
SHA256ROUND1(41, 0xa81a664b, R15, R8, R9, R10, R11, R12, R13, R14)
SHA256ROUND1(42, 0xc24b8b70, R14, R15, R8, R9, R10, R11, R12, R13)
SHA256ROUND1(43, 0xc76c51a3, R13, R14, R15, R8, R9, R10, R11, R12)
SHA256ROUND1(44, 0xd192e819, R12, R13, R14, R15, R8, R9, R10, R11)
SHA256ROUND1(45, 0xd6990624, R11, R12, R13, R14, R15, R8, R9, R10)
SHA256ROUND1(46, 0xf40e3585, R10, R11, R12, R13, R14, R15, R8, R9)
SHA256ROUND1(47, 0x106aa070, R9, R10, R11, R12, R13, R14, R15, R8)
SHA256ROUND1(48, 0x19a4c116, R8, R9, R10, R11, R12, R13, R14, R15)
SHA256ROUND1(49, 0x1e376c08, R15, R8, R9, R10, R11, R12, R13, R14)
SHA256ROUND1(50, 0x2748774c, R14, R15, R8, R9, R10, R11, R12, R13)
SHA256ROUND1(51, 0x34b0bcb5, R13, R14, R15, R8, R9, R10, R11, R12)
SHA256ROUND1(52, 0x391c0cb3, R12, R13, R14, R15, R8, R9, R10, R11)
SHA256ROUND1(53, 0x4ed8aa4a, R11, R12, R13, R14, R15, R8, R9, R10)
SHA256ROUND1(54, 0x5b9cca4f, R10, R11, R12, R13, R14, R15, R8, R9)
SHA256ROUND1(55, 0x682e6ff3, R9, R10, R11, R12, R13, R14, R15, R8)
SHA256ROUND1(56, 0x748f82ee, R8, R9, R10, R11, R12, R13, R14, R15)
SHA256ROUND1(57, 0x78a5636f, R15, R8, R9, R10, R11, R12, R13, R14)
SHA256ROUND1(58, 0x84c87814, R14, R15, R8, R9, R10, R11, R12, R13)
SHA256ROUND1(59, 0x8cc70208, R13, R14, R15, R8, R9, R10, R11, R12)
SHA256ROUND1(60, 0x90befffa, R12, R13, R14, R15, R8, R9, R10, R11)
SHA256ROUND1(61, 0xa4506ceb, R11, R12, R13, R14, R15, R8, R9, R10)
SHA256ROUND1(62, 0xbef9a3f7, R10, R11, R12, R13, R14, R15, R8, R9)
SHA256ROUND1(63, 0xc67178f2, R9, R10, R11, R12, R13, R14, R15, R8)
MOVQ dig+0(FP), BP
ADDL (0*4)(BP), R8 // H0 = a + H0
MOVL R8, (0*4)(BP)
ADDL (1*4)(BP), R9 // H1 = b + H1
MOVL R9, (1*4)(BP)
ADDL (2*4)(BP), R10 // H2 = c + H2
MOVL R10, (2*4)(BP)
ADDL (3*4)(BP), R11 // H3 = d + H3
MOVL R11, (3*4)(BP)
ADDL (4*4)(BP), R12 // H4 = e + H4
MOVL R12, (4*4)(BP)
ADDL (5*4)(BP), R13 // H5 = f + H5
MOVL R13, (5*4)(BP)
ADDL (6*4)(BP), R14 // H6 = g + H6
MOVL R14, (6*4)(BP)
ADDL (7*4)(BP), R15 // H7 = h + H7
MOVL R15, (7*4)(BP)
ADDQ $64, SI
CMPQ SI, 256(SP)
JB loop
end:
RET
avx2:
MOVQ dig+0(FP), CTX // d.h[8]
MOVQ p_base+8(FP), INP
MOVQ p_len+16(FP), NUM_BYTES
LEAQ -64(INP)(NUM_BYTES*1), NUM_BYTES // Pointer to the last block
MOVQ NUM_BYTES, _INP_END(SP)
CMPQ NUM_BYTES, INP
JE avx2_only_one_block
// Load initial digest
MOVL 0(CTX), a // a = H0
MOVL 4(CTX), b // b = H1
MOVL 8(CTX), c // c = H2
MOVL 12(CTX), d // d = H3
MOVL 16(CTX), e // e = H4
MOVL 20(CTX), f // f = H5
MOVL 24(CTX), g // g = H6
MOVL 28(CTX), h // h = H7
avx2_loop0: // at each iteration works with one block (512 bit)
VMOVDQU (0*32)(INP), XTMP0
VMOVDQU (1*32)(INP), XTMP1
VMOVDQU (2*32)(INP), XTMP2
VMOVDQU (3*32)(INP), XTMP3
VMOVDQU flip_mask<>(SB), BYTE_FLIP_MASK
// Apply Byte Flip Mask: LE -> BE
VPSHUFB BYTE_FLIP_MASK, XTMP0, XTMP0
VPSHUFB BYTE_FLIP_MASK, XTMP1, XTMP1
VPSHUFB BYTE_FLIP_MASK, XTMP2, XTMP2
VPSHUFB BYTE_FLIP_MASK, XTMP3, XTMP3
// Transpose data into high/low parts
VPERM2I128 $0x20, XTMP2, XTMP0, XDWORD0 // w3, w2, w1, w0
VPERM2I128 $0x31, XTMP2, XTMP0, XDWORD1 // w7, w6, w5, w4
VPERM2I128 $0x20, XTMP3, XTMP1, XDWORD2 // w11, w10, w9, w8
VPERM2I128 $0x31, XTMP3, XTMP1, XDWORD3 // w15, w14, w13, w12
MOVQ $K256<>(SB), TBL // Loading address of table with round-specific constants
avx2_last_block_enter:
ADDQ $64, INP
MOVQ INP, _INP(SP)
XORQ SRND, SRND
avx2_loop1: // for w0 - w47
// Do 4 rounds and scheduling
VPADDD 0*32(TBL)(SRND*1), XDWORD0, XFER
VMOVDQU XFER, (_XFER + 0*32)(SP)(SRND*1)
ROUND_AND_SCHED_N_0(_XFER + 0*32, a, b, c, d, e, f, g, h, XDWORD0, XDWORD1, XDWORD2, XDWORD3)
ROUND_AND_SCHED_N_1(_XFER + 0*32, h, a, b, c, d, e, f, g, XDWORD0, XDWORD1, XDWORD2, XDWORD3)
ROUND_AND_SCHED_N_2(_XFER + 0*32, g, h, a, b, c, d, e, f, XDWORD0, XDWORD1, XDWORD2, XDWORD3)
ROUND_AND_SCHED_N_3(_XFER + 0*32, f, g, h, a, b, c, d, e, XDWORD0, XDWORD1, XDWORD2, XDWORD3)
// Do 4 rounds and scheduling
VPADDD 1*32(TBL)(SRND*1), XDWORD1, XFER
VMOVDQU XFER, (_XFER + 1*32)(SP)(SRND*1)
ROUND_AND_SCHED_N_0(_XFER + 1*32, e, f, g, h, a, b, c, d, XDWORD1, XDWORD2, XDWORD3, XDWORD0)
ROUND_AND_SCHED_N_1(_XFER + 1*32, d, e, f, g, h, a, b, c, XDWORD1, XDWORD2, XDWORD3, XDWORD0)
ROUND_AND_SCHED_N_2(_XFER + 1*32, c, d, e, f, g, h, a, b, XDWORD1, XDWORD2, XDWORD3, XDWORD0)
ROUND_AND_SCHED_N_3(_XFER + 1*32, b, c, d, e, f, g, h, a, XDWORD1, XDWORD2, XDWORD3, XDWORD0)
// Do 4 rounds and scheduling
VPADDD 2*32(TBL)(SRND*1), XDWORD2, XFER
VMOVDQU XFER, (_XFER + 2*32)(SP)(SRND*1)
ROUND_AND_SCHED_N_0(_XFER + 2*32, a, b, c, d, e, f, g, h, XDWORD2, XDWORD3, XDWORD0, XDWORD1)
ROUND_AND_SCHED_N_1(_XFER + 2*32, h, a, b, c, d, e, f, g, XDWORD2, XDWORD3, XDWORD0, XDWORD1)
ROUND_AND_SCHED_N_2(_XFER + 2*32, g, h, a, b, c, d, e, f, XDWORD2, XDWORD3, XDWORD0, XDWORD1)
ROUND_AND_SCHED_N_3(_XFER + 2*32, f, g, h, a, b, c, d, e, XDWORD2, XDWORD3, XDWORD0, XDWORD1)
// Do 4 rounds and scheduling
VPADDD 3*32(TBL)(SRND*1), XDWORD3, XFER
VMOVDQU XFER, (_XFER + 3*32)(SP)(SRND*1)
ROUND_AND_SCHED_N_0(_XFER + 3*32, e, f, g, h, a, b, c, d, XDWORD3, XDWORD0, XDWORD1, XDWORD2)
ROUND_AND_SCHED_N_1(_XFER + 3*32, d, e, f, g, h, a, b, c, XDWORD3, XDWORD0, XDWORD1, XDWORD2)
ROUND_AND_SCHED_N_2(_XFER + 3*32, c, d, e, f, g, h, a, b, XDWORD3, XDWORD0, XDWORD1, XDWORD2)
ROUND_AND_SCHED_N_3(_XFER + 3*32, b, c, d, e, f, g, h, a, XDWORD3, XDWORD0, XDWORD1, XDWORD2)
ADDQ $4*32, SRND
CMPQ SRND, $3*4*32
JB avx2_loop1
avx2_loop2:
// w48 - w63 processed with no scheduling (last 16 rounds)
VPADDD 0*32(TBL)(SRND*1), XDWORD0, XFER
VMOVDQU XFER, (_XFER + 0*32)(SP)(SRND*1)
DO_ROUND_N_0(_XFER + 0*32, a, b, c, d, e, f, g, h, h)
DO_ROUND_N_1(_XFER + 0*32, h, a, b, c, d, e, f, g, h)
DO_ROUND_N_2(_XFER + 0*32, g, h, a, b, c, d, e, f, g)
DO_ROUND_N_3(_XFER + 0*32, f, g, h, a, b, c, d, e, f)
VPADDD 1*32(TBL)(SRND*1), XDWORD1, XFER
VMOVDQU XFER, (_XFER + 1*32)(SP)(SRND*1)
DO_ROUND_N_0(_XFER + 1*32, e, f, g, h, a, b, c, d, e)
DO_ROUND_N_1(_XFER + 1*32, d, e, f, g, h, a, b, c, d)
DO_ROUND_N_2(_XFER + 1*32, c, d, e, f, g, h, a, b, c)
DO_ROUND_N_3(_XFER + 1*32, b, c, d, e, f, g, h, a, b)
ADDQ $2*32, SRND
VMOVDQU XDWORD2, XDWORD0
VMOVDQU XDWORD3, XDWORD1
CMPQ SRND, $4*4*32
JB avx2_loop2
MOVQ dig+0(FP), CTX // d.h[8]
MOVQ _INP(SP), INP
addm( 0(CTX), a)
addm( 4(CTX), b)
addm( 8(CTX), c)
addm( 12(CTX), d)
addm( 16(CTX), e)
addm( 20(CTX), f)
addm( 24(CTX), g)
addm( 28(CTX), h)
CMPQ _INP_END(SP), INP
JB done_hash
XORQ SRND, SRND
avx2_loop3: // Do second block using previously scheduled results
DO_ROUND_N_0(_XFER + 0*32 + 16, a, b, c, d, e, f, g, h, a)
DO_ROUND_N_1(_XFER + 0*32 + 16, h, a, b, c, d, e, f, g, h)
DO_ROUND_N_2(_XFER + 0*32 + 16, g, h, a, b, c, d, e, f, g)
DO_ROUND_N_3(_XFER + 0*32 + 16, f, g, h, a, b, c, d, e, f)
DO_ROUND_N_0(_XFER + 1*32 + 16, e, f, g, h, a, b, c, d, e)
DO_ROUND_N_1(_XFER + 1*32 + 16, d, e, f, g, h, a, b, c, d)
DO_ROUND_N_2(_XFER + 1*32 + 16, c, d, e, f, g, h, a, b, c)
DO_ROUND_N_3(_XFER + 1*32 + 16, b, c, d, e, f, g, h, a, b)
ADDQ $2*32, SRND
CMPQ SRND, $4*4*32
JB avx2_loop3
MOVQ dig+0(FP), CTX // d.h[8]
MOVQ _INP(SP), INP
ADDQ $64, INP
addm( 0(CTX), a)
addm( 4(CTX), b)
addm( 8(CTX), c)
addm( 12(CTX), d)
addm( 16(CTX), e)
addm( 20(CTX), f)
addm( 24(CTX), g)
addm( 28(CTX), h)
CMPQ _INP_END(SP), INP
JA avx2_loop0
JB done_hash
avx2_do_last_block:
VMOVDQU 0(INP), XWORD0
VMOVDQU 16(INP), XWORD1
VMOVDQU 32(INP), XWORD2
VMOVDQU 48(INP), XWORD3
VMOVDQU flip_mask<>(SB), BYTE_FLIP_MASK
VPSHUFB X_BYTE_FLIP_MASK, XWORD0, XWORD0
VPSHUFB X_BYTE_FLIP_MASK, XWORD1, XWORD1
VPSHUFB X_BYTE_FLIP_MASK, XWORD2, XWORD2
VPSHUFB X_BYTE_FLIP_MASK, XWORD3, XWORD3
MOVQ $K256<>(SB), TBL
JMP avx2_last_block_enter
avx2_only_one_block:
// Load initial digest
MOVL 0(CTX), a // a = H0
MOVL 4(CTX), b // b = H1
MOVL 8(CTX), c // c = H2
MOVL 12(CTX), d // d = H3
MOVL 16(CTX), e // e = H4
MOVL 20(CTX), f // f = H5
MOVL 24(CTX), g // g = H6
MOVL 28(CTX), h // h = H7
JMP avx2_do_last_block
done_hash:
VZEROUPPER
RET
sha_ni:
MOVQ dig+0(FP), digestPtr // init digest hash vector H0, H1,..., H7 pointer
MOVQ p_base+8(FP), dataPtr // init input data base pointer
MOVQ p_len+16(FP), numBytes // get number of input bytes to hash
SHRQ $6, numBytes // force modulo 64 input buffer length
SHLQ $6, numBytes
CMPQ numBytes, $0 // exit early for zero-length input buffer
JEQ done
ADDQ dataPtr, numBytes // point numBytes to end of input buffer
VMOVDQU (0*16)(digestPtr), state0 // load initial hash values and reorder
VMOVDQU (1*16)(digestPtr), state1 // DCBA, HGFE -> ABEF, CDGH
PSHUFD $0xb1, state0, state0 // CDAB
PSHUFD $0x1b, state1, state1 // EFGH
VMOVDQA state0, m4
PALIGNR $8, state1, state0 // ABEF
PBLENDW $0xf0, m4, state1 // CDGH
VMOVDQA flip_mask<>(SB), shufMask
LEAQ K256<>(SB), sha256Constants
roundLoop:
// save hash values for addition after rounds
VMOVDQA state0, abefSave
VMOVDQA state1, cdghSave
// do rounds 0-59
rounds0to11 (m0,-,0,nop) // 0-3
rounds0to11 (m1,m0,1,sha256msg1) // 4-7
rounds0to11 (m2,m1,2,sha256msg1) // 8-11
VMOVDQU (3*16)(dataPtr), msg
PSHUFB shufMask, msg
rounds12to59 (m3,3,m2,m0,sha256msg1,vmovrev) // 12-15
rounds12to59 (m0,4,m3,m1,sha256msg1,vmov) // 16-19
rounds12to59 (m1,5,m0,m2,sha256msg1,vmov) // 20-23
rounds12to59 (m2,6,m1,m3,sha256msg1,vmov) // 24-27
rounds12to59 (m3,7,m2,m0,sha256msg1,vmov) // 28-31
rounds12to59 (m0,8,m3,m1,sha256msg1,vmov) // 32-35
rounds12to59 (m1,9,m0,m2,sha256msg1,vmov) // 36-39
rounds12to59 (m2,10,m1,m3,sha256msg1,vmov) // 40-43
rounds12to59 (m3,11,m2,m0,sha256msg1,vmov) // 44-47
rounds12to59 (m0,12,m3,m1,sha256msg1,vmov) // 48-51
rounds12to59 (m1,13,m0,m2,nop,vmov) // 52-55
rounds12to59 (m2,14,m1,m3,nop,vmov) // 56-59
// do rounds 60-63
VMOVDQA m3, msg
PADDD (15*32)(sha256Constants), msg
SHA256RNDS2 msg, state0, state1
PSHUFD $0x0e, msg, msg
SHA256RNDS2 msg, state1, state0
// add current hash values with previously saved
PADDD abefSave, state0
PADDD cdghSave, state1
// advance data pointer; loop until buffer empty
ADDQ $64, dataPtr
CMPQ numBytes, dataPtr
JNE roundLoop
// write hash values back in the correct order
PSHUFD $0x1b, state0, state0 // FEBA
PSHUFD $0xb1, state1, state1 // DCHG
VMOVDQA state0, m4
PBLENDW $0xf0, state1, state0 // DCBA
PALIGNR $8, m4, state1 // HGFE
VMOVDQU state0, (0*16)(digestPtr)
VMOVDQU state1, (1*16)(digestPtr)
done:
RET
// shuffle byte order from LE to BE
DATA flip_mask<>+0x00(SB)/8, $0x0405060700010203
DATA flip_mask<>+0x08(SB)/8, $0x0c0d0e0f08090a0b
DATA flip_mask<>+0x10(SB)/8, $0x0405060700010203
DATA flip_mask<>+0x18(SB)/8, $0x0c0d0e0f08090a0b
GLOBL flip_mask<>(SB), 8, $32
// shuffle xBxA -> 00BA
DATA shuff_00BA<>+0x00(SB)/8, $0x0b0a090803020100
DATA shuff_00BA<>+0x08(SB)/8, $0xFFFFFFFFFFFFFFFF
DATA shuff_00BA<>+0x10(SB)/8, $0x0b0a090803020100
DATA shuff_00BA<>+0x18(SB)/8, $0xFFFFFFFFFFFFFFFF
GLOBL shuff_00BA<>(SB), 8, $32
// shuffle xDxC -> DC00
DATA shuff_DC00<>+0x00(SB)/8, $0xFFFFFFFFFFFFFFFF
DATA shuff_DC00<>+0x08(SB)/8, $0x0b0a090803020100
DATA shuff_DC00<>+0x10(SB)/8, $0xFFFFFFFFFFFFFFFF
DATA shuff_DC00<>+0x18(SB)/8, $0x0b0a090803020100
GLOBL shuff_DC00<>(SB), 8, $32
// Round specific constants
DATA K256<>+0x00(SB)/4, $0x428a2f98 // k1
DATA K256<>+0x04(SB)/4, $0x71374491 // k2
DATA K256<>+0x08(SB)/4, $0xb5c0fbcf // k3
DATA K256<>+0x0c(SB)/4, $0xe9b5dba5 // k4
DATA K256<>+0x10(SB)/4, $0x428a2f98 // k1
DATA K256<>+0x14(SB)/4, $0x71374491 // k2
DATA K256<>+0x18(SB)/4, $0xb5c0fbcf // k3
DATA K256<>+0x1c(SB)/4, $0xe9b5dba5 // k4
DATA K256<>+0x20(SB)/4, $0x3956c25b // k5 - k8
DATA K256<>+0x24(SB)/4, $0x59f111f1
DATA K256<>+0x28(SB)/4, $0x923f82a4
DATA K256<>+0x2c(SB)/4, $0xab1c5ed5
DATA K256<>+0x30(SB)/4, $0x3956c25b
DATA K256<>+0x34(SB)/4, $0x59f111f1
DATA K256<>+0x38(SB)/4, $0x923f82a4
DATA K256<>+0x3c(SB)/4, $0xab1c5ed5
DATA K256<>+0x40(SB)/4, $0xd807aa98 // k9 - k12
DATA K256<>+0x44(SB)/4, $0x12835b01
DATA K256<>+0x48(SB)/4, $0x243185be
DATA K256<>+0x4c(SB)/4, $0x550c7dc3
DATA K256<>+0x50(SB)/4, $0xd807aa98
DATA K256<>+0x54(SB)/4, $0x12835b01
DATA K256<>+0x58(SB)/4, $0x243185be
DATA K256<>+0x5c(SB)/4, $0x550c7dc3
DATA K256<>+0x60(SB)/4, $0x72be5d74 // k13 - k16
DATA K256<>+0x64(SB)/4, $0x80deb1fe
DATA K256<>+0x68(SB)/4, $0x9bdc06a7
DATA K256<>+0x6c(SB)/4, $0xc19bf174
DATA K256<>+0x70(SB)/4, $0x72be5d74
DATA K256<>+0x74(SB)/4, $0x80deb1fe
DATA K256<>+0x78(SB)/4, $0x9bdc06a7
DATA K256<>+0x7c(SB)/4, $0xc19bf174
DATA K256<>+0x80(SB)/4, $0xe49b69c1 // k17 - k20
DATA K256<>+0x84(SB)/4, $0xefbe4786
DATA K256<>+0x88(SB)/4, $0x0fc19dc6
DATA K256<>+0x8c(SB)/4, $0x240ca1cc
DATA K256<>+0x90(SB)/4, $0xe49b69c1
DATA K256<>+0x94(SB)/4, $0xefbe4786
DATA K256<>+0x98(SB)/4, $0x0fc19dc6
DATA K256<>+0x9c(SB)/4, $0x240ca1cc
DATA K256<>+0xa0(SB)/4, $0x2de92c6f // k21 - k24
DATA K256<>+0xa4(SB)/4, $0x4a7484aa
DATA K256<>+0xa8(SB)/4, $0x5cb0a9dc
DATA K256<>+0xac(SB)/4, $0x76f988da
DATA K256<>+0xb0(SB)/4, $0x2de92c6f
DATA K256<>+0xb4(SB)/4, $0x4a7484aa
DATA K256<>+0xb8(SB)/4, $0x5cb0a9dc
DATA K256<>+0xbc(SB)/4, $0x76f988da
DATA K256<>+0xc0(SB)/4, $0x983e5152 // k25 - k28
DATA K256<>+0xc4(SB)/4, $0xa831c66d
DATA K256<>+0xc8(SB)/4, $0xb00327c8
DATA K256<>+0xcc(SB)/4, $0xbf597fc7
DATA K256<>+0xd0(SB)/4, $0x983e5152
DATA K256<>+0xd4(SB)/4, $0xa831c66d
DATA K256<>+0xd8(SB)/4, $0xb00327c8
DATA K256<>+0xdc(SB)/4, $0xbf597fc7
DATA K256<>+0xe0(SB)/4, $0xc6e00bf3 // k29 - k32
DATA K256<>+0xe4(SB)/4, $0xd5a79147
DATA K256<>+0xe8(SB)/4, $0x06ca6351
DATA K256<>+0xec(SB)/4, $0x14292967
DATA K256<>+0xf0(SB)/4, $0xc6e00bf3
DATA K256<>+0xf4(SB)/4, $0xd5a79147
DATA K256<>+0xf8(SB)/4, $0x06ca6351
DATA K256<>+0xfc(SB)/4, $0x14292967
DATA K256<>+0x100(SB)/4, $0x27b70a85
DATA K256<>+0x104(SB)/4, $0x2e1b2138
DATA K256<>+0x108(SB)/4, $0x4d2c6dfc
DATA K256<>+0x10c(SB)/4, $0x53380d13
DATA K256<>+0x110(SB)/4, $0x27b70a85
DATA K256<>+0x114(SB)/4, $0x2e1b2138
DATA K256<>+0x118(SB)/4, $0x4d2c6dfc
DATA K256<>+0x11c(SB)/4, $0x53380d13
DATA K256<>+0x120(SB)/4, $0x650a7354
DATA K256<>+0x124(SB)/4, $0x766a0abb
DATA K256<>+0x128(SB)/4, $0x81c2c92e
DATA K256<>+0x12c(SB)/4, $0x92722c85
DATA K256<>+0x130(SB)/4, $0x650a7354
DATA K256<>+0x134(SB)/4, $0x766a0abb
DATA K256<>+0x138(SB)/4, $0x81c2c92e
DATA K256<>+0x13c(SB)/4, $0x92722c85
DATA K256<>+0x140(SB)/4, $0xa2bfe8a1
DATA K256<>+0x144(SB)/4, $0xa81a664b
DATA K256<>+0x148(SB)/4, $0xc24b8b70
DATA K256<>+0x14c(SB)/4, $0xc76c51a3
DATA K256<>+0x150(SB)/4, $0xa2bfe8a1
DATA K256<>+0x154(SB)/4, $0xa81a664b
DATA K256<>+0x158(SB)/4, $0xc24b8b70
DATA K256<>+0x15c(SB)/4, $0xc76c51a3
DATA K256<>+0x160(SB)/4, $0xd192e819
DATA K256<>+0x164(SB)/4, $0xd6990624
DATA K256<>+0x168(SB)/4, $0xf40e3585
DATA K256<>+0x16c(SB)/4, $0x106aa070
DATA K256<>+0x170(SB)/4, $0xd192e819
DATA K256<>+0x174(SB)/4, $0xd6990624
DATA K256<>+0x178(SB)/4, $0xf40e3585
DATA K256<>+0x17c(SB)/4, $0x106aa070
DATA K256<>+0x180(SB)/4, $0x19a4c116
DATA K256<>+0x184(SB)/4, $0x1e376c08
DATA K256<>+0x188(SB)/4, $0x2748774c
DATA K256<>+0x18c(SB)/4, $0x34b0bcb5
DATA K256<>+0x190(SB)/4, $0x19a4c116
DATA K256<>+0x194(SB)/4, $0x1e376c08
DATA K256<>+0x198(SB)/4, $0x2748774c
DATA K256<>+0x19c(SB)/4, $0x34b0bcb5
DATA K256<>+0x1a0(SB)/4, $0x391c0cb3
DATA K256<>+0x1a4(SB)/4, $0x4ed8aa4a
DATA K256<>+0x1a8(SB)/4, $0x5b9cca4f
DATA K256<>+0x1ac(SB)/4, $0x682e6ff3
DATA K256<>+0x1b0(SB)/4, $0x391c0cb3
DATA K256<>+0x1b4(SB)/4, $0x4ed8aa4a
DATA K256<>+0x1b8(SB)/4, $0x5b9cca4f
DATA K256<>+0x1bc(SB)/4, $0x682e6ff3
DATA K256<>+0x1c0(SB)/4, $0x748f82ee
DATA K256<>+0x1c4(SB)/4, $0x78a5636f
DATA K256<>+0x1c8(SB)/4, $0x84c87814
DATA K256<>+0x1cc(SB)/4, $0x8cc70208
DATA K256<>+0x1d0(SB)/4, $0x748f82ee
DATA K256<>+0x1d4(SB)/4, $0x78a5636f
DATA K256<>+0x1d8(SB)/4, $0x84c87814
DATA K256<>+0x1dc(SB)/4, $0x8cc70208
DATA K256<>+0x1e0(SB)/4, $0x90befffa
DATA K256<>+0x1e4(SB)/4, $0xa4506ceb
DATA K256<>+0x1e8(SB)/4, $0xbef9a3f7
DATA K256<>+0x1ec(SB)/4, $0xc67178f2
DATA K256<>+0x1f0(SB)/4, $0x90befffa
DATA K256<>+0x1f4(SB)/4, $0xa4506ceb
DATA K256<>+0x1f8(SB)/4, $0xbef9a3f7
DATA K256<>+0x1fc(SB)/4, $0xc67178f2
GLOBL K256<>(SB), (NOPTR + RODATA), $512
| go/src/crypto/sha256/sha256block_amd64.s/0 | {
"file_path": "go/src/crypto/sha256/sha256block_amd64.s",
"repo_id": "go",
"token_count": 31254
} | 218 |
// Copyright 2013 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 subtle_test
import (
"bytes"
"crypto/rand"
. "crypto/subtle"
"fmt"
"io"
"testing"
)
func TestXORBytes(t *testing.T) {
for n := 1; n <= 1024; n++ {
if n > 16 && testing.Short() {
n += n >> 3
}
for alignP := 0; alignP < 8; alignP++ {
for alignQ := 0; alignQ < 8; alignQ++ {
for alignD := 0; alignD < 8; alignD++ {
p := make([]byte, alignP+n, alignP+n+10)[alignP:]
q := make([]byte, alignQ+n, alignQ+n+10)[alignQ:]
if n&1 != 0 {
p = p[:n]
} else {
q = q[:n]
}
if _, err := io.ReadFull(rand.Reader, p); err != nil {
t.Fatal(err)
}
if _, err := io.ReadFull(rand.Reader, q); err != nil {
t.Fatal(err)
}
d := make([]byte, alignD+n, alignD+n+10)
for i := range d {
d[i] = 0xdd
}
want := make([]byte, len(d), cap(d))
copy(want[:cap(want)], d[:cap(d)])
for i := 0; i < n; i++ {
want[alignD+i] = p[i] ^ q[i]
}
if XORBytes(d[alignD:], p, q); !bytes.Equal(d, want) {
t.Fatalf("n=%d alignP=%d alignQ=%d alignD=%d:\n\tp = %x\n\tq = %x\n\td = %x\n\twant %x\n", n, alignP, alignQ, alignD, p, q, d, want)
}
}
}
}
}
}
func TestXorBytesPanic(t *testing.T) {
mustPanic(t, "subtle.XORBytes: dst too short", func() {
XORBytes(nil, make([]byte, 1), make([]byte, 1))
})
mustPanic(t, "subtle.XORBytes: dst too short", func() {
XORBytes(make([]byte, 1), make([]byte, 2), make([]byte, 3))
})
}
func BenchmarkXORBytes(b *testing.B) {
dst := make([]byte, 1<<15)
data0 := make([]byte, 1<<15)
data1 := make([]byte, 1<<15)
sizes := []int64{1 << 3, 1 << 7, 1 << 11, 1 << 15}
for _, size := range sizes {
b.Run(fmt.Sprintf("%dBytes", size), func(b *testing.B) {
s0 := data0[:size]
s1 := data1[:size]
b.SetBytes(int64(size))
for i := 0; i < b.N; i++ {
XORBytes(dst, s0, s1)
}
})
}
}
func mustPanic(t *testing.T, expected string, f func()) {
t.Helper()
defer func() {
switch msg := recover().(type) {
case nil:
t.Errorf("expected panic(%q), but did not panic", expected)
case string:
if msg != expected {
t.Errorf("expected panic(%q), but got panic(%q)", expected, msg)
}
default:
t.Errorf("expected panic(%q), but got panic(%T%v)", expected, msg, msg)
}
}()
f()
}
| go/src/crypto/subtle/xor_test.go/0 | {
"file_path": "go/src/crypto/subtle/xor_test.go",
"repo_id": "go",
"token_count": 1206
} | 219 |
// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package tls
import (
"crypto/internal/hpke"
"errors"
"strings"
"golang.org/x/crypto/cryptobyte"
)
type echCipher struct {
KDFID uint16
AEADID uint16
}
type echExtension struct {
Type uint16
Data []byte
}
type echConfig struct {
raw []byte
Version uint16
Length uint16
ConfigID uint8
KemID uint16
PublicKey []byte
SymmetricCipherSuite []echCipher
MaxNameLength uint8
PublicName []byte
Extensions []echExtension
}
var errMalformedECHConfig = errors.New("tls: malformed ECHConfigList")
// parseECHConfigList parses a draft-ietf-tls-esni-18 ECHConfigList, returning a
// slice of parsed ECHConfigs, in the same order they were parsed, or an error
// if the list is malformed.
func parseECHConfigList(data []byte) ([]echConfig, error) {
s := cryptobyte.String(data)
// Skip the length prefix
var length uint16
if !s.ReadUint16(&length) {
return nil, errMalformedECHConfig
}
if length != uint16(len(data)-2) {
return nil, errMalformedECHConfig
}
var configs []echConfig
for len(s) > 0 {
var ec echConfig
ec.raw = []byte(s)
if !s.ReadUint16(&ec.Version) {
return nil, errMalformedECHConfig
}
if !s.ReadUint16(&ec.Length) {
return nil, errMalformedECHConfig
}
if len(ec.raw) < int(ec.Length)+4 {
return nil, errMalformedECHConfig
}
ec.raw = ec.raw[:ec.Length+4]
if ec.Version != extensionEncryptedClientHello {
s.Skip(int(ec.Length))
continue
}
if !s.ReadUint8(&ec.ConfigID) {
return nil, errMalformedECHConfig
}
if !s.ReadUint16(&ec.KemID) {
return nil, errMalformedECHConfig
}
if !s.ReadUint16LengthPrefixed((*cryptobyte.String)(&ec.PublicKey)) {
return nil, errMalformedECHConfig
}
var cipherSuites cryptobyte.String
if !s.ReadUint16LengthPrefixed(&cipherSuites) {
return nil, errMalformedECHConfig
}
for !cipherSuites.Empty() {
var c echCipher
if !cipherSuites.ReadUint16(&c.KDFID) {
return nil, errMalformedECHConfig
}
if !cipherSuites.ReadUint16(&c.AEADID) {
return nil, errMalformedECHConfig
}
ec.SymmetricCipherSuite = append(ec.SymmetricCipherSuite, c)
}
if !s.ReadUint8(&ec.MaxNameLength) {
return nil, errMalformedECHConfig
}
var publicName cryptobyte.String
if !s.ReadUint8LengthPrefixed(&publicName) {
return nil, errMalformedECHConfig
}
ec.PublicName = publicName
var extensions cryptobyte.String
if !s.ReadUint16LengthPrefixed(&extensions) {
return nil, errMalformedECHConfig
}
for !extensions.Empty() {
var e echExtension
if !extensions.ReadUint16(&e.Type) {
return nil, errMalformedECHConfig
}
if !extensions.ReadUint16LengthPrefixed((*cryptobyte.String)(&e.Data)) {
return nil, errMalformedECHConfig
}
ec.Extensions = append(ec.Extensions, e)
}
configs = append(configs, ec)
}
return configs, nil
}
func pickECHConfig(list []echConfig) *echConfig {
for _, ec := range list {
if _, ok := hpke.SupportedKEMs[ec.KemID]; !ok {
continue
}
var validSCS bool
for _, cs := range ec.SymmetricCipherSuite {
if _, ok := hpke.SupportedAEADs[cs.AEADID]; !ok {
continue
}
if _, ok := hpke.SupportedKDFs[cs.KDFID]; !ok {
continue
}
validSCS = true
break
}
if !validSCS {
continue
}
if !validDNSName(string(ec.PublicName)) {
continue
}
var unsupportedExt bool
for _, ext := range ec.Extensions {
// If high order bit is set to 1 the extension is mandatory.
// Since we don't support any extensions, if we see a mandatory
// bit, we skip the config.
if ext.Type&uint16(1<<15) != 0 {
unsupportedExt = true
}
}
if unsupportedExt {
continue
}
return &ec
}
return nil
}
func pickECHCipherSuite(suites []echCipher) (echCipher, error) {
for _, s := range suites {
// NOTE: all of the supported AEADs and KDFs are fine, rather than
// imposing some sort of preference here, we just pick the first valid
// suite.
if _, ok := hpke.SupportedAEADs[s.AEADID]; !ok {
continue
}
if _, ok := hpke.SupportedKDFs[s.KDFID]; !ok {
continue
}
return s, nil
}
return echCipher{}, errors.New("tls: no supported symmetric ciphersuites for ECH")
}
func encodeInnerClientHello(inner *clientHelloMsg, maxNameLength int) ([]byte, error) {
h, err := inner.marshalMsg(true)
if err != nil {
return nil, err
}
h = h[4:] // strip four byte prefix
var paddingLen int
if inner.serverName != "" {
paddingLen = max(0, maxNameLength-len(inner.serverName))
} else {
paddingLen = maxNameLength + 9
}
paddingLen = 31 - ((len(h) + paddingLen - 1) % 32)
return append(h, make([]byte, paddingLen)...), nil
}
func generateOuterECHExt(id uint8, kdfID, aeadID uint16, encodedKey []byte, payload []byte) ([]byte, error) {
var b cryptobyte.Builder
b.AddUint8(0) // outer
b.AddUint16(kdfID)
b.AddUint16(aeadID)
b.AddUint8(id)
b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { b.AddBytes(encodedKey) })
b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { b.AddBytes(payload) })
return b.Bytes()
}
func computeAndUpdateOuterECHExtension(outer, inner *clientHelloMsg, ech *echContext, useKey bool) error {
var encapKey []byte
if useKey {
encapKey = ech.encapsulatedKey
}
encodedInner, err := encodeInnerClientHello(inner, int(ech.config.MaxNameLength))
if err != nil {
return err
}
// NOTE: the tag lengths for all of the supported AEADs are the same (16
// bytes), so we have hardcoded it here. If we add support for another AEAD
// with a different tag length, we will need to change this.
encryptedLen := len(encodedInner) + 16 // AEAD tag length
outer.encryptedClientHello, err = generateOuterECHExt(ech.config.ConfigID, ech.kdfID, ech.aeadID, encapKey, make([]byte, encryptedLen))
if err != nil {
return err
}
serializedOuter, err := outer.marshal()
if err != nil {
return err
}
serializedOuter = serializedOuter[4:] // strip the four byte prefix
encryptedInner, err := ech.hpkeContext.Seal(serializedOuter, encodedInner)
if err != nil {
return err
}
outer.encryptedClientHello, err = generateOuterECHExt(ech.config.ConfigID, ech.kdfID, ech.aeadID, encapKey, encryptedInner)
if err != nil {
return err
}
return nil
}
// validDNSName is a rather rudimentary check for the validity of a DNS name.
// This is used to check if the public_name in a ECHConfig is valid when we are
// picking a config. This can be somewhat lax because even if we pick a
// valid-looking name, the DNS layer will later reject it anyway.
func validDNSName(name string) bool {
if len(name) > 253 {
return false
}
labels := strings.Split(name, ".")
if len(labels) <= 1 {
return false
}
for _, l := range labels {
labelLen := len(l)
if labelLen == 0 {
return false
}
for i, r := range l {
if r == '-' && (i == 0 || i == labelLen-1) {
return false
}
if (r < '0' || r > '9') && (r < 'a' || r > 'z') && (r < 'A' || r > 'Z') && r != '-' {
return false
}
}
}
return true
}
// ECHRejectionError is the error type returned when ECH is rejected by a remote
// server. If the server offered a ECHConfigList to use for retries, the
// RetryConfigList field will contain this list.
//
// The client may treat an ECHRejectionError with an empty set of RetryConfigs
// as a secure signal from the server.
type ECHRejectionError struct {
RetryConfigList []byte
}
func (e *ECHRejectionError) Error() string {
return "tls: server rejected ECH"
}
| go/src/crypto/tls/ech.go/0 | {
"file_path": "go/src/crypto/tls/ech.go",
"repo_id": "go",
"token_count": 2949
} | 220 |
// Copyright 2010 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 tls
import (
"crypto"
"crypto/ecdh"
"crypto/md5"
"crypto/rsa"
"crypto/sha1"
"crypto/x509"
"errors"
"fmt"
"io"
)
// A keyAgreement implements the client and server side of a TLS 1.0–1.2 key
// agreement protocol by generating and processing key exchange messages.
type keyAgreement interface {
// On the server side, the first two methods are called in order.
// In the case that the key agreement protocol doesn't use a
// ServerKeyExchange message, generateServerKeyExchange can return nil,
// nil.
generateServerKeyExchange(*Config, *Certificate, *clientHelloMsg, *serverHelloMsg) (*serverKeyExchangeMsg, error)
processClientKeyExchange(*Config, *Certificate, *clientKeyExchangeMsg, uint16) ([]byte, error)
// On the client side, the next two methods are called in order.
// This method may not be called if the server doesn't send a
// ServerKeyExchange message.
processServerKeyExchange(*Config, *clientHelloMsg, *serverHelloMsg, *x509.Certificate, *serverKeyExchangeMsg) error
generateClientKeyExchange(*Config, *clientHelloMsg, *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error)
}
var errClientKeyExchange = errors.New("tls: invalid ClientKeyExchange message")
var errServerKeyExchange = errors.New("tls: invalid ServerKeyExchange message")
// rsaKeyAgreement implements the standard TLS key agreement where the client
// encrypts the pre-master secret to the server's public key.
type rsaKeyAgreement struct{}
func (ka rsaKeyAgreement) generateServerKeyExchange(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg) (*serverKeyExchangeMsg, error) {
return nil, nil
}
func (ka rsaKeyAgreement) processClientKeyExchange(config *Config, cert *Certificate, ckx *clientKeyExchangeMsg, version uint16) ([]byte, error) {
if len(ckx.ciphertext) < 2 {
return nil, errClientKeyExchange
}
ciphertextLen := int(ckx.ciphertext[0])<<8 | int(ckx.ciphertext[1])
if ciphertextLen != len(ckx.ciphertext)-2 {
return nil, errClientKeyExchange
}
ciphertext := ckx.ciphertext[2:]
priv, ok := cert.PrivateKey.(crypto.Decrypter)
if !ok {
return nil, errors.New("tls: certificate private key does not implement crypto.Decrypter")
}
// Perform constant time RSA PKCS #1 v1.5 decryption
preMasterSecret, err := priv.Decrypt(config.rand(), ciphertext, &rsa.PKCS1v15DecryptOptions{SessionKeyLen: 48})
if err != nil {
return nil, err
}
// We don't check the version number in the premaster secret. For one,
// by checking it, we would leak information about the validity of the
// encrypted pre-master secret. Secondly, it provides only a small
// benefit against a downgrade attack and some implementations send the
// wrong version anyway. See the discussion at the end of section
// 7.4.7.1 of RFC 4346.
return preMasterSecret, nil
}
func (ka rsaKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) error {
return errors.New("tls: unexpected ServerKeyExchange")
}
func (ka rsaKeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) {
preMasterSecret := make([]byte, 48)
preMasterSecret[0] = byte(clientHello.vers >> 8)
preMasterSecret[1] = byte(clientHello.vers)
_, err := io.ReadFull(config.rand(), preMasterSecret[2:])
if err != nil {
return nil, nil, err
}
rsaKey, ok := cert.PublicKey.(*rsa.PublicKey)
if !ok {
return nil, nil, errors.New("tls: server certificate contains incorrect key type for selected ciphersuite")
}
encrypted, err := rsa.EncryptPKCS1v15(config.rand(), rsaKey, preMasterSecret)
if err != nil {
return nil, nil, err
}
ckx := new(clientKeyExchangeMsg)
ckx.ciphertext = make([]byte, len(encrypted)+2)
ckx.ciphertext[0] = byte(len(encrypted) >> 8)
ckx.ciphertext[1] = byte(len(encrypted))
copy(ckx.ciphertext[2:], encrypted)
return preMasterSecret, ckx, nil
}
// sha1Hash calculates a SHA1 hash over the given byte slices.
func sha1Hash(slices [][]byte) []byte {
hsha1 := sha1.New()
for _, slice := range slices {
hsha1.Write(slice)
}
return hsha1.Sum(nil)
}
// md5SHA1Hash implements TLS 1.0's hybrid hash function which consists of the
// concatenation of an MD5 and SHA1 hash.
func md5SHA1Hash(slices [][]byte) []byte {
md5sha1 := make([]byte, md5.Size+sha1.Size)
hmd5 := md5.New()
for _, slice := range slices {
hmd5.Write(slice)
}
copy(md5sha1, hmd5.Sum(nil))
copy(md5sha1[md5.Size:], sha1Hash(slices))
return md5sha1
}
// hashForServerKeyExchange hashes the given slices and returns their digest
// using the given hash function (for TLS 1.2) or using a default based on
// the sigType (for earlier TLS versions). For Ed25519 signatures, which don't
// do pre-hashing, it returns the concatenation of the slices.
func hashForServerKeyExchange(sigType uint8, hashFunc crypto.Hash, version uint16, slices ...[]byte) []byte {
if sigType == signatureEd25519 {
var signed []byte
for _, slice := range slices {
signed = append(signed, slice...)
}
return signed
}
if version >= VersionTLS12 {
h := hashFunc.New()
for _, slice := range slices {
h.Write(slice)
}
digest := h.Sum(nil)
return digest
}
if sigType == signatureECDSA {
return sha1Hash(slices)
}
return md5SHA1Hash(slices)
}
// ecdheKeyAgreement implements a TLS key agreement where the server
// generates an ephemeral EC public/private key pair and signs it. The
// pre-master secret is then calculated using ECDH. The signature may
// be ECDSA, Ed25519 or RSA.
type ecdheKeyAgreement struct {
version uint16
isRSA bool
key *ecdh.PrivateKey
// ckx and preMasterSecret are generated in processServerKeyExchange
// and returned in generateClientKeyExchange.
ckx *clientKeyExchangeMsg
preMasterSecret []byte
}
func (ka *ecdheKeyAgreement) generateServerKeyExchange(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg) (*serverKeyExchangeMsg, error) {
var curveID CurveID
for _, c := range clientHello.supportedCurves {
if config.supportsCurve(ka.version, c) {
curveID = c
break
}
}
if curveID == 0 {
return nil, errors.New("tls: no supported elliptic curves offered")
}
if _, ok := curveForCurveID(curveID); !ok {
return nil, errors.New("tls: CurvePreferences includes unsupported curve")
}
key, err := generateECDHEKey(config.rand(), curveID)
if err != nil {
return nil, err
}
ka.key = key
// See RFC 4492, Section 5.4.
ecdhePublic := key.PublicKey().Bytes()
serverECDHEParams := make([]byte, 1+2+1+len(ecdhePublic))
serverECDHEParams[0] = 3 // named curve
serverECDHEParams[1] = byte(curveID >> 8)
serverECDHEParams[2] = byte(curveID)
serverECDHEParams[3] = byte(len(ecdhePublic))
copy(serverECDHEParams[4:], ecdhePublic)
priv, ok := cert.PrivateKey.(crypto.Signer)
if !ok {
return nil, fmt.Errorf("tls: certificate private key of type %T does not implement crypto.Signer", cert.PrivateKey)
}
var signatureAlgorithm SignatureScheme
var sigType uint8
var sigHash crypto.Hash
if ka.version >= VersionTLS12 {
signatureAlgorithm, err = selectSignatureScheme(ka.version, cert, clientHello.supportedSignatureAlgorithms)
if err != nil {
return nil, err
}
sigType, sigHash, err = typeAndHashFromSignatureScheme(signatureAlgorithm)
if err != nil {
return nil, err
}
} else {
sigType, sigHash, err = legacyTypeAndHashFromPublicKey(priv.Public())
if err != nil {
return nil, err
}
}
if (sigType == signaturePKCS1v15 || sigType == signatureRSAPSS) != ka.isRSA {
return nil, errors.New("tls: certificate cannot be used with the selected cipher suite")
}
signed := hashForServerKeyExchange(sigType, sigHash, ka.version, clientHello.random, hello.random, serverECDHEParams)
signOpts := crypto.SignerOpts(sigHash)
if sigType == signatureRSAPSS {
signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
}
sig, err := priv.Sign(config.rand(), signed, signOpts)
if err != nil {
return nil, errors.New("tls: failed to sign ECDHE parameters: " + err.Error())
}
skx := new(serverKeyExchangeMsg)
sigAndHashLen := 0
if ka.version >= VersionTLS12 {
sigAndHashLen = 2
}
skx.key = make([]byte, len(serverECDHEParams)+sigAndHashLen+2+len(sig))
copy(skx.key, serverECDHEParams)
k := skx.key[len(serverECDHEParams):]
if ka.version >= VersionTLS12 {
k[0] = byte(signatureAlgorithm >> 8)
k[1] = byte(signatureAlgorithm)
k = k[2:]
}
k[0] = byte(len(sig) >> 8)
k[1] = byte(len(sig))
copy(k[2:], sig)
return skx, nil
}
func (ka *ecdheKeyAgreement) processClientKeyExchange(config *Config, cert *Certificate, ckx *clientKeyExchangeMsg, version uint16) ([]byte, error) {
if len(ckx.ciphertext) == 0 || int(ckx.ciphertext[0]) != len(ckx.ciphertext)-1 {
return nil, errClientKeyExchange
}
peerKey, err := ka.key.Curve().NewPublicKey(ckx.ciphertext[1:])
if err != nil {
return nil, errClientKeyExchange
}
preMasterSecret, err := ka.key.ECDH(peerKey)
if err != nil {
return nil, errClientKeyExchange
}
return preMasterSecret, nil
}
func (ka *ecdheKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) error {
if len(skx.key) < 4 {
return errServerKeyExchange
}
if skx.key[0] != 3 { // named curve
return errors.New("tls: server selected unsupported curve")
}
curveID := CurveID(skx.key[1])<<8 | CurveID(skx.key[2])
publicLen := int(skx.key[3])
if publicLen+4 > len(skx.key) {
return errServerKeyExchange
}
serverECDHEParams := skx.key[:4+publicLen]
publicKey := serverECDHEParams[4:]
sig := skx.key[4+publicLen:]
if len(sig) < 2 {
return errServerKeyExchange
}
if _, ok := curveForCurveID(curveID); !ok {
return errors.New("tls: server selected unsupported curve")
}
key, err := generateECDHEKey(config.rand(), curveID)
if err != nil {
return err
}
ka.key = key
peerKey, err := key.Curve().NewPublicKey(publicKey)
if err != nil {
return errServerKeyExchange
}
ka.preMasterSecret, err = key.ECDH(peerKey)
if err != nil {
return errServerKeyExchange
}
ourPublicKey := key.PublicKey().Bytes()
ka.ckx = new(clientKeyExchangeMsg)
ka.ckx.ciphertext = make([]byte, 1+len(ourPublicKey))
ka.ckx.ciphertext[0] = byte(len(ourPublicKey))
copy(ka.ckx.ciphertext[1:], ourPublicKey)
var sigType uint8
var sigHash crypto.Hash
if ka.version >= VersionTLS12 {
signatureAlgorithm := SignatureScheme(sig[0])<<8 | SignatureScheme(sig[1])
sig = sig[2:]
if len(sig) < 2 {
return errServerKeyExchange
}
if !isSupportedSignatureAlgorithm(signatureAlgorithm, clientHello.supportedSignatureAlgorithms) {
return errors.New("tls: certificate used with invalid signature algorithm")
}
sigType, sigHash, err = typeAndHashFromSignatureScheme(signatureAlgorithm)
if err != nil {
return err
}
} else {
sigType, sigHash, err = legacyTypeAndHashFromPublicKey(cert.PublicKey)
if err != nil {
return err
}
}
if (sigType == signaturePKCS1v15 || sigType == signatureRSAPSS) != ka.isRSA {
return errServerKeyExchange
}
sigLen := int(sig[0])<<8 | int(sig[1])
if sigLen+2 != len(sig) {
return errServerKeyExchange
}
sig = sig[2:]
signed := hashForServerKeyExchange(sigType, sigHash, ka.version, clientHello.random, serverHello.random, serverECDHEParams)
if err := verifyHandshakeSignature(sigType, cert.PublicKey, sigHash, signed, sig); err != nil {
return errors.New("tls: invalid signature by the server certificate: " + err.Error())
}
return nil
}
func (ka *ecdheKeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) {
if ka.ckx == nil {
return nil, nil, errors.New("tls: missing ServerKeyExchange message")
}
return ka.preMasterSecret, ka.ckx, nil
}
| go/src/crypto/tls/key_agreement.go/0 | {
"file_path": "go/src/crypto/tls/key_agreement.go",
"repo_id": "go",
"token_count": 4324
} | 221 |
>>> Flow 1 (client to server)
00000000 16 03 01 00 fe 01 00 00 fa 03 03 00 00 00 00 00 |................|
00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................|
00000020 00 00 00 00 00 00 00 00 00 00 00 20 00 00 00 00 |........... ....|
00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................|
00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 32 cc a9 |.............2..|
00000050 cc a8 c0 2b c0 2f c0 2c c0 30 c0 09 c0 13 c0 0a |...+./.,.0......|
00000060 c0 14 00 9c 00 9d 00 2f 00 35 c0 12 00 0a c0 23 |......./.5.....#|
00000070 c0 27 00 3c c0 07 c0 11 00 05 13 03 13 01 13 02 |.'.<............|
00000080 01 00 00 7f 00 0b 00 02 01 00 ff 01 00 01 00 00 |................|
00000090 17 00 00 00 12 00 00 00 05 00 05 01 00 00 00 00 |................|
000000a0 00 0a 00 0a 00 08 00 1d 00 17 00 18 00 19 00 0d |................|
000000b0 00 1a 00 18 08 04 04 03 08 07 08 05 08 06 04 01 |................|
000000c0 05 01 06 01 05 03 06 03 02 01 02 03 00 2b 00 09 |.............+..|
000000d0 08 03 04 03 03 03 02 03 01 00 33 00 26 00 24 00 |..........3.&.$.|
000000e0 1d 00 20 2f e5 7d a3 47 cd 62 43 15 28 da ac 5f |.. /.}.G.bC.(.._|
000000f0 bb 29 07 30 ff f6 84 af c4 cf c2 ed 90 99 5f 58 |.).0.........._X|
00000100 cb 3b 74 |.;t|
>>> Flow 2 (server to client)
00000000 16 03 03 00 5d 02 00 00 59 03 03 6d b7 f7 cf 1d |....]...Y..m....|
00000010 f9 c0 02 cb ee 90 23 93 41 8e 26 24 3e 74 31 ce |......#.A.&$>t1.|
00000020 4f 53 f8 9d 0f 94 02 b2 66 c9 87 20 d6 5c 35 52 |OS......f.. .\5R|
00000030 4b b1 f2 bb 2e 1d 95 ff 7d 83 f0 58 a8 0a ed b1 |K.......}..X....|
00000040 54 25 03 ca ea 7b 8d 1a 8f 9f 43 51 c0 09 00 00 |T%...{....CQ....|
00000050 11 ff 01 00 01 00 00 0b 00 04 03 00 01 02 00 17 |................|
00000060 00 00 16 03 03 02 0e 0b 00 02 0a 00 02 07 00 02 |................|
00000070 04 30 82 02 00 30 82 01 62 02 09 00 b8 bf 2d 47 |.0...0..b.....-G|
00000080 a0 d2 eb f4 30 09 06 07 2a 86 48 ce 3d 04 01 30 |....0...*.H.=..0|
00000090 45 31 0b 30 09 06 03 55 04 06 13 02 41 55 31 13 |E1.0...U....AU1.|
000000a0 30 11 06 03 55 04 08 13 0a 53 6f 6d 65 2d 53 74 |0...U....Some-St|
000000b0 61 74 65 31 21 30 1f 06 03 55 04 0a 13 18 49 6e |ate1!0...U....In|
000000c0 74 65 72 6e 65 74 20 57 69 64 67 69 74 73 20 50 |ternet Widgits P|
000000d0 74 79 20 4c 74 64 30 1e 17 0d 31 32 31 31 32 32 |ty Ltd0...121122|
000000e0 31 35 30 36 33 32 5a 17 0d 32 32 31 31 32 30 31 |150632Z..2211201|
000000f0 35 30 36 33 32 5a 30 45 31 0b 30 09 06 03 55 04 |50632Z0E1.0...U.|
00000100 06 13 02 41 55 31 13 30 11 06 03 55 04 08 13 0a |...AU1.0...U....|
00000110 53 6f 6d 65 2d 53 74 61 74 65 31 21 30 1f 06 03 |Some-State1!0...|
00000120 55 04 0a 13 18 49 6e 74 65 72 6e 65 74 20 57 69 |U....Internet Wi|
00000130 64 67 69 74 73 20 50 74 79 20 4c 74 64 30 81 9b |dgits Pty Ltd0..|
00000140 30 10 06 07 2a 86 48 ce 3d 02 01 06 05 2b 81 04 |0...*.H.=....+..|
00000150 00 23 03 81 86 00 04 00 c4 a1 ed be 98 f9 0b 48 |.#.............H|
00000160 73 36 7e c3 16 56 11 22 f2 3d 53 c3 3b 4d 21 3d |s6~..V.".=S.;M!=|
00000170 cd 6b 75 e6 f6 b0 dc 9a df 26 c1 bc b2 87 f0 72 |.ku......&.....r|
00000180 32 7c b3 64 2f 1c 90 bc ea 68 23 10 7e fe e3 25 |2|.d/....h#.~..%|
00000190 c0 48 3a 69 e0 28 6d d3 37 00 ef 04 62 dd 0d a0 |.H:i.(m.7...b...|
000001a0 9c 70 62 83 d8 81 d3 64 31 aa 9e 97 31 bd 96 b0 |.pb....d1...1...|
000001b0 68 c0 9b 23 de 76 64 3f 1a 5c 7f e9 12 0e 58 58 |h..#.vd?.\....XX|
000001c0 b6 5f 70 dd 9b d8 ea d5 d7 f5 d5 cc b9 b6 9f 30 |._p............0|
000001d0 66 5b 66 9a 20 e2 27 e5 bf fe 3b 30 09 06 07 2a |f[f. .'...;0...*|
000001e0 86 48 ce 3d 04 01 03 81 8c 00 30 81 88 02 42 01 |.H.=......0...B.|
000001f0 88 a2 4f eb e2 45 c5 48 7d 1b ac f5 ed 98 9d ae |..O..E.H}.......|
00000200 47 70 c0 5e 1b b6 2f bd f1 b6 4d b7 61 40 d3 11 |Gp.^../...M.a@..|
00000210 a2 ce ee 0b 7e 92 7e ff 76 9d c3 3b 7e a5 3f ce |....~.~.v..;~.?.|
00000220 fa 10 e2 59 ec 47 2d 7c ac da 4e 97 0e 15 a0 6f |...Y.G-|..N....o|
00000230 d0 02 42 01 4d fc be 67 13 9c 2d 05 0e bd 3f a3 |..B.M..g..-...?.|
00000240 8c 25 c1 33 13 83 0d 94 06 bb d4 37 7a f6 ec 7a |.%.3.......7z..z|
00000250 c9 86 2e dd d7 11 69 7f 85 7c 56 de fb 31 78 2b |......i..|V..1x+|
00000260 e4 c7 78 0d ae cb be 9e 4e 36 24 31 7b 6a 0f 39 |..x.....N6$1{j.9|
00000270 95 12 07 8f 2a 16 03 03 00 b6 0c 00 00 b2 03 00 |....*...........|
00000280 1d 20 04 b4 79 b4 2c 1d 0f b3 4b ff 67 e7 24 88 |. ..y.,...K.g.$.|
00000290 d6 db 4f 1e 66 da 0e f2 89 5a 53 ed 4e ba ad 4c |..O.f....ZS.N..L|
000002a0 81 0a 04 03 00 8a 30 81 87 02 42 01 fb 16 53 43 |......0...B...SC|
000002b0 2b 86 61 0a 58 a0 68 c1 cd 2c ff ec 79 7f 83 fa |+.a.X.h..,..y...|
000002c0 cc 0b 24 9d 98 54 d0 dc 90 55 e1 b3 e6 48 69 1a |..$..T...U...Hi.|
000002d0 55 62 f4 da 8f 60 db f7 76 80 d5 4d 37 f6 43 49 |Ub...`..v..M7.CI|
000002e0 95 3d 96 f6 e2 fd a4 07 ae 24 8c fa bd 02 41 20 |.=.......$....A |
000002f0 a1 50 78 a3 dd 99 c0 cf 74 f1 c0 79 b1 13 9d bc |.Px.....t..y....|
00000300 0b 37 cf 7c 09 11 b8 a4 71 65 e8 be ff 3a b9 85 |.7.|....qe...:..|
00000310 cd b4 30 f8 1f d6 2e 83 96 6c 01 3e d2 00 a7 5b |..0......l.>...[|
00000320 23 c6 d0 69 eb 90 49 e3 46 ed 45 96 3b 07 d4 a8 |#..i..I.F.E.;...|
00000330 16 03 03 00 3a 0d 00 00 36 03 01 02 40 00 2e 04 |....:...6...@...|
00000340 03 05 03 06 03 08 07 08 08 08 09 08 0a 08 0b 08 |................|
00000350 04 08 05 08 06 04 01 05 01 06 01 03 03 02 03 03 |................|
00000360 01 02 01 03 02 02 02 04 02 05 02 06 02 00 00 16 |................|
00000370 03 03 00 04 0e 00 00 00 |........|
>>> Flow 3 (client to server)
00000000 16 03 03 01 fd 0b 00 01 f9 00 01 f6 00 01 f3 30 |...............0|
00000010 82 01 ef 30 82 01 58 a0 03 02 01 02 02 10 5c 19 |...0..X.......\.|
00000020 c1 89 65 83 55 6f dc 0b c9 b9 93 9f e9 bc 30 0d |..e.Uo........0.|
00000030 06 09 2a 86 48 86 f7 0d 01 01 0b 05 00 30 12 31 |..*.H........0.1|
00000040 10 30 0e 06 03 55 04 0a 13 07 41 63 6d 65 20 43 |.0...U....Acme C|
00000050 6f 30 1e 17 0d 31 36 30 38 31 37 32 31 35 32 33 |o0...16081721523|
00000060 31 5a 17 0d 31 37 30 38 31 37 32 31 35 32 33 31 |1Z..170817215231|
00000070 5a 30 12 31 10 30 0e 06 03 55 04 0a 13 07 41 63 |Z0.1.0...U....Ac|
00000080 6d 65 20 43 6f 30 81 9f 30 0d 06 09 2a 86 48 86 |me Co0..0...*.H.|
00000090 f7 0d 01 01 01 05 00 03 81 8d 00 30 81 89 02 81 |...........0....|
000000a0 81 00 ba 6f aa 86 bd cf bf 9f f2 ef 5c 94 60 78 |...o........\.`x|
000000b0 6f e8 13 f2 d1 96 6f cd d9 32 6e 22 37 ce 41 f9 |o.....o..2n"7.A.|
000000c0 ca 5d 29 ac e1 27 da 61 a2 ee 81 cb 10 c7 df 34 |.])..'.a.......4|
000000d0 58 95 86 e9 3d 19 e6 5c 27 73 60 c8 8d 78 02 f4 |X...=..\'s`..x..|
000000e0 1d a4 98 09 a3 19 70 69 3c 25 62 66 2a ab 22 23 |......pi<%bf*."#|
000000f0 c5 7b 85 38 4f 2e 09 73 32 a7 bd 3e 9b ad ca 84 |.{.8O..s2..>....|
00000100 07 e6 0f 3a ff 77 c5 9d 41 85 00 8a b6 9b ee b0 |...:.w..A.......|
00000110 a4 3f 2d 4c 4c e6 42 3e bb 51 c8 dd 48 54 f4 0c |.?-LL.B>.Q..HT..|
00000120 8e 47 02 03 01 00 01 a3 46 30 44 30 0e 06 03 55 |.G......F0D0...U|
00000130 1d 0f 01 01 ff 04 04 03 02 05 a0 30 13 06 03 55 |...........0...U|
00000140 1d 25 04 0c 30 0a 06 08 2b 06 01 05 05 07 03 01 |.%..0...+.......|
00000150 30 0c 06 03 55 1d 13 01 01 ff 04 02 30 00 30 0f |0...U.......0.0.|
00000160 06 03 55 1d 11 04 08 30 06 87 04 7f 00 00 01 30 |..U....0.......0|
00000170 0d 06 09 2a 86 48 86 f7 0d 01 01 0b 05 00 03 81 |...*.H..........|
00000180 81 00 46 ab 44 a2 fb 28 54 f8 5a 67 f8 62 94 f1 |..F.D..(T.Zg.b..|
00000190 9a b2 18 9e f2 b1 de 1d 7e 6f 76 95 a9 ba e7 5d |........~ov....]|
000001a0 a8 16 6c 9c f7 09 d3 37 e4 4b 2b 36 7c 01 ad 41 |..l....7.K+6|..A|
000001b0 d2 32 d8 c3 d2 93 f9 10 6b 8e 95 b9 2c 17 8a a3 |.2......k...,...|
000001c0 44 48 bc 59 13 83 16 04 88 a4 81 5c 25 0d 98 0c |DH.Y.......\%...|
000001d0 ac 11 b1 28 56 be 1d cd 61 62 84 09 bf d6 80 c6 |...(V...ab......|
000001e0 45 8d 82 2c b4 d8 83 9b db c9 22 b7 2a 12 11 7b |E..,......".*..{|
000001f0 fa 02 3b c1 c9 ff ea c9 9d a8 49 d3 95 d7 d5 0e |..;.......I.....|
00000200 e5 35 16 03 03 00 25 10 00 00 21 20 2f e5 7d a3 |.5....%...! /.}.|
00000210 47 cd 62 43 15 28 da ac 5f bb 29 07 30 ff f6 84 |G.bC.(.._.).0...|
00000220 af c4 cf c2 ed 90 99 5f 58 cb 3b 74 16 03 03 00 |......._X.;t....|
00000230 88 0f 00 00 84 08 04 00 80 3f 4a c2 4f 36 85 f0 |.........?J.O6..|
00000240 d0 c6 b6 8f f1 cc 45 c1 2f f2 c7 24 1e 0f 04 dc |......E./..$....|
00000250 f5 af 6e 38 eb aa a6 6f 36 f4 80 dd 78 78 a7 d4 |..n8...o6...xx..|
00000260 50 3a df e1 23 c4 3f 58 df 1a c0 1d 57 a5 46 3b |P:..#.?X....W.F;|
00000270 5d 09 ac 62 63 28 8a a2 b5 d4 9b 88 7c b9 4d b4 |]..bc(......|.M.|
00000280 66 b2 9d 53 6e 15 9c f2 9b c7 14 ca 19 7f 00 38 |f..Sn..........8|
00000290 81 a3 7b 44 e8 3d 6d 54 0f b3 81 fd 82 07 4d a1 |..{D.=mT......M.|
000002a0 3e 8c 30 34 cd 6e 55 96 58 bf 86 8b 9c f6 be 94 |>.04.nU.X.......|
000002b0 f4 a8 7e 4d 7f 03 07 7e 98 14 03 03 00 01 01 16 |..~M...~........|
000002c0 03 03 00 40 00 00 00 00 00 00 00 00 00 00 00 00 |...@............|
000002d0 00 00 00 00 c7 88 1e 15 dd 36 31 22 0f 30 d1 4d |.........61".0.M|
000002e0 40 2e 3a dd 05 cc fd a8 d2 ea f8 d9 79 1d 07 46 |@.:.........y..F|
000002f0 2c 80 ab ab 54 3c 10 5a a7 79 d2 1c 16 18 94 eb |,...T<.Z.y......|
00000300 46 69 cc 03 |Fi..|
>>> Flow 4 (server to client)
00000000 14 03 03 00 01 01 16 03 03 00 40 9e 65 27 5b 92 |..........@.e'[.|
00000010 1e 2b 1a bc 81 ab 85 29 51 c1 38 04 b6 97 e5 4b |.+.....)Q.8....K|
00000020 b1 7d a5 e2 6d e7 b1 1a 33 6c f1 3d a4 9c de 2d |.}..m...3l.=...-|
00000030 b3 8a 01 da cc f1 d7 83 b1 1e 84 cb b7 e7 fe e6 |................|
00000040 26 83 b0 2d 6f a9 77 46 55 44 7a |&..-o.wFUDz|
>>> Flow 5 (client to server)
00000000 17 03 03 00 30 00 00 00 00 00 00 00 00 00 00 00 |....0...........|
00000010 00 00 00 00 00 e2 55 06 b8 6f 63 c4 63 78 76 4b |......U..oc.cxvK|
00000020 c8 63 8b 4b c6 11 2c ff dc fc 20 f7 52 fe fa 5f |.c.K..,... .R.._|
00000030 e3 45 3a f2 a1 15 03 03 00 30 00 00 00 00 00 00 |.E:......0......|
00000040 00 00 00 00 00 00 00 00 00 00 0e cb 88 2f 1f be |............./..|
00000050 9c 76 4d db 75 7f eb 01 ae bd 76 28 07 41 49 6c |.vM.u.....v(.AIl|
00000060 4c 82 84 d5 fc d3 75 f4 4b 81 |L.....u.K.|
| go/src/crypto/tls/testdata/Client-TLSv12-ClientCert-RSA-ECDSA/0 | {
"file_path": "go/src/crypto/tls/testdata/Client-TLSv12-ClientCert-RSA-ECDSA",
"repo_id": "go",
"token_count": 5090
} | 222 |
>>> Flow 1 (client to server)
00000000 16 03 01 00 fe 01 00 00 fa 03 03 00 00 00 00 00 |................|
00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................|
00000020 00 00 00 00 00 00 00 00 00 00 00 20 00 00 00 00 |........... ....|
00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................|
00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 32 cc a9 |.............2..|
00000050 cc a8 c0 2b c0 2f c0 2c c0 30 c0 09 c0 13 c0 0a |...+./.,.0......|
00000060 c0 14 00 9c 00 9d 00 2f 00 35 c0 12 00 0a c0 23 |......./.5.....#|
00000070 c0 27 00 3c c0 07 c0 11 00 05 13 03 13 01 13 02 |.'.<............|
00000080 01 00 00 7f 00 0b 00 02 01 00 ff 01 00 01 00 00 |................|
00000090 17 00 00 00 12 00 00 00 05 00 05 01 00 00 00 00 |................|
000000a0 00 0a 00 0a 00 08 00 1d 00 17 00 18 00 19 00 0d |................|
000000b0 00 1a 00 18 08 04 04 03 08 07 08 05 08 06 04 01 |................|
000000c0 05 01 06 01 05 03 06 03 02 01 02 03 00 2b 00 09 |.............+..|
000000d0 08 03 04 03 03 03 02 03 01 00 33 00 26 00 24 00 |..........3.&.$.|
000000e0 1d 00 20 2f e5 7d a3 47 cd 62 43 15 28 da ac 5f |.. /.}.G.bC.(.._|
000000f0 bb 29 07 30 ff f6 84 af c4 cf c2 ed 90 99 5f 58 |.).0.........._X|
00000100 cb 3b 74 |.;t|
>>> Flow 2 (server to client)
00000000 16 03 03 00 5d 02 00 00 59 03 03 55 71 df 37 76 |....]...Y..Uq.7v|
00000010 48 bb 86 62 66 f1 58 0d 92 f4 c8 bd 17 6c 00 43 |H..bf.X......l.C|
00000020 a9 da f1 6f 19 2c 76 81 6d aa eb 20 4f c7 eb 3f |...o.,v.m.. O..?|
00000030 b8 48 89 7f d8 61 bc e8 3c e6 a0 3d 6c 29 fd 60 |.H...a..<..=l).`|
00000040 7c 0a 09 1c 71 41 07 04 24 dc e7 27 cc a8 00 00 ||...qA..$..'....|
00000050 11 ff 01 00 01 00 00 0b 00 04 03 00 01 02 00 17 |................|
00000060 00 00 16 03 03 02 59 0b 00 02 55 00 02 52 00 02 |......Y...U..R..|
00000070 4f 30 82 02 4b 30 82 01 b4 a0 03 02 01 02 02 09 |O0..K0..........|
00000080 00 e8 f0 9d 3f e2 5b ea a6 30 0d 06 09 2a 86 48 |....?.[..0...*.H|
00000090 86 f7 0d 01 01 0b 05 00 30 1f 31 0b 30 09 06 03 |........0.1.0...|
000000a0 55 04 0a 13 02 47 6f 31 10 30 0e 06 03 55 04 03 |U....Go1.0...U..|
000000b0 13 07 47 6f 20 52 6f 6f 74 30 1e 17 0d 31 36 30 |..Go Root0...160|
000000c0 31 30 31 30 30 30 30 30 30 5a 17 0d 32 35 30 31 |101000000Z..2501|
000000d0 30 31 30 30 30 30 30 30 5a 30 1a 31 0b 30 09 06 |01000000Z0.1.0..|
000000e0 03 55 04 0a 13 02 47 6f 31 0b 30 09 06 03 55 04 |.U....Go1.0...U.|
000000f0 03 13 02 47 6f 30 81 9f 30 0d 06 09 2a 86 48 86 |...Go0..0...*.H.|
00000100 f7 0d 01 01 01 05 00 03 81 8d 00 30 81 89 02 81 |...........0....|
00000110 81 00 db 46 7d 93 2e 12 27 06 48 bc 06 28 21 ab |...F}...'.H..(!.|
00000120 7e c4 b6 a2 5d fe 1e 52 45 88 7a 36 47 a5 08 0d |~...]..RE.z6G...|
00000130 92 42 5b c2 81 c0 be 97 79 98 40 fb 4f 6d 14 fd |.B[.....y.@.Om..|
00000140 2b 13 8b c2 a5 2e 67 d8 d4 09 9e d6 22 38 b7 4a |+.....g....."8.J|
00000150 0b 74 73 2b c2 34 f1 d1 93 e5 96 d9 74 7b f3 58 |.ts+.4......t{.X|
00000160 9f 6c 61 3c c0 b0 41 d4 d9 2b 2b 24 23 77 5b 1c |.la<..A..++$#w[.|
00000170 3b bd 75 5d ce 20 54 cf a1 63 87 1d 1e 24 c4 f3 |;.u]. T..c...$..|
00000180 1d 1a 50 8b aa b6 14 43 ed 97 a7 75 62 f4 14 c8 |..P....C...ub...|
00000190 52 d7 02 03 01 00 01 a3 81 93 30 81 90 30 0e 06 |R.........0..0..|
000001a0 03 55 1d 0f 01 01 ff 04 04 03 02 05 a0 30 1d 06 |.U...........0..|
000001b0 03 55 1d 25 04 16 30 14 06 08 2b 06 01 05 05 07 |.U.%..0...+.....|
000001c0 03 01 06 08 2b 06 01 05 05 07 03 02 30 0c 06 03 |....+.......0...|
000001d0 55 1d 13 01 01 ff 04 02 30 00 30 19 06 03 55 1d |U.......0.0...U.|
000001e0 0e 04 12 04 10 9f 91 16 1f 43 43 3e 49 a6 de 6d |.........CC>I..m|
000001f0 b6 80 d7 9f 60 30 1b 06 03 55 1d 23 04 14 30 12 |....`0...U.#..0.|
00000200 80 10 48 13 49 4d 13 7e 16 31 bb a3 01 d5 ac ab |..H.IM.~.1......|
00000210 6e 7b 30 19 06 03 55 1d 11 04 12 30 10 82 0e 65 |n{0...U....0...e|
00000220 78 61 6d 70 6c 65 2e 67 6f 6c 61 6e 67 30 0d 06 |xample.golang0..|
00000230 09 2a 86 48 86 f7 0d 01 01 0b 05 00 03 81 81 00 |.*.H............|
00000240 9d 30 cc 40 2b 5b 50 a0 61 cb ba e5 53 58 e1 ed |.0.@+[P.a...SX..|
00000250 83 28 a9 58 1a a9 38 a4 95 a1 ac 31 5a 1a 84 66 |.(.X..8....1Z..f|
00000260 3d 43 d3 2d d9 0b f2 97 df d3 20 64 38 92 24 3a |=C.-...... d8.$:|
00000270 00 bc cf 9c 7d b7 40 20 01 5f aa d3 16 61 09 a2 |....}.@ ._...a..|
00000280 76 fd 13 c3 cc e1 0c 5c ee b1 87 82 f1 6c 04 ed |v......\.....l..|
00000290 73 bb b3 43 77 8d 0c 1c f1 0f a1 d8 40 83 61 c9 |s..Cw.......@.a.|
000002a0 4c 72 2b 9d ae db 46 06 06 4d f4 c1 b3 3e c0 d1 |Lr+...F..M...>..|
000002b0 bd 42 d4 db fe 3d 13 60 84 5c 21 d3 3b e9 fa e7 |.B...=.`.\!.;...|
000002c0 16 03 03 00 ac 0c 00 00 a8 03 00 1d 20 7a 15 23 |............ z.#|
000002d0 f5 78 c2 16 21 72 bb e5 d3 2e c9 67 55 a8 2c 1f |.x..!r.....gU.,.|
000002e0 00 50 a2 04 4f 71 9a 94 4a 90 55 69 33 08 04 00 |.P..Oq..J.Ui3...|
000002f0 80 53 b3 16 f5 08 3a 5a 84 3c 02 5d c3 b6 0e c2 |.S....:Z.<.]....|
00000300 93 f6 27 74 24 b4 e2 3d 22 04 30 a0 d6 5b c8 da |..'t$..=".0..[..|
00000310 6e 56 30 d4 fb 86 fd 76 8f 1b 47 c0 55 95 cd 15 |nV0....v..G.U...|
00000320 bf a7 27 ce 2d c3 43 6b ed 2d 09 bb eb 55 73 c9 |..'.-.Ck.-...Us.|
00000330 2c ee cd 23 af d9 1c 51 1d 0c 00 14 01 61 8a fd |,..#...Q.....a..|
00000340 8f 95 d1 ce 32 57 ae 2b 09 15 b4 86 41 1e 74 f5 |....2W.+....A.t.|
00000350 d5 96 d7 e1 03 03 09 f4 3c 53 fe 6b 9a c1 52 ab |........<S.k..R.|
00000360 91 81 9f f8 f9 6b 23 60 49 22 6b 28 10 e2 6b e8 |.....k#`I"k(..k.|
00000370 e4 16 03 03 00 04 0e 00 00 00 |..........|
>>> Flow 3 (client to server)
00000000 16 03 03 00 25 10 00 00 21 20 2f e5 7d a3 47 cd |....%...! /.}.G.|
00000010 62 43 15 28 da ac 5f bb 29 07 30 ff f6 84 af c4 |bC.(.._.).0.....|
00000020 cf c2 ed 90 99 5f 58 cb 3b 74 14 03 03 00 01 01 |....._X.;t......|
00000030 16 03 03 00 20 bf 35 ae 8c b4 63 82 40 e8 5d d4 |.... .5...c.@.].|
00000040 bb 3d 0a 0f 07 28 3a 74 2c 5b a8 d0 a6 ab 88 ba |.=...(:t,[......|
00000050 7d 5c 1c 42 c7 |}\.B.|
>>> Flow 4 (server to client)
00000000 14 03 03 00 01 01 16 03 03 00 20 e7 86 48 6c 00 |.......... ..Hl.|
00000010 0a 1e f5 5f b8 ff ad 1c 9d 74 24 c5 6e d4 c6 6e |..._.....t$.n..n|
00000020 25 27 7d 6e 18 44 96 29 eb db b0 |%'}n.D.)...|
>>> Flow 5 (client to server)
00000000 17 03 03 00 16 64 9d 31 09 a1 ce 5a 6d ec 6f c4 |.....d.1...Zm.o.|
00000010 e5 09 df 92 5f d2 1c 7d 62 c4 e7 |...._..}b..|
>>> Flow 6 (server to client)
00000000 16 03 03 00 14 9b cb 75 61 99 76 30 9c 14 a5 12 |.......ua.v0....|
00000010 92 de b7 95 cc 8f fe ad f1 |.........|
>>> Flow 7 (client to server)
00000000 16 03 03 01 1a c7 9a be e1 2a 62 9f 01 59 e9 6a |.........*b..Y.j|
00000010 5f d6 32 88 bd 39 76 1b 34 fd 39 8d c7 31 cb 97 |_.2..9v.4.9..1..|
00000020 c6 09 8b 00 c9 f3 f9 00 c5 b6 48 e1 28 ae b8 8b |..........H.(...|
00000030 b2 f0 eb 8b cb e8 68 30 50 b5 23 ba cf f3 8d f3 |......h0P.#.....|
00000040 47 5f 94 ac fb 5e 56 9e 5a f8 e7 12 60 13 83 9c |G_...^V.Z...`...|
00000050 34 ca 45 a7 63 5f 2c 6e 46 c8 5a a0 d3 5b 9a a6 |4.E.c_,nF.Z..[..|
00000060 70 be da df 9e 79 21 98 bd fb 94 01 6d 14 f4 5c |p....y!.....m..\|
00000070 2a 13 56 26 47 33 7d 4f ab 5a fc 9c 9e 8d f4 75 |*.V&G3}O.Z.....u|
00000080 d0 64 16 ba f2 0d 04 ca 5d 94 6b da a8 09 b1 29 |.d......].k....)|
00000090 70 a9 37 1e ac 94 e3 81 60 c3 19 f3 a9 99 6a 11 |p.7.....`.....j.|
000000a0 b1 e7 23 45 8a f5 42 f5 50 76 9f 1e 9e a8 e7 75 |..#E..B.Pv.....u|
000000b0 4a 18 84 80 da 10 ed 83 9a 14 a9 a1 90 54 8e 8b |J............T..|
000000c0 d1 32 83 6d e7 7e be 59 f4 66 59 53 75 37 c6 82 |.2.m.~.Y.fYSu7..|
000000d0 15 aa 56 0a 01 e1 11 ba 64 0c 8e 44 93 60 29 a4 |..V.....d..D.`).|
000000e0 cc 9f b0 b9 d5 df 9c aa 64 2c ef 0c 9a 18 2a 97 |........d,....*.|
000000f0 e1 20 07 37 35 28 97 9d 00 53 61 11 81 22 45 9e |. .75(...Sa.."E.|
00000100 c3 d7 b2 b3 4c f2 05 5b e6 a4 de 11 7f a7 a2 82 |....L..[........|
00000110 88 1c cb d9 24 80 3d 34 0c fc 22 58 32 28 1b |....$.=4.."X2(.|
>>> Flow 8 (server to client)
00000000 16 03 03 00 85 ba 55 5d 15 b8 6d 8a b6 82 a8 e1 |......U]..m.....|
00000010 88 ea fe c0 a6 a8 fe 78 ed 8b ae 44 eb 7b 6c cc |.......x...D.{l.|
00000020 0f ad a1 da da 86 fb 60 07 4a 0e 5c ba 36 09 8b |.......`.J.\.6..|
00000030 95 3f f0 87 26 0f 7a e7 7c 1f af c7 67 42 c9 39 |.?..&.z.|...gB.9|
00000040 39 6a 4d 8d 87 00 3b 14 76 4a 86 87 46 1e d4 04 |9jM...;.vJ..F...|
00000050 2d ea c1 44 1f e8 87 71 da 1e 26 72 a2 e9 40 0c |-..D...q..&r..@.|
00000060 33 6e 6f 06 43 ed 7f fc 8f 4c d4 f4 0f 83 19 cb |3no.C....L......|
00000070 52 a9 94 f3 6a 64 db dd 20 d1 a7 d4 c7 6e 86 ed |R...jd.. ....n..|
00000080 6e ea 5c 66 d1 34 a6 92 7e b1 16 03 03 02 69 48 |n.\f.4..~.....iH|
00000090 13 97 82 60 46 e1 c9 02 d2 e1 f3 62 da d6 3a c1 |...`F......b..:.|
000000a0 2a a7 47 bd c2 ee 09 d5 2d 7e 5e 35 09 79 88 35 |*.G.....-~^5.y.5|
000000b0 96 50 09 68 79 e9 de e1 71 97 11 60 c5 4e 84 54 |.P.hy...q..`.N.T|
000000c0 03 78 69 84 e3 7f 02 1a 58 04 ed 53 47 01 b6 9e |.xi.....X..SG...|
000000d0 bd 5f 77 34 e7 52 3b 73 45 e1 10 3f c8 6e 4c 09 |._w4.R;sE..?.nL.|
000000e0 d0 4b 79 f8 de 0f 15 e7 2d 42 5d 7a 89 80 1f fb |.Ky.....-B]z....|
000000f0 f9 02 6f a1 72 d4 8d 65 8e d0 a8 43 41 4c 48 57 |..o.r..e...CALHW|
00000100 71 21 b3 14 45 e5 b1 f5 55 7a dd 89 c3 0f af 27 |q!..E...Uz.....'|
00000110 03 d6 5c 2d bc 24 5b 51 fa ae 34 7b f9 56 e8 41 |..\-.$[Q..4{.V.A|
00000120 cd 77 1c 3d c8 45 f5 a5 4a 97 92 ff bb cd 5b ff |.w.=.E..J.....[.|
00000130 d5 33 d6 02 9b 2a 5a 3a e4 1b fb 48 34 b3 0b ce |.3...*Z:...H4...|
00000140 d7 34 5c 4a b4 4b bd 87 b6 72 40 ab 29 b0 65 25 |.4\J.K...r@.).e%|
00000150 c7 1d 71 b6 e2 d7 b1 23 b1 96 a6 bd 74 eb ad 69 |..q....#....t..i|
00000160 59 0c 0f af 8a 64 be e4 a7 27 c2 95 11 05 55 a1 |Y....d...'....U.|
00000170 d6 44 df ad 1d 9c 3a 88 24 52 52 9d 42 f2 74 98 |.D....:.$RR.B.t.|
00000180 08 9f 55 1b 2f 79 ca b4 63 38 e4 f2 fa 99 ce 66 |..U./y..c8.....f|
00000190 77 ac 8d 31 91 05 1c bc 51 0a 31 df 5d 3e f8 69 |w..1....Q.1.]>.i|
000001a0 b7 fa f2 35 af 57 6d 7b c3 bf 1d 98 21 40 dd 02 |...5.Wm{....!@..|
000001b0 1c de ac 02 40 c8 d6 04 23 30 71 16 d0 0a 26 29 |....@...#0q...&)|
000001c0 66 e9 f1 a8 76 f8 52 18 3e 3f c5 66 c9 11 04 6c |f...v.R.>?.f...l|
000001d0 32 1b 35 cc 9a 34 70 07 da db 12 51 78 77 dc bc |2.5..4p....Qxw..|
000001e0 7a bb b8 b9 06 79 bb 04 dd d4 46 8e b5 69 d5 39 |z....y....F..i.9|
000001f0 5e 34 8e 37 dd a2 3e 31 be 28 19 45 21 76 5b dc |^4.7..>1.(.E!v[.|
00000200 7d 25 a2 41 98 16 1b 5b 69 f0 90 f9 28 a8 e9 b5 |}%.A...[i...(...|
00000210 6f 00 e3 3e eb f6 f3 e4 c9 0f bb 74 ce 40 23 df |o..>.......t.@#.|
00000220 12 c6 78 b0 2e bb 68 96 04 a3 e3 43 6b 4b c3 37 |..x...h....CkK.7|
00000230 6d 97 c6 79 1a ff 4f 00 c7 76 64 5c b8 b3 17 20 |m..y..O..vd\... |
00000240 3c 3e 6b d5 2b 72 88 11 73 1e 63 a7 6f 1e ae 83 |<>k.+r..s.c.o...|
00000250 10 77 6f d1 96 86 84 63 fd 27 8e b9 54 da 4b b5 |.wo....c.'..T.K.|
00000260 56 f0 50 8a aa c7 e1 b3 cb 9c 36 9e ec 38 31 39 |V.P.......6..819|
00000270 78 ec ea 34 8a 87 cf 6b 34 fd 5e 81 92 81 61 f1 |x..4...k4.^...a.|
00000280 88 e7 50 62 2e 58 0b d9 b9 ca f3 ed 79 a9 9a 01 |..Pb.X......y...|
00000290 80 9d 7f 84 ae de fb 51 ac 0f 6b b9 76 fd 68 d4 |.......Q..k.v.h.|
000002a0 f4 8d c3 92 6b 5e 9e 99 ff 7a f4 b7 0e ec 0d e7 |....k^...z......|
000002b0 6b 24 75 fb 21 49 6f 5b 31 12 f2 88 8e 3b b4 34 |k$u.!Io[1....;.4|
000002c0 f2 f7 c6 e7 48 0e d6 1d 81 11 32 16 01 cb b7 7f |....H.....2.....|
000002d0 a6 bd 9c 87 8c 0f 12 b2 dc 73 5d a0 46 fd f3 e8 |.........s].F...|
000002e0 b8 6f e4 38 ab 94 96 a8 bd ed 90 0e 31 1f fc 2f |.o.8........1../|
000002f0 8f 50 e2 97 6a f5 5c b4 16 03 03 00 bc 65 bb 7c |.P..j.\......e.||
00000300 42 03 0d 42 46 e3 ac 9f 8a 96 b6 a3 f4 cf a5 30 |B..BF..........0|
00000310 5b 02 17 dc 20 7d 18 19 21 a4 70 f4 4b 99 bf b5 |[... }..!.p.K...|
00000320 cd d7 07 59 a5 82 ed 85 03 06 5c 34 3f c8 c3 4d |...Y......\4?..M|
00000330 c3 fb 96 05 bf b5 bd bf e2 28 07 7e 51 a6 84 90 |.........(.~Q...|
00000340 bf 9e 2e f6 b5 04 8e 06 7a 63 c8 00 84 a1 a3 2c |........zc.....,|
00000350 f3 6f 52 52 c4 ce 4a 59 31 1f d4 ab 2e f4 75 90 |.oRR..JY1.....u.|
00000360 a5 3b ff ab 20 be 51 92 c5 f4 4d 8b f2 2a a7 ff |.;.. .Q...M..*..|
00000370 90 07 40 3e d6 9c cf 23 54 d1 65 d3 74 79 af 51 |..@>...#T.e.ty.Q|
00000380 31 35 40 aa 29 42 32 7e 42 2d af 79 e8 59 6a 10 |15@.)B2~B-.y.Yj.|
00000390 c5 55 6b 70 53 53 ab 02 48 ba 1f df 07 59 f8 34 |.UkpSS..H....Y.4|
000003a0 ee 1d d3 e9 12 86 8b 37 2b cc 27 78 fe e1 65 2b |.......7+.'x..e+|
000003b0 c3 1e f2 25 a4 6d 3c b1 d4 16 03 03 00 4a 50 98 |...%.m<......JP.|
000003c0 cd ee ab 2c 94 95 d6 46 06 ef 63 65 5c aa 6d 6e |...,...F..ce\.mn|
000003d0 fb a0 99 62 23 af 7a 7d 17 dc a3 c6 2b 9a 56 2e |...b#.z}....+.V.|
000003e0 b8 60 87 1e 88 5d 58 27 3f 02 b4 f5 2f 3b 17 8c |.`...]X'?.../;..|
000003f0 f9 93 0c a9 58 af 11 ed 27 9d af a5 0a 2b d6 55 |....X...'....+.U|
00000400 7e c4 54 4a 36 51 b7 7b 16 03 03 00 14 c1 c4 d7 |~.TJ6Q.{........|
00000410 ea 2d f0 8c 54 0e 19 33 e1 7e a8 ae 49 7c 5e 05 |.-..T..3.~..I|^.|
00000420 23 |#|
>>> Flow 9 (client to server)
00000000 16 03 03 02 69 83 ef 87 6b aa f1 2a cc c1 b8 5d |....i...k..*...]|
00000010 47 e4 2d da c5 91 62 e4 7d 49 da 54 a3 79 fb 1d |G.-...b.}I.T.y..|
00000020 59 49 e8 a6 ab 79 c0 9f 51 f9 d2 63 0d 8c 6b 7f |YI...y..Q..c..k.|
00000030 b6 77 2d f3 b3 3e 78 86 3a 14 1a ab 3b 5e 23 b2 |.w-..>x.:...;^#.|
00000040 d3 5c b1 2b 5c f4 f0 9d e2 87 08 d0 2f 24 30 d3 |.\.+\......./$0.|
00000050 05 eb f8 a6 b2 d1 52 00 c3 9e 0b 82 34 3e fd 5a |......R.....4>.Z|
00000060 46 d5 b6 b2 f0 a0 96 11 e1 35 c2 32 57 d6 dd b2 |F........5.2W...|
00000070 a8 ad b2 71 a2 6f 83 05 d6 f1 83 38 a0 3c 13 ff |...q.o.....8.<..|
00000080 c1 c1 b0 1e b5 40 5b b5 05 31 65 0b 81 a6 b0 37 |.....@[..1e....7|
00000090 7d 16 3b 7b cb e7 58 7f 81 25 e3 39 37 98 87 b0 |}.;{..X..%.97...|
000000a0 e1 8f c0 d5 de 33 fe de 15 37 41 25 d8 97 5d 84 |.....3...7A%..].|
000000b0 28 12 b4 a5 b0 15 f1 f4 cf 41 28 e9 26 5d ba 36 |(........A(.&].6|
000000c0 da b6 a6 cb 21 92 21 30 4b 21 4d 44 28 4d 76 d1 |....!.!0K!MD(Mv.|
000000d0 61 65 fa 02 05 67 50 ec 7d 98 78 21 46 5d fe 75 |ae...gP.}.x!F].u|
000000e0 78 8e 9d 41 6a 0a d7 0e 27 22 d0 a1 21 57 3d 23 |x..Aj...'"..!W=#|
000000f0 d1 7d 08 f4 0b 1b 90 ec 63 74 4c e7 df c8 8f 8b |.}......ctL.....|
00000100 b8 cd 2b 06 a5 35 f5 c1 62 d5 46 f3 d5 19 5b ce |..+..5..b.F...[.|
00000110 c8 d2 f4 c1 51 5f cd b2 51 23 61 bf 93 7f 5d bd |....Q_..Q#a...].|
00000120 61 f2 b2 e0 ad be ab d7 c9 77 26 c2 61 fb 25 8d |a........w&.a.%.|
00000130 46 38 7a 30 48 9f b5 5c 47 6b ce 10 1d 03 d0 68 |F8z0H..\Gk.....h|
00000140 7f 00 c0 94 f4 35 eb 41 e8 91 f6 d9 5c 44 d6 79 |.....5.A....\D.y|
00000150 72 9f 22 a4 08 fd 74 1b 42 dc 49 06 34 8f b6 f5 |r."...t.B.I.4...|
00000160 12 1c 09 f0 d4 eb e4 6e d5 9a 31 f9 1a 88 c1 bf |.......n..1.....|
00000170 37 42 90 5f c8 e1 38 2b 8b 4b c1 cd 66 72 e6 49 |7B._..8+.K..fr.I|
00000180 d3 19 0e 01 19 60 f7 7d d3 66 b2 bf bd 94 30 c9 |.....`.}.f....0.|
00000190 3a 01 aa b6 dc 2a d6 1a 68 cf a6 31 5e 9a 1d 5b |:....*..h..1^..[|
000001a0 90 bb 77 33 31 f2 28 5a 70 a5 c5 ef 91 91 27 22 |..w31.(Zp.....'"|
000001b0 59 33 d5 22 78 8e 8f 07 91 3c 69 ec b9 81 be e8 |Y3."x....<i.....|
000001c0 be bd 63 20 54 6c 2c 27 46 38 9a 45 06 4e aa b3 |..c Tl,'F8.E.N..|
000001d0 37 93 72 6a 90 a6 18 14 88 6e 5b fc 54 44 48 a8 |7.rj.....n[.TDH.|
000001e0 bc c6 86 52 a6 b8 a7 a4 02 04 91 e0 4b 28 4b dc |...R........K(K.|
000001f0 c8 cc db e3 f7 89 69 a3 3b 22 d0 75 16 c8 16 cc |......i.;".u....|
00000200 a2 3c 56 c5 00 d1 1d 11 7f 74 1f bb 3d ec 1b c0 |.<V......t..=...|
00000210 30 67 81 36 11 11 60 d2 e1 be ce e4 0c f6 d0 df |0g.6..`.........|
00000220 fd 7c dc 7f 3d 40 8d 65 ec 69 c7 55 30 db 9c d3 |.|..=@.e.i.U0...|
00000230 bc 92 ae 14 85 18 ce 10 7e 0f 52 52 a4 c7 b7 1f |........~.RR....|
00000240 2d 3e 87 fc fb 93 eb 47 a3 e0 cc 4e 57 51 d0 59 |->.....G...NWQ.Y|
00000250 05 84 dc 4d fd fb d1 11 33 b6 e5 5e df 65 d4 ed |...M....3..^.e..|
00000260 04 af 89 b3 f0 90 9b 7c 5e 83 b1 66 71 b1 16 03 |.......|^..fq...|
00000270 03 00 35 5b 37 fa e1 97 11 25 7c fd da 7e e8 2a |..5[7....%|..~.*|
00000280 9b 28 fa 20 a6 9b 9b ca 99 ed a2 eb 5b 84 df a0 |.(. ........[...|
00000290 b9 14 c2 fe 38 a8 54 06 e4 54 38 87 2a 24 8b 1e |....8.T..T8.*$..|
000002a0 3e ba 0a bb c2 1d a4 74 16 03 03 00 98 8b 39 c7 |>......t......9.|
000002b0 ac e5 80 bf 49 95 ad f4 c0 cf c9 7c 86 bf 11 65 |....I......|...e|
000002c0 53 40 f3 64 3e 04 ad c9 8d 33 8a 10 4a f5 2e c5 |S@.d>....3..J...|
000002d0 22 18 59 1c 81 65 8a 51 47 b4 8d b1 94 57 3c f8 |".Y..e.QG....W<.|
000002e0 d0 06 60 ce 04 f9 50 8f 6c 43 d8 6e b0 9e d9 da |..`...P.lC.n....|
000002f0 4b e5 b5 05 b7 1b 4b 46 59 d6 ad 20 bb 4c fc aa |K.....KFY.. .L..|
00000300 9a 9b ef fd 59 4b 2a 63 01 b0 1b 2d ed b1 f4 5b |....YK*c...-...[|
00000310 bb ca cd fa 13 06 06 7e 1d a5 cd c3 ca 4e bf 7b |.......~.....N.{|
00000320 7e 92 92 09 61 35 68 a2 38 f9 13 41 f4 a9 a5 0f |~...a5h.8..A....|
00000330 42 63 e4 15 e8 86 00 48 90 2b 43 30 da 05 b6 fc |Bc.....H.+C0....|
00000340 8e 7f 52 d3 b8 14 03 03 00 11 82 73 be a9 08 9d |..R........s....|
00000350 5b 2f fe bd 1f 2c fb e2 f3 94 f3 16 03 03 00 20 |[/...,......... |
00000360 d0 47 0f 2d 7e ce 8f 01 e2 7d 01 3c 32 79 a0 26 |.G.-~....}.<2y.&|
00000370 fe 00 ce d3 37 46 20 b4 f8 af 21 81 0f 1e ba 2d |....7F ...!....-|
>>> Flow 10 (server to client)
00000000 14 03 03 00 11 53 7f 72 ce 10 f4 0e a3 ed ed 8d |.....S.r........|
00000010 3a ad 2d 57 c8 e1 16 03 03 00 20 11 e9 69 5e ff |:.-W...... ..i^.|
00000020 22 0d f6 a3 e1 e5 3f 14 34 a0 33 d7 d5 0a 7f bc |".....?.4.3.....|
00000030 7c 69 9b 9a d2 aa 41 87 fe da de 17 03 03 00 19 ||i....A.........|
00000040 bd a1 83 5d 27 9f cc 0b 40 02 23 6e 6f 18 4c bc |...]'...@.#no.L.|
00000050 48 c4 02 7d 45 08 71 ac d7 |H..}E.q..|
>>> Flow 11 (client to server)
00000000 15 03 03 00 12 80 ae fb 45 cb a1 2d 1f c8 b6 02 |........E..-....|
00000010 3a 28 62 d6 13 48 2c |:(b..H,|
| go/src/crypto/tls/testdata/Client-TLSv12-RenegotiateOnce/0 | {
"file_path": "go/src/crypto/tls/testdata/Client-TLSv12-RenegotiateOnce",
"repo_id": "go",
"token_count": 9553
} | 223 |
>>> Flow 1 (client to server)
00000000 16 03 01 00 fe 01 00 00 fa 03 03 00 00 00 00 00 |................|
00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................|
00000020 00 00 00 00 00 00 00 00 00 00 00 20 00 00 00 00 |........... ....|
00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................|
00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 32 cc a9 |.............2..|
00000050 cc a8 c0 2b c0 2f c0 2c c0 30 c0 09 c0 13 c0 0a |...+./.,.0......|
00000060 c0 14 00 9c 00 9d 00 2f 00 35 c0 12 00 0a c0 23 |......./.5.....#|
00000070 c0 27 00 3c c0 07 c0 11 00 05 13 03 13 01 13 02 |.'.<............|
00000080 01 00 00 7f 00 0b 00 02 01 00 ff 01 00 01 00 00 |................|
00000090 17 00 00 00 12 00 00 00 05 00 05 01 00 00 00 00 |................|
000000a0 00 0a 00 0a 00 08 00 1d 00 17 00 18 00 19 00 0d |................|
000000b0 00 1a 00 18 08 04 04 03 08 07 08 05 08 06 04 01 |................|
000000c0 05 01 06 01 05 03 06 03 02 01 02 03 00 2b 00 09 |.............+..|
000000d0 08 03 04 03 03 03 02 03 01 00 33 00 26 00 24 00 |..........3.&.$.|
000000e0 1d 00 20 2f e5 7d a3 47 cd 62 43 15 28 da ac 5f |.. /.}.G.bC.(.._|
000000f0 bb 29 07 30 ff f6 84 af c4 cf c2 ed 90 99 5f 58 |.).0.........._X|
00000100 cb 3b 74 |.;t|
>>> Flow 2 (server to client)
00000000 16 03 03 00 7a 02 00 00 76 03 03 48 e6 a7 a9 4c |....z...v..H...L|
00000010 c3 a7 cc 18 b7 71 7d ed c5 6a cb ca b5 9f 00 fd |.....q}..j......|
00000020 f8 2c ac 9c 1f 24 27 b9 c6 55 8e 20 00 00 00 00 |.,...$'..U. ....|
00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................|
00000040 00 00 00 00 00 00 00 00 00 00 00 00 13 03 00 00 |................|
00000050 2e 00 2b 00 02 03 04 00 33 00 24 00 1d 00 20 dd |..+.....3.$... .|
00000060 be 27 eb a0 9c b1 22 6a 8c 29 9a d4 47 c2 ee 14 |.'...."j.)..G...|
00000070 39 0c 60 81 c9 06 3f dc e5 e0 24 9a c4 88 35 14 |9.`...?...$...5.|
00000080 03 03 00 01 01 17 03 03 00 17 25 70 5a e5 6b 9e |..........%pZ.k.|
00000090 56 b9 cf 83 48 b0 bc 99 6a 86 e1 cb 4e ce b5 10 |V...H...j...N...|
000000a0 e0 17 03 03 02 6d c7 a6 79 ef b0 81 d6 e4 0e 02 |.....m..y.......|
000000b0 59 32 88 cc b1 0d 53 f6 33 9b d2 e8 74 a9 0a a7 |Y2....S.3...t...|
000000c0 f9 76 e9 6e 0d 16 75 0b e0 8f 5c b5 31 47 6b 68 |.v.n..u...\.1Gkh|
000000d0 52 c7 c2 84 cb 48 81 a3 da bd a1 50 5c ec 5c a7 |R....H.....P\.\.|
000000e0 10 01 58 cc 03 c3 53 04 03 69 80 f4 ad 4d ce 72 |..X...S..i...M.r|
000000f0 26 4e 6c c7 2c 31 69 2b fd 97 67 5e 7d e0 05 b3 |&Nl.,1i+..g^}...|
00000100 f4 40 64 a1 bd a3 fd a8 f9 7b 18 82 89 8f 25 f9 |.@d......{....%.|
00000110 ca ca c4 8f e4 90 7b 26 7a d5 b2 1e fa 05 db ad |......{&z.......|
00000120 8a 9f 93 e9 13 5b 28 cc cb 8b 30 f2 4c 1d 73 09 |.....[(...0.L.s.|
00000130 7f 6b 63 5c 29 36 2f fc a5 6e eb 24 79 f8 7c 63 |.kc\)6/..n.$y.|c|
00000140 1f ef 41 72 98 69 7c d6 8d f9 76 d4 4d af b0 71 |..Ar.i|...v.M..q|
00000150 2e f7 f8 b5 73 45 05 52 fa 25 46 02 28 0d d9 7a |....sE.R.%F.(..z|
00000160 60 13 b9 6c 6d fb f3 be e3 04 74 76 72 d6 a4 91 |`..lm.....tvr...|
00000170 d1 2c 0d 1e fa 23 ef c7 80 ff 1e aa 1b af 50 58 |.,...#........PX|
00000180 77 ea 49 d9 22 4d ed bc bf a6 0a 41 8e e7 5b 31 |w.I."M.....A..[1|
00000190 de 33 05 10 46 a5 54 aa 5e 90 5c 15 64 2d 1b e9 |.3..F.T.^.\.d-..|
000001a0 5c fc 93 8d 2f b2 af 74 d7 d2 c6 7f 27 68 fd 44 |\.../..t....'h.D|
000001b0 13 60 70 87 e8 08 e1 e2 af 7f 1a 2c 29 5f 45 fe |.`p........,)_E.|
000001c0 49 9a d0 42 c9 51 ef f7 5b ae 02 df 27 1c 29 20 |I..B.Q..[...'.) |
000001d0 35 4f 3d 7d 74 97 0c 20 be f8 a3 c9 b7 ff 65 69 |5O=}t.. ......ei|
000001e0 08 89 92 fe 85 65 9f 8a 00 4b 9f 39 8d 6f 29 7c |.....e...K.9.o)||
000001f0 7c e9 16 e4 bd 06 a3 b0 5b 7f cf f0 74 14 56 a2 ||.......[...t.V.|
00000200 76 61 b8 79 10 44 55 4f 25 55 a7 be a4 eb 2e 7d |va.y.DUO%U.....}|
00000210 9a b8 7a d8 d7 34 b6 ef 6c f7 fb ef fd 16 c2 61 |..z..4..l......a|
00000220 89 bb 98 22 c6 80 9e 33 7f e9 35 7a 58 b6 33 1c |..."...3..5zX.3.|
00000230 d6 87 68 b7 62 21 3b 26 9b f1 b1 f2 92 d5 4b 19 |..h.b!;&......K.|
00000240 02 58 05 3c 81 cf 00 5a 54 86 a5 61 8f 71 ae 32 |.X.<...ZT..a.q.2|
00000250 f2 0f 08 3b 13 4d f3 e6 03 2e 73 9c 50 4a b7 6c |...;.M....s.PJ.l|
00000260 d8 0a 04 fc b5 44 a5 45 c8 86 c9 9f 29 b4 00 90 |.....D.E....)...|
00000270 d8 8b e0 c8 ba 63 9f 42 65 ef ba 5b dc b2 61 53 |.....c.Be..[..aS|
00000280 e6 4b 29 72 51 c9 21 d4 d7 2d 14 56 82 80 32 36 |.K)rQ.!..-.V..26|
00000290 fd 72 b6 16 6f 06 71 f9 60 4f 32 ce f6 83 94 75 |.r..o.q.`O2....u|
000002a0 d9 23 d3 41 f8 e7 90 60 80 a8 a5 95 c0 a2 dd 2e |.#.A...`........|
000002b0 e7 60 73 5b c0 a5 a0 bd 8b bc cc 32 8a 9e 30 6a |.`s[.......2..0j|
000002c0 72 2f 61 24 56 0b 1e 3e 52 92 d2 e0 11 cd 52 69 |r/a$V..>R.....Ri|
000002d0 c4 73 7f 72 95 fd f5 c4 72 d7 77 73 85 bf be e0 |.s.r....r.ws....|
000002e0 cd 3c 3b 3d 92 63 91 ba c8 a8 d2 32 40 6a 33 91 |.<;=.c.....2@j3.|
000002f0 c0 71 fe ea 76 9f a9 96 dc c0 a9 bd 67 b6 23 42 |.q..v.......g.#B|
00000300 d9 1b 3d 8d d4 5f 81 38 74 1c db 36 9e bd 79 fd |..=.._.8t..6..y.|
00000310 30 c5 db 17 03 03 00 99 61 1e 25 cb 11 26 61 72 |0.......a.%..&ar|
00000320 a0 9a de 5b ad 5b ad 8a 29 43 eb 76 5a 16 a4 d3 |...[.[..)C.vZ...|
00000330 d4 a1 84 e4 7e a1 2b 76 75 b6 a5 a6 36 da d3 bf |....~.+vu...6...|
00000340 0c 3a 39 ca ef 3f 02 22 63 3d 5d c1 30 94 ba 32 |.:9..?."c=].0..2|
00000350 fe c0 20 c1 ba c8 fa 29 e8 1c c6 ab f0 c9 53 a4 |.. ....)......S.|
00000360 73 d0 9a 2d 50 d8 b4 0c db e5 4a 9f 98 38 34 c9 |s..-P.....J..84.|
00000370 9f ff 63 a9 50 7b 26 00 64 26 4d 0d 20 d5 e5 27 |..c.P{&.d&M. ..'|
00000380 e1 41 7b 5a 03 97 0a 14 8c 55 3c 45 4b 72 ce de |.A{Z.....U<EKr..|
00000390 38 59 4b ed fe 70 a7 af a7 67 c9 03 f8 fe ea 96 |8YK..p...g......|
000003a0 ac 81 9a ed 8e ef 69 aa 7a eb 03 1b 13 1e ca da |......i.z.......|
000003b0 58 17 03 03 00 35 70 23 20 5a eb 40 0b b8 6f 1a |X....5p# Z.@..o.|
000003c0 d8 b0 ae c5 de 52 6b 77 10 87 cd 2f ec fe 99 1c |.....Rkw.../....|
000003d0 93 c0 f7 6b 8b d2 8b 81 9b 05 36 82 bf 4a b4 a0 |...k......6..J..|
000003e0 d2 9f 75 b3 ef 64 50 7f 00 ac fa |..u..dP....|
>>> Flow 3 (client to server)
00000000 14 03 03 00 01 01 17 03 03 00 35 a6 7f ef 71 68 |..........5...qh|
00000010 8b 86 84 20 a6 e7 65 3f 3f f8 c6 8b 62 40 31 e2 |... ..e??...b@1.|
00000020 1a ee 8d 0a 64 88 ea 4b 83 5f c5 ff 1b 9d aa 5f |....d..K._....._|
00000030 ce a4 31 76 06 90 da ad b9 17 49 0b a6 b5 37 80 |..1v......I...7.|
00000040 17 03 03 00 17 2b be e8 98 11 37 0d db 46 69 0d |.....+....7..Fi.|
00000050 51 34 ee 13 00 c3 f1 12 8a 13 21 b7 17 03 03 00 |Q4........!.....|
00000060 13 8d ec 94 6f 55 b1 d5 c0 d6 a3 6e a2 8d 67 76 |....oU.....n..gv|
00000070 7b c7 b8 1d |{...|
| go/src/crypto/tls/testdata/Client-TLSv13-ExportKeyingMaterial/0 | {
"file_path": "go/src/crypto/tls/testdata/Client-TLSv13-ExportKeyingMaterial",
"repo_id": "go",
"token_count": 3486
} | 224 |
>>> Flow 1 (client to server)
00000000 16 03 01 00 6d 01 00 00 69 03 03 5e 92 9d 30 27 |....m...i..^..0'|
00000010 23 da fa a0 07 30 03 c8 bd 60 f2 db e9 5e b3 fc |#....0...`...^..|
00000020 65 d3 c5 e1 49 35 63 86 53 ec 87 00 00 04 00 2f |e...I5c.S....../|
00000030 00 ff 01 00 00 3c 00 16 00 00 00 17 00 00 00 0d |.....<..........|
00000040 00 30 00 2e 04 03 05 03 06 03 08 07 08 08 08 09 |.0..............|
00000050 08 0a 08 0b 08 04 08 05 08 06 04 01 05 01 06 01 |................|
00000060 03 03 02 03 03 01 02 01 03 02 02 02 04 02 05 02 |................|
00000070 06 02 |..|
>>> Flow 2 (server to client)
00000000 16 03 03 00 35 02 00 00 31 03 03 00 00 00 00 00 |....5...1.......|
00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................|
00000020 00 00 00 44 4f 57 4e 47 52 44 01 00 00 2f 00 00 |...DOWNGRD.../..|
00000030 09 ff 01 00 01 00 00 17 00 00 16 03 03 02 59 0b |..............Y.|
00000040 00 02 55 00 02 52 00 02 4f 30 82 02 4b 30 82 01 |..U..R..O0..K0..|
00000050 b4 a0 03 02 01 02 02 09 00 e8 f0 9d 3f e2 5b ea |............?.[.|
00000060 a6 30 0d 06 09 2a 86 48 86 f7 0d 01 01 0b 05 00 |.0...*.H........|
00000070 30 1f 31 0b 30 09 06 03 55 04 0a 13 02 47 6f 31 |0.1.0...U....Go1|
00000080 10 30 0e 06 03 55 04 03 13 07 47 6f 20 52 6f 6f |.0...U....Go Roo|
00000090 74 30 1e 17 0d 31 36 30 31 30 31 30 30 30 30 30 |t0...16010100000|
000000a0 30 5a 17 0d 32 35 30 31 30 31 30 30 30 30 30 30 |0Z..250101000000|
000000b0 5a 30 1a 31 0b 30 09 06 03 55 04 0a 13 02 47 6f |Z0.1.0...U....Go|
000000c0 31 0b 30 09 06 03 55 04 03 13 02 47 6f 30 81 9f |1.0...U....Go0..|
000000d0 30 0d 06 09 2a 86 48 86 f7 0d 01 01 01 05 00 03 |0...*.H.........|
000000e0 81 8d 00 30 81 89 02 81 81 00 db 46 7d 93 2e 12 |...0.......F}...|
000000f0 27 06 48 bc 06 28 21 ab 7e c4 b6 a2 5d fe 1e 52 |'.H..(!.~...]..R|
00000100 45 88 7a 36 47 a5 08 0d 92 42 5b c2 81 c0 be 97 |E.z6G....B[.....|
00000110 79 98 40 fb 4f 6d 14 fd 2b 13 8b c2 a5 2e 67 d8 |y.@.Om..+.....g.|
00000120 d4 09 9e d6 22 38 b7 4a 0b 74 73 2b c2 34 f1 d1 |...."8.J.ts+.4..|
00000130 93 e5 96 d9 74 7b f3 58 9f 6c 61 3c c0 b0 41 d4 |....t{.X.la<..A.|
00000140 d9 2b 2b 24 23 77 5b 1c 3b bd 75 5d ce 20 54 cf |.++$#w[.;.u]. T.|
00000150 a1 63 87 1d 1e 24 c4 f3 1d 1a 50 8b aa b6 14 43 |.c...$....P....C|
00000160 ed 97 a7 75 62 f4 14 c8 52 d7 02 03 01 00 01 a3 |...ub...R.......|
00000170 81 93 30 81 90 30 0e 06 03 55 1d 0f 01 01 ff 04 |..0..0...U......|
00000180 04 03 02 05 a0 30 1d 06 03 55 1d 25 04 16 30 14 |.....0...U.%..0.|
00000190 06 08 2b 06 01 05 05 07 03 01 06 08 2b 06 01 05 |..+.........+...|
000001a0 05 07 03 02 30 0c 06 03 55 1d 13 01 01 ff 04 02 |....0...U.......|
000001b0 30 00 30 19 06 03 55 1d 0e 04 12 04 10 9f 91 16 |0.0...U.........|
000001c0 1f 43 43 3e 49 a6 de 6d b6 80 d7 9f 60 30 1b 06 |.CC>I..m....`0..|
000001d0 03 55 1d 23 04 14 30 12 80 10 48 13 49 4d 13 7e |.U.#..0...H.IM.~|
000001e0 16 31 bb a3 01 d5 ac ab 6e 7b 30 19 06 03 55 1d |.1......n{0...U.|
000001f0 11 04 12 30 10 82 0e 65 78 61 6d 70 6c 65 2e 67 |...0...example.g|
00000200 6f 6c 61 6e 67 30 0d 06 09 2a 86 48 86 f7 0d 01 |olang0...*.H....|
00000210 01 0b 05 00 03 81 81 00 9d 30 cc 40 2b 5b 50 a0 |.........0.@+[P.|
00000220 61 cb ba e5 53 58 e1 ed 83 28 a9 58 1a a9 38 a4 |a...SX...(.X..8.|
00000230 95 a1 ac 31 5a 1a 84 66 3d 43 d3 2d d9 0b f2 97 |...1Z..f=C.-....|
00000240 df d3 20 64 38 92 24 3a 00 bc cf 9c 7d b7 40 20 |.. d8.$:....}.@ |
00000250 01 5f aa d3 16 61 09 a2 76 fd 13 c3 cc e1 0c 5c |._...a..v......\|
00000260 ee b1 87 82 f1 6c 04 ed 73 bb b3 43 77 8d 0c 1c |.....l..s..Cw...|
00000270 f1 0f a1 d8 40 83 61 c9 4c 72 2b 9d ae db 46 06 |....@.a.Lr+...F.|
00000280 06 4d f4 c1 b3 3e c0 d1 bd 42 d4 db fe 3d 13 60 |.M...>...B...=.`|
00000290 84 5c 21 d3 3b e9 fa e7 16 03 03 00 23 0d 00 00 |.\!.;.......#...|
000002a0 1f 02 01 40 00 18 08 04 04 03 08 07 08 05 08 06 |...@............|
000002b0 04 01 05 01 06 01 05 03 06 03 02 01 02 03 00 00 |................|
000002c0 16 03 03 00 04 0e 00 00 00 |.........|
>>> Flow 3 (client to server)
00000000 16 03 03 02 0a 0b 00 02 06 00 02 03 00 02 00 30 |...............0|
00000010 82 01 fc 30 82 01 5e 02 09 00 9a 30 84 6c 26 35 |...0..^....0.l&5|
00000020 d9 17 30 09 06 07 2a 86 48 ce 3d 04 01 30 45 31 |..0...*.H.=..0E1|
00000030 0b 30 09 06 03 55 04 06 13 02 41 55 31 13 30 11 |.0...U....AU1.0.|
00000040 06 03 55 04 08 13 0a 53 6f 6d 65 2d 53 74 61 74 |..U....Some-Stat|
00000050 65 31 21 30 1f 06 03 55 04 0a 13 18 49 6e 74 65 |e1!0...U....Inte|
00000060 72 6e 65 74 20 57 69 64 67 69 74 73 20 50 74 79 |rnet Widgits Pty|
00000070 20 4c 74 64 30 1e 17 0d 31 32 31 31 31 34 31 33 | Ltd0...12111413|
00000080 32 35 35 33 5a 17 0d 32 32 31 31 31 32 31 33 32 |2553Z..221112132|
00000090 35 35 33 5a 30 41 31 0b 30 09 06 03 55 04 06 13 |553Z0A1.0...U...|
000000a0 02 41 55 31 0c 30 0a 06 03 55 04 08 13 03 4e 53 |.AU1.0...U....NS|
000000b0 57 31 10 30 0e 06 03 55 04 07 13 07 50 79 72 6d |W1.0...U....Pyrm|
000000c0 6f 6e 74 31 12 30 10 06 03 55 04 03 13 09 4a 6f |ont1.0...U....Jo|
000000d0 65 6c 20 53 69 6e 67 30 81 9b 30 10 06 07 2a 86 |el Sing0..0...*.|
000000e0 48 ce 3d 02 01 06 05 2b 81 04 00 23 03 81 86 00 |H.=....+...#....|
000000f0 04 00 95 8c 91 75 14 c0 5e c4 57 b4 d4 c3 6f 8d |.....u..^.W...o.|
00000100 ae 68 1e dd 6f ce 86 e1 7e 6e b2 48 3e 81 e5 4e |.h..o...~n.H>..N|
00000110 e2 c6 88 4b 64 dc f5 30 bb d3 ff 65 cc 5b f4 dd |...Kd..0...e.[..|
00000120 b5 6a 3e 3e d0 1d de 47 c3 76 ad 19 f6 45 2c 8c |.j>>...G.v...E,.|
00000130 bc d8 1d 01 4c 1f 70 90 46 76 48 8b 8f 83 cc 4a |....L.p.FvH....J|
00000140 5c 8f 40 76 da e0 89 ec 1d 2b c4 4e 30 76 28 41 |\.@v.....+.N0v(A|
00000150 b2 62 a8 fb 5b f1 f9 4e 7a 8d bd 09 b8 ae ea 8b |.b..[..Nz.......|
00000160 18 27 4f 2e 70 fe 13 96 ba c3 d3 40 16 cd 65 4e |.'O.p......@..eN|
00000170 ac 11 1e e6 f1 30 09 06 07 2a 86 48 ce 3d 04 01 |.....0...*.H.=..|
00000180 03 81 8c 00 30 81 88 02 42 00 e0 14 c4 60 60 0b |....0...B....``.|
00000190 72 68 b0 32 5d 61 4a 02 74 5c c2 81 b9 16 a8 3f |rh.2]aJ.t\.....?|
000001a0 29 c8 36 c7 81 ff 6c b6 5b d9 70 f1 38 3b 50 48 |).6...l.[.p.8;PH|
000001b0 28 94 cb 09 1a 52 f1 5d ee 8d f2 b9 f0 f0 da d9 |(....R.]........|
000001c0 15 3a f9 bd 03 7a 87 a2 23 35 ec 02 42 01 a3 d4 |.:...z..#5..B...|
000001d0 8a 78 35 1c 4a 9a 23 d2 0a be 2b 10 31 9d 9c 5f |.x5.J.#...+.1.._|
000001e0 be e8 91 b3 da 1a f5 5d a3 23 f5 26 8b 45 70 8d |.......].#.&.Ep.|
000001f0 65 62 9b 7e 01 99 3d 18 f6 10 9a 38 61 9b 2e 57 |eb.~..=....8a..W|
00000200 e4 fa cc b1 8a ce e2 23 a0 87 f0 e1 67 51 eb 16 |.......#....gQ..|
00000210 03 03 00 86 10 00 00 82 00 80 02 50 e4 cc a3 ad |...........P....|
00000220 fb 33 24 a1 b3 0a 7c 0f 00 e6 1a 06 2b 9f 1e 1f |.3$...|.....+...|
00000230 cc b8 b2 80 90 e7 86 20 32 40 06 ac 1b b0 41 b7 |....... 2@....A.|
00000240 0d 9c 4c 41 90 01 0b 7a 7e b2 b2 46 39 dc 51 25 |..LA...z~..F9.Q%|
00000250 98 e0 b9 ec 36 fc 08 64 f0 51 2a 41 e1 e5 61 3d |....6..d.Q*A..a=|
00000260 fc 07 c1 9b 1f 6f 48 d4 1f 46 bf 14 e6 92 61 1a |.....oH..F....a.|
00000270 bd 5f 25 1f 5e b1 3c ac c7 58 63 02 0d 3a e0 d6 |._%.^.<..Xc..:..|
00000280 e9 39 fc ec 59 66 2e 91 b2 65 37 eb a8 b5 60 d9 |.9..Yf...e7...`.|
00000290 49 05 9f 6f cc 71 79 bb f7 68 16 03 03 00 93 0f |I..o.qy..h......|
000002a0 00 00 8f 04 03 00 8b 30 81 88 02 42 00 bd 6a 29 |.......0...B..j)|
000002b0 21 06 1a e2 67 a1 7f 10 ab ca 3f 74 5a bc 2f 5d |!...g.....?tZ./]|
000002c0 53 d0 59 90 f2 d0 b4 2d 75 47 67 0b 67 55 b6 4f |S.Y....-uGg.gU.O|
000002d0 75 7d 32 d8 a7 25 c8 4c 90 0b 56 65 be 60 5d ee |u}2..%.L..Ve.`].|
000002e0 f7 b3 80 79 26 e5 25 1d 17 cc d8 36 fc 39 02 42 |...y&.%....6.9.B|
000002f0 01 c3 32 d6 f2 59 9e 10 c8 bf 7f 74 27 a1 00 df |..2..Y.....t'...|
00000300 55 05 f0 b3 81 a1 6e 10 a6 fb 0b e4 1c 3f 62 02 |U.....n......?b.|
00000310 c9 cc c2 4b 97 ad 0c 88 98 07 6c 98 6d db 9d 9f |...K......l.m...|
00000320 68 a0 56 ab 5f f9 a2 21 33 86 64 53 de 37 ff 68 |h.V._..!3.dS.7.h|
00000330 04 9d 14 03 03 00 01 01 16 03 03 00 40 85 14 34 |............@..4|
00000340 d6 74 a9 d0 0b e9 1f 34 a9 e9 6c cf 5a ac 88 22 |.t.....4..l.Z.."|
00000350 51 4d ae 16 05 dd 9e c1 36 5e e3 cf b1 5a b5 48 |QM......6^...Z.H|
00000360 6c 24 b1 d6 fb 7f 03 6a 98 41 90 de 6d c7 b2 49 |l$.....j.A..m..I|
00000370 d9 a3 c7 45 ff 18 7c f7 a4 cf 05 59 87 |...E..|....Y.|
>>> Flow 4 (server to client)
00000000 14 03 03 00 01 01 16 03 03 00 40 00 00 00 00 00 |..........@.....|
00000010 00 00 00 00 00 00 00 00 00 00 00 63 1a 77 66 2a |...........c.wf*|
00000020 49 3a b2 17 83 74 e1 d9 70 96 de 01 84 09 f4 88 |I:...t..p.......|
00000030 c3 e7 3b 65 11 6f 13 32 b8 b4 f4 41 ca 6a d6 d7 |..;e.o.2...A.j..|
00000040 51 a3 a1 f0 2d 5b b4 55 29 f9 d3 17 03 03 00 40 |Q...-[.U)......@|
00000050 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................|
00000060 d7 30 0f 03 89 22 4c 19 5f 06 a7 4b 95 59 91 52 |.0..."L._..K.Y.R|
00000070 2a 65 ab 99 cb 71 99 8b 13 82 44 92 6b ff 59 07 |*e...q....D.k.Y.|
00000080 28 ca 01 68 ab ad ba ee 6c 6a 19 0b e5 6d 82 24 |(..h....lj...m.$|
00000090 15 03 03 00 30 00 00 00 00 00 00 00 00 00 00 00 |....0...........|
000000a0 00 00 00 00 00 fc 07 f4 d4 bb 24 a3 f1 cf dc 3c |..........$....<|
000000b0 ac 14 63 50 32 34 fd 73 c0 eb f2 78 7b 3b ea 58 |..cP24.s...x{;.X|
000000c0 cc 3e ff 7f e5 |.>...|
| go/src/crypto/tls/testdata/Server-TLSv12-ClientAuthRequestedAndECDSAGiven/0 | {
"file_path": "go/src/crypto/tls/testdata/Server-TLSv12-ClientAuthRequestedAndECDSAGiven",
"repo_id": "go",
"token_count": 4719
} | 225 |
>>> Flow 1 (client to server)
00000000 16 03 01 00 59 01 00 00 55 03 03 01 3d 46 ff b5 |....Y...U...=F..|
00000010 47 eb 03 bd 9b 27 66 92 92 db 11 f9 58 1d 21 ba |G....'f.....X.!.|
00000020 b9 51 90 81 d0 8f 7e 3c cd 7b b8 00 00 04 cc a8 |.Q....~<.{......|
00000030 00 ff 01 00 00 28 00 0b 00 04 03 00 01 02 00 0a |.....(..........|
00000040 00 0c 00 0a 00 1d 00 17 00 1e 00 19 00 18 00 16 |................|
00000050 00 00 00 17 00 00 00 0d 00 04 00 02 04 01 |..............|
>>> Flow 2 (server to client)
00000000 16 03 03 00 3b 02 00 00 37 03 03 00 00 00 00 00 |....;...7.......|
00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................|
00000020 00 00 00 44 4f 57 4e 47 52 44 01 00 cc a8 00 00 |...DOWNGRD......|
00000030 0f ff 01 00 01 00 00 17 00 00 00 0b 00 02 01 00 |................|
00000040 16 03 03 02 59 0b 00 02 55 00 02 52 00 02 4f 30 |....Y...U..R..O0|
00000050 82 02 4b 30 82 01 b4 a0 03 02 01 02 02 09 00 e8 |..K0............|
00000060 f0 9d 3f e2 5b ea a6 30 0d 06 09 2a 86 48 86 f7 |..?.[..0...*.H..|
00000070 0d 01 01 0b 05 00 30 1f 31 0b 30 09 06 03 55 04 |......0.1.0...U.|
00000080 0a 13 02 47 6f 31 10 30 0e 06 03 55 04 03 13 07 |...Go1.0...U....|
00000090 47 6f 20 52 6f 6f 74 30 1e 17 0d 31 36 30 31 30 |Go Root0...16010|
000000a0 31 30 30 30 30 30 30 5a 17 0d 32 35 30 31 30 31 |1000000Z..250101|
000000b0 30 30 30 30 30 30 5a 30 1a 31 0b 30 09 06 03 55 |000000Z0.1.0...U|
000000c0 04 0a 13 02 47 6f 31 0b 30 09 06 03 55 04 03 13 |....Go1.0...U...|
000000d0 02 47 6f 30 81 9f 30 0d 06 09 2a 86 48 86 f7 0d |.Go0..0...*.H...|
000000e0 01 01 01 05 00 03 81 8d 00 30 81 89 02 81 81 00 |.........0......|
000000f0 db 46 7d 93 2e 12 27 06 48 bc 06 28 21 ab 7e c4 |.F}...'.H..(!.~.|
00000100 b6 a2 5d fe 1e 52 45 88 7a 36 47 a5 08 0d 92 42 |..]..RE.z6G....B|
00000110 5b c2 81 c0 be 97 79 98 40 fb 4f 6d 14 fd 2b 13 |[.....y.@.Om..+.|
00000120 8b c2 a5 2e 67 d8 d4 09 9e d6 22 38 b7 4a 0b 74 |....g....."8.J.t|
00000130 73 2b c2 34 f1 d1 93 e5 96 d9 74 7b f3 58 9f 6c |s+.4......t{.X.l|
00000140 61 3c c0 b0 41 d4 d9 2b 2b 24 23 77 5b 1c 3b bd |a<..A..++$#w[.;.|
00000150 75 5d ce 20 54 cf a1 63 87 1d 1e 24 c4 f3 1d 1a |u]. T..c...$....|
00000160 50 8b aa b6 14 43 ed 97 a7 75 62 f4 14 c8 52 d7 |P....C...ub...R.|
00000170 02 03 01 00 01 a3 81 93 30 81 90 30 0e 06 03 55 |........0..0...U|
00000180 1d 0f 01 01 ff 04 04 03 02 05 a0 30 1d 06 03 55 |...........0...U|
00000190 1d 25 04 16 30 14 06 08 2b 06 01 05 05 07 03 01 |.%..0...+.......|
000001a0 06 08 2b 06 01 05 05 07 03 02 30 0c 06 03 55 1d |..+.......0...U.|
000001b0 13 01 01 ff 04 02 30 00 30 19 06 03 55 1d 0e 04 |......0.0...U...|
000001c0 12 04 10 9f 91 16 1f 43 43 3e 49 a6 de 6d b6 80 |.......CC>I..m..|
000001d0 d7 9f 60 30 1b 06 03 55 1d 23 04 14 30 12 80 10 |..`0...U.#..0...|
000001e0 48 13 49 4d 13 7e 16 31 bb a3 01 d5 ac ab 6e 7b |H.IM.~.1......n{|
000001f0 30 19 06 03 55 1d 11 04 12 30 10 82 0e 65 78 61 |0...U....0...exa|
00000200 6d 70 6c 65 2e 67 6f 6c 61 6e 67 30 0d 06 09 2a |mple.golang0...*|
00000210 86 48 86 f7 0d 01 01 0b 05 00 03 81 81 00 9d 30 |.H.............0|
00000220 cc 40 2b 5b 50 a0 61 cb ba e5 53 58 e1 ed 83 28 |.@+[P.a...SX...(|
00000230 a9 58 1a a9 38 a4 95 a1 ac 31 5a 1a 84 66 3d 43 |.X..8....1Z..f=C|
00000240 d3 2d d9 0b f2 97 df d3 20 64 38 92 24 3a 00 bc |.-...... d8.$:..|
00000250 cf 9c 7d b7 40 20 01 5f aa d3 16 61 09 a2 76 fd |..}.@ ._...a..v.|
00000260 13 c3 cc e1 0c 5c ee b1 87 82 f1 6c 04 ed 73 bb |.....\.....l..s.|
00000270 b3 43 77 8d 0c 1c f1 0f a1 d8 40 83 61 c9 4c 72 |.Cw.......@.a.Lr|
00000280 2b 9d ae db 46 06 06 4d f4 c1 b3 3e c0 d1 bd 42 |+...F..M...>...B|
00000290 d4 db fe 3d 13 60 84 5c 21 d3 3b e9 fa e7 16 03 |...=.`.\!.;.....|
000002a0 03 00 ac 0c 00 00 a8 03 00 1d 20 2f e5 7d a3 47 |.......... /.}.G|
000002b0 cd 62 43 15 28 da ac 5f bb 29 07 30 ff f6 84 af |.bC.(.._.).0....|
000002c0 c4 cf c2 ed 90 99 5f 58 cb 3b 74 04 01 00 80 21 |......_X.;t....!|
000002d0 b5 82 7e 5a 7d 93 55 15 db e1 eb cc 62 8d f8 45 |..~Z}.U.....b..E|
000002e0 2f e0 5d 57 51 08 80 86 b6 43 85 0f be f7 49 ca |/.]WQ....C....I.|
000002f0 97 f2 f1 20 51 e6 29 8d c6 88 91 e3 60 8c 88 69 |... Q.).....`..i|
00000300 73 9b 38 70 ad 2f 5b 44 62 05 05 20 28 92 57 f9 |s.8p./[Db.. (.W.|
00000310 51 6e 6b 8c b7 3f c3 6e a3 53 b9 bd 02 bd 69 ae |Qnk..?.n.S....i.|
00000320 ee 5f 96 57 7b a2 02 86 70 33 6b e7 ad 03 25 13 |._.W{...p3k...%.|
00000330 10 f8 d7 cb 2e 33 b2 1f 53 64 77 d1 e5 8a 32 bc |.....3..Sdw...2.|
00000340 e0 bc 65 9d 94 de fb 9a d5 66 00 7a 79 dc da 16 |..e......f.zy...|
00000350 03 03 00 04 0e 00 00 00 |........|
>>> Flow 3 (client to server)
00000000 16 03 03 00 25 10 00 00 21 20 6d d3 b6 6a f0 ac |....%...! m..j..|
00000010 40 6e e8 73 db a2 04 41 6a 7f c1 cc ae 13 44 e1 |@n.s...Aj.....D.|
00000020 1c f4 5a 59 1b 88 4b a8 89 61 14 03 03 00 01 01 |..ZY..K..a......|
00000030 16 03 03 00 20 5f 09 a4 44 8e a8 6d 09 14 32 05 |.... _..D..m..2.|
00000040 ce ae f9 ad ad a2 d9 45 77 be e2 2c bd 97 22 1a |.......Ew..,..".|
00000050 7d 3b 54 db 82 |};T..|
>>> Flow 4 (server to client)
00000000 14 03 03 00 01 01 16 03 03 00 20 54 52 24 a8 3a |.......... TR$.:|
00000010 e3 45 a2 49 1c c5 10 62 6e d1 32 fe 70 0f 32 e0 |.E.I...bn.2.p.2.|
00000020 fc 95 22 81 32 38 ab f2 0a ba 6c 17 03 03 00 1d |..".28....l.....|
00000030 b7 a9 2a a5 ad e5 9e 39 cc a9 bc 81 ef a1 67 e1 |..*....9......g.|
00000040 85 08 9f f4 e7 04 c8 0b 0d fd 5c ec 94 15 03 03 |..........\.....|
00000050 00 12 d7 18 99 08 6c 98 dc 05 20 19 cd dd f2 29 |......l... ....)|
00000060 14 3c cf 31 |.<.1|
| go/src/crypto/tls/testdata/Server-TLSv12-RSA-RSAPKCS1v15/0 | {
"file_path": "go/src/crypto/tls/testdata/Server-TLSv12-RSA-RSAPKCS1v15",
"repo_id": "go",
"token_count": 2819
} | 226 |
>>> Flow 1 (client to server)
00000000 16 03 01 00 ca 01 00 00 c6 03 03 e4 83 a9 75 06 |..............u.|
00000010 0f 8b c9 35 1e 62 89 7f a8 df 7c 93 b6 f0 8f 94 |...5.b....|.....|
00000020 ea 31 dc 66 11 66 bd 77 33 54 bf 20 38 77 15 8d |.1.f.f.w3T. 8w..|
00000030 b4 21 50 72 6f 95 61 6c 15 b8 35 c9 92 10 72 99 |.!Pro.al..5...r.|
00000040 bc 41 03 53 7c 5e 7b b3 a4 2e b4 19 00 04 13 01 |.A.S|^{.........|
00000050 00 ff 01 00 00 79 00 0b 00 04 03 00 01 02 00 0a |.....y..........|
00000060 00 0c 00 0a 00 1d 00 17 00 1e 00 19 00 18 00 16 |................|
00000070 00 00 00 17 00 00 00 0d 00 1e 00 1c 04 03 05 03 |................|
00000080 06 03 08 07 08 08 08 09 08 0a 08 0b 08 04 08 05 |................|
00000090 08 06 04 01 05 01 06 01 00 2b 00 03 02 03 04 00 |.........+......|
000000a0 2d 00 02 01 01 00 33 00 26 00 24 00 1d 00 20 8e |-.....3.&.$... .|
000000b0 cf 32 24 aa f2 36 c7 41 50 66 dd 57 ce 97 72 8d |.2$..6.APf.W..r.|
000000c0 f3 b6 7d a0 a4 5e 5d fe be bb ce 32 9f 03 75 |..}..^]....2..u|
>>> Flow 2 (server to client)
00000000 16 03 03 00 7a 02 00 00 76 03 03 00 00 00 00 00 |....z...v.......|
00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................|
00000020 00 00 00 00 00 00 00 00 00 00 00 20 38 77 15 8d |........... 8w..|
00000030 b4 21 50 72 6f 95 61 6c 15 b8 35 c9 92 10 72 99 |.!Pro.al..5...r.|
00000040 bc 41 03 53 7c 5e 7b b3 a4 2e b4 19 13 01 00 00 |.A.S|^{.........|
00000050 2e 00 2b 00 02 03 04 00 33 00 24 00 1d 00 20 2f |..+.....3.$... /|
00000060 e5 7d a3 47 cd 62 43 15 28 da ac 5f bb 29 07 30 |.}.G.bC.(.._.).0|
00000070 ff f6 84 af c4 cf c2 ed 90 99 5f 58 cb 3b 74 14 |.........._X.;t.|
00000080 03 03 00 01 01 17 03 03 00 17 3b ca 9a d3 b7 99 |..........;.....|
00000090 d7 d8 c9 f9 96 b8 70 69 3b 22 42 0f c4 72 de 7c |......pi;"B..r.||
000000a0 05 17 03 03 00 3e 38 d7 00 60 b9 ce 17 31 26 9f |.....>8..`...1&.|
000000b0 db ef e2 b1 99 55 c8 f9 f3 a0 81 19 12 a7 63 85 |.....U........c.|
000000c0 5a 26 2d d1 1c ad 5d ae d6 4b 66 93 62 d7 fe 08 |Z&-...]..Kf.b...|
000000d0 40 e9 fa 16 8b 89 f8 04 e8 33 67 20 2b 21 91 a0 |@........3g +!..|
000000e0 c6 0a 87 ff 17 03 03 02 6d 79 97 6c 2f f6 01 7b |........my.l/..{|
000000f0 3a 49 0e 1a 00 96 10 fd 7f 77 db 76 b2 d4 e4 68 |:I.......w.v...h|
00000100 46 4e 4f 3c 64 54 ca 27 9a 5c 78 98 f4 96 a4 fe |FNO<dT.'.\x.....|
00000110 29 e5 44 cb 6d 3e bd ce 89 15 c6 75 d8 28 00 da |).D.m>.....u.(..|
00000120 ff d8 ec 27 2c f2 4c e5 a0 6e 88 ce 67 6e 35 f4 |...',.L..n..gn5.|
00000130 e5 d5 96 2d 40 af fa 88 12 8a 48 24 2c f9 82 f5 |...-@.....H$,...|
00000140 cb a4 6e 95 a6 53 bc 79 f7 6a ef 66 77 bc 46 f0 |..n..S.y.j.fw.F.|
00000150 1b 0d 6b 5c 76 82 15 c4 d0 1c dd ec cc ce 09 93 |..k\v...........|
00000160 ce 21 55 9b d8 8a 11 1b 0c 24 fa 9e 5f 29 4a f1 |.!U......$.._)J.|
00000170 2a 2e ad c0 6d 6d 46 06 5b c9 75 b3 3e 32 45 67 |*...mmF.[.u.>2Eg|
00000180 05 26 cc d8 a8 4a a9 b1 67 71 a6 82 1c dc f0 15 |.&...J..gq......|
00000190 6d 25 f5 6e be a2 5f 45 39 dc d1 2e df fa e1 e9 |m%.n.._E9.......|
000001a0 48 ca 7a 78 fa 0e 53 d1 5c 8f c2 40 91 d5 fa 40 |H.zx..S.\..@...@|
000001b0 7e a1 52 23 c8 56 1f 31 17 91 5c 38 bb 54 56 f3 |~.R#.V.1..\8.TV.|
000001c0 1e 14 90 43 b7 ef fd 56 b5 ae 13 90 97 dc 60 15 |...C...V......`.|
000001d0 67 72 fc c2 0a 32 90 be ec de 69 16 d3 1b 22 2c |gr...2....i...",|
000001e0 25 9f 91 27 a7 6d 8c a4 de 02 fd 0e da bf ca 71 |%..'.m.........q|
000001f0 77 9b 56 b8 07 e8 80 00 9b d9 36 1c 09 4f 9f 54 |w.V.......6..O.T|
00000200 76 d5 76 f4 9a 03 94 bb 9e 93 f0 b5 3c a1 71 ec |v.v.........<.q.|
00000210 b3 83 3a 06 b4 46 97 bf ef bb f0 26 94 4e b0 08 |..:..F.....&.N..|
00000220 3b ec 81 20 66 92 11 85 a0 c2 90 fd c5 bc ae 39 |;.. f..........9|
00000230 2c 87 ec e4 5d 59 ee b4 e9 0d f7 2a e0 3b 2a 94 |,...]Y.....*.;*.|
00000240 1a 79 2f e8 5c 88 d3 61 2e 47 c0 f3 c4 01 84 a9 |.y/.\..a.G......|
00000250 cf f6 36 13 cb 4b 0b f7 9a 14 f1 d5 0e 10 80 fd |..6..K..........|
00000260 11 79 20 20 ae 56 5e de 58 53 19 38 26 e2 ac bc |.y .V^.XS.8&...|
00000270 0c 40 38 8b f9 67 62 4c 42 7d 18 4f 27 e9 53 96 |.@8..gbLB}.O'.S.|
00000280 78 4b fa 44 fe c2 c3 d9 99 f2 2c 59 2b 2b 2c 88 |xK.D......,Y++,.|
00000290 5b dc a8 98 3d 17 14 09 70 ce e4 02 8b 3c 5d 94 |[...=...p....<].|
000002a0 44 ac ba 57 2d a9 bf b8 70 e9 b8 a8 c3 b8 90 da |D..W-...p.......|
000002b0 ec b1 b4 57 d6 e3 0f 41 82 bb 21 4a 57 dc ac 4b |...W...A..!JW..K|
000002c0 89 34 75 fc c4 56 6b 70 3d 83 2b fa be c8 2b cd |.4u..Vkp=.+...+.|
000002d0 f8 4f 9f 9e 9a 0e d2 d0 46 cd 21 a5 f7 07 a6 2a |.O......F.!....*|
000002e0 85 7b 30 92 78 a2 da a5 1d 1c 1c 54 63 4b 66 b2 |.{0.x......TcKf.|
000002f0 f1 a7 c4 43 57 97 7f 28 37 e7 15 62 9b 1c f5 90 |...CW..(7..b....|
00000300 0c 19 36 1a c1 48 48 e5 7d 56 93 3c 13 e3 cd 6a |..6..HH.}V.<...j|
00000310 aa aa ba d5 24 95 c7 df 9c a9 76 6c 07 bf 09 2d |....$.....vl...-|
00000320 4b 7b 55 94 37 ec d4 69 ce ab 0f 48 37 74 37 99 |K{U.7..i...H7t7.|
00000330 83 0d 60 8a 73 56 fb e2 9e 0c 39 0e 23 bf 68 b2 |..`.sV....9.#.h.|
00000340 92 51 12 bc cf 1b af 9d 7c fe 77 14 c8 66 4a 6f |.Q......|.w..fJo|
00000350 91 06 55 6a 11 61 17 03 03 00 99 c2 bf 26 a6 fa |..Uj.a.......&..|
00000360 67 16 a3 b9 1f 36 f8 4f 5d 59 b1 be 43 3a 70 01 |g....6.O]Y..C:p.|
00000370 c0 3a 4b c5 20 b1 22 49 04 22 bb 7f 5f f4 bb f8 |.:K. ."I.".._...|
00000380 35 03 0e dc ba ce de 2a 25 ea 96 dd 3d 64 34 90 |5......*%...=d4.|
00000390 30 f8 34 22 bb e4 94 00 bb b3 ea 3c d2 87 90 9a |0.4".......<....|
000003a0 86 76 6b b7 e3 78 fc 35 10 50 ce b6 c0 71 52 ae |.vk..x.5.P...qR.|
000003b0 a5 f7 bf 8c 5e 5d c1 96 c7 92 6f f0 04 87 d9 a8 |....^]....o.....|
000003c0 72 f4 9e ed 6d ab 28 42 7c c8 60 39 81 66 74 a1 |r...m.(B|.`9.ft.|
000003d0 79 79 6a 59 02 29 b8 14 12 34 a7 96 8f e0 c1 d6 |yyjY.)...4......|
000003e0 4e da e2 63 22 c1 60 b1 87 64 d3 80 b9 c4 df 9a |N..c".`..d......|
000003f0 5f 2c 22 91 17 03 03 00 35 9a 62 4d a2 ba 27 31 |_,".....5.bM..'1|
00000400 fc 8e 23 cc 5f f0 5c 8c 9b c1 b0 ae 7b b8 fa e2 |..#._.\.....{...|
00000410 f3 af 6c 6c ac 86 1e e1 2b 9f 14 a1 f3 5f b5 f9 |..ll....+...._..|
00000420 76 b6 dd 73 f5 6a 08 29 f1 29 9e 79 87 aa |v..s.j.).).y..|
>>> Flow 3 (client to server)
00000000 14 03 03 00 01 01 17 03 03 01 50 ef 68 27 d6 ec |..........P.h'..|
00000010 76 00 e1 c6 ed 3c f6 a1 83 b4 4b 26 28 ba 0f d6 |v....<....K&(...|
00000020 2a fd f0 4a 10 8f 9c ed 84 3f 0a 0e 5b 77 e2 7d |*..J.....?..[w.}|
00000030 1e 03 2a 76 5b 2b 87 78 ad bd 45 8b 03 b3 8d e7 |..*v[+.x..E.....|
00000040 b7 66 ca 5e 36 f8 53 87 90 3c 1a 33 46 1d 32 4f |.f.^6.S..<.3F.2O|
00000050 f1 90 fb 36 da 96 1c 1a db 9f 9b e6 9f 85 f8 13 |...6............|
00000060 7d e1 ab e1 ca c6 05 df 15 ea af dd 55 58 c7 5f |}...........UX._|
00000070 de 62 1b 93 60 a4 fc 39 0a ef 95 bc 0c ca 8f 84 |.b..`..9........|
00000080 98 0a 6d 5b fd c6 0c ad 02 7f 0c f8 b4 be fe 5a |..m[...........Z|
00000090 fb 22 00 08 09 5d c7 47 76 89 e5 06 d1 90 5b e6 |."...].Gv.....[.|
000000a0 63 64 06 28 37 d9 1b e9 0d 27 45 f7 72 30 d7 f2 |cd.(7....'E.r0..|
000000b0 db 8e bf 95 97 29 43 e7 16 bf a0 59 9c fa d9 59 |.....)C....Y...Y|
000000c0 a0 a6 9b 1f b5 74 80 87 d0 61 2f d5 a5 ac dd b2 |.....t...a/.....|
000000d0 8d 27 fc e6 68 eb 07 b3 3d 97 a9 93 5b 35 99 e9 |.'..h...=...[5..|
000000e0 ba 99 fe 49 d6 39 1a 0a 38 98 cd 47 b9 67 9b 9a |...I.9..8..G.g..|
000000f0 77 65 45 f8 48 fb d3 1c 0f a2 2e af e0 29 68 bc |weE.H........)h.|
00000100 81 24 3b 9b 36 0a ef 51 75 ff 61 6a d4 6c 59 42 |.$;.6..Qu.aj.lYB|
00000110 54 31 47 e9 02 9e 58 33 9e 89 65 b6 65 db b2 81 |T1G...X3..e.e...|
00000120 bd c1 f4 0a 34 eb f3 26 f5 8d 36 6d da 78 e6 88 |....4..&..6m.x..|
00000130 00 8f 92 24 dc 76 e3 95 dc 13 b5 92 91 ee c0 82 |...$.v..........|
00000140 cb 63 85 b6 59 67 dc 14 2e 2d 58 8e 56 7e 7c db |.c..Yg...-X.V~|.|
00000150 2f 54 01 ed 17 8d 9a 97 22 39 7f 17 03 03 00 59 |/T......"9.....Y|
00000160 a1 f2 0d 19 e7 d8 a8 6d cd ea f6 82 ee 5d 0a 55 |.......m.....].U|
00000170 22 61 11 21 f7 b0 1d 86 a8 4d c2 e2 9b ac bb 87 |"a.!.....M......|
00000180 a2 82 67 ee 78 76 9b e0 c0 00 85 bf 1e 2b ab e6 |..g.xv.......+..|
00000190 f1 43 79 69 a0 3d 04 b7 d9 7f 31 c7 7a b7 4f 5c |.Cyi.=....1.z.O\|
000001a0 9f 62 84 dc f4 6d a1 ce 3d ff 24 88 15 10 4a e6 |.b...m..=.$...J.|
000001b0 5c 12 68 08 3c 55 a2 a9 d7 17 03 03 00 35 f4 d9 |\.h.<U.......5..|
000001c0 9f 41 70 39 d4 88 2a 0b 43 c3 78 0f c2 42 48 b8 |.Ap9..*.C.x..BH.|
000001d0 e5 26 ad e3 72 40 66 d7 a0 5e 5e 0c 6a af 1a 47 |.&..r@f..^^.j..G|
000001e0 c6 5f 25 ce c9 13 77 60 8f 6e a7 9f bc e3 f9 58 |._%...w`.n.....X|
000001f0 9c 12 cc |...|
>>> Flow 4 (server to client)
00000000 17 03 03 01 c2 80 69 97 9a 20 30 2a 1c f4 31 f9 |......i.. 0*..1.|
00000010 0f cf f7 79 c0 01 e1 f3 35 f5 16 a0 33 d6 eb 21 |...y....5...3..!|
00000020 44 db bc c6 c4 91 6b a6 75 da ca d3 63 78 47 8b |D.....k.u...cxG.|
00000030 96 e5 6f 63 2c 77 c0 33 29 d8 3e ee bf 8e 6b d4 |..oc,w.3).>...k.|
00000040 de f7 1b 0e e6 ae ce cd 17 0d 24 77 10 3d e4 89 |..........$w.=..|
00000050 06 07 a3 77 68 ac 20 ec 0b ae 47 41 3b 80 4e 95 |...wh. ...GA;.N.|
00000060 02 aa 13 36 19 03 06 1c 47 b3 f7 f0 4b 6d 5a c6 |...6....G...KmZ.|
00000070 42 14 95 03 20 c7 46 96 42 d3 18 5a 40 bd a1 03 |B... .F.B..Z@...|
00000080 b6 d2 8b f9 ff 2d d1 b1 3c 8a 34 af 23 64 31 7d |.....-..<.4.#d1}|
00000090 46 47 21 b4 82 16 df a2 a4 0f 96 03 4b 38 3d 5d |FG!.........K8=]|
000000a0 d0 d1 78 d1 6e 6a a2 95 c0 a7 e6 ee 07 eb 77 68 |..x.nj........wh|
000000b0 35 78 72 3e df d9 4b e9 1b ab 34 99 2d fe 52 99 |5xr>..K...4.-.R.|
000000c0 6e 57 63 13 39 ae 5e ce b6 43 21 07 fd fe b7 6d |nWc.9.^..C!....m|
000000d0 8f 72 a4 f8 7e 0a 56 60 61 d5 5a d4 01 b3 47 8e |.r..~.V`a.Z...G.|
000000e0 f0 48 cd 85 61 a3 d2 d1 eb ba 04 39 6b 5e 5f fc |.H..a......9k^_.|
000000f0 e3 90 c1 cb 3f 40 30 00 5c 94 df bf 5b 89 6d ab |....?@0.\...[.m.|
00000100 15 1e 72 50 ac 56 ee 16 7d 84 4c e6 0c 89 68 fa |..rP.V..}.L...h.|
00000110 d5 8d 5f 09 85 25 5f 8c 70 df 0b b7 94 15 40 20 |.._..%_.p.....@ |
00000120 b1 ff 41 50 5d 9f c6 8a 9b 7f 40 6f dc bd 4f 54 |..AP].....@o..OT|
00000130 d8 1f e6 f1 44 00 11 97 45 ca 80 bc 15 eb 93 01 |....D...E.......|
00000140 dd 54 c6 75 7e 08 b9 38 f5 4d 97 c5 50 56 97 3c |.T.u~..8.M..PV.<|
00000150 3c 72 9a 33 7c 68 b1 73 2b 38 c7 b8 a8 3c 5d af |<r.3|h.s+8...<].|
00000160 a6 3e 12 ef d1 c1 99 36 10 02 af 0c 5b 16 16 7a |.>.....6....[..z|
00000170 f5 74 8d ac a4 0f 38 34 ee cd 08 50 e0 33 b0 e1 |.t....84...P.3..|
00000180 52 e1 5d f2 7d c6 7b 64 c7 46 f6 9e d0 a2 cf 89 |R.].}.{d.F......|
00000190 3c c9 ab 2f fb 8a f3 ba 78 e9 4c c5 2d 62 32 6b |<../....x.L.-b2k|
000001a0 50 4c a0 7e d3 bb 2a 66 57 99 38 69 e8 77 ef 18 |PL.~..*fW.8i.w..|
000001b0 24 af b3 cb e5 c0 37 a2 97 f6 00 d4 68 8a 71 af |$.....7.....h.q.|
000001c0 24 a4 ab 19 07 3b c0 17 03 03 00 1e 60 b4 fc 15 |$....;......`...|
000001d0 f9 9c b1 a1 60 1a ba f5 1b b9 c1 33 f1 8b e5 c0 |....`......3....|
000001e0 48 77 4f 11 42 21 ad 8c d2 d6 17 03 03 00 13 5c |HwO.B!.........\|
000001f0 db 07 5e 65 40 58 74 a4 7f ab 5f cc f0 9a 91 0c |..^e@Xt..._.....|
00000200 17 3d |.=|
| go/src/crypto/tls/testdata/Server-TLSv13-ClientAuthRequestedAndEd25519Given/0 | {
"file_path": "go/src/crypto/tls/testdata/Server-TLSv13-ClientAuthRequestedAndEd25519Given",
"repo_id": "go",
"token_count": 5941
} | 227 |
>>> Flow 1 (client to server)
00000000 16 03 01 00 c2 01 00 00 be 03 03 c1 f4 f0 72 fe |..............r.|
00000010 b9 17 c8 9e 71 08 cf 40 80 1a 11 06 68 dc de 21 |....q..@....h..!|
00000020 14 fe e2 2f 6e 55 cf 9b 83 87 dd 20 63 a3 3f 38 |.../nU..... c.?8|
00000030 4c 26 be 3c c0 2e e0 e0 5d 49 1b 92 45 6b 82 a9 |L&.<....]I..Ek..|
00000040 10 ae c0 e4 65 b0 ce 48 75 5f 5b 12 00 04 13 03 |....e..Hu_[.....|
00000050 00 ff 01 00 00 71 00 0b 00 04 03 00 01 02 00 0a |.....q..........|
00000060 00 04 00 02 00 1d 00 16 00 00 00 17 00 00 00 0d |................|
00000070 00 1e 00 1c 04 03 05 03 06 03 08 07 08 08 08 09 |................|
00000080 08 0a 08 0b 08 04 08 05 08 06 04 01 05 01 06 01 |................|
00000090 00 2b 00 03 02 03 04 00 2d 00 02 01 01 00 33 00 |.+......-.....3.|
000000a0 26 00 24 00 1d 00 20 3e 7f 8c d5 2f 42 d2 cd 67 |&.$... >.../B..g|
000000b0 24 07 69 fe 7e d0 3e 70 24 e4 62 aa 19 d6 c2 00 |$.i.~.>p$.b.....|
000000c0 5c 0d 25 10 5f 36 09 |\.%._6.|
>>> Flow 2 (server to client)
00000000 16 03 03 00 7a 02 00 00 76 03 03 00 00 00 00 00 |....z...v.......|
00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................|
00000020 00 00 00 00 00 00 00 00 00 00 00 20 63 a3 3f 38 |........... c.?8|
00000030 4c 26 be 3c c0 2e e0 e0 5d 49 1b 92 45 6b 82 a9 |L&.<....]I..Ek..|
00000040 10 ae c0 e4 65 b0 ce 48 75 5f 5b 12 13 03 00 00 |....e..Hu_[.....|
00000050 2e 00 2b 00 02 03 04 00 33 00 24 00 1d 00 20 2f |..+.....3.$... /|
00000060 e5 7d a3 47 cd 62 43 15 28 da ac 5f bb 29 07 30 |.}.G.bC.(.._.).0|
00000070 ff f6 84 af c4 cf c2 ed 90 99 5f 58 cb 3b 74 14 |.........._X.;t.|
00000080 03 03 00 01 01 17 03 03 00 17 4f 52 70 18 74 9c |..........ORp.t.|
00000090 40 4e b0 5a 7a bc aa b0 b9 22 70 b1 90 9c 04 ef |@N.Zz...."p.....|
000000a0 e7 17 03 03 02 6d a8 7e 5a 4a 5f 3d 97 f2 74 93 |.....m.~ZJ_=..t.|
000000b0 ce 75 f5 be 0f 2e c4 58 d6 91 4d fb 9f 80 56 3c |.u.....X..M...V<|
000000c0 9c d8 ea 20 2e f7 ce 34 80 af 47 0f 41 3f f9 2f |... ...4..G.A?./|
000000d0 23 c1 94 9e de 51 43 c5 1e 31 98 e6 15 33 63 64 |#....QC..1...3cd|
000000e0 22 39 87 83 87 66 d0 9e 85 2a b2 62 5e fd 50 ec |"9...f...*.b^.P.|
000000f0 0f d0 ec dd d4 75 57 0d 3f 7e a3 a4 40 f7 67 d2 |.....uW.?~..@.g.|
00000100 22 ba 5f a1 38 0b ea 8e 7d 95 43 70 52 0f b0 5f |"._.8...}.CpR.._|
00000110 ef 26 5a 52 a6 94 b4 69 89 e9 0e 4f f5 d8 60 1b |.&ZR...i...O..`.|
00000120 d3 6a fd 74 8d 19 ce 6a 72 f1 c1 96 f9 86 66 3b |.j.t...jr.....f;|
00000130 2b 38 b3 e3 76 4b fd 4a 82 3e f2 2c bc 4c 19 d7 |+8..vK.J.>.,.L..|
00000140 7a 62 21 3e 7c 41 ff 23 87 66 81 79 f0 ad a1 3e |zb!>|A.#.f.y...>|
00000150 c2 e9 f3 ba 38 3a b5 ad 49 f3 ae 70 71 0a af d2 |....8:..I..pq...|
00000160 f3 ae 70 df fd 93 8c 3d ca bd 8c 86 39 c9 9c d4 |..p....=....9...|
00000170 a9 a8 37 04 92 9b 0a 4e 8d 43 96 3d a4 b5 e0 5d |..7....N.C.=...]|
00000180 18 b1 03 32 0a b5 f2 e6 8c ca 1d ff cf 39 b7 00 |...2.........9..|
00000190 5a 5a 1a 3d de 75 17 84 12 a4 f1 08 9d b3 ae 56 |ZZ.=.u.........V|
000001a0 9d e9 af 30 67 64 fb 13 9a de 2e ba 03 ee 52 4c |...0gd........RL|
000001b0 4f 85 f3 1b fc d0 ef 75 1a 31 99 d9 89 74 41 9d |O......u.1...tA.|
000001c0 c8 96 48 49 f5 f3 ca 8c 6f 08 67 2a d1 b5 05 19 |..HI....o.g*....|
000001d0 13 6b 0b 4c 87 f8 00 ab 83 70 4e bb 7e c7 f3 1e |.k.L.....pN.~...|
000001e0 ba 83 4b 7f 65 c2 42 8d 00 b1 3e 3d f8 4d c3 7a |..K.e.B...>=.M.z|
000001f0 b9 af 68 dc 0d 24 7a a6 41 15 16 db fb 57 99 68 |..h..$z.A....W.h|
00000200 a9 35 77 40 6a 45 94 d3 e0 03 8d 41 86 d5 51 c6 |.5w@jE.....A..Q.|
00000210 05 27 c5 56 97 30 41 44 26 18 e0 0f 93 cc f2 5e |.'.V.0AD&......^|
00000220 f1 35 35 0f 54 25 51 23 78 37 39 80 d9 c2 e8 54 |.55.T%Q#x79....T|
00000230 79 16 e0 e0 36 cf f1 8b 23 fa 67 46 66 e0 25 0e |y...6...#.gFf.%.|
00000240 25 33 c4 52 93 ac 12 e0 8e f9 e8 c9 ec e7 f8 e6 |%3.R............|
00000250 09 81 c1 d1 89 33 24 a3 c6 c7 27 6c 3b c8 b7 4f |.....3$...'l;..O|
00000260 8a 14 ed 58 a7 5f ba fc cc 4f 6b eb ff c2 60 68 |...X._...Ok...`h|
00000270 41 9c 4b b6 34 10 a6 8f f8 3c 47 2f 39 75 86 03 |A.K.4....<G/9u..|
00000280 60 35 06 84 f2 96 35 39 0a c2 3e cb 3c fa d8 fa |`5....59..>.<...|
00000290 66 3c 9c c9 6b 32 3f ea bd 5d 4d 75 e5 4b 88 93 |f<..k2?..]Mu.K..|
000002a0 1f 47 73 3b 55 8a e0 e4 7e e5 2f dc 2d d4 f6 c0 |.Gs;U...~./.-...|
000002b0 3a b4 e4 72 b2 5a 0d d1 10 28 3f 61 73 96 94 d0 |:..r.Z...(?as...|
000002c0 fb 26 83 95 0e 7a 47 6d 75 d4 f4 ad cc 3e 8f 4c |.&...zGmu....>.L|
000002d0 3b 95 83 61 40 4f 3e 82 58 d0 ca 7f 1d 9a e3 86 |;..a@O>.X.......|
000002e0 48 53 1f 5d 35 9d 1e 46 c2 4b 70 53 60 1e 1d 04 |HS.]5..F.KpS`...|
000002f0 9c 5b 6a f2 0b fc 4d 04 a6 38 85 b8 f1 06 cd 40 |.[j...M..8.....@|
00000300 bb 73 fa bf 75 21 70 93 31 83 8d 8a a4 b3 4a 2f |.s..u!p.1.....J/|
00000310 45 f0 b2 17 03 03 00 99 eb ae 23 e6 63 22 52 ac |E.........#.c"R.|
00000320 2b 69 05 9d 7d b3 c6 b6 1f 5b 00 7c fb 67 1b af |+i..}....[.|.g..|
00000330 42 38 40 ea ca bb dc 7d 92 94 dd ed 1a 20 65 8a |B8@....}..... e.|
00000340 5c a3 5c 28 9f 10 8b 11 61 bb 0a 56 5a ef ec 7a |\.\(....a..VZ..z|
00000350 50 b5 2d 67 62 77 80 dc ee a6 cd f3 09 ff 8f d8 |P.-gbw..........|
00000360 ff 6d d8 47 95 58 cf 2b e7 b0 f8 26 61 58 35 a3 |.m.G.X.+...&aX5.|
00000370 07 4d 2f 99 5d 33 6b e8 ac 6a 14 ef 2c 57 9a e3 |.M/.]3k..j..,W..|
00000380 b7 1b bf d6 bf b8 6a 29 4a 74 0d 15 91 90 c3 4a |......j)Jt.....J|
00000390 40 13 8c 52 e6 67 d6 de 6c d8 4e 35 20 d3 0b e6 |@..R.g..l.N5 ...|
000003a0 36 58 4e 79 3a 03 f0 bc 34 1b 3e 7e e3 ad d8 e3 |6XNy:...4.>~....|
000003b0 58 17 03 03 00 35 ba 6d a2 40 3a cb 43 80 cb af |X....5.m.@:.C...|
000003c0 df 8f 2c 0d 20 53 f5 13 06 6b 0b e8 e7 36 31 4b |..,. S...k...61K|
000003d0 19 ad 86 5e 39 2e 52 5a d9 86 f4 64 0e 8c 9a d5 |...^9.RZ...d....|
000003e0 9a a2 c1 81 65 1e da 05 28 8a 36 17 03 03 00 8b |....e...(.6.....|
000003f0 48 2d b0 5b 7e 39 95 b2 6a de 46 53 fb ba 7b 12 |H-.[~9..j.FS..{.|
00000400 26 a1 1a b0 24 c0 8c c3 77 e1 0e 09 1c 5f 6a 7b |&...$...w...._j{|
00000410 03 0b 3d 92 77 81 b1 97 22 0f 6e cd 04 97 28 79 |..=.w...".n...(y|
00000420 eb 88 3d 7b 20 93 0b 67 df 32 2e bb 38 13 8f 28 |..={ ..g.2..8..(|
00000430 c1 b8 2c 22 75 42 01 b8 50 2c 20 30 91 0d e5 a0 |..,"uB..P, 0....|
00000440 5c dd 5b 53 c6 30 fd b4 a5 f7 e9 6f 49 61 70 32 |\.[S.0.....oIap2|
00000450 7f fd bb 08 c4 93 e8 e2 0a f6 7d 0f e8 94 22 fe |..........}...".|
00000460 af b7 b6 4a 35 d1 63 6c bd ce 1e 72 63 ca 05 7c |...J5.cl...rc..||
00000470 64 4d ae 94 28 b2 15 b5 71 16 77 |dM..(...q.w|
>>> Flow 3 (client to server)
00000000 14 03 03 00 01 01 17 03 03 00 35 97 9f be 06 f2 |..........5.....|
00000010 96 ae fa 11 e0 23 2b 6a b0 2e f5 e9 fc 10 b2 36 |.....#+j.......6|
00000020 dc 62 b0 70 1e 42 e3 c5 ce c8 f7 a7 cb 1b c6 3b |.b.p.B.........;|
00000030 59 23 d0 10 be f5 f0 1e 38 f4 63 bd 36 28 24 eb |Y#......8.c.6($.|
>>> Flow 4 (server to client)
00000000 17 03 03 00 1e 05 1b a2 f1 4b 74 46 76 1b 23 77 |.........KtFv.#w|
00000010 79 df f1 67 bf e9 39 f3 b7 56 76 ba fa 4f 30 49 |y..g..9..Vv..O0I|
00000020 18 7b 52 17 03 03 00 13 ef 66 20 67 cb 74 a9 b6 |.{R......f g.t..|
00000030 93 6f cc a3 9e d5 f2 7d 81 10 71 |.o.....}..q|
| go/src/crypto/tls/testdata/Server-TLSv13-X25519/0 | {
"file_path": "go/src/crypto/tls/testdata/Server-TLSv13-X25519",
"repo_id": "go",
"token_count": 3813
} | 228 |
// Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build darwin
#include "textflag.h"
// The trampolines are ABIInternal as they are address-taken in
// Go code.
TEXT ·x509_SecTrustSettingsCopyCertificates_trampoline(SB),NOSPLIT,$0-0
JMP x509_SecTrustSettingsCopyCertificates(SB)
TEXT ·x509_SecTrustSettingsCopyTrustSettings_trampoline(SB),NOSPLIT,$0-0
JMP x509_SecTrustSettingsCopyTrustSettings(SB)
TEXT ·x509_SecTrustCreateWithCertificates_trampoline(SB),NOSPLIT,$0-0
JMP x509_SecTrustCreateWithCertificates(SB)
TEXT ·x509_SecCertificateCreateWithData_trampoline(SB),NOSPLIT,$0-0
JMP x509_SecCertificateCreateWithData(SB)
TEXT ·x509_SecPolicyCreateSSL_trampoline(SB),NOSPLIT,$0-0
JMP x509_SecPolicyCreateSSL(SB)
TEXT ·x509_SecTrustSetVerifyDate_trampoline(SB),NOSPLIT,$0-0
JMP x509_SecTrustSetVerifyDate(SB)
TEXT ·x509_SecTrustEvaluate_trampoline(SB),NOSPLIT,$0-0
JMP x509_SecTrustEvaluate(SB)
TEXT ·x509_SecTrustGetResult_trampoline(SB),NOSPLIT,$0-0
JMP x509_SecTrustGetResult(SB)
TEXT ·x509_SecTrustEvaluateWithError_trampoline(SB),NOSPLIT,$0-0
JMP x509_SecTrustEvaluateWithError(SB)
TEXT ·x509_SecTrustGetCertificateCount_trampoline(SB),NOSPLIT,$0-0
JMP x509_SecTrustGetCertificateCount(SB)
TEXT ·x509_SecTrustGetCertificateAtIndex_trampoline(SB),NOSPLIT,$0-0
JMP x509_SecTrustGetCertificateAtIndex(SB)
TEXT ·x509_SecCertificateCopyData_trampoline(SB),NOSPLIT,$0-0
JMP x509_SecCertificateCopyData(SB)
| go/src/crypto/x509/internal/macos/security.s/0 | {
"file_path": "go/src/crypto/x509/internal/macos/security.s",
"repo_id": "go",
"token_count": 611
} | 229 |
// Copyright 2012 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 x509
import (
"internal/godebug"
"sync"
_ "unsafe" // for linkname
)
// systemRoots should be an internal detail,
// but widely used packages access it using linkname.
// Notable members of the hall of shame include:
// - github.com/breml/rootcerts
//
// Do not remove or change the type signature.
// See go.dev/issue/67401.
//
//go:linkname systemRoots
var (
once sync.Once
systemRootsMu sync.RWMutex
systemRoots *CertPool
systemRootsErr error
fallbacksSet bool
)
func systemRootsPool() *CertPool {
once.Do(initSystemRoots)
systemRootsMu.RLock()
defer systemRootsMu.RUnlock()
return systemRoots
}
func initSystemRoots() {
systemRootsMu.Lock()
defer systemRootsMu.Unlock()
systemRoots, systemRootsErr = loadSystemRoots()
if systemRootsErr != nil {
systemRoots = nil
}
}
var x509usefallbackroots = godebug.New("x509usefallbackroots")
// SetFallbackRoots sets the roots to use during certificate verification, if no
// custom roots are specified and a platform verifier or a system certificate
// pool is not available (for instance in a container which does not have a root
// certificate bundle). SetFallbackRoots will panic if roots is nil.
//
// SetFallbackRoots may only be called once, if called multiple times it will
// panic.
//
// The fallback behavior can be forced on all platforms, even when there is a
// system certificate pool, by setting GODEBUG=x509usefallbackroots=1 (note that
// on Windows and macOS this will disable usage of the platform verification
// APIs and cause the pure Go verifier to be used). Setting
// x509usefallbackroots=1 without calling SetFallbackRoots has no effect.
func SetFallbackRoots(roots *CertPool) {
if roots == nil {
panic("roots must be non-nil")
}
// trigger initSystemRoots if it hasn't already been called before we
// take the lock
_ = systemRootsPool()
systemRootsMu.Lock()
defer systemRootsMu.Unlock()
if fallbacksSet {
panic("SetFallbackRoots has already been called")
}
fallbacksSet = true
if systemRoots != nil && (systemRoots.len() > 0 || systemRoots.systemPool) {
if x509usefallbackroots.Value() != "1" {
return
}
x509usefallbackroots.IncNonDefault()
}
systemRoots, systemRootsErr = roots, nil
}
| go/src/crypto/x509/root.go/0 | {
"file_path": "go/src/crypto/x509/root.go",
"repo_id": "go",
"token_count": 769
} | 230 |
// Copyright 2011 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 x509
import (
"bytes"
"crypto"
"crypto/x509/pkix"
"errors"
"fmt"
"net"
"net/url"
"reflect"
"runtime"
"strings"
"time"
"unicode/utf8"
)
type InvalidReason int
const (
// NotAuthorizedToSign results when a certificate is signed by another
// which isn't marked as a CA certificate.
NotAuthorizedToSign InvalidReason = iota
// Expired results when a certificate has expired, based on the time
// given in the VerifyOptions.
Expired
// CANotAuthorizedForThisName results when an intermediate or root
// certificate has a name constraint which doesn't permit a DNS or
// other name (including IP address) in the leaf certificate.
CANotAuthorizedForThisName
// TooManyIntermediates results when a path length constraint is
// violated.
TooManyIntermediates
// IncompatibleUsage results when the certificate's key usage indicates
// that it may only be used for a different purpose.
IncompatibleUsage
// NameMismatch results when the subject name of a parent certificate
// does not match the issuer name in the child.
NameMismatch
// NameConstraintsWithoutSANs is a legacy error and is no longer returned.
NameConstraintsWithoutSANs
// UnconstrainedName results when a CA certificate contains permitted
// name constraints, but leaf certificate contains a name of an
// unsupported or unconstrained type.
UnconstrainedName
// TooManyConstraints results when the number of comparison operations
// needed to check a certificate exceeds the limit set by
// VerifyOptions.MaxConstraintComparisions. This limit exists to
// prevent pathological certificates can consuming excessive amounts of
// CPU time to verify.
TooManyConstraints
// CANotAuthorizedForExtKeyUsage results when an intermediate or root
// certificate does not permit a requested extended key usage.
CANotAuthorizedForExtKeyUsage
)
// CertificateInvalidError results when an odd error occurs. Users of this
// library probably want to handle all these errors uniformly.
type CertificateInvalidError struct {
Cert *Certificate
Reason InvalidReason
Detail string
}
func (e CertificateInvalidError) Error() string {
switch e.Reason {
case NotAuthorizedToSign:
return "x509: certificate is not authorized to sign other certificates"
case Expired:
return "x509: certificate has expired or is not yet valid: " + e.Detail
case CANotAuthorizedForThisName:
return "x509: a root or intermediate certificate is not authorized to sign for this name: " + e.Detail
case CANotAuthorizedForExtKeyUsage:
return "x509: a root or intermediate certificate is not authorized for an extended key usage: " + e.Detail
case TooManyIntermediates:
return "x509: too many intermediates for path length constraint"
case IncompatibleUsage:
return "x509: certificate specifies an incompatible key usage"
case NameMismatch:
return "x509: issuer name does not match subject from issuing certificate"
case NameConstraintsWithoutSANs:
return "x509: issuer has name constraints but leaf doesn't have a SAN extension"
case UnconstrainedName:
return "x509: issuer has name constraints but leaf contains unknown or unconstrained name: " + e.Detail
}
return "x509: unknown error"
}
// HostnameError results when the set of authorized names doesn't match the
// requested name.
type HostnameError struct {
Certificate *Certificate
Host string
}
func (h HostnameError) Error() string {
c := h.Certificate
if !c.hasSANExtension() && matchHostnames(c.Subject.CommonName, h.Host) {
return "x509: certificate relies on legacy Common Name field, use SANs instead"
}
var valid string
if ip := net.ParseIP(h.Host); ip != nil {
// Trying to validate an IP
if len(c.IPAddresses) == 0 {
return "x509: cannot validate certificate for " + h.Host + " because it doesn't contain any IP SANs"
}
for _, san := range c.IPAddresses {
if len(valid) > 0 {
valid += ", "
}
valid += san.String()
}
} else {
valid = strings.Join(c.DNSNames, ", ")
}
if len(valid) == 0 {
return "x509: certificate is not valid for any names, but wanted to match " + h.Host
}
return "x509: certificate is valid for " + valid + ", not " + h.Host
}
// UnknownAuthorityError results when the certificate issuer is unknown
type UnknownAuthorityError struct {
Cert *Certificate
// hintErr contains an error that may be helpful in determining why an
// authority wasn't found.
hintErr error
// hintCert contains a possible authority certificate that was rejected
// because of the error in hintErr.
hintCert *Certificate
}
func (e UnknownAuthorityError) Error() string {
s := "x509: certificate signed by unknown authority"
if e.hintErr != nil {
certName := e.hintCert.Subject.CommonName
if len(certName) == 0 {
if len(e.hintCert.Subject.Organization) > 0 {
certName = e.hintCert.Subject.Organization[0]
} else {
certName = "serial:" + e.hintCert.SerialNumber.String()
}
}
s += fmt.Sprintf(" (possibly because of %q while trying to verify candidate authority certificate %q)", e.hintErr, certName)
}
return s
}
// SystemRootsError results when we fail to load the system root certificates.
type SystemRootsError struct {
Err error
}
func (se SystemRootsError) Error() string {
msg := "x509: failed to load system roots and no roots provided"
if se.Err != nil {
return msg + "; " + se.Err.Error()
}
return msg
}
func (se SystemRootsError) Unwrap() error { return se.Err }
// errNotParsed is returned when a certificate without ASN.1 contents is
// verified. Platform-specific verification needs the ASN.1 contents.
var errNotParsed = errors.New("x509: missing ASN.1 contents; use ParseCertificate")
// VerifyOptions contains parameters for Certificate.Verify.
type VerifyOptions struct {
// DNSName, if set, is checked against the leaf certificate with
// Certificate.VerifyHostname or the platform verifier.
DNSName string
// Intermediates is an optional pool of certificates that are not trust
// anchors, but can be used to form a chain from the leaf certificate to a
// root certificate.
Intermediates *CertPool
// Roots is the set of trusted root certificates the leaf certificate needs
// to chain up to. If nil, the system roots or the platform verifier are used.
Roots *CertPool
// CurrentTime is used to check the validity of all certificates in the
// chain. If zero, the current time is used.
CurrentTime time.Time
// KeyUsages specifies which Extended Key Usage values are acceptable. A
// chain is accepted if it allows any of the listed values. An empty list
// means ExtKeyUsageServerAuth. To accept any key usage, include ExtKeyUsageAny.
KeyUsages []ExtKeyUsage
// MaxConstraintComparisions is the maximum number of comparisons to
// perform when checking a given certificate's name constraints. If
// zero, a sensible default is used. This limit prevents pathological
// certificates from consuming excessive amounts of CPU time when
// validating. It does not apply to the platform verifier.
MaxConstraintComparisions int
}
const (
leafCertificate = iota
intermediateCertificate
rootCertificate
)
// rfc2821Mailbox represents a “mailbox” (which is an email address to most
// people) by breaking it into the “local” (i.e. before the '@') and “domain”
// parts.
type rfc2821Mailbox struct {
local, domain string
}
// parseRFC2821Mailbox parses an email address into local and domain parts,
// based on the ABNF for a “Mailbox” from RFC 2821. According to RFC 5280,
// Section 4.2.1.6 that's correct for an rfc822Name from a certificate: “The
// format of an rfc822Name is a "Mailbox" as defined in RFC 2821, Section 4.1.2”.
func parseRFC2821Mailbox(in string) (mailbox rfc2821Mailbox, ok bool) {
if len(in) == 0 {
return mailbox, false
}
localPartBytes := make([]byte, 0, len(in)/2)
if in[0] == '"' {
// Quoted-string = DQUOTE *qcontent DQUOTE
// non-whitespace-control = %d1-8 / %d11 / %d12 / %d14-31 / %d127
// qcontent = qtext / quoted-pair
// qtext = non-whitespace-control /
// %d33 / %d35-91 / %d93-126
// quoted-pair = ("\" text) / obs-qp
// text = %d1-9 / %d11 / %d12 / %d14-127 / obs-text
//
// (Names beginning with “obs-” are the obsolete syntax from RFC 2822,
// Section 4. Since it has been 16 years, we no longer accept that.)
in = in[1:]
QuotedString:
for {
if len(in) == 0 {
return mailbox, false
}
c := in[0]
in = in[1:]
switch {
case c == '"':
break QuotedString
case c == '\\':
// quoted-pair
if len(in) == 0 {
return mailbox, false
}
if in[0] == 11 ||
in[0] == 12 ||
(1 <= in[0] && in[0] <= 9) ||
(14 <= in[0] && in[0] <= 127) {
localPartBytes = append(localPartBytes, in[0])
in = in[1:]
} else {
return mailbox, false
}
case c == 11 ||
c == 12 ||
// Space (char 32) is not allowed based on the
// BNF, but RFC 3696 gives an example that
// assumes that it is. Several “verified”
// errata continue to argue about this point.
// We choose to accept it.
c == 32 ||
c == 33 ||
c == 127 ||
(1 <= c && c <= 8) ||
(14 <= c && c <= 31) ||
(35 <= c && c <= 91) ||
(93 <= c && c <= 126):
// qtext
localPartBytes = append(localPartBytes, c)
default:
return mailbox, false
}
}
} else {
// Atom ("." Atom)*
NextChar:
for len(in) > 0 {
// atext from RFC 2822, Section 3.2.4
c := in[0]
switch {
case c == '\\':
// Examples given in RFC 3696 suggest that
// escaped characters can appear outside of a
// quoted string. Several “verified” errata
// continue to argue the point. We choose to
// accept it.
in = in[1:]
if len(in) == 0 {
return mailbox, false
}
fallthrough
case ('0' <= c && c <= '9') ||
('a' <= c && c <= 'z') ||
('A' <= c && c <= 'Z') ||
c == '!' || c == '#' || c == '$' || c == '%' ||
c == '&' || c == '\'' || c == '*' || c == '+' ||
c == '-' || c == '/' || c == '=' || c == '?' ||
c == '^' || c == '_' || c == '`' || c == '{' ||
c == '|' || c == '}' || c == '~' || c == '.':
localPartBytes = append(localPartBytes, in[0])
in = in[1:]
default:
break NextChar
}
}
if len(localPartBytes) == 0 {
return mailbox, false
}
// From RFC 3696, Section 3:
// “period (".") may also appear, but may not be used to start
// or end the local part, nor may two or more consecutive
// periods appear.”
twoDots := []byte{'.', '.'}
if localPartBytes[0] == '.' ||
localPartBytes[len(localPartBytes)-1] == '.' ||
bytes.Contains(localPartBytes, twoDots) {
return mailbox, false
}
}
if len(in) == 0 || in[0] != '@' {
return mailbox, false
}
in = in[1:]
// The RFC species a format for domains, but that's known to be
// violated in practice so we accept that anything after an '@' is the
// domain part.
if _, ok := domainToReverseLabels(in); !ok {
return mailbox, false
}
mailbox.local = string(localPartBytes)
mailbox.domain = in
return mailbox, true
}
// domainToReverseLabels converts a textual domain name like foo.example.com to
// the list of labels in reverse order, e.g. ["com", "example", "foo"].
func domainToReverseLabels(domain string) (reverseLabels []string, ok bool) {
for len(domain) > 0 {
if i := strings.LastIndexByte(domain, '.'); i == -1 {
reverseLabels = append(reverseLabels, domain)
domain = ""
} else {
reverseLabels = append(reverseLabels, domain[i+1:])
domain = domain[:i]
if i == 0 { // domain == ""
// domain is prefixed with an empty label, append an empty
// string to reverseLabels to indicate this.
reverseLabels = append(reverseLabels, "")
}
}
}
if len(reverseLabels) > 0 && len(reverseLabels[0]) == 0 {
// An empty label at the end indicates an absolute value.
return nil, false
}
for _, label := range reverseLabels {
if len(label) == 0 {
// Empty labels are otherwise invalid.
return nil, false
}
for _, c := range label {
if c < 33 || c > 126 {
// Invalid character.
return nil, false
}
}
}
return reverseLabels, true
}
func matchEmailConstraint(mailbox rfc2821Mailbox, constraint string) (bool, error) {
// If the constraint contains an @, then it specifies an exact mailbox
// name.
if strings.Contains(constraint, "@") {
constraintMailbox, ok := parseRFC2821Mailbox(constraint)
if !ok {
return false, fmt.Errorf("x509: internal error: cannot parse constraint %q", constraint)
}
return mailbox.local == constraintMailbox.local && strings.EqualFold(mailbox.domain, constraintMailbox.domain), nil
}
// Otherwise the constraint is like a DNS constraint of the domain part
// of the mailbox.
return matchDomainConstraint(mailbox.domain, constraint)
}
func matchURIConstraint(uri *url.URL, constraint string) (bool, error) {
// From RFC 5280, Section 4.2.1.10:
// “a uniformResourceIdentifier that does not include an authority
// component with a host name specified as a fully qualified domain
// name (e.g., if the URI either does not include an authority
// component or includes an authority component in which the host name
// is specified as an IP address), then the application MUST reject the
// certificate.”
host := uri.Host
if len(host) == 0 {
return false, fmt.Errorf("URI with empty host (%q) cannot be matched against constraints", uri.String())
}
if strings.Contains(host, ":") && !strings.HasSuffix(host, "]") {
var err error
host, _, err = net.SplitHostPort(uri.Host)
if err != nil {
return false, err
}
}
if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") ||
net.ParseIP(host) != nil {
return false, fmt.Errorf("URI with IP (%q) cannot be matched against constraints", uri.String())
}
return matchDomainConstraint(host, constraint)
}
func matchIPConstraint(ip net.IP, constraint *net.IPNet) (bool, error) {
if len(ip) != len(constraint.IP) {
return false, nil
}
for i := range ip {
if mask := constraint.Mask[i]; ip[i]&mask != constraint.IP[i]&mask {
return false, nil
}
}
return true, nil
}
func matchDomainConstraint(domain, constraint string) (bool, error) {
// The meaning of zero length constraints is not specified, but this
// code follows NSS and accepts them as matching everything.
if len(constraint) == 0 {
return true, nil
}
domainLabels, ok := domainToReverseLabels(domain)
if !ok {
return false, fmt.Errorf("x509: internal error: cannot parse domain %q", domain)
}
// RFC 5280 says that a leading period in a domain name means that at
// least one label must be prepended, but only for URI and email
// constraints, not DNS constraints. The code also supports that
// behaviour for DNS constraints.
mustHaveSubdomains := false
if constraint[0] == '.' {
mustHaveSubdomains = true
constraint = constraint[1:]
}
constraintLabels, ok := domainToReverseLabels(constraint)
if !ok {
return false, fmt.Errorf("x509: internal error: cannot parse domain %q", constraint)
}
if len(domainLabels) < len(constraintLabels) ||
(mustHaveSubdomains && len(domainLabels) == len(constraintLabels)) {
return false, nil
}
for i, constraintLabel := range constraintLabels {
if !strings.EqualFold(constraintLabel, domainLabels[i]) {
return false, nil
}
}
return true, nil
}
// checkNameConstraints checks that c permits a child certificate to claim the
// given name, of type nameType. The argument parsedName contains the parsed
// form of name, suitable for passing to the match function. The total number
// of comparisons is tracked in the given count and should not exceed the given
// limit.
func (c *Certificate) checkNameConstraints(count *int,
maxConstraintComparisons int,
nameType string,
name string,
parsedName any,
match func(parsedName, constraint any) (match bool, err error),
permitted, excluded any) error {
excludedValue := reflect.ValueOf(excluded)
*count += excludedValue.Len()
if *count > maxConstraintComparisons {
return CertificateInvalidError{c, TooManyConstraints, ""}
}
for i := 0; i < excludedValue.Len(); i++ {
constraint := excludedValue.Index(i).Interface()
match, err := match(parsedName, constraint)
if err != nil {
return CertificateInvalidError{c, CANotAuthorizedForThisName, err.Error()}
}
if match {
return CertificateInvalidError{c, CANotAuthorizedForThisName, fmt.Sprintf("%s %q is excluded by constraint %q", nameType, name, constraint)}
}
}
permittedValue := reflect.ValueOf(permitted)
*count += permittedValue.Len()
if *count > maxConstraintComparisons {
return CertificateInvalidError{c, TooManyConstraints, ""}
}
ok := true
for i := 0; i < permittedValue.Len(); i++ {
constraint := permittedValue.Index(i).Interface()
var err error
if ok, err = match(parsedName, constraint); err != nil {
return CertificateInvalidError{c, CANotAuthorizedForThisName, err.Error()}
}
if ok {
break
}
}
if !ok {
return CertificateInvalidError{c, CANotAuthorizedForThisName, fmt.Sprintf("%s %q is not permitted by any constraint", nameType, name)}
}
return nil
}
// isValid performs validity checks on c given that it is a candidate to append
// to the chain in currentChain.
func (c *Certificate) isValid(certType int, currentChain []*Certificate, opts *VerifyOptions) error {
if len(c.UnhandledCriticalExtensions) > 0 {
return UnhandledCriticalExtension{}
}
if len(currentChain) > 0 {
child := currentChain[len(currentChain)-1]
if !bytes.Equal(child.RawIssuer, c.RawSubject) {
return CertificateInvalidError{c, NameMismatch, ""}
}
}
now := opts.CurrentTime
if now.IsZero() {
now = time.Now()
}
if now.Before(c.NotBefore) {
return CertificateInvalidError{
Cert: c,
Reason: Expired,
Detail: fmt.Sprintf("current time %s is before %s", now.Format(time.RFC3339), c.NotBefore.Format(time.RFC3339)),
}
} else if now.After(c.NotAfter) {
return CertificateInvalidError{
Cert: c,
Reason: Expired,
Detail: fmt.Sprintf("current time %s is after %s", now.Format(time.RFC3339), c.NotAfter.Format(time.RFC3339)),
}
}
maxConstraintComparisons := opts.MaxConstraintComparisions
if maxConstraintComparisons == 0 {
maxConstraintComparisons = 250000
}
comparisonCount := 0
if certType == intermediateCertificate || certType == rootCertificate {
if len(currentChain) == 0 {
return errors.New("x509: internal error: empty chain when appending CA cert")
}
}
if (certType == intermediateCertificate || certType == rootCertificate) &&
c.hasNameConstraints() {
toCheck := []*Certificate{}
for _, c := range currentChain {
if c.hasSANExtension() {
toCheck = append(toCheck, c)
}
}
for _, sanCert := range toCheck {
err := forEachSAN(sanCert.getSANExtension(), func(tag int, data []byte) error {
switch tag {
case nameTypeEmail:
name := string(data)
mailbox, ok := parseRFC2821Mailbox(name)
if !ok {
return fmt.Errorf("x509: cannot parse rfc822Name %q", mailbox)
}
if err := c.checkNameConstraints(&comparisonCount, maxConstraintComparisons, "email address", name, mailbox,
func(parsedName, constraint any) (bool, error) {
return matchEmailConstraint(parsedName.(rfc2821Mailbox), constraint.(string))
}, c.PermittedEmailAddresses, c.ExcludedEmailAddresses); err != nil {
return err
}
case nameTypeDNS:
name := string(data)
if _, ok := domainToReverseLabels(name); !ok {
return fmt.Errorf("x509: cannot parse dnsName %q", name)
}
if err := c.checkNameConstraints(&comparisonCount, maxConstraintComparisons, "DNS name", name, name,
func(parsedName, constraint any) (bool, error) {
return matchDomainConstraint(parsedName.(string), constraint.(string))
}, c.PermittedDNSDomains, c.ExcludedDNSDomains); err != nil {
return err
}
case nameTypeURI:
name := string(data)
uri, err := url.Parse(name)
if err != nil {
return fmt.Errorf("x509: internal error: URI SAN %q failed to parse", name)
}
if err := c.checkNameConstraints(&comparisonCount, maxConstraintComparisons, "URI", name, uri,
func(parsedName, constraint any) (bool, error) {
return matchURIConstraint(parsedName.(*url.URL), constraint.(string))
}, c.PermittedURIDomains, c.ExcludedURIDomains); err != nil {
return err
}
case nameTypeIP:
ip := net.IP(data)
if l := len(ip); l != net.IPv4len && l != net.IPv6len {
return fmt.Errorf("x509: internal error: IP SAN %x failed to parse", data)
}
if err := c.checkNameConstraints(&comparisonCount, maxConstraintComparisons, "IP address", ip.String(), ip,
func(parsedName, constraint any) (bool, error) {
return matchIPConstraint(parsedName.(net.IP), constraint.(*net.IPNet))
}, c.PermittedIPRanges, c.ExcludedIPRanges); err != nil {
return err
}
default:
// Unknown SAN types are ignored.
}
return nil
})
if err != nil {
return err
}
}
}
// KeyUsage status flags are ignored. From Engineering Security, Peter
// Gutmann: A European government CA marked its signing certificates as
// being valid for encryption only, but no-one noticed. Another
// European CA marked its signature keys as not being valid for
// signatures. A different CA marked its own trusted root certificate
// as being invalid for certificate signing. Another national CA
// distributed a certificate to be used to encrypt data for the
// country’s tax authority that was marked as only being usable for
// digital signatures but not for encryption. Yet another CA reversed
// the order of the bit flags in the keyUsage due to confusion over
// encoding endianness, essentially setting a random keyUsage in
// certificates that it issued. Another CA created a self-invalidating
// certificate by adding a certificate policy statement stipulating
// that the certificate had to be used strictly as specified in the
// keyUsage, and a keyUsage containing a flag indicating that the RSA
// encryption key could only be used for Diffie-Hellman key agreement.
if certType == intermediateCertificate && (!c.BasicConstraintsValid || !c.IsCA) {
return CertificateInvalidError{c, NotAuthorizedToSign, ""}
}
if c.BasicConstraintsValid && c.MaxPathLen >= 0 {
numIntermediates := len(currentChain) - 1
if numIntermediates > c.MaxPathLen {
return CertificateInvalidError{c, TooManyIntermediates, ""}
}
}
if !boringAllowCert(c) {
// IncompatibleUsage is not quite right here,
// but it's also the "no chains found" error
// and is close enough.
return CertificateInvalidError{c, IncompatibleUsage, ""}
}
return nil
}
// Verify attempts to verify c by building one or more chains from c to a
// certificate in opts.Roots, using certificates in opts.Intermediates if
// needed. If successful, it returns one or more chains where the first
// element of the chain is c and the last element is from opts.Roots.
//
// If opts.Roots is nil, the platform verifier might be used, and
// verification details might differ from what is described below. If system
// roots are unavailable the returned error will be of type SystemRootsError.
//
// Name constraints in the intermediates will be applied to all names claimed
// in the chain, not just opts.DNSName. Thus it is invalid for a leaf to claim
// example.com if an intermediate doesn't permit it, even if example.com is not
// the name being validated. Note that DirectoryName constraints are not
// supported.
//
// Name constraint validation follows the rules from RFC 5280, with the
// addition that DNS name constraints may use the leading period format
// defined for emails and URIs. When a constraint has a leading period
// it indicates that at least one additional label must be prepended to
// the constrained name to be considered valid.
//
// Extended Key Usage values are enforced nested down a chain, so an intermediate
// or root that enumerates EKUs prevents a leaf from asserting an EKU not in that
// list. (While this is not specified, it is common practice in order to limit
// the types of certificates a CA can issue.)
//
// Certificates that use SHA1WithRSA and ECDSAWithSHA1 signatures are not supported,
// and will not be used to build chains.
//
// Certificates other than c in the returned chains should not be modified.
//
// WARNING: this function doesn't do any revocation checking.
func (c *Certificate) Verify(opts VerifyOptions) (chains [][]*Certificate, err error) {
// Platform-specific verification needs the ASN.1 contents so
// this makes the behavior consistent across platforms.
if len(c.Raw) == 0 {
return nil, errNotParsed
}
for i := 0; i < opts.Intermediates.len(); i++ {
c, _, err := opts.Intermediates.cert(i)
if err != nil {
return nil, fmt.Errorf("crypto/x509: error fetching intermediate: %w", err)
}
if len(c.Raw) == 0 {
return nil, errNotParsed
}
}
// Use platform verifiers, where available, if Roots is from SystemCertPool.
if runtime.GOOS == "windows" || runtime.GOOS == "darwin" || runtime.GOOS == "ios" {
// Don't use the system verifier if the system pool was replaced with a non-system pool,
// i.e. if SetFallbackRoots was called with x509usefallbackroots=1.
systemPool := systemRootsPool()
if opts.Roots == nil && (systemPool == nil || systemPool.systemPool) {
return c.systemVerify(&opts)
}
if opts.Roots != nil && opts.Roots.systemPool {
platformChains, err := c.systemVerify(&opts)
// If the platform verifier succeeded, or there are no additional
// roots, return the platform verifier result. Otherwise, continue
// with the Go verifier.
if err == nil || opts.Roots.len() == 0 {
return platformChains, err
}
}
}
if opts.Roots == nil {
opts.Roots = systemRootsPool()
if opts.Roots == nil {
return nil, SystemRootsError{systemRootsErr}
}
}
err = c.isValid(leafCertificate, nil, &opts)
if err != nil {
return
}
if len(opts.DNSName) > 0 {
err = c.VerifyHostname(opts.DNSName)
if err != nil {
return
}
}
var candidateChains [][]*Certificate
if opts.Roots.contains(c) {
candidateChains = [][]*Certificate{{c}}
} else {
candidateChains, err = c.buildChains([]*Certificate{c}, nil, &opts)
if err != nil {
return nil, err
}
}
if len(opts.KeyUsages) == 0 {
opts.KeyUsages = []ExtKeyUsage{ExtKeyUsageServerAuth}
}
for _, eku := range opts.KeyUsages {
if eku == ExtKeyUsageAny {
// If any key usage is acceptable, no need to check the chain for
// key usages.
return candidateChains, nil
}
}
chains = make([][]*Certificate, 0, len(candidateChains))
for _, candidate := range candidateChains {
if checkChainForKeyUsage(candidate, opts.KeyUsages) {
chains = append(chains, candidate)
}
}
if len(chains) == 0 {
return nil, CertificateInvalidError{c, IncompatibleUsage, ""}
}
return chains, nil
}
func appendToFreshChain(chain []*Certificate, cert *Certificate) []*Certificate {
n := make([]*Certificate, len(chain)+1)
copy(n, chain)
n[len(chain)] = cert
return n
}
// alreadyInChain checks whether a candidate certificate is present in a chain.
// Rather than doing a direct byte for byte equivalency check, we check if the
// subject, public key, and SAN, if present, are equal. This prevents loops that
// are created by mutual cross-signatures, or other cross-signature bridge
// oddities.
func alreadyInChain(candidate *Certificate, chain []*Certificate) bool {
type pubKeyEqual interface {
Equal(crypto.PublicKey) bool
}
var candidateSAN *pkix.Extension
for _, ext := range candidate.Extensions {
if ext.Id.Equal(oidExtensionSubjectAltName) {
candidateSAN = &ext
break
}
}
for _, cert := range chain {
if !bytes.Equal(candidate.RawSubject, cert.RawSubject) {
continue
}
if !candidate.PublicKey.(pubKeyEqual).Equal(cert.PublicKey) {
continue
}
var certSAN *pkix.Extension
for _, ext := range cert.Extensions {
if ext.Id.Equal(oidExtensionSubjectAltName) {
certSAN = &ext
break
}
}
if candidateSAN == nil && certSAN == nil {
return true
} else if candidateSAN == nil || certSAN == nil {
return false
}
if bytes.Equal(candidateSAN.Value, certSAN.Value) {
return true
}
}
return false
}
// maxChainSignatureChecks is the maximum number of CheckSignatureFrom calls
// that an invocation of buildChains will (transitively) make. Most chains are
// less than 15 certificates long, so this leaves space for multiple chains and
// for failed checks due to different intermediates having the same Subject.
const maxChainSignatureChecks = 100
func (c *Certificate) buildChains(currentChain []*Certificate, sigChecks *int, opts *VerifyOptions) (chains [][]*Certificate, err error) {
var (
hintErr error
hintCert *Certificate
)
considerCandidate := func(certType int, candidate potentialParent) {
if candidate.cert.PublicKey == nil || alreadyInChain(candidate.cert, currentChain) {
return
}
if sigChecks == nil {
sigChecks = new(int)
}
*sigChecks++
if *sigChecks > maxChainSignatureChecks {
err = errors.New("x509: signature check attempts limit reached while verifying certificate chain")
return
}
if err := c.CheckSignatureFrom(candidate.cert); err != nil {
if hintErr == nil {
hintErr = err
hintCert = candidate.cert
}
return
}
err = candidate.cert.isValid(certType, currentChain, opts)
if err != nil {
if hintErr == nil {
hintErr = err
hintCert = candidate.cert
}
return
}
if candidate.constraint != nil {
if err := candidate.constraint(currentChain); err != nil {
if hintErr == nil {
hintErr = err
hintCert = candidate.cert
}
return
}
}
switch certType {
case rootCertificate:
chains = append(chains, appendToFreshChain(currentChain, candidate.cert))
case intermediateCertificate:
var childChains [][]*Certificate
childChains, err = candidate.cert.buildChains(appendToFreshChain(currentChain, candidate.cert), sigChecks, opts)
chains = append(chains, childChains...)
}
}
for _, root := range opts.Roots.findPotentialParents(c) {
considerCandidate(rootCertificate, root)
}
for _, intermediate := range opts.Intermediates.findPotentialParents(c) {
considerCandidate(intermediateCertificate, intermediate)
}
if len(chains) > 0 {
err = nil
}
if len(chains) == 0 && err == nil {
err = UnknownAuthorityError{c, hintErr, hintCert}
}
return
}
func validHostnamePattern(host string) bool { return validHostname(host, true) }
func validHostnameInput(host string) bool { return validHostname(host, false) }
// validHostname reports whether host is a valid hostname that can be matched or
// matched against according to RFC 6125 2.2, with some leniency to accommodate
// legacy values.
func validHostname(host string, isPattern bool) bool {
if !isPattern {
host = strings.TrimSuffix(host, ".")
}
if len(host) == 0 {
return false
}
if host == "*" {
// Bare wildcards are not allowed, they are not valid DNS names,
// nor are they allowed per RFC 6125.
return false
}
for i, part := range strings.Split(host, ".") {
if part == "" {
// Empty label.
return false
}
if isPattern && i == 0 && part == "*" {
// Only allow full left-most wildcards, as those are the only ones
// we match, and matching literal '*' characters is probably never
// the expected behavior.
continue
}
for j, c := range part {
if 'a' <= c && c <= 'z' {
continue
}
if '0' <= c && c <= '9' {
continue
}
if 'A' <= c && c <= 'Z' {
continue
}
if c == '-' && j != 0 {
continue
}
if c == '_' {
// Not a valid character in hostnames, but commonly
// found in deployments outside the WebPKI.
continue
}
return false
}
}
return true
}
func matchExactly(hostA, hostB string) bool {
if hostA == "" || hostA == "." || hostB == "" || hostB == "." {
return false
}
return toLowerCaseASCII(hostA) == toLowerCaseASCII(hostB)
}
func matchHostnames(pattern, host string) bool {
pattern = toLowerCaseASCII(pattern)
host = toLowerCaseASCII(strings.TrimSuffix(host, "."))
if len(pattern) == 0 || len(host) == 0 {
return false
}
patternParts := strings.Split(pattern, ".")
hostParts := strings.Split(host, ".")
if len(patternParts) != len(hostParts) {
return false
}
for i, patternPart := range patternParts {
if i == 0 && patternPart == "*" {
continue
}
if patternPart != hostParts[i] {
return false
}
}
return true
}
// toLowerCaseASCII returns a lower-case version of in. See RFC 6125 6.4.1. We use
// an explicitly ASCII function to avoid any sharp corners resulting from
// performing Unicode operations on DNS labels.
func toLowerCaseASCII(in string) string {
// If the string is already lower-case then there's nothing to do.
isAlreadyLowerCase := true
for _, c := range in {
if c == utf8.RuneError {
// If we get a UTF-8 error then there might be
// upper-case ASCII bytes in the invalid sequence.
isAlreadyLowerCase = false
break
}
if 'A' <= c && c <= 'Z' {
isAlreadyLowerCase = false
break
}
}
if isAlreadyLowerCase {
return in
}
out := []byte(in)
for i, c := range out {
if 'A' <= c && c <= 'Z' {
out[i] += 'a' - 'A'
}
}
return string(out)
}
// VerifyHostname returns nil if c is a valid certificate for the named host.
// Otherwise it returns an error describing the mismatch.
//
// IP addresses can be optionally enclosed in square brackets and are checked
// against the IPAddresses field. Other names are checked case insensitively
// against the DNSNames field. If the names are valid hostnames, the certificate
// fields can have a wildcard as the complete left-most label (e.g. *.example.com).
//
// Note that the legacy Common Name field is ignored.
func (c *Certificate) VerifyHostname(h string) error {
// IP addresses may be written in [ ].
candidateIP := h
if len(h) >= 3 && h[0] == '[' && h[len(h)-1] == ']' {
candidateIP = h[1 : len(h)-1]
}
if ip := net.ParseIP(candidateIP); ip != nil {
// We only match IP addresses against IP SANs.
// See RFC 6125, Appendix B.2.
for _, candidate := range c.IPAddresses {
if ip.Equal(candidate) {
return nil
}
}
return HostnameError{c, candidateIP}
}
candidateName := toLowerCaseASCII(h) // Save allocations inside the loop.
validCandidateName := validHostnameInput(candidateName)
for _, match := range c.DNSNames {
// Ideally, we'd only match valid hostnames according to RFC 6125 like
// browsers (more or less) do, but in practice Go is used in a wider
// array of contexts and can't even assume DNS resolution. Instead,
// always allow perfect matches, and only apply wildcard and trailing
// dot processing to valid hostnames.
if validCandidateName && validHostnamePattern(match) {
if matchHostnames(match, candidateName) {
return nil
}
} else {
if matchExactly(match, candidateName) {
return nil
}
}
}
return HostnameError{c, h}
}
func checkChainForKeyUsage(chain []*Certificate, keyUsages []ExtKeyUsage) bool {
usages := make([]ExtKeyUsage, len(keyUsages))
copy(usages, keyUsages)
if len(chain) == 0 {
return false
}
usagesRemaining := len(usages)
// We walk down the list and cross out any usages that aren't supported
// by each certificate. If we cross out all the usages, then the chain
// is unacceptable.
NextCert:
for i := len(chain) - 1; i >= 0; i-- {
cert := chain[i]
if len(cert.ExtKeyUsage) == 0 && len(cert.UnknownExtKeyUsage) == 0 {
// The certificate doesn't have any extended key usage specified.
continue
}
for _, usage := range cert.ExtKeyUsage {
if usage == ExtKeyUsageAny {
// The certificate is explicitly good for any usage.
continue NextCert
}
}
const invalidUsage ExtKeyUsage = -1
NextRequestedUsage:
for i, requestedUsage := range usages {
if requestedUsage == invalidUsage {
continue
}
for _, usage := range cert.ExtKeyUsage {
if requestedUsage == usage {
continue NextRequestedUsage
}
}
usages[i] = invalidUsage
usagesRemaining--
if usagesRemaining == 0 {
return false
}
}
}
return true
}
| go/src/crypto/x509/verify.go/0 | {
"file_path": "go/src/crypto/x509/verify.go",
"repo_id": "go",
"token_count": 12475
} | 231 |
// Copyright 2011 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 sql provides a generic interface around SQL (or SQL-like)
// databases.
//
// The sql package must be used in conjunction with a database driver.
// See https://golang.org/s/sqldrivers for a list of drivers.
//
// Drivers that do not support context cancellation will not return until
// after the query is completed.
//
// For usage examples, see the wiki page at
// https://golang.org/s/sqlwiki.
package sql
import (
"context"
"database/sql/driver"
"errors"
"fmt"
"io"
"math/rand/v2"
"reflect"
"runtime"
"slices"
"strconv"
"sync"
"sync/atomic"
"time"
_ "unsafe"
)
var driversMu sync.RWMutex
// drivers should be an internal detail,
// but widely used packages access it using linkname.
// (It is extra wrong that they linkname drivers but not driversMu.)
// Notable members of the hall of shame include:
// - github.com/instana/go-sensor
//
// Do not remove or change the type signature.
// See go.dev/issue/67401.
//
//go:linkname drivers
var drivers = make(map[string]driver.Driver)
// nowFunc returns the current time; it's overridden in tests.
var nowFunc = time.Now
// Register makes a database driver available by the provided name.
// If Register is called twice with the same name or if driver is nil,
// it panics.
func Register(name string, driver driver.Driver) {
driversMu.Lock()
defer driversMu.Unlock()
if driver == nil {
panic("sql: Register driver is nil")
}
if _, dup := drivers[name]; dup {
panic("sql: Register called twice for driver " + name)
}
drivers[name] = driver
}
func unregisterAllDrivers() {
driversMu.Lock()
defer driversMu.Unlock()
// For tests.
drivers = make(map[string]driver.Driver)
}
// Drivers returns a sorted list of the names of the registered drivers.
func Drivers() []string {
driversMu.RLock()
defer driversMu.RUnlock()
list := make([]string, 0, len(drivers))
for name := range drivers {
list = append(list, name)
}
slices.Sort(list)
return list
}
// A NamedArg is a named argument. NamedArg values may be used as
// arguments to [DB.Query] or [DB.Exec] and bind to the corresponding named
// parameter in the SQL statement.
//
// For a more concise way to create NamedArg values, see
// the [Named] function.
type NamedArg struct {
_NamedFieldsRequired struct{}
// Name is the name of the parameter placeholder.
//
// If empty, the ordinal position in the argument list will be
// used.
//
// Name must omit any symbol prefix.
Name string
// Value is the value of the parameter.
// It may be assigned the same value types as the query
// arguments.
Value any
}
// Named provides a more concise way to create [NamedArg] values.
//
// Example usage:
//
// db.ExecContext(ctx, `
// delete from Invoice
// where
// TimeCreated < @end
// and TimeCreated >= @start;`,
// sql.Named("start", startTime),
// sql.Named("end", endTime),
// )
func Named(name string, value any) NamedArg {
// This method exists because the go1compat promise
// doesn't guarantee that structs don't grow more fields,
// so unkeyed struct literals are a vet error. Thus, we don't
// want to allow sql.NamedArg{name, value}.
return NamedArg{Name: name, Value: value}
}
// IsolationLevel is the transaction isolation level used in [TxOptions].
type IsolationLevel int
// Various isolation levels that drivers may support in [DB.BeginTx].
// If a driver does not support a given isolation level an error may be returned.
//
// See https://en.wikipedia.org/wiki/Isolation_(database_systems)#Isolation_levels.
const (
LevelDefault IsolationLevel = iota
LevelReadUncommitted
LevelReadCommitted
LevelWriteCommitted
LevelRepeatableRead
LevelSnapshot
LevelSerializable
LevelLinearizable
)
// String returns the name of the transaction isolation level.
func (i IsolationLevel) String() string {
switch i {
case LevelDefault:
return "Default"
case LevelReadUncommitted:
return "Read Uncommitted"
case LevelReadCommitted:
return "Read Committed"
case LevelWriteCommitted:
return "Write Committed"
case LevelRepeatableRead:
return "Repeatable Read"
case LevelSnapshot:
return "Snapshot"
case LevelSerializable:
return "Serializable"
case LevelLinearizable:
return "Linearizable"
default:
return "IsolationLevel(" + strconv.Itoa(int(i)) + ")"
}
}
var _ fmt.Stringer = LevelDefault
// TxOptions holds the transaction options to be used in [DB.BeginTx].
type TxOptions struct {
// Isolation is the transaction isolation level.
// If zero, the driver or database's default level is used.
Isolation IsolationLevel
ReadOnly bool
}
// RawBytes is a byte slice that holds a reference to memory owned by
// the database itself. After a [Rows.Scan] into a RawBytes, the slice is only
// valid until the next call to [Rows.Next], [Rows.Scan], or [Rows.Close].
type RawBytes []byte
// NullString represents a string that may be null.
// NullString implements the [Scanner] interface so
// it can be used as a scan destination:
//
// var s NullString
// err := db.QueryRow("SELECT name FROM foo WHERE id=?", id).Scan(&s)
// ...
// if s.Valid {
// // use s.String
// } else {
// // NULL value
// }
type NullString struct {
String string
Valid bool // Valid is true if String is not NULL
}
// Scan implements the [Scanner] interface.
func (ns *NullString) Scan(value any) error {
if value == nil {
ns.String, ns.Valid = "", false
return nil
}
ns.Valid = true
return convertAssign(&ns.String, value)
}
// Value implements the [driver.Valuer] interface.
func (ns NullString) Value() (driver.Value, error) {
if !ns.Valid {
return nil, nil
}
return ns.String, nil
}
// NullInt64 represents an int64 that may be null.
// NullInt64 implements the [Scanner] interface so
// it can be used as a scan destination, similar to [NullString].
type NullInt64 struct {
Int64 int64
Valid bool // Valid is true if Int64 is not NULL
}
// Scan implements the [Scanner] interface.
func (n *NullInt64) Scan(value any) error {
if value == nil {
n.Int64, n.Valid = 0, false
return nil
}
n.Valid = true
return convertAssign(&n.Int64, value)
}
// Value implements the [driver.Valuer] interface.
func (n NullInt64) Value() (driver.Value, error) {
if !n.Valid {
return nil, nil
}
return n.Int64, nil
}
// NullInt32 represents an int32 that may be null.
// NullInt32 implements the [Scanner] interface so
// it can be used as a scan destination, similar to [NullString].
type NullInt32 struct {
Int32 int32
Valid bool // Valid is true if Int32 is not NULL
}
// Scan implements the [Scanner] interface.
func (n *NullInt32) Scan(value any) error {
if value == nil {
n.Int32, n.Valid = 0, false
return nil
}
n.Valid = true
return convertAssign(&n.Int32, value)
}
// Value implements the [driver.Valuer] interface.
func (n NullInt32) Value() (driver.Value, error) {
if !n.Valid {
return nil, nil
}
return int64(n.Int32), nil
}
// NullInt16 represents an int16 that may be null.
// NullInt16 implements the [Scanner] interface so
// it can be used as a scan destination, similar to [NullString].
type NullInt16 struct {
Int16 int16
Valid bool // Valid is true if Int16 is not NULL
}
// Scan implements the [Scanner] interface.
func (n *NullInt16) Scan(value any) error {
if value == nil {
n.Int16, n.Valid = 0, false
return nil
}
err := convertAssign(&n.Int16, value)
n.Valid = err == nil
return err
}
// Value implements the [driver.Valuer] interface.
func (n NullInt16) Value() (driver.Value, error) {
if !n.Valid {
return nil, nil
}
return int64(n.Int16), nil
}
// NullByte represents a byte that may be null.
// NullByte implements the [Scanner] interface so
// it can be used as a scan destination, similar to [NullString].
type NullByte struct {
Byte byte
Valid bool // Valid is true if Byte is not NULL
}
// Scan implements the [Scanner] interface.
func (n *NullByte) Scan(value any) error {
if value == nil {
n.Byte, n.Valid = 0, false
return nil
}
err := convertAssign(&n.Byte, value)
n.Valid = err == nil
return err
}
// Value implements the [driver.Valuer] interface.
func (n NullByte) Value() (driver.Value, error) {
if !n.Valid {
return nil, nil
}
return int64(n.Byte), nil
}
// NullFloat64 represents a float64 that may be null.
// NullFloat64 implements the [Scanner] interface so
// it can be used as a scan destination, similar to [NullString].
type NullFloat64 struct {
Float64 float64
Valid bool // Valid is true if Float64 is not NULL
}
// Scan implements the [Scanner] interface.
func (n *NullFloat64) Scan(value any) error {
if value == nil {
n.Float64, n.Valid = 0, false
return nil
}
n.Valid = true
return convertAssign(&n.Float64, value)
}
// Value implements the [driver.Valuer] interface.
func (n NullFloat64) Value() (driver.Value, error) {
if !n.Valid {
return nil, nil
}
return n.Float64, nil
}
// NullBool represents a bool that may be null.
// NullBool implements the [Scanner] interface so
// it can be used as a scan destination, similar to [NullString].
type NullBool struct {
Bool bool
Valid bool // Valid is true if Bool is not NULL
}
// Scan implements the [Scanner] interface.
func (n *NullBool) Scan(value any) error {
if value == nil {
n.Bool, n.Valid = false, false
return nil
}
n.Valid = true
return convertAssign(&n.Bool, value)
}
// Value implements the [driver.Valuer] interface.
func (n NullBool) Value() (driver.Value, error) {
if !n.Valid {
return nil, nil
}
return n.Bool, nil
}
// NullTime represents a [time.Time] that may be null.
// NullTime implements the [Scanner] interface so
// it can be used as a scan destination, similar to [NullString].
type NullTime struct {
Time time.Time
Valid bool // Valid is true if Time is not NULL
}
// Scan implements the [Scanner] interface.
func (n *NullTime) Scan(value any) error {
if value == nil {
n.Time, n.Valid = time.Time{}, false
return nil
}
n.Valid = true
return convertAssign(&n.Time, value)
}
// Value implements the [driver.Valuer] interface.
func (n NullTime) Value() (driver.Value, error) {
if !n.Valid {
return nil, nil
}
return n.Time, nil
}
// Null represents a value that may be null.
// Null implements the [Scanner] interface so
// it can be used as a scan destination:
//
// var s Null[string]
// err := db.QueryRow("SELECT name FROM foo WHERE id=?", id).Scan(&s)
// ...
// if s.Valid {
// // use s.V
// } else {
// // NULL value
// }
type Null[T any] struct {
V T
Valid bool
}
func (n *Null[T]) Scan(value any) error {
if value == nil {
n.V, n.Valid = *new(T), false
return nil
}
n.Valid = true
return convertAssign(&n.V, value)
}
func (n Null[T]) Value() (driver.Value, error) {
if !n.Valid {
return nil, nil
}
return n.V, nil
}
// Scanner is an interface used by [Rows.Scan].
type Scanner interface {
// Scan assigns a value from a database driver.
//
// The src value will be of one of the following types:
//
// int64
// float64
// bool
// []byte
// string
// time.Time
// nil - for NULL values
//
// An error should be returned if the value cannot be stored
// without loss of information.
//
// Reference types such as []byte are only valid until the next call to Scan
// and should not be retained. Their underlying memory is owned by the driver.
// If retention is necessary, copy their values before the next call to Scan.
Scan(src any) error
}
// Out may be used to retrieve OUTPUT value parameters from stored procedures.
//
// Not all drivers and databases support OUTPUT value parameters.
//
// Example usage:
//
// var outArg string
// _, err := db.ExecContext(ctx, "ProcName", sql.Named("Arg1", sql.Out{Dest: &outArg}))
type Out struct {
_NamedFieldsRequired struct{}
// Dest is a pointer to the value that will be set to the result of the
// stored procedure's OUTPUT parameter.
Dest any
// In is whether the parameter is an INOUT parameter. If so, the input value to the stored
// procedure is the dereferenced value of Dest's pointer, which is then replaced with
// the output value.
In bool
}
// ErrNoRows is returned by [Row.Scan] when [DB.QueryRow] doesn't return a
// row. In such a case, QueryRow returns a placeholder [*Row] value that
// defers this error until a Scan.
var ErrNoRows = errors.New("sql: no rows in result set")
// DB is a database handle representing a pool of zero or more
// underlying connections. It's safe for concurrent use by multiple
// goroutines.
//
// The sql package creates and frees connections automatically; it
// also maintains a free pool of idle connections. If the database has
// a concept of per-connection state, such state can be reliably observed
// within a transaction ([Tx]) or connection ([Conn]). Once [DB.Begin] is called, the
// returned [Tx] is bound to a single connection. Once [Tx.Commit] or
// [Tx.Rollback] is called on the transaction, that transaction's
// connection is returned to [DB]'s idle connection pool. The pool size
// can be controlled with [DB.SetMaxIdleConns].
type DB struct {
// Total time waited for new connections.
waitDuration atomic.Int64
connector driver.Connector
// numClosed is an atomic counter which represents a total number of
// closed connections. Stmt.openStmt checks it before cleaning closed
// connections in Stmt.css.
numClosed atomic.Uint64
mu sync.Mutex // protects following fields
freeConn []*driverConn // free connections ordered by returnedAt oldest to newest
connRequests connRequestSet
numOpen int // number of opened and pending open connections
// Used to signal the need for new connections
// a goroutine running connectionOpener() reads on this chan and
// maybeOpenNewConnections sends on the chan (one send per needed connection)
// It is closed during db.Close(). The close tells the connectionOpener
// goroutine to exit.
openerCh chan struct{}
closed bool
dep map[finalCloser]depSet
lastPut map[*driverConn]string // stacktrace of last conn's put; debug only
maxIdleCount int // zero means defaultMaxIdleConns; negative means 0
maxOpen int // <= 0 means unlimited
maxLifetime time.Duration // maximum amount of time a connection may be reused
maxIdleTime time.Duration // maximum amount of time a connection may be idle before being closed
cleanerCh chan struct{}
waitCount int64 // Total number of connections waited for.
maxIdleClosed int64 // Total number of connections closed due to idle count.
maxIdleTimeClosed int64 // Total number of connections closed due to idle time.
maxLifetimeClosed int64 // Total number of connections closed due to max connection lifetime limit.
stop func() // stop cancels the connection opener.
}
// connReuseStrategy determines how (*DB).conn returns database connections.
type connReuseStrategy uint8
const (
// alwaysNewConn forces a new connection to the database.
alwaysNewConn connReuseStrategy = iota
// cachedOrNewConn returns a cached connection, if available, else waits
// for one to become available (if MaxOpenConns has been reached) or
// creates a new database connection.
cachedOrNewConn
)
// driverConn wraps a driver.Conn with a mutex, to
// be held during all calls into the Conn. (including any calls onto
// interfaces returned via that Conn, such as calls on Tx, Stmt,
// Result, Rows)
type driverConn struct {
db *DB
createdAt time.Time
sync.Mutex // guards following
ci driver.Conn
needReset bool // The connection session should be reset before use if true.
closed bool
finalClosed bool // ci.Close has been called
openStmt map[*driverStmt]bool
// guarded by db.mu
inUse bool
dbmuClosed bool // same as closed, but guarded by db.mu, for removeClosedStmtLocked
returnedAt time.Time // Time the connection was created or returned.
onPut []func() // code (with db.mu held) run when conn is next returned
}
func (dc *driverConn) releaseConn(err error) {
dc.db.putConn(dc, err, true)
}
func (dc *driverConn) removeOpenStmt(ds *driverStmt) {
dc.Lock()
defer dc.Unlock()
delete(dc.openStmt, ds)
}
func (dc *driverConn) expired(timeout time.Duration) bool {
if timeout <= 0 {
return false
}
return dc.createdAt.Add(timeout).Before(nowFunc())
}
// resetSession checks if the driver connection needs the
// session to be reset and if required, resets it.
func (dc *driverConn) resetSession(ctx context.Context) error {
dc.Lock()
defer dc.Unlock()
if !dc.needReset {
return nil
}
if cr, ok := dc.ci.(driver.SessionResetter); ok {
return cr.ResetSession(ctx)
}
return nil
}
// validateConnection checks if the connection is valid and can
// still be used. It also marks the session for reset if required.
func (dc *driverConn) validateConnection(needsReset bool) bool {
dc.Lock()
defer dc.Unlock()
if needsReset {
dc.needReset = true
}
if cv, ok := dc.ci.(driver.Validator); ok {
return cv.IsValid()
}
return true
}
// prepareLocked prepares the query on dc. When cg == nil the dc must keep track of
// the prepared statements in a pool.
func (dc *driverConn) prepareLocked(ctx context.Context, cg stmtConnGrabber, query string) (*driverStmt, error) {
si, err := ctxDriverPrepare(ctx, dc.ci, query)
if err != nil {
return nil, err
}
ds := &driverStmt{Locker: dc, si: si}
// No need to manage open statements if there is a single connection grabber.
if cg != nil {
return ds, nil
}
// Track each driverConn's open statements, so we can close them
// before closing the conn.
//
// Wrap all driver.Stmt is *driverStmt to ensure they are only closed once.
if dc.openStmt == nil {
dc.openStmt = make(map[*driverStmt]bool)
}
dc.openStmt[ds] = true
return ds, nil
}
// the dc.db's Mutex is held.
func (dc *driverConn) closeDBLocked() func() error {
dc.Lock()
defer dc.Unlock()
if dc.closed {
return func() error { return errors.New("sql: duplicate driverConn close") }
}
dc.closed = true
return dc.db.removeDepLocked(dc, dc)
}
func (dc *driverConn) Close() error {
dc.Lock()
if dc.closed {
dc.Unlock()
return errors.New("sql: duplicate driverConn close")
}
dc.closed = true
dc.Unlock() // not defer; removeDep finalClose calls may need to lock
// And now updates that require holding dc.mu.Lock.
dc.db.mu.Lock()
dc.dbmuClosed = true
fn := dc.db.removeDepLocked(dc, dc)
dc.db.mu.Unlock()
return fn()
}
func (dc *driverConn) finalClose() error {
var err error
// Each *driverStmt has a lock to the dc. Copy the list out of the dc
// before calling close on each stmt.
var openStmt []*driverStmt
withLock(dc, func() {
openStmt = make([]*driverStmt, 0, len(dc.openStmt))
for ds := range dc.openStmt {
openStmt = append(openStmt, ds)
}
dc.openStmt = nil
})
for _, ds := range openStmt {
ds.Close()
}
withLock(dc, func() {
dc.finalClosed = true
err = dc.ci.Close()
dc.ci = nil
})
dc.db.mu.Lock()
dc.db.numOpen--
dc.db.maybeOpenNewConnections()
dc.db.mu.Unlock()
dc.db.numClosed.Add(1)
return err
}
// driverStmt associates a driver.Stmt with the
// *driverConn from which it came, so the driverConn's lock can be
// held during calls.
type driverStmt struct {
sync.Locker // the *driverConn
si driver.Stmt
closed bool
closeErr error // return value of previous Close call
}
// Close ensures driver.Stmt is only closed once and always returns the same
// result.
func (ds *driverStmt) Close() error {
ds.Lock()
defer ds.Unlock()
if ds.closed {
return ds.closeErr
}
ds.closed = true
ds.closeErr = ds.si.Close()
return ds.closeErr
}
// depSet is a finalCloser's outstanding dependencies
type depSet map[any]bool // set of true bools
// The finalCloser interface is used by (*DB).addDep and related
// dependency reference counting.
type finalCloser interface {
// finalClose is called when the reference count of an object
// goes to zero. (*DB).mu is not held while calling it.
finalClose() error
}
// addDep notes that x now depends on dep, and x's finalClose won't be
// called until all of x's dependencies are removed with removeDep.
func (db *DB) addDep(x finalCloser, dep any) {
db.mu.Lock()
defer db.mu.Unlock()
db.addDepLocked(x, dep)
}
func (db *DB) addDepLocked(x finalCloser, dep any) {
if db.dep == nil {
db.dep = make(map[finalCloser]depSet)
}
xdep := db.dep[x]
if xdep == nil {
xdep = make(depSet)
db.dep[x] = xdep
}
xdep[dep] = true
}
// removeDep notes that x no longer depends on dep.
// If x still has dependencies, nil is returned.
// If x no longer has any dependencies, its finalClose method will be
// called and its error value will be returned.
func (db *DB) removeDep(x finalCloser, dep any) error {
db.mu.Lock()
fn := db.removeDepLocked(x, dep)
db.mu.Unlock()
return fn()
}
func (db *DB) removeDepLocked(x finalCloser, dep any) func() error {
xdep, ok := db.dep[x]
if !ok {
panic(fmt.Sprintf("unpaired removeDep: no deps for %T", x))
}
l0 := len(xdep)
delete(xdep, dep)
switch len(xdep) {
case l0:
// Nothing removed. Shouldn't happen.
panic(fmt.Sprintf("unpaired removeDep: no %T dep on %T", dep, x))
case 0:
// No more dependencies.
delete(db.dep, x)
return x.finalClose
default:
// Dependencies remain.
return func() error { return nil }
}
}
// This is the size of the connectionOpener request chan (DB.openerCh).
// This value should be larger than the maximum typical value
// used for DB.maxOpen. If maxOpen is significantly larger than
// connectionRequestQueueSize then it is possible for ALL calls into the *DB
// to block until the connectionOpener can satisfy the backlog of requests.
var connectionRequestQueueSize = 1000000
type dsnConnector struct {
dsn string
driver driver.Driver
}
func (t dsnConnector) Connect(_ context.Context) (driver.Conn, error) {
return t.driver.Open(t.dsn)
}
func (t dsnConnector) Driver() driver.Driver {
return t.driver
}
// OpenDB opens a database using a [driver.Connector], allowing drivers to
// bypass a string based data source name.
//
// Most users will open a database via a driver-specific connection
// helper function that returns a [*DB]. No database drivers are included
// in the Go standard library. See https://golang.org/s/sqldrivers for
// a list of third-party drivers.
//
// OpenDB may just validate its arguments without creating a connection
// to the database. To verify that the data source name is valid, call
// [DB.Ping].
//
// The returned [DB] is safe for concurrent use by multiple goroutines
// and maintains its own pool of idle connections. Thus, the OpenDB
// function should be called just once. It is rarely necessary to
// close a [DB].
func OpenDB(c driver.Connector) *DB {
ctx, cancel := context.WithCancel(context.Background())
db := &DB{
connector: c,
openerCh: make(chan struct{}, connectionRequestQueueSize),
lastPut: make(map[*driverConn]string),
stop: cancel,
}
go db.connectionOpener(ctx)
return db
}
// Open opens a database specified by its database driver name and a
// driver-specific data source name, usually consisting of at least a
// database name and connection information.
//
// Most users will open a database via a driver-specific connection
// helper function that returns a [*DB]. No database drivers are included
// in the Go standard library. See https://golang.org/s/sqldrivers for
// a list of third-party drivers.
//
// Open may just validate its arguments without creating a connection
// to the database. To verify that the data source name is valid, call
// [DB.Ping].
//
// The returned [DB] is safe for concurrent use by multiple goroutines
// and maintains its own pool of idle connections. Thus, the Open
// function should be called just once. It is rarely necessary to
// close a [DB].
func Open(driverName, dataSourceName string) (*DB, error) {
driversMu.RLock()
driveri, ok := drivers[driverName]
driversMu.RUnlock()
if !ok {
return nil, fmt.Errorf("sql: unknown driver %q (forgotten import?)", driverName)
}
if driverCtx, ok := driveri.(driver.DriverContext); ok {
connector, err := driverCtx.OpenConnector(dataSourceName)
if err != nil {
return nil, err
}
return OpenDB(connector), nil
}
return OpenDB(dsnConnector{dsn: dataSourceName, driver: driveri}), nil
}
func (db *DB) pingDC(ctx context.Context, dc *driverConn, release func(error)) error {
var err error
if pinger, ok := dc.ci.(driver.Pinger); ok {
withLock(dc, func() {
err = pinger.Ping(ctx)
})
}
release(err)
return err
}
// PingContext verifies a connection to the database is still alive,
// establishing a connection if necessary.
func (db *DB) PingContext(ctx context.Context) error {
var dc *driverConn
var err error
err = db.retry(func(strategy connReuseStrategy) error {
dc, err = db.conn(ctx, strategy)
return err
})
if err != nil {
return err
}
return db.pingDC(ctx, dc, dc.releaseConn)
}
// Ping verifies a connection to the database is still alive,
// establishing a connection if necessary.
//
// Ping uses [context.Background] internally; to specify the context, use
// [DB.PingContext].
func (db *DB) Ping() error {
return db.PingContext(context.Background())
}
// Close closes the database and prevents new queries from starting.
// Close then waits for all queries that have started processing on the server
// to finish.
//
// It is rare to Close a [DB], as the [DB] handle is meant to be
// long-lived and shared between many goroutines.
func (db *DB) Close() error {
db.mu.Lock()
if db.closed { // Make DB.Close idempotent
db.mu.Unlock()
return nil
}
if db.cleanerCh != nil {
close(db.cleanerCh)
}
var err error
fns := make([]func() error, 0, len(db.freeConn))
for _, dc := range db.freeConn {
fns = append(fns, dc.closeDBLocked())
}
db.freeConn = nil
db.closed = true
db.connRequests.CloseAndRemoveAll()
db.mu.Unlock()
for _, fn := range fns {
err1 := fn()
if err1 != nil {
err = err1
}
}
db.stop()
if c, ok := db.connector.(io.Closer); ok {
err1 := c.Close()
if err1 != nil {
err = err1
}
}
return err
}
const defaultMaxIdleConns = 2
func (db *DB) maxIdleConnsLocked() int {
n := db.maxIdleCount
switch {
case n == 0:
// TODO(bradfitz): ask driver, if supported, for its default preference
return defaultMaxIdleConns
case n < 0:
return 0
default:
return n
}
}
func (db *DB) shortestIdleTimeLocked() time.Duration {
if db.maxIdleTime <= 0 {
return db.maxLifetime
}
if db.maxLifetime <= 0 {
return db.maxIdleTime
}
return min(db.maxIdleTime, db.maxLifetime)
}
// SetMaxIdleConns sets the maximum number of connections in the idle
// connection pool.
//
// If MaxOpenConns is greater than 0 but less than the new MaxIdleConns,
// then the new MaxIdleConns will be reduced to match the MaxOpenConns limit.
//
// If n <= 0, no idle connections are retained.
//
// The default max idle connections is currently 2. This may change in
// a future release.
func (db *DB) SetMaxIdleConns(n int) {
db.mu.Lock()
if n > 0 {
db.maxIdleCount = n
} else {
// No idle connections.
db.maxIdleCount = -1
}
// Make sure maxIdle doesn't exceed maxOpen
if db.maxOpen > 0 && db.maxIdleConnsLocked() > db.maxOpen {
db.maxIdleCount = db.maxOpen
}
var closing []*driverConn
idleCount := len(db.freeConn)
maxIdle := db.maxIdleConnsLocked()
if idleCount > maxIdle {
closing = db.freeConn[maxIdle:]
db.freeConn = db.freeConn[:maxIdle]
}
db.maxIdleClosed += int64(len(closing))
db.mu.Unlock()
for _, c := range closing {
c.Close()
}
}
// SetMaxOpenConns sets the maximum number of open connections to the database.
//
// If MaxIdleConns is greater than 0 and the new MaxOpenConns is less than
// MaxIdleConns, then MaxIdleConns will be reduced to match the new
// MaxOpenConns limit.
//
// If n <= 0, then there is no limit on the number of open connections.
// The default is 0 (unlimited).
func (db *DB) SetMaxOpenConns(n int) {
db.mu.Lock()
db.maxOpen = n
if n < 0 {
db.maxOpen = 0
}
syncMaxIdle := db.maxOpen > 0 && db.maxIdleConnsLocked() > db.maxOpen
db.mu.Unlock()
if syncMaxIdle {
db.SetMaxIdleConns(n)
}
}
// SetConnMaxLifetime sets the maximum amount of time a connection may be reused.
//
// Expired connections may be closed lazily before reuse.
//
// If d <= 0, connections are not closed due to a connection's age.
func (db *DB) SetConnMaxLifetime(d time.Duration) {
if d < 0 {
d = 0
}
db.mu.Lock()
// Wake cleaner up when lifetime is shortened.
if d > 0 && d < db.maxLifetime && db.cleanerCh != nil {
select {
case db.cleanerCh <- struct{}{}:
default:
}
}
db.maxLifetime = d
db.startCleanerLocked()
db.mu.Unlock()
}
// SetConnMaxIdleTime sets the maximum amount of time a connection may be idle.
//
// Expired connections may be closed lazily before reuse.
//
// If d <= 0, connections are not closed due to a connection's idle time.
func (db *DB) SetConnMaxIdleTime(d time.Duration) {
if d < 0 {
d = 0
}
db.mu.Lock()
defer db.mu.Unlock()
// Wake cleaner up when idle time is shortened.
if d > 0 && d < db.maxIdleTime && db.cleanerCh != nil {
select {
case db.cleanerCh <- struct{}{}:
default:
}
}
db.maxIdleTime = d
db.startCleanerLocked()
}
// startCleanerLocked starts connectionCleaner if needed.
func (db *DB) startCleanerLocked() {
if (db.maxLifetime > 0 || db.maxIdleTime > 0) && db.numOpen > 0 && db.cleanerCh == nil {
db.cleanerCh = make(chan struct{}, 1)
go db.connectionCleaner(db.shortestIdleTimeLocked())
}
}
func (db *DB) connectionCleaner(d time.Duration) {
const minInterval = time.Second
if d < minInterval {
d = minInterval
}
t := time.NewTimer(d)
for {
select {
case <-t.C:
case <-db.cleanerCh: // maxLifetime was changed or db was closed.
}
db.mu.Lock()
d = db.shortestIdleTimeLocked()
if db.closed || db.numOpen == 0 || d <= 0 {
db.cleanerCh = nil
db.mu.Unlock()
return
}
d, closing := db.connectionCleanerRunLocked(d)
db.mu.Unlock()
for _, c := range closing {
c.Close()
}
if d < minInterval {
d = minInterval
}
if !t.Stop() {
select {
case <-t.C:
default:
}
}
t.Reset(d)
}
}
// connectionCleanerRunLocked removes connections that should be closed from
// freeConn and returns them along side an updated duration to the next check
// if a quicker check is required to ensure connections are checked appropriately.
func (db *DB) connectionCleanerRunLocked(d time.Duration) (time.Duration, []*driverConn) {
var idleClosing int64
var closing []*driverConn
if db.maxIdleTime > 0 {
// As freeConn is ordered by returnedAt process
// in reverse order to minimise the work needed.
idleSince := nowFunc().Add(-db.maxIdleTime)
last := len(db.freeConn) - 1
for i := last; i >= 0; i-- {
c := db.freeConn[i]
if c.returnedAt.Before(idleSince) {
i++
closing = db.freeConn[:i:i]
db.freeConn = db.freeConn[i:]
idleClosing = int64(len(closing))
db.maxIdleTimeClosed += idleClosing
break
}
}
if len(db.freeConn) > 0 {
c := db.freeConn[0]
if d2 := c.returnedAt.Sub(idleSince); d2 < d {
// Ensure idle connections are cleaned up as soon as
// possible.
d = d2
}
}
}
if db.maxLifetime > 0 {
expiredSince := nowFunc().Add(-db.maxLifetime)
for i := 0; i < len(db.freeConn); i++ {
c := db.freeConn[i]
if c.createdAt.Before(expiredSince) {
closing = append(closing, c)
last := len(db.freeConn) - 1
// Use slow delete as order is required to ensure
// connections are reused least idle time first.
copy(db.freeConn[i:], db.freeConn[i+1:])
db.freeConn[last] = nil
db.freeConn = db.freeConn[:last]
i--
} else if d2 := c.createdAt.Sub(expiredSince); d2 < d {
// Prevent connections sitting the freeConn when they
// have expired by updating our next deadline d.
d = d2
}
}
db.maxLifetimeClosed += int64(len(closing)) - idleClosing
}
return d, closing
}
// DBStats contains database statistics.
type DBStats struct {
MaxOpenConnections int // Maximum number of open connections to the database.
// Pool Status
OpenConnections int // The number of established connections both in use and idle.
InUse int // The number of connections currently in use.
Idle int // The number of idle connections.
// Counters
WaitCount int64 // The total number of connections waited for.
WaitDuration time.Duration // The total time blocked waiting for a new connection.
MaxIdleClosed int64 // The total number of connections closed due to SetMaxIdleConns.
MaxIdleTimeClosed int64 // The total number of connections closed due to SetConnMaxIdleTime.
MaxLifetimeClosed int64 // The total number of connections closed due to SetConnMaxLifetime.
}
// Stats returns database statistics.
func (db *DB) Stats() DBStats {
wait := db.waitDuration.Load()
db.mu.Lock()
defer db.mu.Unlock()
stats := DBStats{
MaxOpenConnections: db.maxOpen,
Idle: len(db.freeConn),
OpenConnections: db.numOpen,
InUse: db.numOpen - len(db.freeConn),
WaitCount: db.waitCount,
WaitDuration: time.Duration(wait),
MaxIdleClosed: db.maxIdleClosed,
MaxIdleTimeClosed: db.maxIdleTimeClosed,
MaxLifetimeClosed: db.maxLifetimeClosed,
}
return stats
}
// Assumes db.mu is locked.
// If there are connRequests and the connection limit hasn't been reached,
// then tell the connectionOpener to open new connections.
func (db *DB) maybeOpenNewConnections() {
numRequests := db.connRequests.Len()
if db.maxOpen > 0 {
numCanOpen := db.maxOpen - db.numOpen
if numRequests > numCanOpen {
numRequests = numCanOpen
}
}
for numRequests > 0 {
db.numOpen++ // optimistically
numRequests--
if db.closed {
return
}
db.openerCh <- struct{}{}
}
}
// Runs in a separate goroutine, opens new connections when requested.
func (db *DB) connectionOpener(ctx context.Context) {
for {
select {
case <-ctx.Done():
return
case <-db.openerCh:
db.openNewConnection(ctx)
}
}
}
// Open one new connection
func (db *DB) openNewConnection(ctx context.Context) {
// maybeOpenNewConnections has already executed db.numOpen++ before it sent
// on db.openerCh. This function must execute db.numOpen-- if the
// connection fails or is closed before returning.
ci, err := db.connector.Connect(ctx)
db.mu.Lock()
defer db.mu.Unlock()
if db.closed {
if err == nil {
ci.Close()
}
db.numOpen--
return
}
if err != nil {
db.numOpen--
db.putConnDBLocked(nil, err)
db.maybeOpenNewConnections()
return
}
dc := &driverConn{
db: db,
createdAt: nowFunc(),
returnedAt: nowFunc(),
ci: ci,
}
if db.putConnDBLocked(dc, err) {
db.addDepLocked(dc, dc)
} else {
db.numOpen--
ci.Close()
}
}
// connRequest represents one request for a new connection
// When there are no idle connections available, DB.conn will create
// a new connRequest and put it on the db.connRequests list.
type connRequest struct {
conn *driverConn
err error
}
var errDBClosed = errors.New("sql: database is closed")
// conn returns a newly-opened or cached *driverConn.
func (db *DB) conn(ctx context.Context, strategy connReuseStrategy) (*driverConn, error) {
db.mu.Lock()
if db.closed {
db.mu.Unlock()
return nil, errDBClosed
}
// Check if the context is expired.
select {
default:
case <-ctx.Done():
db.mu.Unlock()
return nil, ctx.Err()
}
lifetime := db.maxLifetime
// Prefer a free connection, if possible.
last := len(db.freeConn) - 1
if strategy == cachedOrNewConn && last >= 0 {
// Reuse the lowest idle time connection so we can close
// connections which remain idle as soon as possible.
conn := db.freeConn[last]
db.freeConn = db.freeConn[:last]
conn.inUse = true
if conn.expired(lifetime) {
db.maxLifetimeClosed++
db.mu.Unlock()
conn.Close()
return nil, driver.ErrBadConn
}
db.mu.Unlock()
// Reset the session if required.
if err := conn.resetSession(ctx); errors.Is(err, driver.ErrBadConn) {
conn.Close()
return nil, err
}
return conn, nil
}
// Out of free connections or we were asked not to use one. If we're not
// allowed to open any more connections, make a request and wait.
if db.maxOpen > 0 && db.numOpen >= db.maxOpen {
// Make the connRequest channel. It's buffered so that the
// connectionOpener doesn't block while waiting for the req to be read.
req := make(chan connRequest, 1)
delHandle := db.connRequests.Add(req)
db.waitCount++
db.mu.Unlock()
waitStart := nowFunc()
// Timeout the connection request with the context.
select {
case <-ctx.Done():
// Remove the connection request and ensure no value has been sent
// on it after removing.
db.mu.Lock()
deleted := db.connRequests.Delete(delHandle)
db.mu.Unlock()
db.waitDuration.Add(int64(time.Since(waitStart)))
// If we failed to delete it, that means something else
// grabbed it and is about to send on it.
if !deleted {
// TODO(bradfitz): rather than this best effort select, we
// should probably start a goroutine to read from req. This best
// effort select existed before the change to check 'deleted'.
// But if we know for sure it wasn't deleted and a sender is
// outstanding, we should probably block on req (in a new
// goroutine) to get the connection back.
select {
default:
case ret, ok := <-req:
if ok && ret.conn != nil {
db.putConn(ret.conn, ret.err, false)
}
}
}
return nil, ctx.Err()
case ret, ok := <-req:
db.waitDuration.Add(int64(time.Since(waitStart)))
if !ok {
return nil, errDBClosed
}
// Only check if the connection is expired if the strategy is cachedOrNewConns.
// If we require a new connection, just re-use the connection without looking
// at the expiry time. If it is expired, it will be checked when it is placed
// back into the connection pool.
// This prioritizes giving a valid connection to a client over the exact connection
// lifetime, which could expire exactly after this point anyway.
if strategy == cachedOrNewConn && ret.err == nil && ret.conn.expired(lifetime) {
db.mu.Lock()
db.maxLifetimeClosed++
db.mu.Unlock()
ret.conn.Close()
return nil, driver.ErrBadConn
}
if ret.conn == nil {
return nil, ret.err
}
// Reset the session if required.
if err := ret.conn.resetSession(ctx); errors.Is(err, driver.ErrBadConn) {
ret.conn.Close()
return nil, err
}
return ret.conn, ret.err
}
}
db.numOpen++ // optimistically
db.mu.Unlock()
ci, err := db.connector.Connect(ctx)
if err != nil {
db.mu.Lock()
db.numOpen-- // correct for earlier optimism
db.maybeOpenNewConnections()
db.mu.Unlock()
return nil, err
}
db.mu.Lock()
dc := &driverConn{
db: db,
createdAt: nowFunc(),
returnedAt: nowFunc(),
ci: ci,
inUse: true,
}
db.addDepLocked(dc, dc)
db.mu.Unlock()
return dc, nil
}
// putConnHook is a hook for testing.
var putConnHook func(*DB, *driverConn)
// noteUnusedDriverStatement notes that ds is no longer used and should
// be closed whenever possible (when c is next not in use), unless c is
// already closed.
func (db *DB) noteUnusedDriverStatement(c *driverConn, ds *driverStmt) {
db.mu.Lock()
defer db.mu.Unlock()
if c.inUse {
c.onPut = append(c.onPut, func() {
ds.Close()
})
} else {
c.Lock()
fc := c.finalClosed
c.Unlock()
if !fc {
ds.Close()
}
}
}
// debugGetPut determines whether getConn & putConn calls' stack traces
// are returned for more verbose crashes.
const debugGetPut = false
// putConn adds a connection to the db's free pool.
// err is optionally the last error that occurred on this connection.
func (db *DB) putConn(dc *driverConn, err error, resetSession bool) {
if !errors.Is(err, driver.ErrBadConn) {
if !dc.validateConnection(resetSession) {
err = driver.ErrBadConn
}
}
db.mu.Lock()
if !dc.inUse {
db.mu.Unlock()
if debugGetPut {
fmt.Printf("putConn(%v) DUPLICATE was: %s\n\nPREVIOUS was: %s", dc, stack(), db.lastPut[dc])
}
panic("sql: connection returned that was never out")
}
if !errors.Is(err, driver.ErrBadConn) && dc.expired(db.maxLifetime) {
db.maxLifetimeClosed++
err = driver.ErrBadConn
}
if debugGetPut {
db.lastPut[dc] = stack()
}
dc.inUse = false
dc.returnedAt = nowFunc()
for _, fn := range dc.onPut {
fn()
}
dc.onPut = nil
if errors.Is(err, driver.ErrBadConn) {
// Don't reuse bad connections.
// Since the conn is considered bad and is being discarded, treat it
// as closed. Don't decrement the open count here, finalClose will
// take care of that.
db.maybeOpenNewConnections()
db.mu.Unlock()
dc.Close()
return
}
if putConnHook != nil {
putConnHook(db, dc)
}
added := db.putConnDBLocked(dc, nil)
db.mu.Unlock()
if !added {
dc.Close()
return
}
}
// Satisfy a connRequest or put the driverConn in the idle pool and return true
// or return false.
// putConnDBLocked will satisfy a connRequest if there is one, or it will
// return the *driverConn to the freeConn list if err == nil and the idle
// connection limit will not be exceeded.
// If err != nil, the value of dc is ignored.
// If err == nil, then dc must not equal nil.
// If a connRequest was fulfilled or the *driverConn was placed in the
// freeConn list, then true is returned, otherwise false is returned.
func (db *DB) putConnDBLocked(dc *driverConn, err error) bool {
if db.closed {
return false
}
if db.maxOpen > 0 && db.numOpen > db.maxOpen {
return false
}
if req, ok := db.connRequests.TakeRandom(); ok {
if err == nil {
dc.inUse = true
}
req <- connRequest{
conn: dc,
err: err,
}
return true
} else if err == nil && !db.closed {
if db.maxIdleConnsLocked() > len(db.freeConn) {
db.freeConn = append(db.freeConn, dc)
db.startCleanerLocked()
return true
}
db.maxIdleClosed++
}
return false
}
// maxBadConnRetries is the number of maximum retries if the driver returns
// driver.ErrBadConn to signal a broken connection before forcing a new
// connection to be opened.
const maxBadConnRetries = 2
func (db *DB) retry(fn func(strategy connReuseStrategy) error) error {
for i := int64(0); i < maxBadConnRetries; i++ {
err := fn(cachedOrNewConn)
// retry if err is driver.ErrBadConn
if err == nil || !errors.Is(err, driver.ErrBadConn) {
return err
}
}
return fn(alwaysNewConn)
}
// PrepareContext creates a prepared statement for later queries or executions.
// Multiple queries or executions may be run concurrently from the
// returned statement.
// The caller must call the statement's [*Stmt.Close] method
// when the statement is no longer needed.
//
// The provided context is used for the preparation of the statement, not for the
// execution of the statement.
func (db *DB) PrepareContext(ctx context.Context, query string) (*Stmt, error) {
var stmt *Stmt
var err error
err = db.retry(func(strategy connReuseStrategy) error {
stmt, err = db.prepare(ctx, query, strategy)
return err
})
return stmt, err
}
// Prepare creates a prepared statement for later queries or executions.
// Multiple queries or executions may be run concurrently from the
// returned statement.
// The caller must call the statement's [*Stmt.Close] method
// when the statement is no longer needed.
//
// Prepare uses [context.Background] internally; to specify the context, use
// [DB.PrepareContext].
func (db *DB) Prepare(query string) (*Stmt, error) {
return db.PrepareContext(context.Background(), query)
}
func (db *DB) prepare(ctx context.Context, query string, strategy connReuseStrategy) (*Stmt, error) {
// TODO: check if db.driver supports an optional
// driver.Preparer interface and call that instead, if so,
// otherwise we make a prepared statement that's bound
// to a connection, and to execute this prepared statement
// we either need to use this connection (if it's free), else
// get a new connection + re-prepare + execute on that one.
dc, err := db.conn(ctx, strategy)
if err != nil {
return nil, err
}
return db.prepareDC(ctx, dc, dc.releaseConn, nil, query)
}
// prepareDC prepares a query on the driverConn and calls release before
// returning. When cg == nil it implies that a connection pool is used, and
// when cg != nil only a single driver connection is used.
func (db *DB) prepareDC(ctx context.Context, dc *driverConn, release func(error), cg stmtConnGrabber, query string) (*Stmt, error) {
var ds *driverStmt
var err error
defer func() {
release(err)
}()
withLock(dc, func() {
ds, err = dc.prepareLocked(ctx, cg, query)
})
if err != nil {
return nil, err
}
stmt := &Stmt{
db: db,
query: query,
cg: cg,
cgds: ds,
}
// When cg == nil this statement will need to keep track of various
// connections they are prepared on and record the stmt dependency on
// the DB.
if cg == nil {
stmt.css = []connStmt{{dc, ds}}
stmt.lastNumClosed = db.numClosed.Load()
db.addDep(stmt, stmt)
}
return stmt, nil
}
// ExecContext executes a query without returning any rows.
// The args are for any placeholder parameters in the query.
func (db *DB) ExecContext(ctx context.Context, query string, args ...any) (Result, error) {
var res Result
var err error
err = db.retry(func(strategy connReuseStrategy) error {
res, err = db.exec(ctx, query, args, strategy)
return err
})
return res, err
}
// Exec executes a query without returning any rows.
// The args are for any placeholder parameters in the query.
//
// Exec uses [context.Background] internally; to specify the context, use
// [DB.ExecContext].
func (db *DB) Exec(query string, args ...any) (Result, error) {
return db.ExecContext(context.Background(), query, args...)
}
func (db *DB) exec(ctx context.Context, query string, args []any, strategy connReuseStrategy) (Result, error) {
dc, err := db.conn(ctx, strategy)
if err != nil {
return nil, err
}
return db.execDC(ctx, dc, dc.releaseConn, query, args)
}
func (db *DB) execDC(ctx context.Context, dc *driverConn, release func(error), query string, args []any) (res Result, err error) {
defer func() {
release(err)
}()
execerCtx, ok := dc.ci.(driver.ExecerContext)
var execer driver.Execer
if !ok {
execer, ok = dc.ci.(driver.Execer)
}
if ok {
var nvdargs []driver.NamedValue
var resi driver.Result
withLock(dc, func() {
nvdargs, err = driverArgsConnLocked(dc.ci, nil, args)
if err != nil {
return
}
resi, err = ctxDriverExec(ctx, execerCtx, execer, query, nvdargs)
})
if err != driver.ErrSkip {
if err != nil {
return nil, err
}
return driverResult{dc, resi}, nil
}
}
var si driver.Stmt
withLock(dc, func() {
si, err = ctxDriverPrepare(ctx, dc.ci, query)
})
if err != nil {
return nil, err
}
ds := &driverStmt{Locker: dc, si: si}
defer ds.Close()
return resultFromStatement(ctx, dc.ci, ds, args...)
}
// QueryContext executes a query that returns rows, typically a SELECT.
// The args are for any placeholder parameters in the query.
func (db *DB) QueryContext(ctx context.Context, query string, args ...any) (*Rows, error) {
var rows *Rows
var err error
err = db.retry(func(strategy connReuseStrategy) error {
rows, err = db.query(ctx, query, args, strategy)
return err
})
return rows, err
}
// Query executes a query that returns rows, typically a SELECT.
// The args are for any placeholder parameters in the query.
//
// Query uses [context.Background] internally; to specify the context, use
// [DB.QueryContext].
func (db *DB) Query(query string, args ...any) (*Rows, error) {
return db.QueryContext(context.Background(), query, args...)
}
func (db *DB) query(ctx context.Context, query string, args []any, strategy connReuseStrategy) (*Rows, error) {
dc, err := db.conn(ctx, strategy)
if err != nil {
return nil, err
}
return db.queryDC(ctx, nil, dc, dc.releaseConn, query, args)
}
// queryDC executes a query on the given connection.
// The connection gets released by the releaseConn function.
// The ctx context is from a query method and the txctx context is from an
// optional transaction context.
func (db *DB) queryDC(ctx, txctx context.Context, dc *driverConn, releaseConn func(error), query string, args []any) (*Rows, error) {
queryerCtx, ok := dc.ci.(driver.QueryerContext)
var queryer driver.Queryer
if !ok {
queryer, ok = dc.ci.(driver.Queryer)
}
if ok {
var nvdargs []driver.NamedValue
var rowsi driver.Rows
var err error
withLock(dc, func() {
nvdargs, err = driverArgsConnLocked(dc.ci, nil, args)
if err != nil {
return
}
rowsi, err = ctxDriverQuery(ctx, queryerCtx, queryer, query, nvdargs)
})
if err != driver.ErrSkip {
if err != nil {
releaseConn(err)
return nil, err
}
// Note: ownership of dc passes to the *Rows, to be freed
// with releaseConn.
rows := &Rows{
dc: dc,
releaseConn: releaseConn,
rowsi: rowsi,
}
rows.initContextClose(ctx, txctx)
return rows, nil
}
}
var si driver.Stmt
var err error
withLock(dc, func() {
si, err = ctxDriverPrepare(ctx, dc.ci, query)
})
if err != nil {
releaseConn(err)
return nil, err
}
ds := &driverStmt{Locker: dc, si: si}
rowsi, err := rowsiFromStatement(ctx, dc.ci, ds, args...)
if err != nil {
ds.Close()
releaseConn(err)
return nil, err
}
// Note: ownership of ci passes to the *Rows, to be freed
// with releaseConn.
rows := &Rows{
dc: dc,
releaseConn: releaseConn,
rowsi: rowsi,
closeStmt: ds,
}
rows.initContextClose(ctx, txctx)
return rows, nil
}
// QueryRowContext executes a query that is expected to return at most one row.
// QueryRowContext always returns a non-nil value. Errors are deferred until
// [Row]'s Scan method is called.
// If the query selects no rows, the [*Row.Scan] will return [ErrNoRows].
// Otherwise, [*Row.Scan] scans the first selected row and discards
// the rest.
func (db *DB) QueryRowContext(ctx context.Context, query string, args ...any) *Row {
rows, err := db.QueryContext(ctx, query, args...)
return &Row{rows: rows, err: err}
}
// QueryRow executes a query that is expected to return at most one row.
// QueryRow always returns a non-nil value. Errors are deferred until
// [Row]'s Scan method is called.
// If the query selects no rows, the [*Row.Scan] will return [ErrNoRows].
// Otherwise, [*Row.Scan] scans the first selected row and discards
// the rest.
//
// QueryRow uses [context.Background] internally; to specify the context, use
// [DB.QueryRowContext].
func (db *DB) QueryRow(query string, args ...any) *Row {
return db.QueryRowContext(context.Background(), query, args...)
}
// BeginTx starts a transaction.
//
// The provided context is used until the transaction is committed or rolled back.
// If the context is canceled, the sql package will roll back
// the transaction. [Tx.Commit] will return an error if the context provided to
// BeginTx is canceled.
//
// The provided [TxOptions] is optional and may be nil if defaults should be used.
// If a non-default isolation level is used that the driver doesn't support,
// an error will be returned.
func (db *DB) BeginTx(ctx context.Context, opts *TxOptions) (*Tx, error) {
var tx *Tx
var err error
err = db.retry(func(strategy connReuseStrategy) error {
tx, err = db.begin(ctx, opts, strategy)
return err
})
return tx, err
}
// Begin starts a transaction. The default isolation level is dependent on
// the driver.
//
// Begin uses [context.Background] internally; to specify the context, use
// [DB.BeginTx].
func (db *DB) Begin() (*Tx, error) {
return db.BeginTx(context.Background(), nil)
}
func (db *DB) begin(ctx context.Context, opts *TxOptions, strategy connReuseStrategy) (tx *Tx, err error) {
dc, err := db.conn(ctx, strategy)
if err != nil {
return nil, err
}
return db.beginDC(ctx, dc, dc.releaseConn, opts)
}
// beginDC starts a transaction. The provided dc must be valid and ready to use.
func (db *DB) beginDC(ctx context.Context, dc *driverConn, release func(error), opts *TxOptions) (tx *Tx, err error) {
var txi driver.Tx
keepConnOnRollback := false
withLock(dc, func() {
_, hasSessionResetter := dc.ci.(driver.SessionResetter)
_, hasConnectionValidator := dc.ci.(driver.Validator)
keepConnOnRollback = hasSessionResetter && hasConnectionValidator
txi, err = ctxDriverBegin(ctx, opts, dc.ci)
})
if err != nil {
release(err)
return nil, err
}
// Schedule the transaction to rollback when the context is canceled.
// The cancel function in Tx will be called after done is set to true.
ctx, cancel := context.WithCancel(ctx)
tx = &Tx{
db: db,
dc: dc,
releaseConn: release,
txi: txi,
cancel: cancel,
keepConnOnRollback: keepConnOnRollback,
ctx: ctx,
}
go tx.awaitDone()
return tx, nil
}
// Driver returns the database's underlying driver.
func (db *DB) Driver() driver.Driver {
return db.connector.Driver()
}
// ErrConnDone is returned by any operation that is performed on a connection
// that has already been returned to the connection pool.
var ErrConnDone = errors.New("sql: connection is already closed")
// Conn returns a single connection by either opening a new connection
// or returning an existing connection from the connection pool. Conn will
// block until either a connection is returned or ctx is canceled.
// Queries run on the same Conn will be run in the same database session.
//
// Every Conn must be returned to the database pool after use by
// calling [Conn.Close].
func (db *DB) Conn(ctx context.Context) (*Conn, error) {
var dc *driverConn
var err error
err = db.retry(func(strategy connReuseStrategy) error {
dc, err = db.conn(ctx, strategy)
return err
})
if err != nil {
return nil, err
}
conn := &Conn{
db: db,
dc: dc,
}
return conn, nil
}
type releaseConn func(error)
// Conn represents a single database connection rather than a pool of database
// connections. Prefer running queries from [DB] unless there is a specific
// need for a continuous single database connection.
//
// A Conn must call [Conn.Close] to return the connection to the database pool
// and may do so concurrently with a running query.
//
// After a call to [Conn.Close], all operations on the
// connection fail with [ErrConnDone].
type Conn struct {
db *DB
// closemu prevents the connection from closing while there
// is an active query. It is held for read during queries
// and exclusively during close.
closemu sync.RWMutex
// dc is owned until close, at which point
// it's returned to the connection pool.
dc *driverConn
// done transitions from false to true exactly once, on close.
// Once done, all operations fail with ErrConnDone.
done atomic.Bool
releaseConnOnce sync.Once
// releaseConnCache is a cache of c.closemuRUnlockCondReleaseConn
// to save allocations in a call to grabConn.
releaseConnCache releaseConn
}
// grabConn takes a context to implement stmtConnGrabber
// but the context is not used.
func (c *Conn) grabConn(context.Context) (*driverConn, releaseConn, error) {
if c.done.Load() {
return nil, nil, ErrConnDone
}
c.releaseConnOnce.Do(func() {
c.releaseConnCache = c.closemuRUnlockCondReleaseConn
})
c.closemu.RLock()
return c.dc, c.releaseConnCache, nil
}
// PingContext verifies the connection to the database is still alive.
func (c *Conn) PingContext(ctx context.Context) error {
dc, release, err := c.grabConn(ctx)
if err != nil {
return err
}
return c.db.pingDC(ctx, dc, release)
}
// ExecContext executes a query without returning any rows.
// The args are for any placeholder parameters in the query.
func (c *Conn) ExecContext(ctx context.Context, query string, args ...any) (Result, error) {
dc, release, err := c.grabConn(ctx)
if err != nil {
return nil, err
}
return c.db.execDC(ctx, dc, release, query, args)
}
// QueryContext executes a query that returns rows, typically a SELECT.
// The args are for any placeholder parameters in the query.
func (c *Conn) QueryContext(ctx context.Context, query string, args ...any) (*Rows, error) {
dc, release, err := c.grabConn(ctx)
if err != nil {
return nil, err
}
return c.db.queryDC(ctx, nil, dc, release, query, args)
}
// QueryRowContext executes a query that is expected to return at most one row.
// QueryRowContext always returns a non-nil value. Errors are deferred until
// the [*Row.Scan] method is called.
// If the query selects no rows, the [*Row.Scan] will return [ErrNoRows].
// Otherwise, the [*Row.Scan] scans the first selected row and discards
// the rest.
func (c *Conn) QueryRowContext(ctx context.Context, query string, args ...any) *Row {
rows, err := c.QueryContext(ctx, query, args...)
return &Row{rows: rows, err: err}
}
// PrepareContext creates a prepared statement for later queries or executions.
// Multiple queries or executions may be run concurrently from the
// returned statement.
// The caller must call the statement's [*Stmt.Close] method
// when the statement is no longer needed.
//
// The provided context is used for the preparation of the statement, not for the
// execution of the statement.
func (c *Conn) PrepareContext(ctx context.Context, query string) (*Stmt, error) {
dc, release, err := c.grabConn(ctx)
if err != nil {
return nil, err
}
return c.db.prepareDC(ctx, dc, release, c, query)
}
// Raw executes f exposing the underlying driver connection for the
// duration of f. The driverConn must not be used outside of f.
//
// Once f returns and err is not [driver.ErrBadConn], the [Conn] will continue to be usable
// until [Conn.Close] is called.
func (c *Conn) Raw(f func(driverConn any) error) (err error) {
var dc *driverConn
var release releaseConn
// grabConn takes a context to implement stmtConnGrabber, but the context is not used.
dc, release, err = c.grabConn(nil)
if err != nil {
return
}
fPanic := true
dc.Mutex.Lock()
defer func() {
dc.Mutex.Unlock()
// If f panics fPanic will remain true.
// Ensure an error is passed to release so the connection
// may be discarded.
if fPanic {
err = driver.ErrBadConn
}
release(err)
}()
err = f(dc.ci)
fPanic = false
return
}
// BeginTx starts a transaction.
//
// The provided context is used until the transaction is committed or rolled back.
// If the context is canceled, the sql package will roll back
// the transaction. [Tx.Commit] will return an error if the context provided to
// BeginTx is canceled.
//
// The provided [TxOptions] is optional and may be nil if defaults should be used.
// If a non-default isolation level is used that the driver doesn't support,
// an error will be returned.
func (c *Conn) BeginTx(ctx context.Context, opts *TxOptions) (*Tx, error) {
dc, release, err := c.grabConn(ctx)
if err != nil {
return nil, err
}
return c.db.beginDC(ctx, dc, release, opts)
}
// closemuRUnlockCondReleaseConn read unlocks closemu
// as the sql operation is done with the dc.
func (c *Conn) closemuRUnlockCondReleaseConn(err error) {
c.closemu.RUnlock()
if errors.Is(err, driver.ErrBadConn) {
c.close(err)
}
}
func (c *Conn) txCtx() context.Context {
return nil
}
func (c *Conn) close(err error) error {
if !c.done.CompareAndSwap(false, true) {
return ErrConnDone
}
// Lock around releasing the driver connection
// to ensure all queries have been stopped before doing so.
c.closemu.Lock()
defer c.closemu.Unlock()
c.dc.releaseConn(err)
c.dc = nil
c.db = nil
return err
}
// Close returns the connection to the connection pool.
// All operations after a Close will return with [ErrConnDone].
// Close is safe to call concurrently with other operations and will
// block until all other operations finish. It may be useful to first
// cancel any used context and then call close directly after.
func (c *Conn) Close() error {
return c.close(nil)
}
// Tx is an in-progress database transaction.
//
// A transaction must end with a call to [Tx.Commit] or [Tx.Rollback].
//
// After a call to [Tx.Commit] or [Tx.Rollback], all operations on the
// transaction fail with [ErrTxDone].
//
// The statements prepared for a transaction by calling
// the transaction's [Tx.Prepare] or [Tx.Stmt] methods are closed
// by the call to [Tx.Commit] or [Tx.Rollback].
type Tx struct {
db *DB
// closemu prevents the transaction from closing while there
// is an active query. It is held for read during queries
// and exclusively during close.
closemu sync.RWMutex
// dc is owned exclusively until Commit or Rollback, at which point
// it's returned with putConn.
dc *driverConn
txi driver.Tx
// releaseConn is called once the Tx is closed to release
// any held driverConn back to the pool.
releaseConn func(error)
// done transitions from false to true exactly once, on Commit
// or Rollback. once done, all operations fail with
// ErrTxDone.
done atomic.Bool
// keepConnOnRollback is true if the driver knows
// how to reset the connection's session and if need be discard
// the connection.
keepConnOnRollback bool
// All Stmts prepared for this transaction. These will be closed after the
// transaction has been committed or rolled back.
stmts struct {
sync.Mutex
v []*Stmt
}
// cancel is called after done transitions from 0 to 1.
cancel func()
// ctx lives for the life of the transaction.
ctx context.Context
}
// awaitDone blocks until the context in Tx is canceled and rolls back
// the transaction if it's not already done.
func (tx *Tx) awaitDone() {
// Wait for either the transaction to be committed or rolled
// back, or for the associated context to be closed.
<-tx.ctx.Done()
// Discard and close the connection used to ensure the
// transaction is closed and the resources are released. This
// rollback does nothing if the transaction has already been
// committed or rolled back.
// Do not discard the connection if the connection knows
// how to reset the session.
discardConnection := !tx.keepConnOnRollback
tx.rollback(discardConnection)
}
func (tx *Tx) isDone() bool {
return tx.done.Load()
}
// ErrTxDone is returned by any operation that is performed on a transaction
// that has already been committed or rolled back.
var ErrTxDone = errors.New("sql: transaction has already been committed or rolled back")
// close returns the connection to the pool and
// must only be called by Tx.rollback or Tx.Commit while
// tx is already canceled and won't be executed concurrently.
func (tx *Tx) close(err error) {
tx.releaseConn(err)
tx.dc = nil
tx.txi = nil
}
// hookTxGrabConn specifies an optional hook to be called on
// a successful call to (*Tx).grabConn. For tests.
var hookTxGrabConn func()
func (tx *Tx) grabConn(ctx context.Context) (*driverConn, releaseConn, error) {
select {
default:
case <-ctx.Done():
return nil, nil, ctx.Err()
}
// closemu.RLock must come before the check for isDone to prevent the Tx from
// closing while a query is executing.
tx.closemu.RLock()
if tx.isDone() {
tx.closemu.RUnlock()
return nil, nil, ErrTxDone
}
if hookTxGrabConn != nil { // test hook
hookTxGrabConn()
}
return tx.dc, tx.closemuRUnlockRelease, nil
}
func (tx *Tx) txCtx() context.Context {
return tx.ctx
}
// closemuRUnlockRelease is used as a func(error) method value in
// [DB.ExecContext] and [DB.QueryContext]. Unlocking in the releaseConn keeps
// the driver conn from being returned to the connection pool until
// the Rows has been closed.
func (tx *Tx) closemuRUnlockRelease(error) {
tx.closemu.RUnlock()
}
// Closes all Stmts prepared for this transaction.
func (tx *Tx) closePrepared() {
tx.stmts.Lock()
defer tx.stmts.Unlock()
for _, stmt := range tx.stmts.v {
stmt.Close()
}
}
// Commit commits the transaction.
func (tx *Tx) Commit() error {
// Check context first to avoid transaction leak.
// If put it behind tx.done CompareAndSwap statement, we can't ensure
// the consistency between tx.done and the real COMMIT operation.
select {
default:
case <-tx.ctx.Done():
if tx.done.Load() {
return ErrTxDone
}
return tx.ctx.Err()
}
if !tx.done.CompareAndSwap(false, true) {
return ErrTxDone
}
// Cancel the Tx to release any active R-closemu locks.
// This is safe to do because tx.done has already transitioned
// from 0 to 1. Hold the W-closemu lock prior to rollback
// to ensure no other connection has an active query.
tx.cancel()
tx.closemu.Lock()
tx.closemu.Unlock()
var err error
withLock(tx.dc, func() {
err = tx.txi.Commit()
})
if !errors.Is(err, driver.ErrBadConn) {
tx.closePrepared()
}
tx.close(err)
return err
}
var rollbackHook func()
// rollback aborts the transaction and optionally forces the pool to discard
// the connection.
func (tx *Tx) rollback(discardConn bool) error {
if !tx.done.CompareAndSwap(false, true) {
return ErrTxDone
}
if rollbackHook != nil {
rollbackHook()
}
// Cancel the Tx to release any active R-closemu locks.
// This is safe to do because tx.done has already transitioned
// from 0 to 1. Hold the W-closemu lock prior to rollback
// to ensure no other connection has an active query.
tx.cancel()
tx.closemu.Lock()
tx.closemu.Unlock()
var err error
withLock(tx.dc, func() {
err = tx.txi.Rollback()
})
if !errors.Is(err, driver.ErrBadConn) {
tx.closePrepared()
}
if discardConn {
err = driver.ErrBadConn
}
tx.close(err)
return err
}
// Rollback aborts the transaction.
func (tx *Tx) Rollback() error {
return tx.rollback(false)
}
// PrepareContext creates a prepared statement for use within a transaction.
//
// The returned statement operates within the transaction and will be closed
// when the transaction has been committed or rolled back.
//
// To use an existing prepared statement on this transaction, see [Tx.Stmt].
//
// The provided context will be used for the preparation of the context, not
// for the execution of the returned statement. The returned statement
// will run in the transaction context.
func (tx *Tx) PrepareContext(ctx context.Context, query string) (*Stmt, error) {
dc, release, err := tx.grabConn(ctx)
if err != nil {
return nil, err
}
stmt, err := tx.db.prepareDC(ctx, dc, release, tx, query)
if err != nil {
return nil, err
}
tx.stmts.Lock()
tx.stmts.v = append(tx.stmts.v, stmt)
tx.stmts.Unlock()
return stmt, nil
}
// Prepare creates a prepared statement for use within a transaction.
//
// The returned statement operates within the transaction and will be closed
// when the transaction has been committed or rolled back.
//
// To use an existing prepared statement on this transaction, see [Tx.Stmt].
//
// Prepare uses [context.Background] internally; to specify the context, use
// [Tx.PrepareContext].
func (tx *Tx) Prepare(query string) (*Stmt, error) {
return tx.PrepareContext(context.Background(), query)
}
// StmtContext returns a transaction-specific prepared statement from
// an existing statement.
//
// Example:
//
// updateMoney, err := db.Prepare("UPDATE balance SET money=money+? WHERE id=?")
// ...
// tx, err := db.Begin()
// ...
// res, err := tx.StmtContext(ctx, updateMoney).Exec(123.45, 98293203)
//
// The provided context is used for the preparation of the statement, not for the
// execution of the statement.
//
// The returned statement operates within the transaction and will be closed
// when the transaction has been committed or rolled back.
func (tx *Tx) StmtContext(ctx context.Context, stmt *Stmt) *Stmt {
dc, release, err := tx.grabConn(ctx)
if err != nil {
return &Stmt{stickyErr: err}
}
defer release(nil)
if tx.db != stmt.db {
return &Stmt{stickyErr: errors.New("sql: Tx.Stmt: statement from different database used")}
}
var si driver.Stmt
var parentStmt *Stmt
stmt.mu.Lock()
if stmt.closed || stmt.cg != nil {
// If the statement has been closed or already belongs to a
// transaction, we can't reuse it in this connection.
// Since tx.StmtContext should never need to be called with a
// Stmt already belonging to tx, we ignore this edge case and
// re-prepare the statement in this case. No need to add
// code-complexity for this.
stmt.mu.Unlock()
withLock(dc, func() {
si, err = ctxDriverPrepare(ctx, dc.ci, stmt.query)
})
if err != nil {
return &Stmt{stickyErr: err}
}
} else {
stmt.removeClosedStmtLocked()
// See if the statement has already been prepared on this connection,
// and reuse it if possible.
for _, v := range stmt.css {
if v.dc == dc {
si = v.ds.si
break
}
}
stmt.mu.Unlock()
if si == nil {
var ds *driverStmt
withLock(dc, func() {
ds, err = stmt.prepareOnConnLocked(ctx, dc)
})
if err != nil {
return &Stmt{stickyErr: err}
}
si = ds.si
}
parentStmt = stmt
}
txs := &Stmt{
db: tx.db,
cg: tx,
cgds: &driverStmt{
Locker: dc,
si: si,
},
parentStmt: parentStmt,
query: stmt.query,
}
if parentStmt != nil {
tx.db.addDep(parentStmt, txs)
}
tx.stmts.Lock()
tx.stmts.v = append(tx.stmts.v, txs)
tx.stmts.Unlock()
return txs
}
// Stmt returns a transaction-specific prepared statement from
// an existing statement.
//
// Example:
//
// updateMoney, err := db.Prepare("UPDATE balance SET money=money+? WHERE id=?")
// ...
// tx, err := db.Begin()
// ...
// res, err := tx.Stmt(updateMoney).Exec(123.45, 98293203)
//
// The returned statement operates within the transaction and will be closed
// when the transaction has been committed or rolled back.
//
// Stmt uses [context.Background] internally; to specify the context, use
// [Tx.StmtContext].
func (tx *Tx) Stmt(stmt *Stmt) *Stmt {
return tx.StmtContext(context.Background(), stmt)
}
// ExecContext executes a query that doesn't return rows.
// For example: an INSERT and UPDATE.
func (tx *Tx) ExecContext(ctx context.Context, query string, args ...any) (Result, error) {
dc, release, err := tx.grabConn(ctx)
if err != nil {
return nil, err
}
return tx.db.execDC(ctx, dc, release, query, args)
}
// Exec executes a query that doesn't return rows.
// For example: an INSERT and UPDATE.
//
// Exec uses [context.Background] internally; to specify the context, use
// [Tx.ExecContext].
func (tx *Tx) Exec(query string, args ...any) (Result, error) {
return tx.ExecContext(context.Background(), query, args...)
}
// QueryContext executes a query that returns rows, typically a SELECT.
func (tx *Tx) QueryContext(ctx context.Context, query string, args ...any) (*Rows, error) {
dc, release, err := tx.grabConn(ctx)
if err != nil {
return nil, err
}
return tx.db.queryDC(ctx, tx.ctx, dc, release, query, args)
}
// Query executes a query that returns rows, typically a SELECT.
//
// Query uses [context.Background] internally; to specify the context, use
// [Tx.QueryContext].
func (tx *Tx) Query(query string, args ...any) (*Rows, error) {
return tx.QueryContext(context.Background(), query, args...)
}
// QueryRowContext executes a query that is expected to return at most one row.
// QueryRowContext always returns a non-nil value. Errors are deferred until
// [Row]'s Scan method is called.
// If the query selects no rows, the [*Row.Scan] will return [ErrNoRows].
// Otherwise, the [*Row.Scan] scans the first selected row and discards
// the rest.
func (tx *Tx) QueryRowContext(ctx context.Context, query string, args ...any) *Row {
rows, err := tx.QueryContext(ctx, query, args...)
return &Row{rows: rows, err: err}
}
// QueryRow executes a query that is expected to return at most one row.
// QueryRow always returns a non-nil value. Errors are deferred until
// [Row]'s Scan method is called.
// If the query selects no rows, the [*Row.Scan] will return [ErrNoRows].
// Otherwise, the [*Row.Scan] scans the first selected row and discards
// the rest.
//
// QueryRow uses [context.Background] internally; to specify the context, use
// [Tx.QueryRowContext].
func (tx *Tx) QueryRow(query string, args ...any) *Row {
return tx.QueryRowContext(context.Background(), query, args...)
}
// connStmt is a prepared statement on a particular connection.
type connStmt struct {
dc *driverConn
ds *driverStmt
}
// stmtConnGrabber represents a Tx or Conn that will return the underlying
// driverConn and release function.
type stmtConnGrabber interface {
// grabConn returns the driverConn and the associated release function
// that must be called when the operation completes.
grabConn(context.Context) (*driverConn, releaseConn, error)
// txCtx returns the transaction context if available.
// The returned context should be selected on along with
// any query context when awaiting a cancel.
txCtx() context.Context
}
var (
_ stmtConnGrabber = &Tx{}
_ stmtConnGrabber = &Conn{}
)
// Stmt is a prepared statement.
// A Stmt is safe for concurrent use by multiple goroutines.
//
// If a Stmt is prepared on a [Tx] or [Conn], it will be bound to a single
// underlying connection forever. If the [Tx] or [Conn] closes, the Stmt will
// become unusable and all operations will return an error.
// If a Stmt is prepared on a [DB], it will remain usable for the lifetime of the
// [DB]. When the Stmt needs to execute on a new underlying connection, it will
// prepare itself on the new connection automatically.
type Stmt struct {
// Immutable:
db *DB // where we came from
query string // that created the Stmt
stickyErr error // if non-nil, this error is returned for all operations
closemu sync.RWMutex // held exclusively during close, for read otherwise.
// If Stmt is prepared on a Tx or Conn then cg is present and will
// only ever grab a connection from cg.
// If cg is nil then the Stmt must grab an arbitrary connection
// from db and determine if it must prepare the stmt again by
// inspecting css.
cg stmtConnGrabber
cgds *driverStmt
// parentStmt is set when a transaction-specific statement
// is requested from an identical statement prepared on the same
// conn. parentStmt is used to track the dependency of this statement
// on its originating ("parent") statement so that parentStmt may
// be closed by the user without them having to know whether or not
// any transactions are still using it.
parentStmt *Stmt
mu sync.Mutex // protects the rest of the fields
closed bool
// css is a list of underlying driver statement interfaces
// that are valid on particular connections. This is only
// used if cg == nil and one is found that has idle
// connections. If cg != nil, cgds is always used.
css []connStmt
// lastNumClosed is copied from db.numClosed when Stmt is created
// without tx and closed connections in css are removed.
lastNumClosed uint64
}
// ExecContext executes a prepared statement with the given arguments and
// returns a [Result] summarizing the effect of the statement.
func (s *Stmt) ExecContext(ctx context.Context, args ...any) (Result, error) {
s.closemu.RLock()
defer s.closemu.RUnlock()
var res Result
err := s.db.retry(func(strategy connReuseStrategy) error {
dc, releaseConn, ds, err := s.connStmt(ctx, strategy)
if err != nil {
return err
}
res, err = resultFromStatement(ctx, dc.ci, ds, args...)
releaseConn(err)
return err
})
return res, err
}
// Exec executes a prepared statement with the given arguments and
// returns a [Result] summarizing the effect of the statement.
//
// Exec uses [context.Background] internally; to specify the context, use
// [Stmt.ExecContext].
func (s *Stmt) Exec(args ...any) (Result, error) {
return s.ExecContext(context.Background(), args...)
}
func resultFromStatement(ctx context.Context, ci driver.Conn, ds *driverStmt, args ...any) (Result, error) {
ds.Lock()
defer ds.Unlock()
dargs, err := driverArgsConnLocked(ci, ds, args)
if err != nil {
return nil, err
}
resi, err := ctxDriverStmtExec(ctx, ds.si, dargs)
if err != nil {
return nil, err
}
return driverResult{ds.Locker, resi}, nil
}
// removeClosedStmtLocked removes closed conns in s.css.
//
// To avoid lock contention on DB.mu, we do it only when
// s.db.numClosed - s.lastNum is large enough.
func (s *Stmt) removeClosedStmtLocked() {
t := len(s.css)/2 + 1
if t > 10 {
t = 10
}
dbClosed := s.db.numClosed.Load()
if dbClosed-s.lastNumClosed < uint64(t) {
return
}
s.db.mu.Lock()
for i := 0; i < len(s.css); i++ {
if s.css[i].dc.dbmuClosed {
s.css[i] = s.css[len(s.css)-1]
// Zero out the last element (for GC) before shrinking the slice.
s.css[len(s.css)-1] = connStmt{}
s.css = s.css[:len(s.css)-1]
i--
}
}
s.db.mu.Unlock()
s.lastNumClosed = dbClosed
}
// connStmt returns a free driver connection on which to execute the
// statement, a function to call to release the connection, and a
// statement bound to that connection.
func (s *Stmt) connStmt(ctx context.Context, strategy connReuseStrategy) (dc *driverConn, releaseConn func(error), ds *driverStmt, err error) {
if err = s.stickyErr; err != nil {
return
}
s.mu.Lock()
if s.closed {
s.mu.Unlock()
err = errors.New("sql: statement is closed")
return
}
// In a transaction or connection, we always use the connection that the
// stmt was created on.
if s.cg != nil {
s.mu.Unlock()
dc, releaseConn, err = s.cg.grabConn(ctx) // blocks, waiting for the connection.
if err != nil {
return
}
return dc, releaseConn, s.cgds, nil
}
s.removeClosedStmtLocked()
s.mu.Unlock()
dc, err = s.db.conn(ctx, strategy)
if err != nil {
return nil, nil, nil, err
}
s.mu.Lock()
for _, v := range s.css {
if v.dc == dc {
s.mu.Unlock()
return dc, dc.releaseConn, v.ds, nil
}
}
s.mu.Unlock()
// No luck; we need to prepare the statement on this connection
withLock(dc, func() {
ds, err = s.prepareOnConnLocked(ctx, dc)
})
if err != nil {
dc.releaseConn(err)
return nil, nil, nil, err
}
return dc, dc.releaseConn, ds, nil
}
// prepareOnConnLocked prepares the query in Stmt s on dc and adds it to the list of
// open connStmt on the statement. It assumes the caller is holding the lock on dc.
func (s *Stmt) prepareOnConnLocked(ctx context.Context, dc *driverConn) (*driverStmt, error) {
si, err := dc.prepareLocked(ctx, s.cg, s.query)
if err != nil {
return nil, err
}
cs := connStmt{dc, si}
s.mu.Lock()
s.css = append(s.css, cs)
s.mu.Unlock()
return cs.ds, nil
}
// QueryContext executes a prepared query statement with the given arguments
// and returns the query results as a [*Rows].
func (s *Stmt) QueryContext(ctx context.Context, args ...any) (*Rows, error) {
s.closemu.RLock()
defer s.closemu.RUnlock()
var rowsi driver.Rows
var rows *Rows
err := s.db.retry(func(strategy connReuseStrategy) error {
dc, releaseConn, ds, err := s.connStmt(ctx, strategy)
if err != nil {
return err
}
rowsi, err = rowsiFromStatement(ctx, dc.ci, ds, args...)
if err == nil {
// Note: ownership of ci passes to the *Rows, to be freed
// with releaseConn.
rows = &Rows{
dc: dc,
rowsi: rowsi,
// releaseConn set below
}
// addDep must be added before initContextClose or it could attempt
// to removeDep before it has been added.
s.db.addDep(s, rows)
// releaseConn must be set before initContextClose or it could
// release the connection before it is set.
rows.releaseConn = func(err error) {
releaseConn(err)
s.db.removeDep(s, rows)
}
var txctx context.Context
if s.cg != nil {
txctx = s.cg.txCtx()
}
rows.initContextClose(ctx, txctx)
return nil
}
releaseConn(err)
return err
})
return rows, err
}
// Query executes a prepared query statement with the given arguments
// and returns the query results as a *Rows.
//
// Query uses [context.Background] internally; to specify the context, use
// [Stmt.QueryContext].
func (s *Stmt) Query(args ...any) (*Rows, error) {
return s.QueryContext(context.Background(), args...)
}
func rowsiFromStatement(ctx context.Context, ci driver.Conn, ds *driverStmt, args ...any) (driver.Rows, error) {
ds.Lock()
defer ds.Unlock()
dargs, err := driverArgsConnLocked(ci, ds, args)
if err != nil {
return nil, err
}
return ctxDriverStmtQuery(ctx, ds.si, dargs)
}
// QueryRowContext executes a prepared query statement with the given arguments.
// If an error occurs during the execution of the statement, that error will
// be returned by a call to Scan on the returned [*Row], which is always non-nil.
// If the query selects no rows, the [*Row.Scan] will return [ErrNoRows].
// Otherwise, the [*Row.Scan] scans the first selected row and discards
// the rest.
func (s *Stmt) QueryRowContext(ctx context.Context, args ...any) *Row {
rows, err := s.QueryContext(ctx, args...)
if err != nil {
return &Row{err: err}
}
return &Row{rows: rows}
}
// QueryRow executes a prepared query statement with the given arguments.
// If an error occurs during the execution of the statement, that error will
// be returned by a call to Scan on the returned [*Row], which is always non-nil.
// If the query selects no rows, the [*Row.Scan] will return [ErrNoRows].
// Otherwise, the [*Row.Scan] scans the first selected row and discards
// the rest.
//
// Example usage:
//
// var name string
// err := nameByUseridStmt.QueryRow(id).Scan(&name)
//
// QueryRow uses [context.Background] internally; to specify the context, use
// [Stmt.QueryRowContext].
func (s *Stmt) QueryRow(args ...any) *Row {
return s.QueryRowContext(context.Background(), args...)
}
// Close closes the statement.
func (s *Stmt) Close() error {
s.closemu.Lock()
defer s.closemu.Unlock()
if s.stickyErr != nil {
return s.stickyErr
}
s.mu.Lock()
if s.closed {
s.mu.Unlock()
return nil
}
s.closed = true
txds := s.cgds
s.cgds = nil
s.mu.Unlock()
if s.cg == nil {
return s.db.removeDep(s, s)
}
if s.parentStmt != nil {
// If parentStmt is set, we must not close s.txds since it's stored
// in the css array of the parentStmt.
return s.db.removeDep(s.parentStmt, s)
}
return txds.Close()
}
func (s *Stmt) finalClose() error {
s.mu.Lock()
defer s.mu.Unlock()
if s.css != nil {
for _, v := range s.css {
s.db.noteUnusedDriverStatement(v.dc, v.ds)
v.dc.removeOpenStmt(v.ds)
}
s.css = nil
}
return nil
}
// Rows is the result of a query. Its cursor starts before the first row
// of the result set. Use [Rows.Next] to advance from row to row.
type Rows struct {
dc *driverConn // owned; must call releaseConn when closed to release
releaseConn func(error)
rowsi driver.Rows
cancel func() // called when Rows is closed, may be nil.
closeStmt *driverStmt // if non-nil, statement to Close on close
contextDone atomic.Pointer[error] // error that awaitDone saw; set before close attempt
// closemu prevents Rows from closing while there
// is an active streaming result. It is held for read during non-close operations
// and exclusively during close.
//
// closemu guards lasterr and closed.
closemu sync.RWMutex
lasterr error // non-nil only if closed is true
closed bool
// closemuScanHold is whether the previous call to Scan kept closemu RLock'ed
// without unlocking it. It does that when the user passes a *RawBytes scan
// target. In that case, we need to prevent awaitDone from closing the Rows
// while the user's still using the memory. See go.dev/issue/60304.
//
// It is only used by Scan, Next, and NextResultSet which are expected
// not to be called concurrently.
closemuScanHold bool
// hitEOF is whether Next hit the end of the rows without
// encountering an error. It's set in Next before
// returning. It's only used by Next and Err which are
// expected not to be called concurrently.
hitEOF bool
// lastcols is only used in Scan, Next, and NextResultSet which are expected
// not to be called concurrently.
lastcols []driver.Value
// raw is a buffer for RawBytes that persists between Scan calls.
// This is used when the driver returns a mismatched type that requires
// a cloning allocation. For example, if the driver returns a *string and
// the user is scanning into a *RawBytes, we need to copy the string.
// The raw buffer here lets us reuse the memory for that copy across Scan calls.
raw []byte
}
// lasterrOrErrLocked returns either lasterr or the provided err.
// rs.closemu must be read-locked.
func (rs *Rows) lasterrOrErrLocked(err error) error {
if rs.lasterr != nil && rs.lasterr != io.EOF {
return rs.lasterr
}
return err
}
// bypassRowsAwaitDone is only used for testing.
// If true, it will not close the Rows automatically from the context.
var bypassRowsAwaitDone = false
func (rs *Rows) initContextClose(ctx, txctx context.Context) {
if ctx.Done() == nil && (txctx == nil || txctx.Done() == nil) {
return
}
if bypassRowsAwaitDone {
return
}
closectx, cancel := context.WithCancel(ctx)
rs.cancel = cancel
go rs.awaitDone(ctx, txctx, closectx)
}
// awaitDone blocks until ctx, txctx, or closectx is canceled.
// The ctx is provided from the query context.
// If the query was issued in a transaction, the transaction's context
// is also provided in txctx, to ensure Rows is closed if the Tx is closed.
// The closectx is closed by an explicit call to rs.Close.
func (rs *Rows) awaitDone(ctx, txctx, closectx context.Context) {
var txctxDone <-chan struct{}
if txctx != nil {
txctxDone = txctx.Done()
}
select {
case <-ctx.Done():
err := ctx.Err()
rs.contextDone.Store(&err)
case <-txctxDone:
err := txctx.Err()
rs.contextDone.Store(&err)
case <-closectx.Done():
// rs.cancel was called via Close(); don't store this into contextDone
// to ensure Err() is unaffected.
}
rs.close(ctx.Err())
}
// Next prepares the next result row for reading with the [Rows.Scan] method. It
// returns true on success, or false if there is no next result row or an error
// happened while preparing it. [Rows.Err] should be consulted to distinguish between
// the two cases.
//
// Every call to [Rows.Scan], even the first one, must be preceded by a call to [Rows.Next].
func (rs *Rows) Next() bool {
// If the user's calling Next, they're done with their previous row's Scan
// results (any RawBytes memory), so we can release the read lock that would
// be preventing awaitDone from calling close.
rs.closemuRUnlockIfHeldByScan()
if rs.contextDone.Load() != nil {
return false
}
var doClose, ok bool
withLock(rs.closemu.RLocker(), func() {
doClose, ok = rs.nextLocked()
})
if doClose {
rs.Close()
}
if doClose && !ok {
rs.hitEOF = true
}
return ok
}
func (rs *Rows) nextLocked() (doClose, ok bool) {
if rs.closed {
return false, false
}
// Lock the driver connection before calling the driver interface
// rowsi to prevent a Tx from rolling back the connection at the same time.
rs.dc.Lock()
defer rs.dc.Unlock()
if rs.lastcols == nil {
rs.lastcols = make([]driver.Value, len(rs.rowsi.Columns()))
}
rs.lasterr = rs.rowsi.Next(rs.lastcols)
if rs.lasterr != nil {
// Close the connection if there is a driver error.
if rs.lasterr != io.EOF {
return true, false
}
nextResultSet, ok := rs.rowsi.(driver.RowsNextResultSet)
if !ok {
return true, false
}
// The driver is at the end of the current result set.
// Test to see if there is another result set after the current one.
// Only close Rows if there is no further result sets to read.
if !nextResultSet.HasNextResultSet() {
doClose = true
}
return doClose, false
}
return false, true
}
// NextResultSet prepares the next result set for reading. It reports whether
// there is further result sets, or false if there is no further result set
// or if there is an error advancing to it. The [Rows.Err] method should be consulted
// to distinguish between the two cases.
//
// After calling NextResultSet, the [Rows.Next] method should always be called before
// scanning. If there are further result sets they may not have rows in the result
// set.
func (rs *Rows) NextResultSet() bool {
// If the user's calling NextResultSet, they're done with their previous
// row's Scan results (any RawBytes memory), so we can release the read lock
// that would be preventing awaitDone from calling close.
rs.closemuRUnlockIfHeldByScan()
var doClose bool
defer func() {
if doClose {
rs.Close()
}
}()
rs.closemu.RLock()
defer rs.closemu.RUnlock()
if rs.closed {
return false
}
rs.lastcols = nil
nextResultSet, ok := rs.rowsi.(driver.RowsNextResultSet)
if !ok {
doClose = true
return false
}
// Lock the driver connection before calling the driver interface
// rowsi to prevent a Tx from rolling back the connection at the same time.
rs.dc.Lock()
defer rs.dc.Unlock()
rs.lasterr = nextResultSet.NextResultSet()
if rs.lasterr != nil {
doClose = true
return false
}
return true
}
// Err returns the error, if any, that was encountered during iteration.
// Err may be called after an explicit or implicit [Rows.Close].
func (rs *Rows) Err() error {
// Return any context error that might've happened during row iteration,
// but only if we haven't reported the final Next() = false after rows
// are done, in which case the user might've canceled their own context
// before calling Rows.Err.
if !rs.hitEOF {
if errp := rs.contextDone.Load(); errp != nil {
return *errp
}
}
rs.closemu.RLock()
defer rs.closemu.RUnlock()
return rs.lasterrOrErrLocked(nil)
}
// rawbuf returns the buffer to append RawBytes values to.
// This buffer is reused across calls to Rows.Scan.
//
// Usage:
//
// rawBytes = rows.setrawbuf(append(rows.rawbuf(), value...))
func (rs *Rows) rawbuf() []byte {
if rs == nil {
// convertAssignRows can take a nil *Rows; for simplicity handle it here
return nil
}
return rs.raw
}
// setrawbuf updates the RawBytes buffer with the result of appending a new value to it.
// It returns the new value.
func (rs *Rows) setrawbuf(b []byte) RawBytes {
if rs == nil {
// convertAssignRows can take a nil *Rows; for simplicity handle it here
return RawBytes(b)
}
off := len(rs.raw)
rs.raw = b
return RawBytes(rs.raw[off:])
}
var errRowsClosed = errors.New("sql: Rows are closed")
var errNoRows = errors.New("sql: no Rows available")
// Columns returns the column names.
// Columns returns an error if the rows are closed.
func (rs *Rows) Columns() ([]string, error) {
rs.closemu.RLock()
defer rs.closemu.RUnlock()
if rs.closed {
return nil, rs.lasterrOrErrLocked(errRowsClosed)
}
if rs.rowsi == nil {
return nil, rs.lasterrOrErrLocked(errNoRows)
}
rs.dc.Lock()
defer rs.dc.Unlock()
return rs.rowsi.Columns(), nil
}
// ColumnTypes returns column information such as column type, length,
// and nullable. Some information may not be available from some drivers.
func (rs *Rows) ColumnTypes() ([]*ColumnType, error) {
rs.closemu.RLock()
defer rs.closemu.RUnlock()
if rs.closed {
return nil, rs.lasterrOrErrLocked(errRowsClosed)
}
if rs.rowsi == nil {
return nil, rs.lasterrOrErrLocked(errNoRows)
}
rs.dc.Lock()
defer rs.dc.Unlock()
return rowsColumnInfoSetupConnLocked(rs.rowsi), nil
}
// ColumnType contains the name and type of a column.
type ColumnType struct {
name string
hasNullable bool
hasLength bool
hasPrecisionScale bool
nullable bool
length int64
databaseType string
precision int64
scale int64
scanType reflect.Type
}
// Name returns the name or alias of the column.
func (ci *ColumnType) Name() string {
return ci.name
}
// Length returns the column type length for variable length column types such
// as text and binary field types. If the type length is unbounded the value will
// be [math.MaxInt64] (any database limits will still apply).
// If the column type is not variable length, such as an int, or if not supported
// by the driver ok is false.
func (ci *ColumnType) Length() (length int64, ok bool) {
return ci.length, ci.hasLength
}
// DecimalSize returns the scale and precision of a decimal type.
// If not applicable or if not supported ok is false.
func (ci *ColumnType) DecimalSize() (precision, scale int64, ok bool) {
return ci.precision, ci.scale, ci.hasPrecisionScale
}
// ScanType returns a Go type suitable for scanning into using [Rows.Scan].
// If a driver does not support this property ScanType will return
// the type of an empty interface.
func (ci *ColumnType) ScanType() reflect.Type {
return ci.scanType
}
// Nullable reports whether the column may be null.
// If a driver does not support this property ok will be false.
func (ci *ColumnType) Nullable() (nullable, ok bool) {
return ci.nullable, ci.hasNullable
}
// DatabaseTypeName returns the database system name of the column type. If an empty
// string is returned, then the driver type name is not supported.
// Consult your driver documentation for a list of driver data types. [ColumnType.Length] specifiers
// are not included.
// Common type names include "VARCHAR", "TEXT", "NVARCHAR", "DECIMAL", "BOOL",
// "INT", and "BIGINT".
func (ci *ColumnType) DatabaseTypeName() string {
return ci.databaseType
}
func rowsColumnInfoSetupConnLocked(rowsi driver.Rows) []*ColumnType {
names := rowsi.Columns()
list := make([]*ColumnType, len(names))
for i := range list {
ci := &ColumnType{
name: names[i],
}
list[i] = ci
if prop, ok := rowsi.(driver.RowsColumnTypeScanType); ok {
ci.scanType = prop.ColumnTypeScanType(i)
} else {
ci.scanType = reflect.TypeFor[any]()
}
if prop, ok := rowsi.(driver.RowsColumnTypeDatabaseTypeName); ok {
ci.databaseType = prop.ColumnTypeDatabaseTypeName(i)
}
if prop, ok := rowsi.(driver.RowsColumnTypeLength); ok {
ci.length, ci.hasLength = prop.ColumnTypeLength(i)
}
if prop, ok := rowsi.(driver.RowsColumnTypeNullable); ok {
ci.nullable, ci.hasNullable = prop.ColumnTypeNullable(i)
}
if prop, ok := rowsi.(driver.RowsColumnTypePrecisionScale); ok {
ci.precision, ci.scale, ci.hasPrecisionScale = prop.ColumnTypePrecisionScale(i)
}
}
return list
}
// Scan copies the columns in the current row into the values pointed
// at by dest. The number of values in dest must be the same as the
// number of columns in [Rows].
//
// Scan converts columns read from the database into the following
// common Go types and special types provided by the sql package:
//
// *string
// *[]byte
// *int, *int8, *int16, *int32, *int64
// *uint, *uint8, *uint16, *uint32, *uint64
// *bool
// *float32, *float64
// *interface{}
// *RawBytes
// *Rows (cursor value)
// any type implementing Scanner (see Scanner docs)
//
// In the most simple case, if the type of the value from the source
// column is an integer, bool or string type T and dest is of type *T,
// Scan simply assigns the value through the pointer.
//
// Scan also converts between string and numeric types, as long as no
// information would be lost. While Scan stringifies all numbers
// scanned from numeric database columns into *string, scans into
// numeric types are checked for overflow. For example, a float64 with
// value 300 or a string with value "300" can scan into a uint16, but
// not into a uint8, though float64(255) or "255" can scan into a
// uint8. One exception is that scans of some float64 numbers to
// strings may lose information when stringifying. In general, scan
// floating point columns into *float64.
//
// If a dest argument has type *[]byte, Scan saves in that argument a
// copy of the corresponding data. The copy is owned by the caller and
// can be modified and held indefinitely. The copy can be avoided by
// using an argument of type [*RawBytes] instead; see the documentation
// for [RawBytes] for restrictions on its use.
//
// If an argument has type *interface{}, Scan copies the value
// provided by the underlying driver without conversion. When scanning
// from a source value of type []byte to *interface{}, a copy of the
// slice is made and the caller owns the result.
//
// Source values of type [time.Time] may be scanned into values of type
// *time.Time, *interface{}, *string, or *[]byte. When converting to
// the latter two, [time.RFC3339Nano] is used.
//
// Source values of type bool may be scanned into types *bool,
// *interface{}, *string, *[]byte, or [*RawBytes].
//
// For scanning into *bool, the source may be true, false, 1, 0, or
// string inputs parseable by [strconv.ParseBool].
//
// Scan can also convert a cursor returned from a query, such as
// "select cursor(select * from my_table) from dual", into a
// [*Rows] value that can itself be scanned from. The parent
// select query will close any cursor [*Rows] if the parent [*Rows] is closed.
//
// If any of the first arguments implementing [Scanner] returns an error,
// that error will be wrapped in the returned error.
func (rs *Rows) Scan(dest ...any) error {
if rs.closemuScanHold {
// This should only be possible if the user calls Scan twice in a row
// without calling Next.
return fmt.Errorf("sql: Scan called without calling Next (closemuScanHold)")
}
rs.closemu.RLock()
if rs.lasterr != nil && rs.lasterr != io.EOF {
rs.closemu.RUnlock()
return rs.lasterr
}
if rs.closed {
err := rs.lasterrOrErrLocked(errRowsClosed)
rs.closemu.RUnlock()
return err
}
if scanArgsContainRawBytes(dest) {
rs.closemuScanHold = true
rs.raw = rs.raw[:0]
} else {
rs.closemu.RUnlock()
}
if rs.lastcols == nil {
rs.closemuRUnlockIfHeldByScan()
return errors.New("sql: Scan called without calling Next")
}
if len(dest) != len(rs.lastcols) {
rs.closemuRUnlockIfHeldByScan()
return fmt.Errorf("sql: expected %d destination arguments in Scan, not %d", len(rs.lastcols), len(dest))
}
for i, sv := range rs.lastcols {
err := convertAssignRows(dest[i], sv, rs)
if err != nil {
rs.closemuRUnlockIfHeldByScan()
return fmt.Errorf(`sql: Scan error on column index %d, name %q: %w`, i, rs.rowsi.Columns()[i], err)
}
}
return nil
}
// closemuRUnlockIfHeldByScan releases any closemu.RLock held open by a previous
// call to Scan with *RawBytes.
func (rs *Rows) closemuRUnlockIfHeldByScan() {
if rs.closemuScanHold {
rs.closemuScanHold = false
rs.closemu.RUnlock()
}
}
func scanArgsContainRawBytes(args []any) bool {
for _, a := range args {
if _, ok := a.(*RawBytes); ok {
return true
}
}
return false
}
// rowsCloseHook returns a function so tests may install the
// hook through a test only mutex.
var rowsCloseHook = func() func(*Rows, *error) { return nil }
// Close closes the [Rows], preventing further enumeration. If [Rows.Next] is called
// and returns false and there are no further result sets,
// the [Rows] are closed automatically and it will suffice to check the
// result of [Rows.Err]. Close is idempotent and does not affect the result of [Rows.Err].
func (rs *Rows) Close() error {
// If the user's calling Close, they're done with their previous row's Scan
// results (any RawBytes memory), so we can release the read lock that would
// be preventing awaitDone from calling the unexported close before we do so.
rs.closemuRUnlockIfHeldByScan()
return rs.close(nil)
}
func (rs *Rows) close(err error) error {
rs.closemu.Lock()
defer rs.closemu.Unlock()
if rs.closed {
return nil
}
rs.closed = true
if rs.lasterr == nil {
rs.lasterr = err
}
withLock(rs.dc, func() {
err = rs.rowsi.Close()
})
if fn := rowsCloseHook(); fn != nil {
fn(rs, &err)
}
if rs.cancel != nil {
rs.cancel()
}
if rs.closeStmt != nil {
rs.closeStmt.Close()
}
rs.releaseConn(err)
rs.lasterr = rs.lasterrOrErrLocked(err)
return err
}
// Row is the result of calling [DB.QueryRow] to select a single row.
type Row struct {
// One of these two will be non-nil:
err error // deferred error for easy chaining
rows *Rows
}
// Scan copies the columns from the matched row into the values
// pointed at by dest. See the documentation on [Rows.Scan] for details.
// If more than one row matches the query,
// Scan uses the first row and discards the rest. If no row matches
// the query, Scan returns [ErrNoRows].
func (r *Row) Scan(dest ...any) error {
if r.err != nil {
return r.err
}
// TODO(bradfitz): for now we need to defensively clone all
// []byte that the driver returned (not permitting
// *RawBytes in Rows.Scan), since we're about to close
// the Rows in our defer, when we return from this function.
// the contract with the driver.Next(...) interface is that it
// can return slices into read-only temporary memory that's
// only valid until the next Scan/Close. But the TODO is that
// for a lot of drivers, this copy will be unnecessary. We
// should provide an optional interface for drivers to
// implement to say, "don't worry, the []bytes that I return
// from Next will not be modified again." (for instance, if
// they were obtained from the network anyway) But for now we
// don't care.
defer r.rows.Close()
if scanArgsContainRawBytes(dest) {
return errors.New("sql: RawBytes isn't allowed on Row.Scan")
}
if !r.rows.Next() {
if err := r.rows.Err(); err != nil {
return err
}
return ErrNoRows
}
err := r.rows.Scan(dest...)
if err != nil {
return err
}
// Make sure the query can be processed to completion with no errors.
return r.rows.Close()
}
// Err provides a way for wrapping packages to check for
// query errors without calling [Row.Scan].
// Err returns the error, if any, that was encountered while running the query.
// If this error is not nil, this error will also be returned from [Row.Scan].
func (r *Row) Err() error {
return r.err
}
// A Result summarizes an executed SQL command.
type Result interface {
// LastInsertId returns the integer generated by the database
// in response to a command. Typically this will be from an
// "auto increment" column when inserting a new row. Not all
// databases support this feature, and the syntax of such
// statements varies.
LastInsertId() (int64, error)
// RowsAffected returns the number of rows affected by an
// update, insert, or delete. Not every database or database
// driver may support this.
RowsAffected() (int64, error)
}
type driverResult struct {
sync.Locker // the *driverConn
resi driver.Result
}
func (dr driverResult) LastInsertId() (int64, error) {
dr.Lock()
defer dr.Unlock()
return dr.resi.LastInsertId()
}
func (dr driverResult) RowsAffected() (int64, error) {
dr.Lock()
defer dr.Unlock()
return dr.resi.RowsAffected()
}
func stack() string {
var buf [2 << 10]byte
return string(buf[:runtime.Stack(buf[:], false)])
}
// withLock runs while holding lk.
func withLock(lk sync.Locker, fn func()) {
lk.Lock()
defer lk.Unlock() // in case fn panics
fn()
}
// connRequestSet is a set of chan connRequest that's
// optimized for:
//
// - adding an element
// - removing an element (only by the caller who added it)
// - taking (get + delete) a random element
//
// We previously used a map for this but the take of a random element
// was expensive, making mapiters. This type avoids a map entirely
// and just uses a slice.
type connRequestSet struct {
// s are the elements in the set.
s []connRequestAndIndex
}
type connRequestAndIndex struct {
// req is the element in the set.
req chan connRequest
// curIdx points to the current location of this element in
// connRequestSet.s. It gets set to -1 upon removal.
curIdx *int
}
// CloseAndRemoveAll closes all channels in the set
// and clears the set.
func (s *connRequestSet) CloseAndRemoveAll() {
for _, v := range s.s {
close(v.req)
}
s.s = nil
}
// Len returns the length of the set.
func (s *connRequestSet) Len() int { return len(s.s) }
// connRequestDelHandle is an opaque handle to delete an
// item from calling Add.
type connRequestDelHandle struct {
idx *int // pointer to index; or -1 if not in slice
}
// Add adds v to the set of waiting requests.
// The returned connRequestDelHandle can be used to remove the item from
// the set.
func (s *connRequestSet) Add(v chan connRequest) connRequestDelHandle {
idx := len(s.s)
// TODO(bradfitz): for simplicity, this always allocates a new int-sized
// allocation to store the index. But generally the set will be small and
// under a scannable-threshold. As an optimization, we could permit the *int
// to be nil when the set is small and should be scanned. This works even if
// the set grows over the threshold with delete handles outstanding because
// an element can only move to a lower index. So if it starts with a nil
// position, it'll always be in a low index and thus scannable. But that
// can be done in a follow-up change.
idxPtr := &idx
s.s = append(s.s, connRequestAndIndex{v, idxPtr})
return connRequestDelHandle{idxPtr}
}
// Delete removes an element from the set.
//
// It reports whether the element was deleted. (It can return false if a caller
// of TakeRandom took it meanwhile, or upon the second call to Delete)
func (s *connRequestSet) Delete(h connRequestDelHandle) bool {
idx := *h.idx
if idx < 0 {
return false
}
s.deleteIndex(idx)
return true
}
func (s *connRequestSet) deleteIndex(idx int) {
// Mark item as deleted.
*(s.s[idx].curIdx) = -1
// Copy last element, updating its position
// to its new home.
if idx < len(s.s)-1 {
last := s.s[len(s.s)-1]
*last.curIdx = idx
s.s[idx] = last
}
// Zero out last element (for GC) before shrinking the slice.
s.s[len(s.s)-1] = connRequestAndIndex{}
s.s = s.s[:len(s.s)-1]
}
// TakeRandom returns and removes a random element from s
// and reports whether there was one to take. (It returns ok=false
// if the set is empty.)
func (s *connRequestSet) TakeRandom() (v chan connRequest, ok bool) {
if len(s.s) == 0 {
return nil, false
}
pick := rand.IntN(len(s.s))
e := s.s[pick]
s.deleteIndex(pick)
return e.req, true
}
| go/src/database/sql/sql.go/0 | {
"file_path": "go/src/database/sql/sql.go",
"repo_id": "go",
"token_count": 35974
} | 232 |
// Copyright 2022 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
/*
Linux ELF:
gcc -gdwarf-4 -m64 -c bitfields.c -o bitfields.elf4
*/
typedef struct another_struct {
unsigned short quix;
int xyz[0];
unsigned x:1;
long long array[40];
} t_another_struct;
t_another_struct q2;
| go/src/debug/dwarf/testdata/bitfields.c/0 | {
"file_path": "go/src/debug/dwarf/testdata/bitfields.c",
"repo_id": "go",
"token_count": 133
} | 233 |
// gcc -g -O2 -freorder-blocks-and-partition
const char *arr[10000];
const char *hot = "hot";
const char *cold = "cold";
__attribute__((noinline))
void fn(int path) {
int i;
if (path) {
for (i = 0; i < sizeof arr / sizeof arr[0]; i++) {
arr[i] = hot;
}
} else {
for (i = 0; i < sizeof arr / sizeof arr[0]; i++) {
arr[i] = cold;
}
}
}
int main(int argc, char *argv[]) {
fn(argc);
return 0;
}
| go/src/debug/dwarf/testdata/ranges.c/0 | {
"file_path": "go/src/debug/dwarf/testdata/ranges.c",
"repo_id": "go",
"token_count": 188
} | 234 |
/*
* ELF constants and data structures
*
* Derived from:
* $FreeBSD: src/sys/sys/elf32.h,v 1.8.14.1 2005/12/30 22:13:58 marcel Exp $
* $FreeBSD: src/sys/sys/elf64.h,v 1.10.14.1 2005/12/30 22:13:58 marcel Exp $
* $FreeBSD: src/sys/sys/elf_common.h,v 1.15.8.1 2005/12/30 22:13:58 marcel Exp $
* $FreeBSD: src/sys/alpha/include/elf.h,v 1.14 2003/09/25 01:10:22 peter Exp $
* $FreeBSD: src/sys/amd64/include/elf.h,v 1.18 2004/08/03 08:21:48 dfr Exp $
* $FreeBSD: src/sys/arm/include/elf.h,v 1.5.2.1 2006/06/30 21:42:52 cognet Exp $
* $FreeBSD: src/sys/i386/include/elf.h,v 1.16 2004/08/02 19:12:17 dfr Exp $
* $FreeBSD: src/sys/powerpc/include/elf.h,v 1.7 2004/11/02 09:47:01 ssouhlal Exp $
* $FreeBSD: src/sys/sparc64/include/elf.h,v 1.12 2003/09/25 01:10:26 peter Exp $
* "System V ABI" (http://www.sco.com/developers/gabi/latest/ch4.eheader.html)
* "ELF for the ARM® 64-bit Architecture (AArch64)" (ARM IHI 0056B)
* "RISC-V ELF psABI specification" (https://github.com/riscv-non-isa/riscv-elf-psabi-doc/blob/master/riscv-elf.adoc)
* llvm/BinaryFormat/ELF.h - ELF constants and structures
*
* Copyright (c) 1996-1998 John D. Polstra. All rights reserved.
* Copyright (c) 2001 David E. O'Brien
* Portions Copyright 2009 The Go Authors. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
*/
package elf
import "strconv"
/*
* Constants
*/
// Indexes into the Header.Ident array.
const (
EI_CLASS = 4 /* Class of machine. */
EI_DATA = 5 /* Data format. */
EI_VERSION = 6 /* ELF format version. */
EI_OSABI = 7 /* Operating system / ABI identification */
EI_ABIVERSION = 8 /* ABI version */
EI_PAD = 9 /* Start of padding (per SVR4 ABI). */
EI_NIDENT = 16 /* Size of e_ident array. */
)
// Initial magic number for ELF files.
const ELFMAG = "\177ELF"
// Version is found in Header.Ident[EI_VERSION] and Header.Version.
type Version byte
const (
EV_NONE Version = 0
EV_CURRENT Version = 1
)
var versionStrings = []intName{
{0, "EV_NONE"},
{1, "EV_CURRENT"},
}
func (i Version) String() string { return stringName(uint32(i), versionStrings, false) }
func (i Version) GoString() string { return stringName(uint32(i), versionStrings, true) }
// Class is found in Header.Ident[EI_CLASS] and Header.Class.
type Class byte
const (
ELFCLASSNONE Class = 0 /* Unknown class. */
ELFCLASS32 Class = 1 /* 32-bit architecture. */
ELFCLASS64 Class = 2 /* 64-bit architecture. */
)
var classStrings = []intName{
{0, "ELFCLASSNONE"},
{1, "ELFCLASS32"},
{2, "ELFCLASS64"},
}
func (i Class) String() string { return stringName(uint32(i), classStrings, false) }
func (i Class) GoString() string { return stringName(uint32(i), classStrings, true) }
// Data is found in Header.Ident[EI_DATA] and Header.Data.
type Data byte
const (
ELFDATANONE Data = 0 /* Unknown data format. */
ELFDATA2LSB Data = 1 /* 2's complement little-endian. */
ELFDATA2MSB Data = 2 /* 2's complement big-endian. */
)
var dataStrings = []intName{
{0, "ELFDATANONE"},
{1, "ELFDATA2LSB"},
{2, "ELFDATA2MSB"},
}
func (i Data) String() string { return stringName(uint32(i), dataStrings, false) }
func (i Data) GoString() string { return stringName(uint32(i), dataStrings, true) }
// OSABI is found in Header.Ident[EI_OSABI] and Header.OSABI.
type OSABI byte
const (
ELFOSABI_NONE OSABI = 0 /* UNIX System V ABI */
ELFOSABI_HPUX OSABI = 1 /* HP-UX operating system */
ELFOSABI_NETBSD OSABI = 2 /* NetBSD */
ELFOSABI_LINUX OSABI = 3 /* Linux */
ELFOSABI_HURD OSABI = 4 /* Hurd */
ELFOSABI_86OPEN OSABI = 5 /* 86Open common IA32 ABI */
ELFOSABI_SOLARIS OSABI = 6 /* Solaris */
ELFOSABI_AIX OSABI = 7 /* AIX */
ELFOSABI_IRIX OSABI = 8 /* IRIX */
ELFOSABI_FREEBSD OSABI = 9 /* FreeBSD */
ELFOSABI_TRU64 OSABI = 10 /* TRU64 UNIX */
ELFOSABI_MODESTO OSABI = 11 /* Novell Modesto */
ELFOSABI_OPENBSD OSABI = 12 /* OpenBSD */
ELFOSABI_OPENVMS OSABI = 13 /* Open VMS */
ELFOSABI_NSK OSABI = 14 /* HP Non-Stop Kernel */
ELFOSABI_AROS OSABI = 15 /* Amiga Research OS */
ELFOSABI_FENIXOS OSABI = 16 /* The FenixOS highly scalable multi-core OS */
ELFOSABI_CLOUDABI OSABI = 17 /* Nuxi CloudABI */
ELFOSABI_ARM OSABI = 97 /* ARM */
ELFOSABI_STANDALONE OSABI = 255 /* Standalone (embedded) application */
)
var osabiStrings = []intName{
{0, "ELFOSABI_NONE"},
{1, "ELFOSABI_HPUX"},
{2, "ELFOSABI_NETBSD"},
{3, "ELFOSABI_LINUX"},
{4, "ELFOSABI_HURD"},
{5, "ELFOSABI_86OPEN"},
{6, "ELFOSABI_SOLARIS"},
{7, "ELFOSABI_AIX"},
{8, "ELFOSABI_IRIX"},
{9, "ELFOSABI_FREEBSD"},
{10, "ELFOSABI_TRU64"},
{11, "ELFOSABI_MODESTO"},
{12, "ELFOSABI_OPENBSD"},
{13, "ELFOSABI_OPENVMS"},
{14, "ELFOSABI_NSK"},
{15, "ELFOSABI_AROS"},
{16, "ELFOSABI_FENIXOS"},
{17, "ELFOSABI_CLOUDABI"},
{97, "ELFOSABI_ARM"},
{255, "ELFOSABI_STANDALONE"},
}
func (i OSABI) String() string { return stringName(uint32(i), osabiStrings, false) }
func (i OSABI) GoString() string { return stringName(uint32(i), osabiStrings, true) }
// Type is found in Header.Type.
type Type uint16
const (
ET_NONE Type = 0 /* Unknown type. */
ET_REL Type = 1 /* Relocatable. */
ET_EXEC Type = 2 /* Executable. */
ET_DYN Type = 3 /* Shared object. */
ET_CORE Type = 4 /* Core file. */
ET_LOOS Type = 0xfe00 /* First operating system specific. */
ET_HIOS Type = 0xfeff /* Last operating system-specific. */
ET_LOPROC Type = 0xff00 /* First processor-specific. */
ET_HIPROC Type = 0xffff /* Last processor-specific. */
)
var typeStrings = []intName{
{0, "ET_NONE"},
{1, "ET_REL"},
{2, "ET_EXEC"},
{3, "ET_DYN"},
{4, "ET_CORE"},
{0xfe00, "ET_LOOS"},
{0xfeff, "ET_HIOS"},
{0xff00, "ET_LOPROC"},
{0xffff, "ET_HIPROC"},
}
func (i Type) String() string { return stringName(uint32(i), typeStrings, false) }
func (i Type) GoString() string { return stringName(uint32(i), typeStrings, true) }
// Machine is found in Header.Machine.
type Machine uint16
const (
EM_NONE Machine = 0 /* Unknown machine. */
EM_M32 Machine = 1 /* AT&T WE32100. */
EM_SPARC Machine = 2 /* Sun SPARC. */
EM_386 Machine = 3 /* Intel i386. */
EM_68K Machine = 4 /* Motorola 68000. */
EM_88K Machine = 5 /* Motorola 88000. */
EM_860 Machine = 7 /* Intel i860. */
EM_MIPS Machine = 8 /* MIPS R3000 Big-Endian only. */
EM_S370 Machine = 9 /* IBM System/370. */
EM_MIPS_RS3_LE Machine = 10 /* MIPS R3000 Little-Endian. */
EM_PARISC Machine = 15 /* HP PA-RISC. */
EM_VPP500 Machine = 17 /* Fujitsu VPP500. */
EM_SPARC32PLUS Machine = 18 /* SPARC v8plus. */
EM_960 Machine = 19 /* Intel 80960. */
EM_PPC Machine = 20 /* PowerPC 32-bit. */
EM_PPC64 Machine = 21 /* PowerPC 64-bit. */
EM_S390 Machine = 22 /* IBM System/390. */
EM_V800 Machine = 36 /* NEC V800. */
EM_FR20 Machine = 37 /* Fujitsu FR20. */
EM_RH32 Machine = 38 /* TRW RH-32. */
EM_RCE Machine = 39 /* Motorola RCE. */
EM_ARM Machine = 40 /* ARM. */
EM_SH Machine = 42 /* Hitachi SH. */
EM_SPARCV9 Machine = 43 /* SPARC v9 64-bit. */
EM_TRICORE Machine = 44 /* Siemens TriCore embedded processor. */
EM_ARC Machine = 45 /* Argonaut RISC Core. */
EM_H8_300 Machine = 46 /* Hitachi H8/300. */
EM_H8_300H Machine = 47 /* Hitachi H8/300H. */
EM_H8S Machine = 48 /* Hitachi H8S. */
EM_H8_500 Machine = 49 /* Hitachi H8/500. */
EM_IA_64 Machine = 50 /* Intel IA-64 Processor. */
EM_MIPS_X Machine = 51 /* Stanford MIPS-X. */
EM_COLDFIRE Machine = 52 /* Motorola ColdFire. */
EM_68HC12 Machine = 53 /* Motorola M68HC12. */
EM_MMA Machine = 54 /* Fujitsu MMA. */
EM_PCP Machine = 55 /* Siemens PCP. */
EM_NCPU Machine = 56 /* Sony nCPU. */
EM_NDR1 Machine = 57 /* Denso NDR1 microprocessor. */
EM_STARCORE Machine = 58 /* Motorola Star*Core processor. */
EM_ME16 Machine = 59 /* Toyota ME16 processor. */
EM_ST100 Machine = 60 /* STMicroelectronics ST100 processor. */
EM_TINYJ Machine = 61 /* Advanced Logic Corp. TinyJ processor. */
EM_X86_64 Machine = 62 /* Advanced Micro Devices x86-64 */
EM_PDSP Machine = 63 /* Sony DSP Processor */
EM_PDP10 Machine = 64 /* Digital Equipment Corp. PDP-10 */
EM_PDP11 Machine = 65 /* Digital Equipment Corp. PDP-11 */
EM_FX66 Machine = 66 /* Siemens FX66 microcontroller */
EM_ST9PLUS Machine = 67 /* STMicroelectronics ST9+ 8/16 bit microcontroller */
EM_ST7 Machine = 68 /* STMicroelectronics ST7 8-bit microcontroller */
EM_68HC16 Machine = 69 /* Motorola MC68HC16 Microcontroller */
EM_68HC11 Machine = 70 /* Motorola MC68HC11 Microcontroller */
EM_68HC08 Machine = 71 /* Motorola MC68HC08 Microcontroller */
EM_68HC05 Machine = 72 /* Motorola MC68HC05 Microcontroller */
EM_SVX Machine = 73 /* Silicon Graphics SVx */
EM_ST19 Machine = 74 /* STMicroelectronics ST19 8-bit microcontroller */
EM_VAX Machine = 75 /* Digital VAX */
EM_CRIS Machine = 76 /* Axis Communications 32-bit embedded processor */
EM_JAVELIN Machine = 77 /* Infineon Technologies 32-bit embedded processor */
EM_FIREPATH Machine = 78 /* Element 14 64-bit DSP Processor */
EM_ZSP Machine = 79 /* LSI Logic 16-bit DSP Processor */
EM_MMIX Machine = 80 /* Donald Knuth's educational 64-bit processor */
EM_HUANY Machine = 81 /* Harvard University machine-independent object files */
EM_PRISM Machine = 82 /* SiTera Prism */
EM_AVR Machine = 83 /* Atmel AVR 8-bit microcontroller */
EM_FR30 Machine = 84 /* Fujitsu FR30 */
EM_D10V Machine = 85 /* Mitsubishi D10V */
EM_D30V Machine = 86 /* Mitsubishi D30V */
EM_V850 Machine = 87 /* NEC v850 */
EM_M32R Machine = 88 /* Mitsubishi M32R */
EM_MN10300 Machine = 89 /* Matsushita MN10300 */
EM_MN10200 Machine = 90 /* Matsushita MN10200 */
EM_PJ Machine = 91 /* picoJava */
EM_OPENRISC Machine = 92 /* OpenRISC 32-bit embedded processor */
EM_ARC_COMPACT Machine = 93 /* ARC International ARCompact processor (old spelling/synonym: EM_ARC_A5) */
EM_XTENSA Machine = 94 /* Tensilica Xtensa Architecture */
EM_VIDEOCORE Machine = 95 /* Alphamosaic VideoCore processor */
EM_TMM_GPP Machine = 96 /* Thompson Multimedia General Purpose Processor */
EM_NS32K Machine = 97 /* National Semiconductor 32000 series */
EM_TPC Machine = 98 /* Tenor Network TPC processor */
EM_SNP1K Machine = 99 /* Trebia SNP 1000 processor */
EM_ST200 Machine = 100 /* STMicroelectronics (www.st.com) ST200 microcontroller */
EM_IP2K Machine = 101 /* Ubicom IP2xxx microcontroller family */
EM_MAX Machine = 102 /* MAX Processor */
EM_CR Machine = 103 /* National Semiconductor CompactRISC microprocessor */
EM_F2MC16 Machine = 104 /* Fujitsu F2MC16 */
EM_MSP430 Machine = 105 /* Texas Instruments embedded microcontroller msp430 */
EM_BLACKFIN Machine = 106 /* Analog Devices Blackfin (DSP) processor */
EM_SE_C33 Machine = 107 /* S1C33 Family of Seiko Epson processors */
EM_SEP Machine = 108 /* Sharp embedded microprocessor */
EM_ARCA Machine = 109 /* Arca RISC Microprocessor */
EM_UNICORE Machine = 110 /* Microprocessor series from PKU-Unity Ltd. and MPRC of Peking University */
EM_EXCESS Machine = 111 /* eXcess: 16/32/64-bit configurable embedded CPU */
EM_DXP Machine = 112 /* Icera Semiconductor Inc. Deep Execution Processor */
EM_ALTERA_NIOS2 Machine = 113 /* Altera Nios II soft-core processor */
EM_CRX Machine = 114 /* National Semiconductor CompactRISC CRX microprocessor */
EM_XGATE Machine = 115 /* Motorola XGATE embedded processor */
EM_C166 Machine = 116 /* Infineon C16x/XC16x processor */
EM_M16C Machine = 117 /* Renesas M16C series microprocessors */
EM_DSPIC30F Machine = 118 /* Microchip Technology dsPIC30F Digital Signal Controller */
EM_CE Machine = 119 /* Freescale Communication Engine RISC core */
EM_M32C Machine = 120 /* Renesas M32C series microprocessors */
EM_TSK3000 Machine = 131 /* Altium TSK3000 core */
EM_RS08 Machine = 132 /* Freescale RS08 embedded processor */
EM_SHARC Machine = 133 /* Analog Devices SHARC family of 32-bit DSP processors */
EM_ECOG2 Machine = 134 /* Cyan Technology eCOG2 microprocessor */
EM_SCORE7 Machine = 135 /* Sunplus S+core7 RISC processor */
EM_DSP24 Machine = 136 /* New Japan Radio (NJR) 24-bit DSP Processor */
EM_VIDEOCORE3 Machine = 137 /* Broadcom VideoCore III processor */
EM_LATTICEMICO32 Machine = 138 /* RISC processor for Lattice FPGA architecture */
EM_SE_C17 Machine = 139 /* Seiko Epson C17 family */
EM_TI_C6000 Machine = 140 /* The Texas Instruments TMS320C6000 DSP family */
EM_TI_C2000 Machine = 141 /* The Texas Instruments TMS320C2000 DSP family */
EM_TI_C5500 Machine = 142 /* The Texas Instruments TMS320C55x DSP family */
EM_TI_ARP32 Machine = 143 /* Texas Instruments Application Specific RISC Processor, 32bit fetch */
EM_TI_PRU Machine = 144 /* Texas Instruments Programmable Realtime Unit */
EM_MMDSP_PLUS Machine = 160 /* STMicroelectronics 64bit VLIW Data Signal Processor */
EM_CYPRESS_M8C Machine = 161 /* Cypress M8C microprocessor */
EM_R32C Machine = 162 /* Renesas R32C series microprocessors */
EM_TRIMEDIA Machine = 163 /* NXP Semiconductors TriMedia architecture family */
EM_QDSP6 Machine = 164 /* QUALCOMM DSP6 Processor */
EM_8051 Machine = 165 /* Intel 8051 and variants */
EM_STXP7X Machine = 166 /* STMicroelectronics STxP7x family of configurable and extensible RISC processors */
EM_NDS32 Machine = 167 /* Andes Technology compact code size embedded RISC processor family */
EM_ECOG1 Machine = 168 /* Cyan Technology eCOG1X family */
EM_ECOG1X Machine = 168 /* Cyan Technology eCOG1X family */
EM_MAXQ30 Machine = 169 /* Dallas Semiconductor MAXQ30 Core Micro-controllers */
EM_XIMO16 Machine = 170 /* New Japan Radio (NJR) 16-bit DSP Processor */
EM_MANIK Machine = 171 /* M2000 Reconfigurable RISC Microprocessor */
EM_CRAYNV2 Machine = 172 /* Cray Inc. NV2 vector architecture */
EM_RX Machine = 173 /* Renesas RX family */
EM_METAG Machine = 174 /* Imagination Technologies META processor architecture */
EM_MCST_ELBRUS Machine = 175 /* MCST Elbrus general purpose hardware architecture */
EM_ECOG16 Machine = 176 /* Cyan Technology eCOG16 family */
EM_CR16 Machine = 177 /* National Semiconductor CompactRISC CR16 16-bit microprocessor */
EM_ETPU Machine = 178 /* Freescale Extended Time Processing Unit */
EM_SLE9X Machine = 179 /* Infineon Technologies SLE9X core */
EM_L10M Machine = 180 /* Intel L10M */
EM_K10M Machine = 181 /* Intel K10M */
EM_AARCH64 Machine = 183 /* ARM 64-bit Architecture (AArch64) */
EM_AVR32 Machine = 185 /* Atmel Corporation 32-bit microprocessor family */
EM_STM8 Machine = 186 /* STMicroeletronics STM8 8-bit microcontroller */
EM_TILE64 Machine = 187 /* Tilera TILE64 multicore architecture family */
EM_TILEPRO Machine = 188 /* Tilera TILEPro multicore architecture family */
EM_MICROBLAZE Machine = 189 /* Xilinx MicroBlaze 32-bit RISC soft processor core */
EM_CUDA Machine = 190 /* NVIDIA CUDA architecture */
EM_TILEGX Machine = 191 /* Tilera TILE-Gx multicore architecture family */
EM_CLOUDSHIELD Machine = 192 /* CloudShield architecture family */
EM_COREA_1ST Machine = 193 /* KIPO-KAIST Core-A 1st generation processor family */
EM_COREA_2ND Machine = 194 /* KIPO-KAIST Core-A 2nd generation processor family */
EM_ARC_COMPACT2 Machine = 195 /* Synopsys ARCompact V2 */
EM_OPEN8 Machine = 196 /* Open8 8-bit RISC soft processor core */
EM_RL78 Machine = 197 /* Renesas RL78 family */
EM_VIDEOCORE5 Machine = 198 /* Broadcom VideoCore V processor */
EM_78KOR Machine = 199 /* Renesas 78KOR family */
EM_56800EX Machine = 200 /* Freescale 56800EX Digital Signal Controller (DSC) */
EM_BA1 Machine = 201 /* Beyond BA1 CPU architecture */
EM_BA2 Machine = 202 /* Beyond BA2 CPU architecture */
EM_XCORE Machine = 203 /* XMOS xCORE processor family */
EM_MCHP_PIC Machine = 204 /* Microchip 8-bit PIC(r) family */
EM_INTEL205 Machine = 205 /* Reserved by Intel */
EM_INTEL206 Machine = 206 /* Reserved by Intel */
EM_INTEL207 Machine = 207 /* Reserved by Intel */
EM_INTEL208 Machine = 208 /* Reserved by Intel */
EM_INTEL209 Machine = 209 /* Reserved by Intel */
EM_KM32 Machine = 210 /* KM211 KM32 32-bit processor */
EM_KMX32 Machine = 211 /* KM211 KMX32 32-bit processor */
EM_KMX16 Machine = 212 /* KM211 KMX16 16-bit processor */
EM_KMX8 Machine = 213 /* KM211 KMX8 8-bit processor */
EM_KVARC Machine = 214 /* KM211 KVARC processor */
EM_CDP Machine = 215 /* Paneve CDP architecture family */
EM_COGE Machine = 216 /* Cognitive Smart Memory Processor */
EM_COOL Machine = 217 /* Bluechip Systems CoolEngine */
EM_NORC Machine = 218 /* Nanoradio Optimized RISC */
EM_CSR_KALIMBA Machine = 219 /* CSR Kalimba architecture family */
EM_Z80 Machine = 220 /* Zilog Z80 */
EM_VISIUM Machine = 221 /* Controls and Data Services VISIUMcore processor */
EM_FT32 Machine = 222 /* FTDI Chip FT32 high performance 32-bit RISC architecture */
EM_MOXIE Machine = 223 /* Moxie processor family */
EM_AMDGPU Machine = 224 /* AMD GPU architecture */
EM_RISCV Machine = 243 /* RISC-V */
EM_LANAI Machine = 244 /* Lanai 32-bit processor */
EM_BPF Machine = 247 /* Linux BPF – in-kernel virtual machine */
EM_LOONGARCH Machine = 258 /* LoongArch */
/* Non-standard or deprecated. */
EM_486 Machine = 6 /* Intel i486. */
EM_MIPS_RS4_BE Machine = 10 /* MIPS R4000 Big-Endian */
EM_ALPHA_STD Machine = 41 /* Digital Alpha (standard value). */
EM_ALPHA Machine = 0x9026 /* Alpha (written in the absence of an ABI) */
)
var machineStrings = []intName{
{0, "EM_NONE"},
{1, "EM_M32"},
{2, "EM_SPARC"},
{3, "EM_386"},
{4, "EM_68K"},
{5, "EM_88K"},
{7, "EM_860"},
{8, "EM_MIPS"},
{9, "EM_S370"},
{10, "EM_MIPS_RS3_LE"},
{15, "EM_PARISC"},
{17, "EM_VPP500"},
{18, "EM_SPARC32PLUS"},
{19, "EM_960"},
{20, "EM_PPC"},
{21, "EM_PPC64"},
{22, "EM_S390"},
{36, "EM_V800"},
{37, "EM_FR20"},
{38, "EM_RH32"},
{39, "EM_RCE"},
{40, "EM_ARM"},
{42, "EM_SH"},
{43, "EM_SPARCV9"},
{44, "EM_TRICORE"},
{45, "EM_ARC"},
{46, "EM_H8_300"},
{47, "EM_H8_300H"},
{48, "EM_H8S"},
{49, "EM_H8_500"},
{50, "EM_IA_64"},
{51, "EM_MIPS_X"},
{52, "EM_COLDFIRE"},
{53, "EM_68HC12"},
{54, "EM_MMA"},
{55, "EM_PCP"},
{56, "EM_NCPU"},
{57, "EM_NDR1"},
{58, "EM_STARCORE"},
{59, "EM_ME16"},
{60, "EM_ST100"},
{61, "EM_TINYJ"},
{62, "EM_X86_64"},
{63, "EM_PDSP"},
{64, "EM_PDP10"},
{65, "EM_PDP11"},
{66, "EM_FX66"},
{67, "EM_ST9PLUS"},
{68, "EM_ST7"},
{69, "EM_68HC16"},
{70, "EM_68HC11"},
{71, "EM_68HC08"},
{72, "EM_68HC05"},
{73, "EM_SVX"},
{74, "EM_ST19"},
{75, "EM_VAX"},
{76, "EM_CRIS"},
{77, "EM_JAVELIN"},
{78, "EM_FIREPATH"},
{79, "EM_ZSP"},
{80, "EM_MMIX"},
{81, "EM_HUANY"},
{82, "EM_PRISM"},
{83, "EM_AVR"},
{84, "EM_FR30"},
{85, "EM_D10V"},
{86, "EM_D30V"},
{87, "EM_V850"},
{88, "EM_M32R"},
{89, "EM_MN10300"},
{90, "EM_MN10200"},
{91, "EM_PJ"},
{92, "EM_OPENRISC"},
{93, "EM_ARC_COMPACT"},
{94, "EM_XTENSA"},
{95, "EM_VIDEOCORE"},
{96, "EM_TMM_GPP"},
{97, "EM_NS32K"},
{98, "EM_TPC"},
{99, "EM_SNP1K"},
{100, "EM_ST200"},
{101, "EM_IP2K"},
{102, "EM_MAX"},
{103, "EM_CR"},
{104, "EM_F2MC16"},
{105, "EM_MSP430"},
{106, "EM_BLACKFIN"},
{107, "EM_SE_C33"},
{108, "EM_SEP"},
{109, "EM_ARCA"},
{110, "EM_UNICORE"},
{111, "EM_EXCESS"},
{112, "EM_DXP"},
{113, "EM_ALTERA_NIOS2"},
{114, "EM_CRX"},
{115, "EM_XGATE"},
{116, "EM_C166"},
{117, "EM_M16C"},
{118, "EM_DSPIC30F"},
{119, "EM_CE"},
{120, "EM_M32C"},
{131, "EM_TSK3000"},
{132, "EM_RS08"},
{133, "EM_SHARC"},
{134, "EM_ECOG2"},
{135, "EM_SCORE7"},
{136, "EM_DSP24"},
{137, "EM_VIDEOCORE3"},
{138, "EM_LATTICEMICO32"},
{139, "EM_SE_C17"},
{140, "EM_TI_C6000"},
{141, "EM_TI_C2000"},
{142, "EM_TI_C5500"},
{143, "EM_TI_ARP32"},
{144, "EM_TI_PRU"},
{160, "EM_MMDSP_PLUS"},
{161, "EM_CYPRESS_M8C"},
{162, "EM_R32C"},
{163, "EM_TRIMEDIA"},
{164, "EM_QDSP6"},
{165, "EM_8051"},
{166, "EM_STXP7X"},
{167, "EM_NDS32"},
{168, "EM_ECOG1"},
{168, "EM_ECOG1X"},
{169, "EM_MAXQ30"},
{170, "EM_XIMO16"},
{171, "EM_MANIK"},
{172, "EM_CRAYNV2"},
{173, "EM_RX"},
{174, "EM_METAG"},
{175, "EM_MCST_ELBRUS"},
{176, "EM_ECOG16"},
{177, "EM_CR16"},
{178, "EM_ETPU"},
{179, "EM_SLE9X"},
{180, "EM_L10M"},
{181, "EM_K10M"},
{183, "EM_AARCH64"},
{185, "EM_AVR32"},
{186, "EM_STM8"},
{187, "EM_TILE64"},
{188, "EM_TILEPRO"},
{189, "EM_MICROBLAZE"},
{190, "EM_CUDA"},
{191, "EM_TILEGX"},
{192, "EM_CLOUDSHIELD"},
{193, "EM_COREA_1ST"},
{194, "EM_COREA_2ND"},
{195, "EM_ARC_COMPACT2"},
{196, "EM_OPEN8"},
{197, "EM_RL78"},
{198, "EM_VIDEOCORE5"},
{199, "EM_78KOR"},
{200, "EM_56800EX"},
{201, "EM_BA1"},
{202, "EM_BA2"},
{203, "EM_XCORE"},
{204, "EM_MCHP_PIC"},
{205, "EM_INTEL205"},
{206, "EM_INTEL206"},
{207, "EM_INTEL207"},
{208, "EM_INTEL208"},
{209, "EM_INTEL209"},
{210, "EM_KM32"},
{211, "EM_KMX32"},
{212, "EM_KMX16"},
{213, "EM_KMX8"},
{214, "EM_KVARC"},
{215, "EM_CDP"},
{216, "EM_COGE"},
{217, "EM_COOL"},
{218, "EM_NORC"},
{219, "EM_CSR_KALIMBA "},
{220, "EM_Z80 "},
{221, "EM_VISIUM "},
{222, "EM_FT32 "},
{223, "EM_MOXIE"},
{224, "EM_AMDGPU"},
{243, "EM_RISCV"},
{244, "EM_LANAI"},
{247, "EM_BPF"},
{258, "EM_LOONGARCH"},
/* Non-standard or deprecated. */
{6, "EM_486"},
{10, "EM_MIPS_RS4_BE"},
{41, "EM_ALPHA_STD"},
{0x9026, "EM_ALPHA"},
}
func (i Machine) String() string { return stringName(uint32(i), machineStrings, false) }
func (i Machine) GoString() string { return stringName(uint32(i), machineStrings, true) }
// Special section indices.
type SectionIndex int
const (
SHN_UNDEF SectionIndex = 0 /* Undefined, missing, irrelevant. */
SHN_LORESERVE SectionIndex = 0xff00 /* First of reserved range. */
SHN_LOPROC SectionIndex = 0xff00 /* First processor-specific. */
SHN_HIPROC SectionIndex = 0xff1f /* Last processor-specific. */
SHN_LOOS SectionIndex = 0xff20 /* First operating system-specific. */
SHN_HIOS SectionIndex = 0xff3f /* Last operating system-specific. */
SHN_ABS SectionIndex = 0xfff1 /* Absolute values. */
SHN_COMMON SectionIndex = 0xfff2 /* Common data. */
SHN_XINDEX SectionIndex = 0xffff /* Escape; index stored elsewhere. */
SHN_HIRESERVE SectionIndex = 0xffff /* Last of reserved range. */
)
var shnStrings = []intName{
{0, "SHN_UNDEF"},
{0xff00, "SHN_LOPROC"},
{0xff20, "SHN_LOOS"},
{0xfff1, "SHN_ABS"},
{0xfff2, "SHN_COMMON"},
{0xffff, "SHN_XINDEX"},
}
func (i SectionIndex) String() string { return stringName(uint32(i), shnStrings, false) }
func (i SectionIndex) GoString() string { return stringName(uint32(i), shnStrings, true) }
// Section type.
type SectionType uint32
const (
SHT_NULL SectionType = 0 /* inactive */
SHT_PROGBITS SectionType = 1 /* program defined information */
SHT_SYMTAB SectionType = 2 /* symbol table section */
SHT_STRTAB SectionType = 3 /* string table section */
SHT_RELA SectionType = 4 /* relocation section with addends */
SHT_HASH SectionType = 5 /* symbol hash table section */
SHT_DYNAMIC SectionType = 6 /* dynamic section */
SHT_NOTE SectionType = 7 /* note section */
SHT_NOBITS SectionType = 8 /* no space section */
SHT_REL SectionType = 9 /* relocation section - no addends */
SHT_SHLIB SectionType = 10 /* reserved - purpose unknown */
SHT_DYNSYM SectionType = 11 /* dynamic symbol table section */
SHT_INIT_ARRAY SectionType = 14 /* Initialization function pointers. */
SHT_FINI_ARRAY SectionType = 15 /* Termination function pointers. */
SHT_PREINIT_ARRAY SectionType = 16 /* Pre-initialization function ptrs. */
SHT_GROUP SectionType = 17 /* Section group. */
SHT_SYMTAB_SHNDX SectionType = 18 /* Section indexes (see SHN_XINDEX). */
SHT_LOOS SectionType = 0x60000000 /* First of OS specific semantics */
SHT_GNU_ATTRIBUTES SectionType = 0x6ffffff5 /* GNU object attributes */
SHT_GNU_HASH SectionType = 0x6ffffff6 /* GNU hash table */
SHT_GNU_LIBLIST SectionType = 0x6ffffff7 /* GNU prelink library list */
SHT_GNU_VERDEF SectionType = 0x6ffffffd /* GNU version definition section */
SHT_GNU_VERNEED SectionType = 0x6ffffffe /* GNU version needs section */
SHT_GNU_VERSYM SectionType = 0x6fffffff /* GNU version symbol table */
SHT_HIOS SectionType = 0x6fffffff /* Last of OS specific semantics */
SHT_LOPROC SectionType = 0x70000000 /* reserved range for processor */
SHT_MIPS_ABIFLAGS SectionType = 0x7000002a /* .MIPS.abiflags */
SHT_HIPROC SectionType = 0x7fffffff /* specific section header types */
SHT_LOUSER SectionType = 0x80000000 /* reserved range for application */
SHT_HIUSER SectionType = 0xffffffff /* specific indexes */
)
var shtStrings = []intName{
{0, "SHT_NULL"},
{1, "SHT_PROGBITS"},
{2, "SHT_SYMTAB"},
{3, "SHT_STRTAB"},
{4, "SHT_RELA"},
{5, "SHT_HASH"},
{6, "SHT_DYNAMIC"},
{7, "SHT_NOTE"},
{8, "SHT_NOBITS"},
{9, "SHT_REL"},
{10, "SHT_SHLIB"},
{11, "SHT_DYNSYM"},
{14, "SHT_INIT_ARRAY"},
{15, "SHT_FINI_ARRAY"},
{16, "SHT_PREINIT_ARRAY"},
{17, "SHT_GROUP"},
{18, "SHT_SYMTAB_SHNDX"},
{0x60000000, "SHT_LOOS"},
{0x6ffffff5, "SHT_GNU_ATTRIBUTES"},
{0x6ffffff6, "SHT_GNU_HASH"},
{0x6ffffff7, "SHT_GNU_LIBLIST"},
{0x6ffffffd, "SHT_GNU_VERDEF"},
{0x6ffffffe, "SHT_GNU_VERNEED"},
{0x6fffffff, "SHT_GNU_VERSYM"},
{0x70000000, "SHT_LOPROC"},
{0x7000002a, "SHT_MIPS_ABIFLAGS"},
{0x7fffffff, "SHT_HIPROC"},
{0x80000000, "SHT_LOUSER"},
{0xffffffff, "SHT_HIUSER"},
}
func (i SectionType) String() string { return stringName(uint32(i), shtStrings, false) }
func (i SectionType) GoString() string { return stringName(uint32(i), shtStrings, true) }
// Section flags.
type SectionFlag uint32
const (
SHF_WRITE SectionFlag = 0x1 /* Section contains writable data. */
SHF_ALLOC SectionFlag = 0x2 /* Section occupies memory. */
SHF_EXECINSTR SectionFlag = 0x4 /* Section contains instructions. */
SHF_MERGE SectionFlag = 0x10 /* Section may be merged. */
SHF_STRINGS SectionFlag = 0x20 /* Section contains strings. */
SHF_INFO_LINK SectionFlag = 0x40 /* sh_info holds section index. */
SHF_LINK_ORDER SectionFlag = 0x80 /* Special ordering requirements. */
SHF_OS_NONCONFORMING SectionFlag = 0x100 /* OS-specific processing required. */
SHF_GROUP SectionFlag = 0x200 /* Member of section group. */
SHF_TLS SectionFlag = 0x400 /* Section contains TLS data. */
SHF_COMPRESSED SectionFlag = 0x800 /* Section is compressed. */
SHF_MASKOS SectionFlag = 0x0ff00000 /* OS-specific semantics. */
SHF_MASKPROC SectionFlag = 0xf0000000 /* Processor-specific semantics. */
)
var shfStrings = []intName{
{0x1, "SHF_WRITE"},
{0x2, "SHF_ALLOC"},
{0x4, "SHF_EXECINSTR"},
{0x10, "SHF_MERGE"},
{0x20, "SHF_STRINGS"},
{0x40, "SHF_INFO_LINK"},
{0x80, "SHF_LINK_ORDER"},
{0x100, "SHF_OS_NONCONFORMING"},
{0x200, "SHF_GROUP"},
{0x400, "SHF_TLS"},
{0x800, "SHF_COMPRESSED"},
}
func (i SectionFlag) String() string { return flagName(uint32(i), shfStrings, false) }
func (i SectionFlag) GoString() string { return flagName(uint32(i), shfStrings, true) }
// Section compression type.
type CompressionType int
const (
COMPRESS_ZLIB CompressionType = 1 /* ZLIB compression. */
COMPRESS_ZSTD CompressionType = 2 /* ZSTD compression. */
COMPRESS_LOOS CompressionType = 0x60000000 /* First OS-specific. */
COMPRESS_HIOS CompressionType = 0x6fffffff /* Last OS-specific. */
COMPRESS_LOPROC CompressionType = 0x70000000 /* First processor-specific type. */
COMPRESS_HIPROC CompressionType = 0x7fffffff /* Last processor-specific type. */
)
var compressionStrings = []intName{
{1, "COMPRESS_ZLIB"},
{2, "COMPRESS_ZSTD"},
{0x60000000, "COMPRESS_LOOS"},
{0x6fffffff, "COMPRESS_HIOS"},
{0x70000000, "COMPRESS_LOPROC"},
{0x7fffffff, "COMPRESS_HIPROC"},
}
func (i CompressionType) String() string { return stringName(uint32(i), compressionStrings, false) }
func (i CompressionType) GoString() string { return stringName(uint32(i), compressionStrings, true) }
// Prog.Type
type ProgType int
const (
PT_NULL ProgType = 0 /* Unused entry. */
PT_LOAD ProgType = 1 /* Loadable segment. */
PT_DYNAMIC ProgType = 2 /* Dynamic linking information segment. */
PT_INTERP ProgType = 3 /* Pathname of interpreter. */
PT_NOTE ProgType = 4 /* Auxiliary information. */
PT_SHLIB ProgType = 5 /* Reserved (not used). */
PT_PHDR ProgType = 6 /* Location of program header itself. */
PT_TLS ProgType = 7 /* Thread local storage segment */
PT_LOOS ProgType = 0x60000000 /* First OS-specific. */
PT_GNU_EH_FRAME ProgType = 0x6474e550 /* Frame unwind information */
PT_GNU_STACK ProgType = 0x6474e551 /* Stack flags */
PT_GNU_RELRO ProgType = 0x6474e552 /* Read only after relocs */
PT_GNU_PROPERTY ProgType = 0x6474e553 /* GNU property */
PT_GNU_MBIND_LO ProgType = 0x6474e555 /* Mbind segments start */
PT_GNU_MBIND_HI ProgType = 0x6474f554 /* Mbind segments finish */
PT_PAX_FLAGS ProgType = 0x65041580 /* PAX flags */
PT_OPENBSD_RANDOMIZE ProgType = 0x65a3dbe6 /* Random data */
PT_OPENBSD_WXNEEDED ProgType = 0x65a3dbe7 /* W^X violations */
PT_OPENBSD_NOBTCFI ProgType = 0x65a3dbe8 /* No branch target CFI */
PT_OPENBSD_BOOTDATA ProgType = 0x65a41be6 /* Boot arguments */
PT_SUNW_EH_FRAME ProgType = 0x6474e550 /* Frame unwind information */
PT_SUNWSTACK ProgType = 0x6ffffffb /* Stack segment */
PT_HIOS ProgType = 0x6fffffff /* Last OS-specific. */
PT_LOPROC ProgType = 0x70000000 /* First processor-specific type. */
PT_ARM_ARCHEXT ProgType = 0x70000000 /* Architecture compatibility */
PT_ARM_EXIDX ProgType = 0x70000001 /* Exception unwind tables */
PT_AARCH64_ARCHEXT ProgType = 0x70000000 /* Architecture compatibility */
PT_AARCH64_UNWIND ProgType = 0x70000001 /* Exception unwind tables */
PT_MIPS_REGINFO ProgType = 0x70000000 /* Register usage */
PT_MIPS_RTPROC ProgType = 0x70000001 /* Runtime procedures */
PT_MIPS_OPTIONS ProgType = 0x70000002 /* Options */
PT_MIPS_ABIFLAGS ProgType = 0x70000003 /* ABI flags */
PT_S390_PGSTE ProgType = 0x70000000 /* 4k page table size */
PT_HIPROC ProgType = 0x7fffffff /* Last processor-specific type. */
)
var ptStrings = []intName{
{0, "PT_NULL"},
{1, "PT_LOAD"},
{2, "PT_DYNAMIC"},
{3, "PT_INTERP"},
{4, "PT_NOTE"},
{5, "PT_SHLIB"},
{6, "PT_PHDR"},
{7, "PT_TLS"},
{0x60000000, "PT_LOOS"},
{0x6474e550, "PT_GNU_EH_FRAME"},
{0x6474e551, "PT_GNU_STACK"},
{0x6474e552, "PT_GNU_RELRO"},
{0x6474e553, "PT_GNU_PROPERTY"},
{0x65041580, "PT_PAX_FLAGS"},
{0x65a3dbe6, "PT_OPENBSD_RANDOMIZE"},
{0x65a3dbe7, "PT_OPENBSD_WXNEEDED"},
{0x65a41be6, "PT_OPENBSD_BOOTDATA"},
{0x6ffffffb, "PT_SUNWSTACK"},
{0x6fffffff, "PT_HIOS"},
{0x70000000, "PT_LOPROC"},
// We don't list the processor-dependent ProgTypes,
// as the values overlap.
{0x7fffffff, "PT_HIPROC"},
}
func (i ProgType) String() string { return stringName(uint32(i), ptStrings, false) }
func (i ProgType) GoString() string { return stringName(uint32(i), ptStrings, true) }
// Prog.Flag
type ProgFlag uint32
const (
PF_X ProgFlag = 0x1 /* Executable. */
PF_W ProgFlag = 0x2 /* Writable. */
PF_R ProgFlag = 0x4 /* Readable. */
PF_MASKOS ProgFlag = 0x0ff00000 /* Operating system-specific. */
PF_MASKPROC ProgFlag = 0xf0000000 /* Processor-specific. */
)
var pfStrings = []intName{
{0x1, "PF_X"},
{0x2, "PF_W"},
{0x4, "PF_R"},
}
func (i ProgFlag) String() string { return flagName(uint32(i), pfStrings, false) }
func (i ProgFlag) GoString() string { return flagName(uint32(i), pfStrings, true) }
// Dyn.Tag
type DynTag int
const (
DT_NULL DynTag = 0 /* Terminating entry. */
DT_NEEDED DynTag = 1 /* String table offset of a needed shared library. */
DT_PLTRELSZ DynTag = 2 /* Total size in bytes of PLT relocations. */
DT_PLTGOT DynTag = 3 /* Processor-dependent address. */
DT_HASH DynTag = 4 /* Address of symbol hash table. */
DT_STRTAB DynTag = 5 /* Address of string table. */
DT_SYMTAB DynTag = 6 /* Address of symbol table. */
DT_RELA DynTag = 7 /* Address of ElfNN_Rela relocations. */
DT_RELASZ DynTag = 8 /* Total size of ElfNN_Rela relocations. */
DT_RELAENT DynTag = 9 /* Size of each ElfNN_Rela relocation entry. */
DT_STRSZ DynTag = 10 /* Size of string table. */
DT_SYMENT DynTag = 11 /* Size of each symbol table entry. */
DT_INIT DynTag = 12 /* Address of initialization function. */
DT_FINI DynTag = 13 /* Address of finalization function. */
DT_SONAME DynTag = 14 /* String table offset of shared object name. */
DT_RPATH DynTag = 15 /* String table offset of library path. [sup] */
DT_SYMBOLIC DynTag = 16 /* Indicates "symbolic" linking. [sup] */
DT_REL DynTag = 17 /* Address of ElfNN_Rel relocations. */
DT_RELSZ DynTag = 18 /* Total size of ElfNN_Rel relocations. */
DT_RELENT DynTag = 19 /* Size of each ElfNN_Rel relocation. */
DT_PLTREL DynTag = 20 /* Type of relocation used for PLT. */
DT_DEBUG DynTag = 21 /* Reserved (not used). */
DT_TEXTREL DynTag = 22 /* Indicates there may be relocations in non-writable segments. [sup] */
DT_JMPREL DynTag = 23 /* Address of PLT relocations. */
DT_BIND_NOW DynTag = 24 /* [sup] */
DT_INIT_ARRAY DynTag = 25 /* Address of the array of pointers to initialization functions */
DT_FINI_ARRAY DynTag = 26 /* Address of the array of pointers to termination functions */
DT_INIT_ARRAYSZ DynTag = 27 /* Size in bytes of the array of initialization functions. */
DT_FINI_ARRAYSZ DynTag = 28 /* Size in bytes of the array of termination functions. */
DT_RUNPATH DynTag = 29 /* String table offset of a null-terminated library search path string. */
DT_FLAGS DynTag = 30 /* Object specific flag values. */
DT_ENCODING DynTag = 32 /* Values greater than or equal to DT_ENCODING
and less than DT_LOOS follow the rules for
the interpretation of the d_un union
as follows: even == 'd_ptr', even == 'd_val'
or none */
DT_PREINIT_ARRAY DynTag = 32 /* Address of the array of pointers to pre-initialization functions. */
DT_PREINIT_ARRAYSZ DynTag = 33 /* Size in bytes of the array of pre-initialization functions. */
DT_SYMTAB_SHNDX DynTag = 34 /* Address of SHT_SYMTAB_SHNDX section. */
DT_LOOS DynTag = 0x6000000d /* First OS-specific */
DT_HIOS DynTag = 0x6ffff000 /* Last OS-specific */
DT_VALRNGLO DynTag = 0x6ffffd00
DT_GNU_PRELINKED DynTag = 0x6ffffdf5
DT_GNU_CONFLICTSZ DynTag = 0x6ffffdf6
DT_GNU_LIBLISTSZ DynTag = 0x6ffffdf7
DT_CHECKSUM DynTag = 0x6ffffdf8
DT_PLTPADSZ DynTag = 0x6ffffdf9
DT_MOVEENT DynTag = 0x6ffffdfa
DT_MOVESZ DynTag = 0x6ffffdfb
DT_FEATURE DynTag = 0x6ffffdfc
DT_POSFLAG_1 DynTag = 0x6ffffdfd
DT_SYMINSZ DynTag = 0x6ffffdfe
DT_SYMINENT DynTag = 0x6ffffdff
DT_VALRNGHI DynTag = 0x6ffffdff
DT_ADDRRNGLO DynTag = 0x6ffffe00
DT_GNU_HASH DynTag = 0x6ffffef5
DT_TLSDESC_PLT DynTag = 0x6ffffef6
DT_TLSDESC_GOT DynTag = 0x6ffffef7
DT_GNU_CONFLICT DynTag = 0x6ffffef8
DT_GNU_LIBLIST DynTag = 0x6ffffef9
DT_CONFIG DynTag = 0x6ffffefa
DT_DEPAUDIT DynTag = 0x6ffffefb
DT_AUDIT DynTag = 0x6ffffefc
DT_PLTPAD DynTag = 0x6ffffefd
DT_MOVETAB DynTag = 0x6ffffefe
DT_SYMINFO DynTag = 0x6ffffeff
DT_ADDRRNGHI DynTag = 0x6ffffeff
DT_VERSYM DynTag = 0x6ffffff0
DT_RELACOUNT DynTag = 0x6ffffff9
DT_RELCOUNT DynTag = 0x6ffffffa
DT_FLAGS_1 DynTag = 0x6ffffffb
DT_VERDEF DynTag = 0x6ffffffc
DT_VERDEFNUM DynTag = 0x6ffffffd
DT_VERNEED DynTag = 0x6ffffffe
DT_VERNEEDNUM DynTag = 0x6fffffff
DT_LOPROC DynTag = 0x70000000 /* First processor-specific type. */
DT_MIPS_RLD_VERSION DynTag = 0x70000001
DT_MIPS_TIME_STAMP DynTag = 0x70000002
DT_MIPS_ICHECKSUM DynTag = 0x70000003
DT_MIPS_IVERSION DynTag = 0x70000004
DT_MIPS_FLAGS DynTag = 0x70000005
DT_MIPS_BASE_ADDRESS DynTag = 0x70000006
DT_MIPS_MSYM DynTag = 0x70000007
DT_MIPS_CONFLICT DynTag = 0x70000008
DT_MIPS_LIBLIST DynTag = 0x70000009
DT_MIPS_LOCAL_GOTNO DynTag = 0x7000000a
DT_MIPS_CONFLICTNO DynTag = 0x7000000b
DT_MIPS_LIBLISTNO DynTag = 0x70000010
DT_MIPS_SYMTABNO DynTag = 0x70000011
DT_MIPS_UNREFEXTNO DynTag = 0x70000012
DT_MIPS_GOTSYM DynTag = 0x70000013
DT_MIPS_HIPAGENO DynTag = 0x70000014
DT_MIPS_RLD_MAP DynTag = 0x70000016
DT_MIPS_DELTA_CLASS DynTag = 0x70000017
DT_MIPS_DELTA_CLASS_NO DynTag = 0x70000018
DT_MIPS_DELTA_INSTANCE DynTag = 0x70000019
DT_MIPS_DELTA_INSTANCE_NO DynTag = 0x7000001a
DT_MIPS_DELTA_RELOC DynTag = 0x7000001b
DT_MIPS_DELTA_RELOC_NO DynTag = 0x7000001c
DT_MIPS_DELTA_SYM DynTag = 0x7000001d
DT_MIPS_DELTA_SYM_NO DynTag = 0x7000001e
DT_MIPS_DELTA_CLASSSYM DynTag = 0x70000020
DT_MIPS_DELTA_CLASSSYM_NO DynTag = 0x70000021
DT_MIPS_CXX_FLAGS DynTag = 0x70000022
DT_MIPS_PIXIE_INIT DynTag = 0x70000023
DT_MIPS_SYMBOL_LIB DynTag = 0x70000024
DT_MIPS_LOCALPAGE_GOTIDX DynTag = 0x70000025
DT_MIPS_LOCAL_GOTIDX DynTag = 0x70000026
DT_MIPS_HIDDEN_GOTIDX DynTag = 0x70000027
DT_MIPS_PROTECTED_GOTIDX DynTag = 0x70000028
DT_MIPS_OPTIONS DynTag = 0x70000029
DT_MIPS_INTERFACE DynTag = 0x7000002a
DT_MIPS_DYNSTR_ALIGN DynTag = 0x7000002b
DT_MIPS_INTERFACE_SIZE DynTag = 0x7000002c
DT_MIPS_RLD_TEXT_RESOLVE_ADDR DynTag = 0x7000002d
DT_MIPS_PERF_SUFFIX DynTag = 0x7000002e
DT_MIPS_COMPACT_SIZE DynTag = 0x7000002f
DT_MIPS_GP_VALUE DynTag = 0x70000030
DT_MIPS_AUX_DYNAMIC DynTag = 0x70000031
DT_MIPS_PLTGOT DynTag = 0x70000032
DT_MIPS_RWPLT DynTag = 0x70000034
DT_MIPS_RLD_MAP_REL DynTag = 0x70000035
DT_PPC_GOT DynTag = 0x70000000
DT_PPC_OPT DynTag = 0x70000001
DT_PPC64_GLINK DynTag = 0x70000000
DT_PPC64_OPD DynTag = 0x70000001
DT_PPC64_OPDSZ DynTag = 0x70000002
DT_PPC64_OPT DynTag = 0x70000003
DT_SPARC_REGISTER DynTag = 0x70000001
DT_AUXILIARY DynTag = 0x7ffffffd
DT_USED DynTag = 0x7ffffffe
DT_FILTER DynTag = 0x7fffffff
DT_HIPROC DynTag = 0x7fffffff /* Last processor-specific type. */
)
var dtStrings = []intName{
{0, "DT_NULL"},
{1, "DT_NEEDED"},
{2, "DT_PLTRELSZ"},
{3, "DT_PLTGOT"},
{4, "DT_HASH"},
{5, "DT_STRTAB"},
{6, "DT_SYMTAB"},
{7, "DT_RELA"},
{8, "DT_RELASZ"},
{9, "DT_RELAENT"},
{10, "DT_STRSZ"},
{11, "DT_SYMENT"},
{12, "DT_INIT"},
{13, "DT_FINI"},
{14, "DT_SONAME"},
{15, "DT_RPATH"},
{16, "DT_SYMBOLIC"},
{17, "DT_REL"},
{18, "DT_RELSZ"},
{19, "DT_RELENT"},
{20, "DT_PLTREL"},
{21, "DT_DEBUG"},
{22, "DT_TEXTREL"},
{23, "DT_JMPREL"},
{24, "DT_BIND_NOW"},
{25, "DT_INIT_ARRAY"},
{26, "DT_FINI_ARRAY"},
{27, "DT_INIT_ARRAYSZ"},
{28, "DT_FINI_ARRAYSZ"},
{29, "DT_RUNPATH"},
{30, "DT_FLAGS"},
{32, "DT_ENCODING"},
{32, "DT_PREINIT_ARRAY"},
{33, "DT_PREINIT_ARRAYSZ"},
{34, "DT_SYMTAB_SHNDX"},
{0x6000000d, "DT_LOOS"},
{0x6ffff000, "DT_HIOS"},
{0x6ffffd00, "DT_VALRNGLO"},
{0x6ffffdf5, "DT_GNU_PRELINKED"},
{0x6ffffdf6, "DT_GNU_CONFLICTSZ"},
{0x6ffffdf7, "DT_GNU_LIBLISTSZ"},
{0x6ffffdf8, "DT_CHECKSUM"},
{0x6ffffdf9, "DT_PLTPADSZ"},
{0x6ffffdfa, "DT_MOVEENT"},
{0x6ffffdfb, "DT_MOVESZ"},
{0x6ffffdfc, "DT_FEATURE"},
{0x6ffffdfd, "DT_POSFLAG_1"},
{0x6ffffdfe, "DT_SYMINSZ"},
{0x6ffffdff, "DT_SYMINENT"},
{0x6ffffdff, "DT_VALRNGHI"},
{0x6ffffe00, "DT_ADDRRNGLO"},
{0x6ffffef5, "DT_GNU_HASH"},
{0x6ffffef6, "DT_TLSDESC_PLT"},
{0x6ffffef7, "DT_TLSDESC_GOT"},
{0x6ffffef8, "DT_GNU_CONFLICT"},
{0x6ffffef9, "DT_GNU_LIBLIST"},
{0x6ffffefa, "DT_CONFIG"},
{0x6ffffefb, "DT_DEPAUDIT"},
{0x6ffffefc, "DT_AUDIT"},
{0x6ffffefd, "DT_PLTPAD"},
{0x6ffffefe, "DT_MOVETAB"},
{0x6ffffeff, "DT_SYMINFO"},
{0x6ffffeff, "DT_ADDRRNGHI"},
{0x6ffffff0, "DT_VERSYM"},
{0x6ffffff9, "DT_RELACOUNT"},
{0x6ffffffa, "DT_RELCOUNT"},
{0x6ffffffb, "DT_FLAGS_1"},
{0x6ffffffc, "DT_VERDEF"},
{0x6ffffffd, "DT_VERDEFNUM"},
{0x6ffffffe, "DT_VERNEED"},
{0x6fffffff, "DT_VERNEEDNUM"},
{0x70000000, "DT_LOPROC"},
// We don't list the processor-dependent DynTags,
// as the values overlap.
{0x7ffffffd, "DT_AUXILIARY"},
{0x7ffffffe, "DT_USED"},
{0x7fffffff, "DT_FILTER"},
}
func (i DynTag) String() string { return stringName(uint32(i), dtStrings, false) }
func (i DynTag) GoString() string { return stringName(uint32(i), dtStrings, true) }
// DT_FLAGS values.
type DynFlag int
const (
DF_ORIGIN DynFlag = 0x0001 /* Indicates that the object being loaded may
make reference to the
$ORIGIN substitution string */
DF_SYMBOLIC DynFlag = 0x0002 /* Indicates "symbolic" linking. */
DF_TEXTREL DynFlag = 0x0004 /* Indicates there may be relocations in non-writable segments. */
DF_BIND_NOW DynFlag = 0x0008 /* Indicates that the dynamic linker should
process all relocations for the object
containing this entry before transferring
control to the program. */
DF_STATIC_TLS DynFlag = 0x0010 /* Indicates that the shared object or
executable contains code using a static
thread-local storage scheme. */
)
var dflagStrings = []intName{
{0x0001, "DF_ORIGIN"},
{0x0002, "DF_SYMBOLIC"},
{0x0004, "DF_TEXTREL"},
{0x0008, "DF_BIND_NOW"},
{0x0010, "DF_STATIC_TLS"},
}
func (i DynFlag) String() string { return flagName(uint32(i), dflagStrings, false) }
func (i DynFlag) GoString() string { return flagName(uint32(i), dflagStrings, true) }
// DT_FLAGS_1 values.
type DynFlag1 uint32
const (
// Indicates that all relocations for this object must be processed before
// returning control to the program.
DF_1_NOW DynFlag1 = 0x00000001
// Unused.
DF_1_GLOBAL DynFlag1 = 0x00000002
// Indicates that the object is a member of a group.
DF_1_GROUP DynFlag1 = 0x00000004
// Indicates that the object cannot be deleted from a process.
DF_1_NODELETE DynFlag1 = 0x00000008
// Meaningful only for filters. Indicates that all associated filtees be
// processed immediately.
DF_1_LOADFLTR DynFlag1 = 0x00000010
// Indicates that this object's initialization section be run before any other
// objects loaded.
DF_1_INITFIRST DynFlag1 = 0x00000020
// Indicates that the object cannot be added to a running process with dlopen.
DF_1_NOOPEN DynFlag1 = 0x00000040
// Indicates the object requires $ORIGIN processing.
DF_1_ORIGIN DynFlag1 = 0x00000080
// Indicates that the object should use direct binding information.
DF_1_DIRECT DynFlag1 = 0x00000100
// Unused.
DF_1_TRANS DynFlag1 = 0x00000200
// Indicates that the objects symbol table is to interpose before all symbols
// except the primary load object, which is typically the executable.
DF_1_INTERPOSE DynFlag1 = 0x00000400
// Indicates that the search for dependencies of this object ignores any
// default library search paths.
DF_1_NODEFLIB DynFlag1 = 0x00000800
// Indicates that this object is not dumped by dldump. Candidates are objects
// with no relocations that might get included when generating alternative
// objects using.
DF_1_NODUMP DynFlag1 = 0x00001000
// Identifies this object as a configuration alternative object generated by
// crle. Triggers the runtime linker to search for a configuration file $ORIGIN/ld.config.app-name.
DF_1_CONFALT DynFlag1 = 0x00002000
// Meaningful only for filtees. Terminates a filters search for any
// further filtees.
DF_1_ENDFILTEE DynFlag1 = 0x00004000
// Indicates that this object has displacement relocations applied.
DF_1_DISPRELDNE DynFlag1 = 0x00008000
// Indicates that this object has displacement relocations pending.
DF_1_DISPRELPND DynFlag1 = 0x00010000
// Indicates that this object contains symbols that cannot be directly
// bound to.
DF_1_NODIRECT DynFlag1 = 0x00020000
// Reserved for internal use by the kernel runtime-linker.
DF_1_IGNMULDEF DynFlag1 = 0x00040000
// Reserved for internal use by the kernel runtime-linker.
DF_1_NOKSYMS DynFlag1 = 0x00080000
// Reserved for internal use by the kernel runtime-linker.
DF_1_NOHDR DynFlag1 = 0x00100000
// Indicates that this object has been edited or has been modified since the
// objects original construction by the link-editor.
DF_1_EDITED DynFlag1 = 0x00200000
// Reserved for internal use by the kernel runtime-linker.
DF_1_NORELOC DynFlag1 = 0x00400000
// Indicates that the object contains individual symbols that should interpose
// before all symbols except the primary load object, which is typically the
// executable.
DF_1_SYMINTPOSE DynFlag1 = 0x00800000
// Indicates that the executable requires global auditing.
DF_1_GLOBAUDIT DynFlag1 = 0x01000000
// Indicates that the object defines, or makes reference to singleton symbols.
DF_1_SINGLETON DynFlag1 = 0x02000000
// Indicates that the object is a stub.
DF_1_STUB DynFlag1 = 0x04000000
// Indicates that the object is a position-independent executable.
DF_1_PIE DynFlag1 = 0x08000000
// Indicates that the object is a kernel module.
DF_1_KMOD DynFlag1 = 0x10000000
// Indicates that the object is a weak standard filter.
DF_1_WEAKFILTER DynFlag1 = 0x20000000
// Unused.
DF_1_NOCOMMON DynFlag1 = 0x40000000
)
var dflag1Strings = []intName{
{0x00000001, "DF_1_NOW"},
{0x00000002, "DF_1_GLOBAL"},
{0x00000004, "DF_1_GROUP"},
{0x00000008, "DF_1_NODELETE"},
{0x00000010, "DF_1_LOADFLTR"},
{0x00000020, "DF_1_INITFIRST"},
{0x00000040, "DF_1_NOOPEN"},
{0x00000080, "DF_1_ORIGIN"},
{0x00000100, "DF_1_DIRECT"},
{0x00000200, "DF_1_TRANS"},
{0x00000400, "DF_1_INTERPOSE"},
{0x00000800, "DF_1_NODEFLIB"},
{0x00001000, "DF_1_NODUMP"},
{0x00002000, "DF_1_CONFALT"},
{0x00004000, "DF_1_ENDFILTEE"},
{0x00008000, "DF_1_DISPRELDNE"},
{0x00010000, "DF_1_DISPRELPND"},
{0x00020000, "DF_1_NODIRECT"},
{0x00040000, "DF_1_IGNMULDEF"},
{0x00080000, "DF_1_NOKSYMS"},
{0x00100000, "DF_1_NOHDR"},
{0x00200000, "DF_1_EDITED"},
{0x00400000, "DF_1_NORELOC"},
{0x00800000, "DF_1_SYMINTPOSE"},
{0x01000000, "DF_1_GLOBAUDIT"},
{0x02000000, "DF_1_SINGLETON"},
{0x04000000, "DF_1_STUB"},
{0x08000000, "DF_1_PIE"},
{0x10000000, "DF_1_KMOD"},
{0x20000000, "DF_1_WEAKFILTER"},
{0x40000000, "DF_1_NOCOMMON"},
}
func (i DynFlag1) String() string { return flagName(uint32(i), dflag1Strings, false) }
func (i DynFlag1) GoString() string { return flagName(uint32(i), dflag1Strings, true) }
// NType values; used in core files.
type NType int
const (
NT_PRSTATUS NType = 1 /* Process status. */
NT_FPREGSET NType = 2 /* Floating point registers. */
NT_PRPSINFO NType = 3 /* Process state info. */
)
var ntypeStrings = []intName{
{1, "NT_PRSTATUS"},
{2, "NT_FPREGSET"},
{3, "NT_PRPSINFO"},
}
func (i NType) String() string { return stringName(uint32(i), ntypeStrings, false) }
func (i NType) GoString() string { return stringName(uint32(i), ntypeStrings, true) }
/* Symbol Binding - ELFNN_ST_BIND - st_info */
type SymBind int
const (
STB_LOCAL SymBind = 0 /* Local symbol */
STB_GLOBAL SymBind = 1 /* Global symbol */
STB_WEAK SymBind = 2 /* like global - lower precedence */
STB_LOOS SymBind = 10 /* Reserved range for operating system */
STB_HIOS SymBind = 12 /* specific semantics. */
STB_LOPROC SymBind = 13 /* reserved range for processor */
STB_HIPROC SymBind = 15 /* specific semantics. */
)
var stbStrings = []intName{
{0, "STB_LOCAL"},
{1, "STB_GLOBAL"},
{2, "STB_WEAK"},
{10, "STB_LOOS"},
{12, "STB_HIOS"},
{13, "STB_LOPROC"},
{15, "STB_HIPROC"},
}
func (i SymBind) String() string { return stringName(uint32(i), stbStrings, false) }
func (i SymBind) GoString() string { return stringName(uint32(i), stbStrings, true) }
/* Symbol type - ELFNN_ST_TYPE - st_info */
type SymType int
const (
STT_NOTYPE SymType = 0 /* Unspecified type. */
STT_OBJECT SymType = 1 /* Data object. */
STT_FUNC SymType = 2 /* Function. */
STT_SECTION SymType = 3 /* Section. */
STT_FILE SymType = 4 /* Source file. */
STT_COMMON SymType = 5 /* Uninitialized common block. */
STT_TLS SymType = 6 /* TLS object. */
STT_LOOS SymType = 10 /* Reserved range for operating system */
STT_HIOS SymType = 12 /* specific semantics. */
STT_LOPROC SymType = 13 /* reserved range for processor */
STT_HIPROC SymType = 15 /* specific semantics. */
/* Non-standard symbol types. */
STT_RELC SymType = 8 /* Complex relocation expression. */
STT_SRELC SymType = 9 /* Signed complex relocation expression. */
STT_GNU_IFUNC SymType = 10 /* Indirect code object. */
)
var sttStrings = []intName{
{0, "STT_NOTYPE"},
{1, "STT_OBJECT"},
{2, "STT_FUNC"},
{3, "STT_SECTION"},
{4, "STT_FILE"},
{5, "STT_COMMON"},
{6, "STT_TLS"},
{8, "STT_RELC"},
{9, "STT_SRELC"},
{10, "STT_LOOS"},
{12, "STT_HIOS"},
{13, "STT_LOPROC"},
{15, "STT_HIPROC"},
}
func (i SymType) String() string { return stringName(uint32(i), sttStrings, false) }
func (i SymType) GoString() string { return stringName(uint32(i), sttStrings, true) }
/* Symbol visibility - ELFNN_ST_VISIBILITY - st_other */
type SymVis int
const (
STV_DEFAULT SymVis = 0x0 /* Default visibility (see binding). */
STV_INTERNAL SymVis = 0x1 /* Special meaning in relocatable objects. */
STV_HIDDEN SymVis = 0x2 /* Not visible. */
STV_PROTECTED SymVis = 0x3 /* Visible but not preemptible. */
)
var stvStrings = []intName{
{0x0, "STV_DEFAULT"},
{0x1, "STV_INTERNAL"},
{0x2, "STV_HIDDEN"},
{0x3, "STV_PROTECTED"},
}
func (i SymVis) String() string { return stringName(uint32(i), stvStrings, false) }
func (i SymVis) GoString() string { return stringName(uint32(i), stvStrings, true) }
/*
* Relocation types.
*/
// Relocation types for x86-64.
type R_X86_64 int
const (
R_X86_64_NONE R_X86_64 = 0 /* No relocation. */
R_X86_64_64 R_X86_64 = 1 /* Add 64 bit symbol value. */
R_X86_64_PC32 R_X86_64 = 2 /* PC-relative 32 bit signed sym value. */
R_X86_64_GOT32 R_X86_64 = 3 /* PC-relative 32 bit GOT offset. */
R_X86_64_PLT32 R_X86_64 = 4 /* PC-relative 32 bit PLT offset. */
R_X86_64_COPY R_X86_64 = 5 /* Copy data from shared object. */
R_X86_64_GLOB_DAT R_X86_64 = 6 /* Set GOT entry to data address. */
R_X86_64_JMP_SLOT R_X86_64 = 7 /* Set GOT entry to code address. */
R_X86_64_RELATIVE R_X86_64 = 8 /* Add load address of shared object. */
R_X86_64_GOTPCREL R_X86_64 = 9 /* Add 32 bit signed pcrel offset to GOT. */
R_X86_64_32 R_X86_64 = 10 /* Add 32 bit zero extended symbol value */
R_X86_64_32S R_X86_64 = 11 /* Add 32 bit sign extended symbol value */
R_X86_64_16 R_X86_64 = 12 /* Add 16 bit zero extended symbol value */
R_X86_64_PC16 R_X86_64 = 13 /* Add 16 bit signed extended pc relative symbol value */
R_X86_64_8 R_X86_64 = 14 /* Add 8 bit zero extended symbol value */
R_X86_64_PC8 R_X86_64 = 15 /* Add 8 bit signed extended pc relative symbol value */
R_X86_64_DTPMOD64 R_X86_64 = 16 /* ID of module containing symbol */
R_X86_64_DTPOFF64 R_X86_64 = 17 /* Offset in TLS block */
R_X86_64_TPOFF64 R_X86_64 = 18 /* Offset in static TLS block */
R_X86_64_TLSGD R_X86_64 = 19 /* PC relative offset to GD GOT entry */
R_X86_64_TLSLD R_X86_64 = 20 /* PC relative offset to LD GOT entry */
R_X86_64_DTPOFF32 R_X86_64 = 21 /* Offset in TLS block */
R_X86_64_GOTTPOFF R_X86_64 = 22 /* PC relative offset to IE GOT entry */
R_X86_64_TPOFF32 R_X86_64 = 23 /* Offset in static TLS block */
R_X86_64_PC64 R_X86_64 = 24 /* PC relative 64-bit sign extended symbol value. */
R_X86_64_GOTOFF64 R_X86_64 = 25
R_X86_64_GOTPC32 R_X86_64 = 26
R_X86_64_GOT64 R_X86_64 = 27
R_X86_64_GOTPCREL64 R_X86_64 = 28
R_X86_64_GOTPC64 R_X86_64 = 29
R_X86_64_GOTPLT64 R_X86_64 = 30
R_X86_64_PLTOFF64 R_X86_64 = 31
R_X86_64_SIZE32 R_X86_64 = 32
R_X86_64_SIZE64 R_X86_64 = 33
R_X86_64_GOTPC32_TLSDESC R_X86_64 = 34
R_X86_64_TLSDESC_CALL R_X86_64 = 35
R_X86_64_TLSDESC R_X86_64 = 36
R_X86_64_IRELATIVE R_X86_64 = 37
R_X86_64_RELATIVE64 R_X86_64 = 38
R_X86_64_PC32_BND R_X86_64 = 39
R_X86_64_PLT32_BND R_X86_64 = 40
R_X86_64_GOTPCRELX R_X86_64 = 41
R_X86_64_REX_GOTPCRELX R_X86_64 = 42
)
var rx86_64Strings = []intName{
{0, "R_X86_64_NONE"},
{1, "R_X86_64_64"},
{2, "R_X86_64_PC32"},
{3, "R_X86_64_GOT32"},
{4, "R_X86_64_PLT32"},
{5, "R_X86_64_COPY"},
{6, "R_X86_64_GLOB_DAT"},
{7, "R_X86_64_JMP_SLOT"},
{8, "R_X86_64_RELATIVE"},
{9, "R_X86_64_GOTPCREL"},
{10, "R_X86_64_32"},
{11, "R_X86_64_32S"},
{12, "R_X86_64_16"},
{13, "R_X86_64_PC16"},
{14, "R_X86_64_8"},
{15, "R_X86_64_PC8"},
{16, "R_X86_64_DTPMOD64"},
{17, "R_X86_64_DTPOFF64"},
{18, "R_X86_64_TPOFF64"},
{19, "R_X86_64_TLSGD"},
{20, "R_X86_64_TLSLD"},
{21, "R_X86_64_DTPOFF32"},
{22, "R_X86_64_GOTTPOFF"},
{23, "R_X86_64_TPOFF32"},
{24, "R_X86_64_PC64"},
{25, "R_X86_64_GOTOFF64"},
{26, "R_X86_64_GOTPC32"},
{27, "R_X86_64_GOT64"},
{28, "R_X86_64_GOTPCREL64"},
{29, "R_X86_64_GOTPC64"},
{30, "R_X86_64_GOTPLT64"},
{31, "R_X86_64_PLTOFF64"},
{32, "R_X86_64_SIZE32"},
{33, "R_X86_64_SIZE64"},
{34, "R_X86_64_GOTPC32_TLSDESC"},
{35, "R_X86_64_TLSDESC_CALL"},
{36, "R_X86_64_TLSDESC"},
{37, "R_X86_64_IRELATIVE"},
{38, "R_X86_64_RELATIVE64"},
{39, "R_X86_64_PC32_BND"},
{40, "R_X86_64_PLT32_BND"},
{41, "R_X86_64_GOTPCRELX"},
{42, "R_X86_64_REX_GOTPCRELX"},
}
func (i R_X86_64) String() string { return stringName(uint32(i), rx86_64Strings, false) }
func (i R_X86_64) GoString() string { return stringName(uint32(i), rx86_64Strings, true) }
// Relocation types for AArch64 (aka arm64)
type R_AARCH64 int
const (
R_AARCH64_NONE R_AARCH64 = 0
R_AARCH64_P32_ABS32 R_AARCH64 = 1
R_AARCH64_P32_ABS16 R_AARCH64 = 2
R_AARCH64_P32_PREL32 R_AARCH64 = 3
R_AARCH64_P32_PREL16 R_AARCH64 = 4
R_AARCH64_P32_MOVW_UABS_G0 R_AARCH64 = 5
R_AARCH64_P32_MOVW_UABS_G0_NC R_AARCH64 = 6
R_AARCH64_P32_MOVW_UABS_G1 R_AARCH64 = 7
R_AARCH64_P32_MOVW_SABS_G0 R_AARCH64 = 8
R_AARCH64_P32_LD_PREL_LO19 R_AARCH64 = 9
R_AARCH64_P32_ADR_PREL_LO21 R_AARCH64 = 10
R_AARCH64_P32_ADR_PREL_PG_HI21 R_AARCH64 = 11
R_AARCH64_P32_ADD_ABS_LO12_NC R_AARCH64 = 12
R_AARCH64_P32_LDST8_ABS_LO12_NC R_AARCH64 = 13
R_AARCH64_P32_LDST16_ABS_LO12_NC R_AARCH64 = 14
R_AARCH64_P32_LDST32_ABS_LO12_NC R_AARCH64 = 15
R_AARCH64_P32_LDST64_ABS_LO12_NC R_AARCH64 = 16
R_AARCH64_P32_LDST128_ABS_LO12_NC R_AARCH64 = 17
R_AARCH64_P32_TSTBR14 R_AARCH64 = 18
R_AARCH64_P32_CONDBR19 R_AARCH64 = 19
R_AARCH64_P32_JUMP26 R_AARCH64 = 20
R_AARCH64_P32_CALL26 R_AARCH64 = 21
R_AARCH64_P32_GOT_LD_PREL19 R_AARCH64 = 25
R_AARCH64_P32_ADR_GOT_PAGE R_AARCH64 = 26
R_AARCH64_P32_LD32_GOT_LO12_NC R_AARCH64 = 27
R_AARCH64_P32_TLSGD_ADR_PAGE21 R_AARCH64 = 81
R_AARCH64_P32_TLSGD_ADD_LO12_NC R_AARCH64 = 82
R_AARCH64_P32_TLSIE_ADR_GOTTPREL_PAGE21 R_AARCH64 = 103
R_AARCH64_P32_TLSIE_LD32_GOTTPREL_LO12_NC R_AARCH64 = 104
R_AARCH64_P32_TLSIE_LD_GOTTPREL_PREL19 R_AARCH64 = 105
R_AARCH64_P32_TLSLE_MOVW_TPREL_G1 R_AARCH64 = 106
R_AARCH64_P32_TLSLE_MOVW_TPREL_G0 R_AARCH64 = 107
R_AARCH64_P32_TLSLE_MOVW_TPREL_G0_NC R_AARCH64 = 108
R_AARCH64_P32_TLSLE_ADD_TPREL_HI12 R_AARCH64 = 109
R_AARCH64_P32_TLSLE_ADD_TPREL_LO12 R_AARCH64 = 110
R_AARCH64_P32_TLSLE_ADD_TPREL_LO12_NC R_AARCH64 = 111
R_AARCH64_P32_TLSDESC_LD_PREL19 R_AARCH64 = 122
R_AARCH64_P32_TLSDESC_ADR_PREL21 R_AARCH64 = 123
R_AARCH64_P32_TLSDESC_ADR_PAGE21 R_AARCH64 = 124
R_AARCH64_P32_TLSDESC_LD32_LO12_NC R_AARCH64 = 125
R_AARCH64_P32_TLSDESC_ADD_LO12_NC R_AARCH64 = 126
R_AARCH64_P32_TLSDESC_CALL R_AARCH64 = 127
R_AARCH64_P32_COPY R_AARCH64 = 180
R_AARCH64_P32_GLOB_DAT R_AARCH64 = 181
R_AARCH64_P32_JUMP_SLOT R_AARCH64 = 182
R_AARCH64_P32_RELATIVE R_AARCH64 = 183
R_AARCH64_P32_TLS_DTPMOD R_AARCH64 = 184
R_AARCH64_P32_TLS_DTPREL R_AARCH64 = 185
R_AARCH64_P32_TLS_TPREL R_AARCH64 = 186
R_AARCH64_P32_TLSDESC R_AARCH64 = 187
R_AARCH64_P32_IRELATIVE R_AARCH64 = 188
R_AARCH64_NULL R_AARCH64 = 256
R_AARCH64_ABS64 R_AARCH64 = 257
R_AARCH64_ABS32 R_AARCH64 = 258
R_AARCH64_ABS16 R_AARCH64 = 259
R_AARCH64_PREL64 R_AARCH64 = 260
R_AARCH64_PREL32 R_AARCH64 = 261
R_AARCH64_PREL16 R_AARCH64 = 262
R_AARCH64_MOVW_UABS_G0 R_AARCH64 = 263
R_AARCH64_MOVW_UABS_G0_NC R_AARCH64 = 264
R_AARCH64_MOVW_UABS_G1 R_AARCH64 = 265
R_AARCH64_MOVW_UABS_G1_NC R_AARCH64 = 266
R_AARCH64_MOVW_UABS_G2 R_AARCH64 = 267
R_AARCH64_MOVW_UABS_G2_NC R_AARCH64 = 268
R_AARCH64_MOVW_UABS_G3 R_AARCH64 = 269
R_AARCH64_MOVW_SABS_G0 R_AARCH64 = 270
R_AARCH64_MOVW_SABS_G1 R_AARCH64 = 271
R_AARCH64_MOVW_SABS_G2 R_AARCH64 = 272
R_AARCH64_LD_PREL_LO19 R_AARCH64 = 273
R_AARCH64_ADR_PREL_LO21 R_AARCH64 = 274
R_AARCH64_ADR_PREL_PG_HI21 R_AARCH64 = 275
R_AARCH64_ADR_PREL_PG_HI21_NC R_AARCH64 = 276
R_AARCH64_ADD_ABS_LO12_NC R_AARCH64 = 277
R_AARCH64_LDST8_ABS_LO12_NC R_AARCH64 = 278
R_AARCH64_TSTBR14 R_AARCH64 = 279
R_AARCH64_CONDBR19 R_AARCH64 = 280
R_AARCH64_JUMP26 R_AARCH64 = 282
R_AARCH64_CALL26 R_AARCH64 = 283
R_AARCH64_LDST16_ABS_LO12_NC R_AARCH64 = 284
R_AARCH64_LDST32_ABS_LO12_NC R_AARCH64 = 285
R_AARCH64_LDST64_ABS_LO12_NC R_AARCH64 = 286
R_AARCH64_LDST128_ABS_LO12_NC R_AARCH64 = 299
R_AARCH64_GOT_LD_PREL19 R_AARCH64 = 309
R_AARCH64_LD64_GOTOFF_LO15 R_AARCH64 = 310
R_AARCH64_ADR_GOT_PAGE R_AARCH64 = 311
R_AARCH64_LD64_GOT_LO12_NC R_AARCH64 = 312
R_AARCH64_LD64_GOTPAGE_LO15 R_AARCH64 = 313
R_AARCH64_TLSGD_ADR_PREL21 R_AARCH64 = 512
R_AARCH64_TLSGD_ADR_PAGE21 R_AARCH64 = 513
R_AARCH64_TLSGD_ADD_LO12_NC R_AARCH64 = 514
R_AARCH64_TLSGD_MOVW_G1 R_AARCH64 = 515
R_AARCH64_TLSGD_MOVW_G0_NC R_AARCH64 = 516
R_AARCH64_TLSLD_ADR_PREL21 R_AARCH64 = 517
R_AARCH64_TLSLD_ADR_PAGE21 R_AARCH64 = 518
R_AARCH64_TLSIE_MOVW_GOTTPREL_G1 R_AARCH64 = 539
R_AARCH64_TLSIE_MOVW_GOTTPREL_G0_NC R_AARCH64 = 540
R_AARCH64_TLSIE_ADR_GOTTPREL_PAGE21 R_AARCH64 = 541
R_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC R_AARCH64 = 542
R_AARCH64_TLSIE_LD_GOTTPREL_PREL19 R_AARCH64 = 543
R_AARCH64_TLSLE_MOVW_TPREL_G2 R_AARCH64 = 544
R_AARCH64_TLSLE_MOVW_TPREL_G1 R_AARCH64 = 545
R_AARCH64_TLSLE_MOVW_TPREL_G1_NC R_AARCH64 = 546
R_AARCH64_TLSLE_MOVW_TPREL_G0 R_AARCH64 = 547
R_AARCH64_TLSLE_MOVW_TPREL_G0_NC R_AARCH64 = 548
R_AARCH64_TLSLE_ADD_TPREL_HI12 R_AARCH64 = 549
R_AARCH64_TLSLE_ADD_TPREL_LO12 R_AARCH64 = 550
R_AARCH64_TLSLE_ADD_TPREL_LO12_NC R_AARCH64 = 551
R_AARCH64_TLSDESC_LD_PREL19 R_AARCH64 = 560
R_AARCH64_TLSDESC_ADR_PREL21 R_AARCH64 = 561
R_AARCH64_TLSDESC_ADR_PAGE21 R_AARCH64 = 562
R_AARCH64_TLSDESC_LD64_LO12_NC R_AARCH64 = 563
R_AARCH64_TLSDESC_ADD_LO12_NC R_AARCH64 = 564
R_AARCH64_TLSDESC_OFF_G1 R_AARCH64 = 565
R_AARCH64_TLSDESC_OFF_G0_NC R_AARCH64 = 566
R_AARCH64_TLSDESC_LDR R_AARCH64 = 567
R_AARCH64_TLSDESC_ADD R_AARCH64 = 568
R_AARCH64_TLSDESC_CALL R_AARCH64 = 569
R_AARCH64_TLSLE_LDST128_TPREL_LO12 R_AARCH64 = 570
R_AARCH64_TLSLE_LDST128_TPREL_LO12_NC R_AARCH64 = 571
R_AARCH64_TLSLD_LDST128_DTPREL_LO12 R_AARCH64 = 572
R_AARCH64_TLSLD_LDST128_DTPREL_LO12_NC R_AARCH64 = 573
R_AARCH64_COPY R_AARCH64 = 1024
R_AARCH64_GLOB_DAT R_AARCH64 = 1025
R_AARCH64_JUMP_SLOT R_AARCH64 = 1026
R_AARCH64_RELATIVE R_AARCH64 = 1027
R_AARCH64_TLS_DTPMOD64 R_AARCH64 = 1028
R_AARCH64_TLS_DTPREL64 R_AARCH64 = 1029
R_AARCH64_TLS_TPREL64 R_AARCH64 = 1030
R_AARCH64_TLSDESC R_AARCH64 = 1031
R_AARCH64_IRELATIVE R_AARCH64 = 1032
)
var raarch64Strings = []intName{
{0, "R_AARCH64_NONE"},
{1, "R_AARCH64_P32_ABS32"},
{2, "R_AARCH64_P32_ABS16"},
{3, "R_AARCH64_P32_PREL32"},
{4, "R_AARCH64_P32_PREL16"},
{5, "R_AARCH64_P32_MOVW_UABS_G0"},
{6, "R_AARCH64_P32_MOVW_UABS_G0_NC"},
{7, "R_AARCH64_P32_MOVW_UABS_G1"},
{8, "R_AARCH64_P32_MOVW_SABS_G0"},
{9, "R_AARCH64_P32_LD_PREL_LO19"},
{10, "R_AARCH64_P32_ADR_PREL_LO21"},
{11, "R_AARCH64_P32_ADR_PREL_PG_HI21"},
{12, "R_AARCH64_P32_ADD_ABS_LO12_NC"},
{13, "R_AARCH64_P32_LDST8_ABS_LO12_NC"},
{14, "R_AARCH64_P32_LDST16_ABS_LO12_NC"},
{15, "R_AARCH64_P32_LDST32_ABS_LO12_NC"},
{16, "R_AARCH64_P32_LDST64_ABS_LO12_NC"},
{17, "R_AARCH64_P32_LDST128_ABS_LO12_NC"},
{18, "R_AARCH64_P32_TSTBR14"},
{19, "R_AARCH64_P32_CONDBR19"},
{20, "R_AARCH64_P32_JUMP26"},
{21, "R_AARCH64_P32_CALL26"},
{25, "R_AARCH64_P32_GOT_LD_PREL19"},
{26, "R_AARCH64_P32_ADR_GOT_PAGE"},
{27, "R_AARCH64_P32_LD32_GOT_LO12_NC"},
{81, "R_AARCH64_P32_TLSGD_ADR_PAGE21"},
{82, "R_AARCH64_P32_TLSGD_ADD_LO12_NC"},
{103, "R_AARCH64_P32_TLSIE_ADR_GOTTPREL_PAGE21"},
{104, "R_AARCH64_P32_TLSIE_LD32_GOTTPREL_LO12_NC"},
{105, "R_AARCH64_P32_TLSIE_LD_GOTTPREL_PREL19"},
{106, "R_AARCH64_P32_TLSLE_MOVW_TPREL_G1"},
{107, "R_AARCH64_P32_TLSLE_MOVW_TPREL_G0"},
{108, "R_AARCH64_P32_TLSLE_MOVW_TPREL_G0_NC"},
{109, "R_AARCH64_P32_TLSLE_ADD_TPREL_HI12"},
{110, "R_AARCH64_P32_TLSLE_ADD_TPREL_LO12"},
{111, "R_AARCH64_P32_TLSLE_ADD_TPREL_LO12_NC"},
{122, "R_AARCH64_P32_TLSDESC_LD_PREL19"},
{123, "R_AARCH64_P32_TLSDESC_ADR_PREL21"},
{124, "R_AARCH64_P32_TLSDESC_ADR_PAGE21"},
{125, "R_AARCH64_P32_TLSDESC_LD32_LO12_NC"},
{126, "R_AARCH64_P32_TLSDESC_ADD_LO12_NC"},
{127, "R_AARCH64_P32_TLSDESC_CALL"},
{180, "R_AARCH64_P32_COPY"},
{181, "R_AARCH64_P32_GLOB_DAT"},
{182, "R_AARCH64_P32_JUMP_SLOT"},
{183, "R_AARCH64_P32_RELATIVE"},
{184, "R_AARCH64_P32_TLS_DTPMOD"},
{185, "R_AARCH64_P32_TLS_DTPREL"},
{186, "R_AARCH64_P32_TLS_TPREL"},
{187, "R_AARCH64_P32_TLSDESC"},
{188, "R_AARCH64_P32_IRELATIVE"},
{256, "R_AARCH64_NULL"},
{257, "R_AARCH64_ABS64"},
{258, "R_AARCH64_ABS32"},
{259, "R_AARCH64_ABS16"},
{260, "R_AARCH64_PREL64"},
{261, "R_AARCH64_PREL32"},
{262, "R_AARCH64_PREL16"},
{263, "R_AARCH64_MOVW_UABS_G0"},
{264, "R_AARCH64_MOVW_UABS_G0_NC"},
{265, "R_AARCH64_MOVW_UABS_G1"},
{266, "R_AARCH64_MOVW_UABS_G1_NC"},
{267, "R_AARCH64_MOVW_UABS_G2"},
{268, "R_AARCH64_MOVW_UABS_G2_NC"},
{269, "R_AARCH64_MOVW_UABS_G3"},
{270, "R_AARCH64_MOVW_SABS_G0"},
{271, "R_AARCH64_MOVW_SABS_G1"},
{272, "R_AARCH64_MOVW_SABS_G2"},
{273, "R_AARCH64_LD_PREL_LO19"},
{274, "R_AARCH64_ADR_PREL_LO21"},
{275, "R_AARCH64_ADR_PREL_PG_HI21"},
{276, "R_AARCH64_ADR_PREL_PG_HI21_NC"},
{277, "R_AARCH64_ADD_ABS_LO12_NC"},
{278, "R_AARCH64_LDST8_ABS_LO12_NC"},
{279, "R_AARCH64_TSTBR14"},
{280, "R_AARCH64_CONDBR19"},
{282, "R_AARCH64_JUMP26"},
{283, "R_AARCH64_CALL26"},
{284, "R_AARCH64_LDST16_ABS_LO12_NC"},
{285, "R_AARCH64_LDST32_ABS_LO12_NC"},
{286, "R_AARCH64_LDST64_ABS_LO12_NC"},
{299, "R_AARCH64_LDST128_ABS_LO12_NC"},
{309, "R_AARCH64_GOT_LD_PREL19"},
{310, "R_AARCH64_LD64_GOTOFF_LO15"},
{311, "R_AARCH64_ADR_GOT_PAGE"},
{312, "R_AARCH64_LD64_GOT_LO12_NC"},
{313, "R_AARCH64_LD64_GOTPAGE_LO15"},
{512, "R_AARCH64_TLSGD_ADR_PREL21"},
{513, "R_AARCH64_TLSGD_ADR_PAGE21"},
{514, "R_AARCH64_TLSGD_ADD_LO12_NC"},
{515, "R_AARCH64_TLSGD_MOVW_G1"},
{516, "R_AARCH64_TLSGD_MOVW_G0_NC"},
{517, "R_AARCH64_TLSLD_ADR_PREL21"},
{518, "R_AARCH64_TLSLD_ADR_PAGE21"},
{539, "R_AARCH64_TLSIE_MOVW_GOTTPREL_G1"},
{540, "R_AARCH64_TLSIE_MOVW_GOTTPREL_G0_NC"},
{541, "R_AARCH64_TLSIE_ADR_GOTTPREL_PAGE21"},
{542, "R_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC"},
{543, "R_AARCH64_TLSIE_LD_GOTTPREL_PREL19"},
{544, "R_AARCH64_TLSLE_MOVW_TPREL_G2"},
{545, "R_AARCH64_TLSLE_MOVW_TPREL_G1"},
{546, "R_AARCH64_TLSLE_MOVW_TPREL_G1_NC"},
{547, "R_AARCH64_TLSLE_MOVW_TPREL_G0"},
{548, "R_AARCH64_TLSLE_MOVW_TPREL_G0_NC"},
{549, "R_AARCH64_TLSLE_ADD_TPREL_HI12"},
{550, "R_AARCH64_TLSLE_ADD_TPREL_LO12"},
{551, "R_AARCH64_TLSLE_ADD_TPREL_LO12_NC"},
{560, "R_AARCH64_TLSDESC_LD_PREL19"},
{561, "R_AARCH64_TLSDESC_ADR_PREL21"},
{562, "R_AARCH64_TLSDESC_ADR_PAGE21"},
{563, "R_AARCH64_TLSDESC_LD64_LO12_NC"},
{564, "R_AARCH64_TLSDESC_ADD_LO12_NC"},
{565, "R_AARCH64_TLSDESC_OFF_G1"},
{566, "R_AARCH64_TLSDESC_OFF_G0_NC"},
{567, "R_AARCH64_TLSDESC_LDR"},
{568, "R_AARCH64_TLSDESC_ADD"},
{569, "R_AARCH64_TLSDESC_CALL"},
{570, "R_AARCH64_TLSLE_LDST128_TPREL_LO12"},
{571, "R_AARCH64_TLSLE_LDST128_TPREL_LO12_NC"},
{572, "R_AARCH64_TLSLD_LDST128_DTPREL_LO12"},
{573, "R_AARCH64_TLSLD_LDST128_DTPREL_LO12_NC"},
{1024, "R_AARCH64_COPY"},
{1025, "R_AARCH64_GLOB_DAT"},
{1026, "R_AARCH64_JUMP_SLOT"},
{1027, "R_AARCH64_RELATIVE"},
{1028, "R_AARCH64_TLS_DTPMOD64"},
{1029, "R_AARCH64_TLS_DTPREL64"},
{1030, "R_AARCH64_TLS_TPREL64"},
{1031, "R_AARCH64_TLSDESC"},
{1032, "R_AARCH64_IRELATIVE"},
}
func (i R_AARCH64) String() string { return stringName(uint32(i), raarch64Strings, false) }
func (i R_AARCH64) GoString() string { return stringName(uint32(i), raarch64Strings, true) }
// Relocation types for Alpha.
type R_ALPHA int
const (
R_ALPHA_NONE R_ALPHA = 0 /* No reloc */
R_ALPHA_REFLONG R_ALPHA = 1 /* Direct 32 bit */
R_ALPHA_REFQUAD R_ALPHA = 2 /* Direct 64 bit */
R_ALPHA_GPREL32 R_ALPHA = 3 /* GP relative 32 bit */
R_ALPHA_LITERAL R_ALPHA = 4 /* GP relative 16 bit w/optimization */
R_ALPHA_LITUSE R_ALPHA = 5 /* Optimization hint for LITERAL */
R_ALPHA_GPDISP R_ALPHA = 6 /* Add displacement to GP */
R_ALPHA_BRADDR R_ALPHA = 7 /* PC+4 relative 23 bit shifted */
R_ALPHA_HINT R_ALPHA = 8 /* PC+4 relative 16 bit shifted */
R_ALPHA_SREL16 R_ALPHA = 9 /* PC relative 16 bit */
R_ALPHA_SREL32 R_ALPHA = 10 /* PC relative 32 bit */
R_ALPHA_SREL64 R_ALPHA = 11 /* PC relative 64 bit */
R_ALPHA_OP_PUSH R_ALPHA = 12 /* OP stack push */
R_ALPHA_OP_STORE R_ALPHA = 13 /* OP stack pop and store */
R_ALPHA_OP_PSUB R_ALPHA = 14 /* OP stack subtract */
R_ALPHA_OP_PRSHIFT R_ALPHA = 15 /* OP stack right shift */
R_ALPHA_GPVALUE R_ALPHA = 16
R_ALPHA_GPRELHIGH R_ALPHA = 17
R_ALPHA_GPRELLOW R_ALPHA = 18
R_ALPHA_IMMED_GP_16 R_ALPHA = 19
R_ALPHA_IMMED_GP_HI32 R_ALPHA = 20
R_ALPHA_IMMED_SCN_HI32 R_ALPHA = 21
R_ALPHA_IMMED_BR_HI32 R_ALPHA = 22
R_ALPHA_IMMED_LO32 R_ALPHA = 23
R_ALPHA_COPY R_ALPHA = 24 /* Copy symbol at runtime */
R_ALPHA_GLOB_DAT R_ALPHA = 25 /* Create GOT entry */
R_ALPHA_JMP_SLOT R_ALPHA = 26 /* Create PLT entry */
R_ALPHA_RELATIVE R_ALPHA = 27 /* Adjust by program base */
)
var ralphaStrings = []intName{
{0, "R_ALPHA_NONE"},
{1, "R_ALPHA_REFLONG"},
{2, "R_ALPHA_REFQUAD"},
{3, "R_ALPHA_GPREL32"},
{4, "R_ALPHA_LITERAL"},
{5, "R_ALPHA_LITUSE"},
{6, "R_ALPHA_GPDISP"},
{7, "R_ALPHA_BRADDR"},
{8, "R_ALPHA_HINT"},
{9, "R_ALPHA_SREL16"},
{10, "R_ALPHA_SREL32"},
{11, "R_ALPHA_SREL64"},
{12, "R_ALPHA_OP_PUSH"},
{13, "R_ALPHA_OP_STORE"},
{14, "R_ALPHA_OP_PSUB"},
{15, "R_ALPHA_OP_PRSHIFT"},
{16, "R_ALPHA_GPVALUE"},
{17, "R_ALPHA_GPRELHIGH"},
{18, "R_ALPHA_GPRELLOW"},
{19, "R_ALPHA_IMMED_GP_16"},
{20, "R_ALPHA_IMMED_GP_HI32"},
{21, "R_ALPHA_IMMED_SCN_HI32"},
{22, "R_ALPHA_IMMED_BR_HI32"},
{23, "R_ALPHA_IMMED_LO32"},
{24, "R_ALPHA_COPY"},
{25, "R_ALPHA_GLOB_DAT"},
{26, "R_ALPHA_JMP_SLOT"},
{27, "R_ALPHA_RELATIVE"},
}
func (i R_ALPHA) String() string { return stringName(uint32(i), ralphaStrings, false) }
func (i R_ALPHA) GoString() string { return stringName(uint32(i), ralphaStrings, true) }
// Relocation types for ARM.
type R_ARM int
const (
R_ARM_NONE R_ARM = 0 /* No relocation. */
R_ARM_PC24 R_ARM = 1
R_ARM_ABS32 R_ARM = 2
R_ARM_REL32 R_ARM = 3
R_ARM_PC13 R_ARM = 4
R_ARM_ABS16 R_ARM = 5
R_ARM_ABS12 R_ARM = 6
R_ARM_THM_ABS5 R_ARM = 7
R_ARM_ABS8 R_ARM = 8
R_ARM_SBREL32 R_ARM = 9
R_ARM_THM_PC22 R_ARM = 10
R_ARM_THM_PC8 R_ARM = 11
R_ARM_AMP_VCALL9 R_ARM = 12
R_ARM_SWI24 R_ARM = 13
R_ARM_THM_SWI8 R_ARM = 14
R_ARM_XPC25 R_ARM = 15
R_ARM_THM_XPC22 R_ARM = 16
R_ARM_TLS_DTPMOD32 R_ARM = 17
R_ARM_TLS_DTPOFF32 R_ARM = 18
R_ARM_TLS_TPOFF32 R_ARM = 19
R_ARM_COPY R_ARM = 20 /* Copy data from shared object. */
R_ARM_GLOB_DAT R_ARM = 21 /* Set GOT entry to data address. */
R_ARM_JUMP_SLOT R_ARM = 22 /* Set GOT entry to code address. */
R_ARM_RELATIVE R_ARM = 23 /* Add load address of shared object. */
R_ARM_GOTOFF R_ARM = 24 /* Add GOT-relative symbol address. */
R_ARM_GOTPC R_ARM = 25 /* Add PC-relative GOT table address. */
R_ARM_GOT32 R_ARM = 26 /* Add PC-relative GOT offset. */
R_ARM_PLT32 R_ARM = 27 /* Add PC-relative PLT offset. */
R_ARM_CALL R_ARM = 28
R_ARM_JUMP24 R_ARM = 29
R_ARM_THM_JUMP24 R_ARM = 30
R_ARM_BASE_ABS R_ARM = 31
R_ARM_ALU_PCREL_7_0 R_ARM = 32
R_ARM_ALU_PCREL_15_8 R_ARM = 33
R_ARM_ALU_PCREL_23_15 R_ARM = 34
R_ARM_LDR_SBREL_11_10_NC R_ARM = 35
R_ARM_ALU_SBREL_19_12_NC R_ARM = 36
R_ARM_ALU_SBREL_27_20_CK R_ARM = 37
R_ARM_TARGET1 R_ARM = 38
R_ARM_SBREL31 R_ARM = 39
R_ARM_V4BX R_ARM = 40
R_ARM_TARGET2 R_ARM = 41
R_ARM_PREL31 R_ARM = 42
R_ARM_MOVW_ABS_NC R_ARM = 43
R_ARM_MOVT_ABS R_ARM = 44
R_ARM_MOVW_PREL_NC R_ARM = 45
R_ARM_MOVT_PREL R_ARM = 46
R_ARM_THM_MOVW_ABS_NC R_ARM = 47
R_ARM_THM_MOVT_ABS R_ARM = 48
R_ARM_THM_MOVW_PREL_NC R_ARM = 49
R_ARM_THM_MOVT_PREL R_ARM = 50
R_ARM_THM_JUMP19 R_ARM = 51
R_ARM_THM_JUMP6 R_ARM = 52
R_ARM_THM_ALU_PREL_11_0 R_ARM = 53
R_ARM_THM_PC12 R_ARM = 54
R_ARM_ABS32_NOI R_ARM = 55
R_ARM_REL32_NOI R_ARM = 56
R_ARM_ALU_PC_G0_NC R_ARM = 57
R_ARM_ALU_PC_G0 R_ARM = 58
R_ARM_ALU_PC_G1_NC R_ARM = 59
R_ARM_ALU_PC_G1 R_ARM = 60
R_ARM_ALU_PC_G2 R_ARM = 61
R_ARM_LDR_PC_G1 R_ARM = 62
R_ARM_LDR_PC_G2 R_ARM = 63
R_ARM_LDRS_PC_G0 R_ARM = 64
R_ARM_LDRS_PC_G1 R_ARM = 65
R_ARM_LDRS_PC_G2 R_ARM = 66
R_ARM_LDC_PC_G0 R_ARM = 67
R_ARM_LDC_PC_G1 R_ARM = 68
R_ARM_LDC_PC_G2 R_ARM = 69
R_ARM_ALU_SB_G0_NC R_ARM = 70
R_ARM_ALU_SB_G0 R_ARM = 71
R_ARM_ALU_SB_G1_NC R_ARM = 72
R_ARM_ALU_SB_G1 R_ARM = 73
R_ARM_ALU_SB_G2 R_ARM = 74
R_ARM_LDR_SB_G0 R_ARM = 75
R_ARM_LDR_SB_G1 R_ARM = 76
R_ARM_LDR_SB_G2 R_ARM = 77
R_ARM_LDRS_SB_G0 R_ARM = 78
R_ARM_LDRS_SB_G1 R_ARM = 79
R_ARM_LDRS_SB_G2 R_ARM = 80
R_ARM_LDC_SB_G0 R_ARM = 81
R_ARM_LDC_SB_G1 R_ARM = 82
R_ARM_LDC_SB_G2 R_ARM = 83
R_ARM_MOVW_BREL_NC R_ARM = 84
R_ARM_MOVT_BREL R_ARM = 85
R_ARM_MOVW_BREL R_ARM = 86
R_ARM_THM_MOVW_BREL_NC R_ARM = 87
R_ARM_THM_MOVT_BREL R_ARM = 88
R_ARM_THM_MOVW_BREL R_ARM = 89
R_ARM_TLS_GOTDESC R_ARM = 90
R_ARM_TLS_CALL R_ARM = 91
R_ARM_TLS_DESCSEQ R_ARM = 92
R_ARM_THM_TLS_CALL R_ARM = 93
R_ARM_PLT32_ABS R_ARM = 94
R_ARM_GOT_ABS R_ARM = 95
R_ARM_GOT_PREL R_ARM = 96
R_ARM_GOT_BREL12 R_ARM = 97
R_ARM_GOTOFF12 R_ARM = 98
R_ARM_GOTRELAX R_ARM = 99
R_ARM_GNU_VTENTRY R_ARM = 100
R_ARM_GNU_VTINHERIT R_ARM = 101
R_ARM_THM_JUMP11 R_ARM = 102
R_ARM_THM_JUMP8 R_ARM = 103
R_ARM_TLS_GD32 R_ARM = 104
R_ARM_TLS_LDM32 R_ARM = 105
R_ARM_TLS_LDO32 R_ARM = 106
R_ARM_TLS_IE32 R_ARM = 107
R_ARM_TLS_LE32 R_ARM = 108
R_ARM_TLS_LDO12 R_ARM = 109
R_ARM_TLS_LE12 R_ARM = 110
R_ARM_TLS_IE12GP R_ARM = 111
R_ARM_PRIVATE_0 R_ARM = 112
R_ARM_PRIVATE_1 R_ARM = 113
R_ARM_PRIVATE_2 R_ARM = 114
R_ARM_PRIVATE_3 R_ARM = 115
R_ARM_PRIVATE_4 R_ARM = 116
R_ARM_PRIVATE_5 R_ARM = 117
R_ARM_PRIVATE_6 R_ARM = 118
R_ARM_PRIVATE_7 R_ARM = 119
R_ARM_PRIVATE_8 R_ARM = 120
R_ARM_PRIVATE_9 R_ARM = 121
R_ARM_PRIVATE_10 R_ARM = 122
R_ARM_PRIVATE_11 R_ARM = 123
R_ARM_PRIVATE_12 R_ARM = 124
R_ARM_PRIVATE_13 R_ARM = 125
R_ARM_PRIVATE_14 R_ARM = 126
R_ARM_PRIVATE_15 R_ARM = 127
R_ARM_ME_TOO R_ARM = 128
R_ARM_THM_TLS_DESCSEQ16 R_ARM = 129
R_ARM_THM_TLS_DESCSEQ32 R_ARM = 130
R_ARM_THM_GOT_BREL12 R_ARM = 131
R_ARM_THM_ALU_ABS_G0_NC R_ARM = 132
R_ARM_THM_ALU_ABS_G1_NC R_ARM = 133
R_ARM_THM_ALU_ABS_G2_NC R_ARM = 134
R_ARM_THM_ALU_ABS_G3 R_ARM = 135
R_ARM_IRELATIVE R_ARM = 160
R_ARM_RXPC25 R_ARM = 249
R_ARM_RSBREL32 R_ARM = 250
R_ARM_THM_RPC22 R_ARM = 251
R_ARM_RREL32 R_ARM = 252
R_ARM_RABS32 R_ARM = 253
R_ARM_RPC24 R_ARM = 254
R_ARM_RBASE R_ARM = 255
)
var rarmStrings = []intName{
{0, "R_ARM_NONE"},
{1, "R_ARM_PC24"},
{2, "R_ARM_ABS32"},
{3, "R_ARM_REL32"},
{4, "R_ARM_PC13"},
{5, "R_ARM_ABS16"},
{6, "R_ARM_ABS12"},
{7, "R_ARM_THM_ABS5"},
{8, "R_ARM_ABS8"},
{9, "R_ARM_SBREL32"},
{10, "R_ARM_THM_PC22"},
{11, "R_ARM_THM_PC8"},
{12, "R_ARM_AMP_VCALL9"},
{13, "R_ARM_SWI24"},
{14, "R_ARM_THM_SWI8"},
{15, "R_ARM_XPC25"},
{16, "R_ARM_THM_XPC22"},
{17, "R_ARM_TLS_DTPMOD32"},
{18, "R_ARM_TLS_DTPOFF32"},
{19, "R_ARM_TLS_TPOFF32"},
{20, "R_ARM_COPY"},
{21, "R_ARM_GLOB_DAT"},
{22, "R_ARM_JUMP_SLOT"},
{23, "R_ARM_RELATIVE"},
{24, "R_ARM_GOTOFF"},
{25, "R_ARM_GOTPC"},
{26, "R_ARM_GOT32"},
{27, "R_ARM_PLT32"},
{28, "R_ARM_CALL"},
{29, "R_ARM_JUMP24"},
{30, "R_ARM_THM_JUMP24"},
{31, "R_ARM_BASE_ABS"},
{32, "R_ARM_ALU_PCREL_7_0"},
{33, "R_ARM_ALU_PCREL_15_8"},
{34, "R_ARM_ALU_PCREL_23_15"},
{35, "R_ARM_LDR_SBREL_11_10_NC"},
{36, "R_ARM_ALU_SBREL_19_12_NC"},
{37, "R_ARM_ALU_SBREL_27_20_CK"},
{38, "R_ARM_TARGET1"},
{39, "R_ARM_SBREL31"},
{40, "R_ARM_V4BX"},
{41, "R_ARM_TARGET2"},
{42, "R_ARM_PREL31"},
{43, "R_ARM_MOVW_ABS_NC"},
{44, "R_ARM_MOVT_ABS"},
{45, "R_ARM_MOVW_PREL_NC"},
{46, "R_ARM_MOVT_PREL"},
{47, "R_ARM_THM_MOVW_ABS_NC"},
{48, "R_ARM_THM_MOVT_ABS"},
{49, "R_ARM_THM_MOVW_PREL_NC"},
{50, "R_ARM_THM_MOVT_PREL"},
{51, "R_ARM_THM_JUMP19"},
{52, "R_ARM_THM_JUMP6"},
{53, "R_ARM_THM_ALU_PREL_11_0"},
{54, "R_ARM_THM_PC12"},
{55, "R_ARM_ABS32_NOI"},
{56, "R_ARM_REL32_NOI"},
{57, "R_ARM_ALU_PC_G0_NC"},
{58, "R_ARM_ALU_PC_G0"},
{59, "R_ARM_ALU_PC_G1_NC"},
{60, "R_ARM_ALU_PC_G1"},
{61, "R_ARM_ALU_PC_G2"},
{62, "R_ARM_LDR_PC_G1"},
{63, "R_ARM_LDR_PC_G2"},
{64, "R_ARM_LDRS_PC_G0"},
{65, "R_ARM_LDRS_PC_G1"},
{66, "R_ARM_LDRS_PC_G2"},
{67, "R_ARM_LDC_PC_G0"},
{68, "R_ARM_LDC_PC_G1"},
{69, "R_ARM_LDC_PC_G2"},
{70, "R_ARM_ALU_SB_G0_NC"},
{71, "R_ARM_ALU_SB_G0"},
{72, "R_ARM_ALU_SB_G1_NC"},
{73, "R_ARM_ALU_SB_G1"},
{74, "R_ARM_ALU_SB_G2"},
{75, "R_ARM_LDR_SB_G0"},
{76, "R_ARM_LDR_SB_G1"},
{77, "R_ARM_LDR_SB_G2"},
{78, "R_ARM_LDRS_SB_G0"},
{79, "R_ARM_LDRS_SB_G1"},
{80, "R_ARM_LDRS_SB_G2"},
{81, "R_ARM_LDC_SB_G0"},
{82, "R_ARM_LDC_SB_G1"},
{83, "R_ARM_LDC_SB_G2"},
{84, "R_ARM_MOVW_BREL_NC"},
{85, "R_ARM_MOVT_BREL"},
{86, "R_ARM_MOVW_BREL"},
{87, "R_ARM_THM_MOVW_BREL_NC"},
{88, "R_ARM_THM_MOVT_BREL"},
{89, "R_ARM_THM_MOVW_BREL"},
{90, "R_ARM_TLS_GOTDESC"},
{91, "R_ARM_TLS_CALL"},
{92, "R_ARM_TLS_DESCSEQ"},
{93, "R_ARM_THM_TLS_CALL"},
{94, "R_ARM_PLT32_ABS"},
{95, "R_ARM_GOT_ABS"},
{96, "R_ARM_GOT_PREL"},
{97, "R_ARM_GOT_BREL12"},
{98, "R_ARM_GOTOFF12"},
{99, "R_ARM_GOTRELAX"},
{100, "R_ARM_GNU_VTENTRY"},
{101, "R_ARM_GNU_VTINHERIT"},
{102, "R_ARM_THM_JUMP11"},
{103, "R_ARM_THM_JUMP8"},
{104, "R_ARM_TLS_GD32"},
{105, "R_ARM_TLS_LDM32"},
{106, "R_ARM_TLS_LDO32"},
{107, "R_ARM_TLS_IE32"},
{108, "R_ARM_TLS_LE32"},
{109, "R_ARM_TLS_LDO12"},
{110, "R_ARM_TLS_LE12"},
{111, "R_ARM_TLS_IE12GP"},
{112, "R_ARM_PRIVATE_0"},
{113, "R_ARM_PRIVATE_1"},
{114, "R_ARM_PRIVATE_2"},
{115, "R_ARM_PRIVATE_3"},
{116, "R_ARM_PRIVATE_4"},
{117, "R_ARM_PRIVATE_5"},
{118, "R_ARM_PRIVATE_6"},
{119, "R_ARM_PRIVATE_7"},
{120, "R_ARM_PRIVATE_8"},
{121, "R_ARM_PRIVATE_9"},
{122, "R_ARM_PRIVATE_10"},
{123, "R_ARM_PRIVATE_11"},
{124, "R_ARM_PRIVATE_12"},
{125, "R_ARM_PRIVATE_13"},
{126, "R_ARM_PRIVATE_14"},
{127, "R_ARM_PRIVATE_15"},
{128, "R_ARM_ME_TOO"},
{129, "R_ARM_THM_TLS_DESCSEQ16"},
{130, "R_ARM_THM_TLS_DESCSEQ32"},
{131, "R_ARM_THM_GOT_BREL12"},
{132, "R_ARM_THM_ALU_ABS_G0_NC"},
{133, "R_ARM_THM_ALU_ABS_G1_NC"},
{134, "R_ARM_THM_ALU_ABS_G2_NC"},
{135, "R_ARM_THM_ALU_ABS_G3"},
{160, "R_ARM_IRELATIVE"},
{249, "R_ARM_RXPC25"},
{250, "R_ARM_RSBREL32"},
{251, "R_ARM_THM_RPC22"},
{252, "R_ARM_RREL32"},
{253, "R_ARM_RABS32"},
{254, "R_ARM_RPC24"},
{255, "R_ARM_RBASE"},
}
func (i R_ARM) String() string { return stringName(uint32(i), rarmStrings, false) }
func (i R_ARM) GoString() string { return stringName(uint32(i), rarmStrings, true) }
// Relocation types for 386.
type R_386 int
const (
R_386_NONE R_386 = 0 /* No relocation. */
R_386_32 R_386 = 1 /* Add symbol value. */
R_386_PC32 R_386 = 2 /* Add PC-relative symbol value. */
R_386_GOT32 R_386 = 3 /* Add PC-relative GOT offset. */
R_386_PLT32 R_386 = 4 /* Add PC-relative PLT offset. */
R_386_COPY R_386 = 5 /* Copy data from shared object. */
R_386_GLOB_DAT R_386 = 6 /* Set GOT entry to data address. */
R_386_JMP_SLOT R_386 = 7 /* Set GOT entry to code address. */
R_386_RELATIVE R_386 = 8 /* Add load address of shared object. */
R_386_GOTOFF R_386 = 9 /* Add GOT-relative symbol address. */
R_386_GOTPC R_386 = 10 /* Add PC-relative GOT table address. */
R_386_32PLT R_386 = 11
R_386_TLS_TPOFF R_386 = 14 /* Negative offset in static TLS block */
R_386_TLS_IE R_386 = 15 /* Absolute address of GOT for -ve static TLS */
R_386_TLS_GOTIE R_386 = 16 /* GOT entry for negative static TLS block */
R_386_TLS_LE R_386 = 17 /* Negative offset relative to static TLS */
R_386_TLS_GD R_386 = 18 /* 32 bit offset to GOT (index,off) pair */
R_386_TLS_LDM R_386 = 19 /* 32 bit offset to GOT (index,zero) pair */
R_386_16 R_386 = 20
R_386_PC16 R_386 = 21
R_386_8 R_386 = 22
R_386_PC8 R_386 = 23
R_386_TLS_GD_32 R_386 = 24 /* 32 bit offset to GOT (index,off) pair */
R_386_TLS_GD_PUSH R_386 = 25 /* pushl instruction for Sun ABI GD sequence */
R_386_TLS_GD_CALL R_386 = 26 /* call instruction for Sun ABI GD sequence */
R_386_TLS_GD_POP R_386 = 27 /* popl instruction for Sun ABI GD sequence */
R_386_TLS_LDM_32 R_386 = 28 /* 32 bit offset to GOT (index,zero) pair */
R_386_TLS_LDM_PUSH R_386 = 29 /* pushl instruction for Sun ABI LD sequence */
R_386_TLS_LDM_CALL R_386 = 30 /* call instruction for Sun ABI LD sequence */
R_386_TLS_LDM_POP R_386 = 31 /* popl instruction for Sun ABI LD sequence */
R_386_TLS_LDO_32 R_386 = 32 /* 32 bit offset from start of TLS block */
R_386_TLS_IE_32 R_386 = 33 /* 32 bit offset to GOT static TLS offset entry */
R_386_TLS_LE_32 R_386 = 34 /* 32 bit offset within static TLS block */
R_386_TLS_DTPMOD32 R_386 = 35 /* GOT entry containing TLS index */
R_386_TLS_DTPOFF32 R_386 = 36 /* GOT entry containing TLS offset */
R_386_TLS_TPOFF32 R_386 = 37 /* GOT entry of -ve static TLS offset */
R_386_SIZE32 R_386 = 38
R_386_TLS_GOTDESC R_386 = 39
R_386_TLS_DESC_CALL R_386 = 40
R_386_TLS_DESC R_386 = 41
R_386_IRELATIVE R_386 = 42
R_386_GOT32X R_386 = 43
)
var r386Strings = []intName{
{0, "R_386_NONE"},
{1, "R_386_32"},
{2, "R_386_PC32"},
{3, "R_386_GOT32"},
{4, "R_386_PLT32"},
{5, "R_386_COPY"},
{6, "R_386_GLOB_DAT"},
{7, "R_386_JMP_SLOT"},
{8, "R_386_RELATIVE"},
{9, "R_386_GOTOFF"},
{10, "R_386_GOTPC"},
{11, "R_386_32PLT"},
{14, "R_386_TLS_TPOFF"},
{15, "R_386_TLS_IE"},
{16, "R_386_TLS_GOTIE"},
{17, "R_386_TLS_LE"},
{18, "R_386_TLS_GD"},
{19, "R_386_TLS_LDM"},
{20, "R_386_16"},
{21, "R_386_PC16"},
{22, "R_386_8"},
{23, "R_386_PC8"},
{24, "R_386_TLS_GD_32"},
{25, "R_386_TLS_GD_PUSH"},
{26, "R_386_TLS_GD_CALL"},
{27, "R_386_TLS_GD_POP"},
{28, "R_386_TLS_LDM_32"},
{29, "R_386_TLS_LDM_PUSH"},
{30, "R_386_TLS_LDM_CALL"},
{31, "R_386_TLS_LDM_POP"},
{32, "R_386_TLS_LDO_32"},
{33, "R_386_TLS_IE_32"},
{34, "R_386_TLS_LE_32"},
{35, "R_386_TLS_DTPMOD32"},
{36, "R_386_TLS_DTPOFF32"},
{37, "R_386_TLS_TPOFF32"},
{38, "R_386_SIZE32"},
{39, "R_386_TLS_GOTDESC"},
{40, "R_386_TLS_DESC_CALL"},
{41, "R_386_TLS_DESC"},
{42, "R_386_IRELATIVE"},
{43, "R_386_GOT32X"},
}
func (i R_386) String() string { return stringName(uint32(i), r386Strings, false) }
func (i R_386) GoString() string { return stringName(uint32(i), r386Strings, true) }
// Relocation types for MIPS.
type R_MIPS int
const (
R_MIPS_NONE R_MIPS = 0
R_MIPS_16 R_MIPS = 1
R_MIPS_32 R_MIPS = 2
R_MIPS_REL32 R_MIPS = 3
R_MIPS_26 R_MIPS = 4
R_MIPS_HI16 R_MIPS = 5 /* high 16 bits of symbol value */
R_MIPS_LO16 R_MIPS = 6 /* low 16 bits of symbol value */
R_MIPS_GPREL16 R_MIPS = 7 /* GP-relative reference */
R_MIPS_LITERAL R_MIPS = 8 /* Reference to literal section */
R_MIPS_GOT16 R_MIPS = 9 /* Reference to global offset table */
R_MIPS_PC16 R_MIPS = 10 /* 16 bit PC relative reference */
R_MIPS_CALL16 R_MIPS = 11 /* 16 bit call through glbl offset tbl */
R_MIPS_GPREL32 R_MIPS = 12
R_MIPS_SHIFT5 R_MIPS = 16
R_MIPS_SHIFT6 R_MIPS = 17
R_MIPS_64 R_MIPS = 18
R_MIPS_GOT_DISP R_MIPS = 19
R_MIPS_GOT_PAGE R_MIPS = 20
R_MIPS_GOT_OFST R_MIPS = 21
R_MIPS_GOT_HI16 R_MIPS = 22
R_MIPS_GOT_LO16 R_MIPS = 23
R_MIPS_SUB R_MIPS = 24
R_MIPS_INSERT_A R_MIPS = 25
R_MIPS_INSERT_B R_MIPS = 26
R_MIPS_DELETE R_MIPS = 27
R_MIPS_HIGHER R_MIPS = 28
R_MIPS_HIGHEST R_MIPS = 29
R_MIPS_CALL_HI16 R_MIPS = 30
R_MIPS_CALL_LO16 R_MIPS = 31
R_MIPS_SCN_DISP R_MIPS = 32
R_MIPS_REL16 R_MIPS = 33
R_MIPS_ADD_IMMEDIATE R_MIPS = 34
R_MIPS_PJUMP R_MIPS = 35
R_MIPS_RELGOT R_MIPS = 36
R_MIPS_JALR R_MIPS = 37
R_MIPS_TLS_DTPMOD32 R_MIPS = 38 /* Module number 32 bit */
R_MIPS_TLS_DTPREL32 R_MIPS = 39 /* Module-relative offset 32 bit */
R_MIPS_TLS_DTPMOD64 R_MIPS = 40 /* Module number 64 bit */
R_MIPS_TLS_DTPREL64 R_MIPS = 41 /* Module-relative offset 64 bit */
R_MIPS_TLS_GD R_MIPS = 42 /* 16 bit GOT offset for GD */
R_MIPS_TLS_LDM R_MIPS = 43 /* 16 bit GOT offset for LDM */
R_MIPS_TLS_DTPREL_HI16 R_MIPS = 44 /* Module-relative offset, high 16 bits */
R_MIPS_TLS_DTPREL_LO16 R_MIPS = 45 /* Module-relative offset, low 16 bits */
R_MIPS_TLS_GOTTPREL R_MIPS = 46 /* 16 bit GOT offset for IE */
R_MIPS_TLS_TPREL32 R_MIPS = 47 /* TP-relative offset, 32 bit */
R_MIPS_TLS_TPREL64 R_MIPS = 48 /* TP-relative offset, 64 bit */
R_MIPS_TLS_TPREL_HI16 R_MIPS = 49 /* TP-relative offset, high 16 bits */
R_MIPS_TLS_TPREL_LO16 R_MIPS = 50 /* TP-relative offset, low 16 bits */
R_MIPS_PC32 R_MIPS = 248 /* 32 bit PC relative reference */
)
var rmipsStrings = []intName{
{0, "R_MIPS_NONE"},
{1, "R_MIPS_16"},
{2, "R_MIPS_32"},
{3, "R_MIPS_REL32"},
{4, "R_MIPS_26"},
{5, "R_MIPS_HI16"},
{6, "R_MIPS_LO16"},
{7, "R_MIPS_GPREL16"},
{8, "R_MIPS_LITERAL"},
{9, "R_MIPS_GOT16"},
{10, "R_MIPS_PC16"},
{11, "R_MIPS_CALL16"},
{12, "R_MIPS_GPREL32"},
{16, "R_MIPS_SHIFT5"},
{17, "R_MIPS_SHIFT6"},
{18, "R_MIPS_64"},
{19, "R_MIPS_GOT_DISP"},
{20, "R_MIPS_GOT_PAGE"},
{21, "R_MIPS_GOT_OFST"},
{22, "R_MIPS_GOT_HI16"},
{23, "R_MIPS_GOT_LO16"},
{24, "R_MIPS_SUB"},
{25, "R_MIPS_INSERT_A"},
{26, "R_MIPS_INSERT_B"},
{27, "R_MIPS_DELETE"},
{28, "R_MIPS_HIGHER"},
{29, "R_MIPS_HIGHEST"},
{30, "R_MIPS_CALL_HI16"},
{31, "R_MIPS_CALL_LO16"},
{32, "R_MIPS_SCN_DISP"},
{33, "R_MIPS_REL16"},
{34, "R_MIPS_ADD_IMMEDIATE"},
{35, "R_MIPS_PJUMP"},
{36, "R_MIPS_RELGOT"},
{37, "R_MIPS_JALR"},
{38, "R_MIPS_TLS_DTPMOD32"},
{39, "R_MIPS_TLS_DTPREL32"},
{40, "R_MIPS_TLS_DTPMOD64"},
{41, "R_MIPS_TLS_DTPREL64"},
{42, "R_MIPS_TLS_GD"},
{43, "R_MIPS_TLS_LDM"},
{44, "R_MIPS_TLS_DTPREL_HI16"},
{45, "R_MIPS_TLS_DTPREL_LO16"},
{46, "R_MIPS_TLS_GOTTPREL"},
{47, "R_MIPS_TLS_TPREL32"},
{48, "R_MIPS_TLS_TPREL64"},
{49, "R_MIPS_TLS_TPREL_HI16"},
{50, "R_MIPS_TLS_TPREL_LO16"},
{248, "R_MIPS_PC32"},
}
func (i R_MIPS) String() string { return stringName(uint32(i), rmipsStrings, false) }
func (i R_MIPS) GoString() string { return stringName(uint32(i), rmipsStrings, true) }
// Relocation types for LoongArch.
type R_LARCH int
const (
R_LARCH_NONE R_LARCH = 0
R_LARCH_32 R_LARCH = 1
R_LARCH_64 R_LARCH = 2
R_LARCH_RELATIVE R_LARCH = 3
R_LARCH_COPY R_LARCH = 4
R_LARCH_JUMP_SLOT R_LARCH = 5
R_LARCH_TLS_DTPMOD32 R_LARCH = 6
R_LARCH_TLS_DTPMOD64 R_LARCH = 7
R_LARCH_TLS_DTPREL32 R_LARCH = 8
R_LARCH_TLS_DTPREL64 R_LARCH = 9
R_LARCH_TLS_TPREL32 R_LARCH = 10
R_LARCH_TLS_TPREL64 R_LARCH = 11
R_LARCH_IRELATIVE R_LARCH = 12
R_LARCH_MARK_LA R_LARCH = 20
R_LARCH_MARK_PCREL R_LARCH = 21
R_LARCH_SOP_PUSH_PCREL R_LARCH = 22
R_LARCH_SOP_PUSH_ABSOLUTE R_LARCH = 23
R_LARCH_SOP_PUSH_DUP R_LARCH = 24
R_LARCH_SOP_PUSH_GPREL R_LARCH = 25
R_LARCH_SOP_PUSH_TLS_TPREL R_LARCH = 26
R_LARCH_SOP_PUSH_TLS_GOT R_LARCH = 27
R_LARCH_SOP_PUSH_TLS_GD R_LARCH = 28
R_LARCH_SOP_PUSH_PLT_PCREL R_LARCH = 29
R_LARCH_SOP_ASSERT R_LARCH = 30
R_LARCH_SOP_NOT R_LARCH = 31
R_LARCH_SOP_SUB R_LARCH = 32
R_LARCH_SOP_SL R_LARCH = 33
R_LARCH_SOP_SR R_LARCH = 34
R_LARCH_SOP_ADD R_LARCH = 35
R_LARCH_SOP_AND R_LARCH = 36
R_LARCH_SOP_IF_ELSE R_LARCH = 37
R_LARCH_SOP_POP_32_S_10_5 R_LARCH = 38
R_LARCH_SOP_POP_32_U_10_12 R_LARCH = 39
R_LARCH_SOP_POP_32_S_10_12 R_LARCH = 40
R_LARCH_SOP_POP_32_S_10_16 R_LARCH = 41
R_LARCH_SOP_POP_32_S_10_16_S2 R_LARCH = 42
R_LARCH_SOP_POP_32_S_5_20 R_LARCH = 43
R_LARCH_SOP_POP_32_S_0_5_10_16_S2 R_LARCH = 44
R_LARCH_SOP_POP_32_S_0_10_10_16_S2 R_LARCH = 45
R_LARCH_SOP_POP_32_U R_LARCH = 46
R_LARCH_ADD8 R_LARCH = 47
R_LARCH_ADD16 R_LARCH = 48
R_LARCH_ADD24 R_LARCH = 49
R_LARCH_ADD32 R_LARCH = 50
R_LARCH_ADD64 R_LARCH = 51
R_LARCH_SUB8 R_LARCH = 52
R_LARCH_SUB16 R_LARCH = 53
R_LARCH_SUB24 R_LARCH = 54
R_LARCH_SUB32 R_LARCH = 55
R_LARCH_SUB64 R_LARCH = 56
R_LARCH_GNU_VTINHERIT R_LARCH = 57
R_LARCH_GNU_VTENTRY R_LARCH = 58
R_LARCH_B16 R_LARCH = 64
R_LARCH_B21 R_LARCH = 65
R_LARCH_B26 R_LARCH = 66
R_LARCH_ABS_HI20 R_LARCH = 67
R_LARCH_ABS_LO12 R_LARCH = 68
R_LARCH_ABS64_LO20 R_LARCH = 69
R_LARCH_ABS64_HI12 R_LARCH = 70
R_LARCH_PCALA_HI20 R_LARCH = 71
R_LARCH_PCALA_LO12 R_LARCH = 72
R_LARCH_PCALA64_LO20 R_LARCH = 73
R_LARCH_PCALA64_HI12 R_LARCH = 74
R_LARCH_GOT_PC_HI20 R_LARCH = 75
R_LARCH_GOT_PC_LO12 R_LARCH = 76
R_LARCH_GOT64_PC_LO20 R_LARCH = 77
R_LARCH_GOT64_PC_HI12 R_LARCH = 78
R_LARCH_GOT_HI20 R_LARCH = 79
R_LARCH_GOT_LO12 R_LARCH = 80
R_LARCH_GOT64_LO20 R_LARCH = 81
R_LARCH_GOT64_HI12 R_LARCH = 82
R_LARCH_TLS_LE_HI20 R_LARCH = 83
R_LARCH_TLS_LE_LO12 R_LARCH = 84
R_LARCH_TLS_LE64_LO20 R_LARCH = 85
R_LARCH_TLS_LE64_HI12 R_LARCH = 86
R_LARCH_TLS_IE_PC_HI20 R_LARCH = 87
R_LARCH_TLS_IE_PC_LO12 R_LARCH = 88
R_LARCH_TLS_IE64_PC_LO20 R_LARCH = 89
R_LARCH_TLS_IE64_PC_HI12 R_LARCH = 90
R_LARCH_TLS_IE_HI20 R_LARCH = 91
R_LARCH_TLS_IE_LO12 R_LARCH = 92
R_LARCH_TLS_IE64_LO20 R_LARCH = 93
R_LARCH_TLS_IE64_HI12 R_LARCH = 94
R_LARCH_TLS_LD_PC_HI20 R_LARCH = 95
R_LARCH_TLS_LD_HI20 R_LARCH = 96
R_LARCH_TLS_GD_PC_HI20 R_LARCH = 97
R_LARCH_TLS_GD_HI20 R_LARCH = 98
R_LARCH_32_PCREL R_LARCH = 99
R_LARCH_RELAX R_LARCH = 100
R_LARCH_DELETE R_LARCH = 101
R_LARCH_ALIGN R_LARCH = 102
R_LARCH_PCREL20_S2 R_LARCH = 103
R_LARCH_CFA R_LARCH = 104
R_LARCH_ADD6 R_LARCH = 105
R_LARCH_SUB6 R_LARCH = 106
R_LARCH_ADD_ULEB128 R_LARCH = 107
R_LARCH_SUB_ULEB128 R_LARCH = 108
R_LARCH_64_PCREL R_LARCH = 109
)
var rlarchStrings = []intName{
{0, "R_LARCH_NONE"},
{1, "R_LARCH_32"},
{2, "R_LARCH_64"},
{3, "R_LARCH_RELATIVE"},
{4, "R_LARCH_COPY"},
{5, "R_LARCH_JUMP_SLOT"},
{6, "R_LARCH_TLS_DTPMOD32"},
{7, "R_LARCH_TLS_DTPMOD64"},
{8, "R_LARCH_TLS_DTPREL32"},
{9, "R_LARCH_TLS_DTPREL64"},
{10, "R_LARCH_TLS_TPREL32"},
{11, "R_LARCH_TLS_TPREL64"},
{12, "R_LARCH_IRELATIVE"},
{20, "R_LARCH_MARK_LA"},
{21, "R_LARCH_MARK_PCREL"},
{22, "R_LARCH_SOP_PUSH_PCREL"},
{23, "R_LARCH_SOP_PUSH_ABSOLUTE"},
{24, "R_LARCH_SOP_PUSH_DUP"},
{25, "R_LARCH_SOP_PUSH_GPREL"},
{26, "R_LARCH_SOP_PUSH_TLS_TPREL"},
{27, "R_LARCH_SOP_PUSH_TLS_GOT"},
{28, "R_LARCH_SOP_PUSH_TLS_GD"},
{29, "R_LARCH_SOP_PUSH_PLT_PCREL"},
{30, "R_LARCH_SOP_ASSERT"},
{31, "R_LARCH_SOP_NOT"},
{32, "R_LARCH_SOP_SUB"},
{33, "R_LARCH_SOP_SL"},
{34, "R_LARCH_SOP_SR"},
{35, "R_LARCH_SOP_ADD"},
{36, "R_LARCH_SOP_AND"},
{37, "R_LARCH_SOP_IF_ELSE"},
{38, "R_LARCH_SOP_POP_32_S_10_5"},
{39, "R_LARCH_SOP_POP_32_U_10_12"},
{40, "R_LARCH_SOP_POP_32_S_10_12"},
{41, "R_LARCH_SOP_POP_32_S_10_16"},
{42, "R_LARCH_SOP_POP_32_S_10_16_S2"},
{43, "R_LARCH_SOP_POP_32_S_5_20"},
{44, "R_LARCH_SOP_POP_32_S_0_5_10_16_S2"},
{45, "R_LARCH_SOP_POP_32_S_0_10_10_16_S2"},
{46, "R_LARCH_SOP_POP_32_U"},
{47, "R_LARCH_ADD8"},
{48, "R_LARCH_ADD16"},
{49, "R_LARCH_ADD24"},
{50, "R_LARCH_ADD32"},
{51, "R_LARCH_ADD64"},
{52, "R_LARCH_SUB8"},
{53, "R_LARCH_SUB16"},
{54, "R_LARCH_SUB24"},
{55, "R_LARCH_SUB32"},
{56, "R_LARCH_SUB64"},
{57, "R_LARCH_GNU_VTINHERIT"},
{58, "R_LARCH_GNU_VTENTRY"},
{64, "R_LARCH_B16"},
{65, "R_LARCH_B21"},
{66, "R_LARCH_B26"},
{67, "R_LARCH_ABS_HI20"},
{68, "R_LARCH_ABS_LO12"},
{69, "R_LARCH_ABS64_LO20"},
{70, "R_LARCH_ABS64_HI12"},
{71, "R_LARCH_PCALA_HI20"},
{72, "R_LARCH_PCALA_LO12"},
{73, "R_LARCH_PCALA64_LO20"},
{74, "R_LARCH_PCALA64_HI12"},
{75, "R_LARCH_GOT_PC_HI20"},
{76, "R_LARCH_GOT_PC_LO12"},
{77, "R_LARCH_GOT64_PC_LO20"},
{78, "R_LARCH_GOT64_PC_HI12"},
{79, "R_LARCH_GOT_HI20"},
{80, "R_LARCH_GOT_LO12"},
{81, "R_LARCH_GOT64_LO20"},
{82, "R_LARCH_GOT64_HI12"},
{83, "R_LARCH_TLS_LE_HI20"},
{84, "R_LARCH_TLS_LE_LO12"},
{85, "R_LARCH_TLS_LE64_LO20"},
{86, "R_LARCH_TLS_LE64_HI12"},
{87, "R_LARCH_TLS_IE_PC_HI20"},
{88, "R_LARCH_TLS_IE_PC_LO12"},
{89, "R_LARCH_TLS_IE64_PC_LO20"},
{90, "R_LARCH_TLS_IE64_PC_HI12"},
{91, "R_LARCH_TLS_IE_HI20"},
{92, "R_LARCH_TLS_IE_LO12"},
{93, "R_LARCH_TLS_IE64_LO20"},
{94, "R_LARCH_TLS_IE64_HI12"},
{95, "R_LARCH_TLS_LD_PC_HI20"},
{96, "R_LARCH_TLS_LD_HI20"},
{97, "R_LARCH_TLS_GD_PC_HI20"},
{98, "R_LARCH_TLS_GD_HI20"},
{99, "R_LARCH_32_PCREL"},
{100, "R_LARCH_RELAX"},
{101, "R_LARCH_DELETE"},
{102, "R_LARCH_ALIGN"},
{103, "R_LARCH_PCREL20_S2"},
{104, "R_LARCH_CFA"},
{105, "R_LARCH_ADD6"},
{106, "R_LARCH_SUB6"},
{107, "R_LARCH_ADD_ULEB128"},
{108, "R_LARCH_SUB_ULEB128"},
{109, "R_LARCH_64_PCREL"},
}
func (i R_LARCH) String() string { return stringName(uint32(i), rlarchStrings, false) }
func (i R_LARCH) GoString() string { return stringName(uint32(i), rlarchStrings, true) }
// Relocation types for PowerPC.
//
// Values that are shared by both R_PPC and R_PPC64 are prefixed with
// R_POWERPC_ in the ELF standard. For the R_PPC type, the relevant
// shared relocations have been renamed with the prefix R_PPC_.
// The original name follows the value in a comment.
type R_PPC int
const (
R_PPC_NONE R_PPC = 0 // R_POWERPC_NONE
R_PPC_ADDR32 R_PPC = 1 // R_POWERPC_ADDR32
R_PPC_ADDR24 R_PPC = 2 // R_POWERPC_ADDR24
R_PPC_ADDR16 R_PPC = 3 // R_POWERPC_ADDR16
R_PPC_ADDR16_LO R_PPC = 4 // R_POWERPC_ADDR16_LO
R_PPC_ADDR16_HI R_PPC = 5 // R_POWERPC_ADDR16_HI
R_PPC_ADDR16_HA R_PPC = 6 // R_POWERPC_ADDR16_HA
R_PPC_ADDR14 R_PPC = 7 // R_POWERPC_ADDR14
R_PPC_ADDR14_BRTAKEN R_PPC = 8 // R_POWERPC_ADDR14_BRTAKEN
R_PPC_ADDR14_BRNTAKEN R_PPC = 9 // R_POWERPC_ADDR14_BRNTAKEN
R_PPC_REL24 R_PPC = 10 // R_POWERPC_REL24
R_PPC_REL14 R_PPC = 11 // R_POWERPC_REL14
R_PPC_REL14_BRTAKEN R_PPC = 12 // R_POWERPC_REL14_BRTAKEN
R_PPC_REL14_BRNTAKEN R_PPC = 13 // R_POWERPC_REL14_BRNTAKEN
R_PPC_GOT16 R_PPC = 14 // R_POWERPC_GOT16
R_PPC_GOT16_LO R_PPC = 15 // R_POWERPC_GOT16_LO
R_PPC_GOT16_HI R_PPC = 16 // R_POWERPC_GOT16_HI
R_PPC_GOT16_HA R_PPC = 17 // R_POWERPC_GOT16_HA
R_PPC_PLTREL24 R_PPC = 18
R_PPC_COPY R_PPC = 19 // R_POWERPC_COPY
R_PPC_GLOB_DAT R_PPC = 20 // R_POWERPC_GLOB_DAT
R_PPC_JMP_SLOT R_PPC = 21 // R_POWERPC_JMP_SLOT
R_PPC_RELATIVE R_PPC = 22 // R_POWERPC_RELATIVE
R_PPC_LOCAL24PC R_PPC = 23
R_PPC_UADDR32 R_PPC = 24 // R_POWERPC_UADDR32
R_PPC_UADDR16 R_PPC = 25 // R_POWERPC_UADDR16
R_PPC_REL32 R_PPC = 26 // R_POWERPC_REL32
R_PPC_PLT32 R_PPC = 27 // R_POWERPC_PLT32
R_PPC_PLTREL32 R_PPC = 28 // R_POWERPC_PLTREL32
R_PPC_PLT16_LO R_PPC = 29 // R_POWERPC_PLT16_LO
R_PPC_PLT16_HI R_PPC = 30 // R_POWERPC_PLT16_HI
R_PPC_PLT16_HA R_PPC = 31 // R_POWERPC_PLT16_HA
R_PPC_SDAREL16 R_PPC = 32
R_PPC_SECTOFF R_PPC = 33 // R_POWERPC_SECTOFF
R_PPC_SECTOFF_LO R_PPC = 34 // R_POWERPC_SECTOFF_LO
R_PPC_SECTOFF_HI R_PPC = 35 // R_POWERPC_SECTOFF_HI
R_PPC_SECTOFF_HA R_PPC = 36 // R_POWERPC_SECTOFF_HA
R_PPC_TLS R_PPC = 67 // R_POWERPC_TLS
R_PPC_DTPMOD32 R_PPC = 68 // R_POWERPC_DTPMOD32
R_PPC_TPREL16 R_PPC = 69 // R_POWERPC_TPREL16
R_PPC_TPREL16_LO R_PPC = 70 // R_POWERPC_TPREL16_LO
R_PPC_TPREL16_HI R_PPC = 71 // R_POWERPC_TPREL16_HI
R_PPC_TPREL16_HA R_PPC = 72 // R_POWERPC_TPREL16_HA
R_PPC_TPREL32 R_PPC = 73 // R_POWERPC_TPREL32
R_PPC_DTPREL16 R_PPC = 74 // R_POWERPC_DTPREL16
R_PPC_DTPREL16_LO R_PPC = 75 // R_POWERPC_DTPREL16_LO
R_PPC_DTPREL16_HI R_PPC = 76 // R_POWERPC_DTPREL16_HI
R_PPC_DTPREL16_HA R_PPC = 77 // R_POWERPC_DTPREL16_HA
R_PPC_DTPREL32 R_PPC = 78 // R_POWERPC_DTPREL32
R_PPC_GOT_TLSGD16 R_PPC = 79 // R_POWERPC_GOT_TLSGD16
R_PPC_GOT_TLSGD16_LO R_PPC = 80 // R_POWERPC_GOT_TLSGD16_LO
R_PPC_GOT_TLSGD16_HI R_PPC = 81 // R_POWERPC_GOT_TLSGD16_HI
R_PPC_GOT_TLSGD16_HA R_PPC = 82 // R_POWERPC_GOT_TLSGD16_HA
R_PPC_GOT_TLSLD16 R_PPC = 83 // R_POWERPC_GOT_TLSLD16
R_PPC_GOT_TLSLD16_LO R_PPC = 84 // R_POWERPC_GOT_TLSLD16_LO
R_PPC_GOT_TLSLD16_HI R_PPC = 85 // R_POWERPC_GOT_TLSLD16_HI
R_PPC_GOT_TLSLD16_HA R_PPC = 86 // R_POWERPC_GOT_TLSLD16_HA
R_PPC_GOT_TPREL16 R_PPC = 87 // R_POWERPC_GOT_TPREL16
R_PPC_GOT_TPREL16_LO R_PPC = 88 // R_POWERPC_GOT_TPREL16_LO
R_PPC_GOT_TPREL16_HI R_PPC = 89 // R_POWERPC_GOT_TPREL16_HI
R_PPC_GOT_TPREL16_HA R_PPC = 90 // R_POWERPC_GOT_TPREL16_HA
R_PPC_EMB_NADDR32 R_PPC = 101
R_PPC_EMB_NADDR16 R_PPC = 102
R_PPC_EMB_NADDR16_LO R_PPC = 103
R_PPC_EMB_NADDR16_HI R_PPC = 104
R_PPC_EMB_NADDR16_HA R_PPC = 105
R_PPC_EMB_SDAI16 R_PPC = 106
R_PPC_EMB_SDA2I16 R_PPC = 107
R_PPC_EMB_SDA2REL R_PPC = 108
R_PPC_EMB_SDA21 R_PPC = 109
R_PPC_EMB_MRKREF R_PPC = 110
R_PPC_EMB_RELSEC16 R_PPC = 111
R_PPC_EMB_RELST_LO R_PPC = 112
R_PPC_EMB_RELST_HI R_PPC = 113
R_PPC_EMB_RELST_HA R_PPC = 114
R_PPC_EMB_BIT_FLD R_PPC = 115
R_PPC_EMB_RELSDA R_PPC = 116
)
var rppcStrings = []intName{
{0, "R_PPC_NONE"},
{1, "R_PPC_ADDR32"},
{2, "R_PPC_ADDR24"},
{3, "R_PPC_ADDR16"},
{4, "R_PPC_ADDR16_LO"},
{5, "R_PPC_ADDR16_HI"},
{6, "R_PPC_ADDR16_HA"},
{7, "R_PPC_ADDR14"},
{8, "R_PPC_ADDR14_BRTAKEN"},
{9, "R_PPC_ADDR14_BRNTAKEN"},
{10, "R_PPC_REL24"},
{11, "R_PPC_REL14"},
{12, "R_PPC_REL14_BRTAKEN"},
{13, "R_PPC_REL14_BRNTAKEN"},
{14, "R_PPC_GOT16"},
{15, "R_PPC_GOT16_LO"},
{16, "R_PPC_GOT16_HI"},
{17, "R_PPC_GOT16_HA"},
{18, "R_PPC_PLTREL24"},
{19, "R_PPC_COPY"},
{20, "R_PPC_GLOB_DAT"},
{21, "R_PPC_JMP_SLOT"},
{22, "R_PPC_RELATIVE"},
{23, "R_PPC_LOCAL24PC"},
{24, "R_PPC_UADDR32"},
{25, "R_PPC_UADDR16"},
{26, "R_PPC_REL32"},
{27, "R_PPC_PLT32"},
{28, "R_PPC_PLTREL32"},
{29, "R_PPC_PLT16_LO"},
{30, "R_PPC_PLT16_HI"},
{31, "R_PPC_PLT16_HA"},
{32, "R_PPC_SDAREL16"},
{33, "R_PPC_SECTOFF"},
{34, "R_PPC_SECTOFF_LO"},
{35, "R_PPC_SECTOFF_HI"},
{36, "R_PPC_SECTOFF_HA"},
{67, "R_PPC_TLS"},
{68, "R_PPC_DTPMOD32"},
{69, "R_PPC_TPREL16"},
{70, "R_PPC_TPREL16_LO"},
{71, "R_PPC_TPREL16_HI"},
{72, "R_PPC_TPREL16_HA"},
{73, "R_PPC_TPREL32"},
{74, "R_PPC_DTPREL16"},
{75, "R_PPC_DTPREL16_LO"},
{76, "R_PPC_DTPREL16_HI"},
{77, "R_PPC_DTPREL16_HA"},
{78, "R_PPC_DTPREL32"},
{79, "R_PPC_GOT_TLSGD16"},
{80, "R_PPC_GOT_TLSGD16_LO"},
{81, "R_PPC_GOT_TLSGD16_HI"},
{82, "R_PPC_GOT_TLSGD16_HA"},
{83, "R_PPC_GOT_TLSLD16"},
{84, "R_PPC_GOT_TLSLD16_LO"},
{85, "R_PPC_GOT_TLSLD16_HI"},
{86, "R_PPC_GOT_TLSLD16_HA"},
{87, "R_PPC_GOT_TPREL16"},
{88, "R_PPC_GOT_TPREL16_LO"},
{89, "R_PPC_GOT_TPREL16_HI"},
{90, "R_PPC_GOT_TPREL16_HA"},
{101, "R_PPC_EMB_NADDR32"},
{102, "R_PPC_EMB_NADDR16"},
{103, "R_PPC_EMB_NADDR16_LO"},
{104, "R_PPC_EMB_NADDR16_HI"},
{105, "R_PPC_EMB_NADDR16_HA"},
{106, "R_PPC_EMB_SDAI16"},
{107, "R_PPC_EMB_SDA2I16"},
{108, "R_PPC_EMB_SDA2REL"},
{109, "R_PPC_EMB_SDA21"},
{110, "R_PPC_EMB_MRKREF"},
{111, "R_PPC_EMB_RELSEC16"},
{112, "R_PPC_EMB_RELST_LO"},
{113, "R_PPC_EMB_RELST_HI"},
{114, "R_PPC_EMB_RELST_HA"},
{115, "R_PPC_EMB_BIT_FLD"},
{116, "R_PPC_EMB_RELSDA"},
}
func (i R_PPC) String() string { return stringName(uint32(i), rppcStrings, false) }
func (i R_PPC) GoString() string { return stringName(uint32(i), rppcStrings, true) }
// Relocation types for 64-bit PowerPC or Power Architecture processors.
//
// Values that are shared by both R_PPC and R_PPC64 are prefixed with
// R_POWERPC_ in the ELF standard. For the R_PPC64 type, the relevant
// shared relocations have been renamed with the prefix R_PPC64_.
// The original name follows the value in a comment.
type R_PPC64 int
const (
R_PPC64_NONE R_PPC64 = 0 // R_POWERPC_NONE
R_PPC64_ADDR32 R_PPC64 = 1 // R_POWERPC_ADDR32
R_PPC64_ADDR24 R_PPC64 = 2 // R_POWERPC_ADDR24
R_PPC64_ADDR16 R_PPC64 = 3 // R_POWERPC_ADDR16
R_PPC64_ADDR16_LO R_PPC64 = 4 // R_POWERPC_ADDR16_LO
R_PPC64_ADDR16_HI R_PPC64 = 5 // R_POWERPC_ADDR16_HI
R_PPC64_ADDR16_HA R_PPC64 = 6 // R_POWERPC_ADDR16_HA
R_PPC64_ADDR14 R_PPC64 = 7 // R_POWERPC_ADDR14
R_PPC64_ADDR14_BRTAKEN R_PPC64 = 8 // R_POWERPC_ADDR14_BRTAKEN
R_PPC64_ADDR14_BRNTAKEN R_PPC64 = 9 // R_POWERPC_ADDR14_BRNTAKEN
R_PPC64_REL24 R_PPC64 = 10 // R_POWERPC_REL24
R_PPC64_REL14 R_PPC64 = 11 // R_POWERPC_REL14
R_PPC64_REL14_BRTAKEN R_PPC64 = 12 // R_POWERPC_REL14_BRTAKEN
R_PPC64_REL14_BRNTAKEN R_PPC64 = 13 // R_POWERPC_REL14_BRNTAKEN
R_PPC64_GOT16 R_PPC64 = 14 // R_POWERPC_GOT16
R_PPC64_GOT16_LO R_PPC64 = 15 // R_POWERPC_GOT16_LO
R_PPC64_GOT16_HI R_PPC64 = 16 // R_POWERPC_GOT16_HI
R_PPC64_GOT16_HA R_PPC64 = 17 // R_POWERPC_GOT16_HA
R_PPC64_COPY R_PPC64 = 19 // R_POWERPC_COPY
R_PPC64_GLOB_DAT R_PPC64 = 20 // R_POWERPC_GLOB_DAT
R_PPC64_JMP_SLOT R_PPC64 = 21 // R_POWERPC_JMP_SLOT
R_PPC64_RELATIVE R_PPC64 = 22 // R_POWERPC_RELATIVE
R_PPC64_UADDR32 R_PPC64 = 24 // R_POWERPC_UADDR32
R_PPC64_UADDR16 R_PPC64 = 25 // R_POWERPC_UADDR16
R_PPC64_REL32 R_PPC64 = 26 // R_POWERPC_REL32
R_PPC64_PLT32 R_PPC64 = 27 // R_POWERPC_PLT32
R_PPC64_PLTREL32 R_PPC64 = 28 // R_POWERPC_PLTREL32
R_PPC64_PLT16_LO R_PPC64 = 29 // R_POWERPC_PLT16_LO
R_PPC64_PLT16_HI R_PPC64 = 30 // R_POWERPC_PLT16_HI
R_PPC64_PLT16_HA R_PPC64 = 31 // R_POWERPC_PLT16_HA
R_PPC64_SECTOFF R_PPC64 = 33 // R_POWERPC_SECTOFF
R_PPC64_SECTOFF_LO R_PPC64 = 34 // R_POWERPC_SECTOFF_LO
R_PPC64_SECTOFF_HI R_PPC64 = 35 // R_POWERPC_SECTOFF_HI
R_PPC64_SECTOFF_HA R_PPC64 = 36 // R_POWERPC_SECTOFF_HA
R_PPC64_REL30 R_PPC64 = 37 // R_POWERPC_ADDR30
R_PPC64_ADDR64 R_PPC64 = 38
R_PPC64_ADDR16_HIGHER R_PPC64 = 39
R_PPC64_ADDR16_HIGHERA R_PPC64 = 40
R_PPC64_ADDR16_HIGHEST R_PPC64 = 41
R_PPC64_ADDR16_HIGHESTA R_PPC64 = 42
R_PPC64_UADDR64 R_PPC64 = 43
R_PPC64_REL64 R_PPC64 = 44
R_PPC64_PLT64 R_PPC64 = 45
R_PPC64_PLTREL64 R_PPC64 = 46
R_PPC64_TOC16 R_PPC64 = 47
R_PPC64_TOC16_LO R_PPC64 = 48
R_PPC64_TOC16_HI R_PPC64 = 49
R_PPC64_TOC16_HA R_PPC64 = 50
R_PPC64_TOC R_PPC64 = 51
R_PPC64_PLTGOT16 R_PPC64 = 52
R_PPC64_PLTGOT16_LO R_PPC64 = 53
R_PPC64_PLTGOT16_HI R_PPC64 = 54
R_PPC64_PLTGOT16_HA R_PPC64 = 55
R_PPC64_ADDR16_DS R_PPC64 = 56
R_PPC64_ADDR16_LO_DS R_PPC64 = 57
R_PPC64_GOT16_DS R_PPC64 = 58
R_PPC64_GOT16_LO_DS R_PPC64 = 59
R_PPC64_PLT16_LO_DS R_PPC64 = 60
R_PPC64_SECTOFF_DS R_PPC64 = 61
R_PPC64_SECTOFF_LO_DS R_PPC64 = 62
R_PPC64_TOC16_DS R_PPC64 = 63
R_PPC64_TOC16_LO_DS R_PPC64 = 64
R_PPC64_PLTGOT16_DS R_PPC64 = 65
R_PPC64_PLTGOT_LO_DS R_PPC64 = 66
R_PPC64_TLS R_PPC64 = 67 // R_POWERPC_TLS
R_PPC64_DTPMOD64 R_PPC64 = 68 // R_POWERPC_DTPMOD64
R_PPC64_TPREL16 R_PPC64 = 69 // R_POWERPC_TPREL16
R_PPC64_TPREL16_LO R_PPC64 = 70 // R_POWERPC_TPREL16_LO
R_PPC64_TPREL16_HI R_PPC64 = 71 // R_POWERPC_TPREL16_HI
R_PPC64_TPREL16_HA R_PPC64 = 72 // R_POWERPC_TPREL16_HA
R_PPC64_TPREL64 R_PPC64 = 73 // R_POWERPC_TPREL64
R_PPC64_DTPREL16 R_PPC64 = 74 // R_POWERPC_DTPREL16
R_PPC64_DTPREL16_LO R_PPC64 = 75 // R_POWERPC_DTPREL16_LO
R_PPC64_DTPREL16_HI R_PPC64 = 76 // R_POWERPC_DTPREL16_HI
R_PPC64_DTPREL16_HA R_PPC64 = 77 // R_POWERPC_DTPREL16_HA
R_PPC64_DTPREL64 R_PPC64 = 78 // R_POWERPC_DTPREL64
R_PPC64_GOT_TLSGD16 R_PPC64 = 79 // R_POWERPC_GOT_TLSGD16
R_PPC64_GOT_TLSGD16_LO R_PPC64 = 80 // R_POWERPC_GOT_TLSGD16_LO
R_PPC64_GOT_TLSGD16_HI R_PPC64 = 81 // R_POWERPC_GOT_TLSGD16_HI
R_PPC64_GOT_TLSGD16_HA R_PPC64 = 82 // R_POWERPC_GOT_TLSGD16_HA
R_PPC64_GOT_TLSLD16 R_PPC64 = 83 // R_POWERPC_GOT_TLSLD16
R_PPC64_GOT_TLSLD16_LO R_PPC64 = 84 // R_POWERPC_GOT_TLSLD16_LO
R_PPC64_GOT_TLSLD16_HI R_PPC64 = 85 // R_POWERPC_GOT_TLSLD16_HI
R_PPC64_GOT_TLSLD16_HA R_PPC64 = 86 // R_POWERPC_GOT_TLSLD16_HA
R_PPC64_GOT_TPREL16_DS R_PPC64 = 87 // R_POWERPC_GOT_TPREL16_DS
R_PPC64_GOT_TPREL16_LO_DS R_PPC64 = 88 // R_POWERPC_GOT_TPREL16_LO_DS
R_PPC64_GOT_TPREL16_HI R_PPC64 = 89 // R_POWERPC_GOT_TPREL16_HI
R_PPC64_GOT_TPREL16_HA R_PPC64 = 90 // R_POWERPC_GOT_TPREL16_HA
R_PPC64_GOT_DTPREL16_DS R_PPC64 = 91 // R_POWERPC_GOT_DTPREL16_DS
R_PPC64_GOT_DTPREL16_LO_DS R_PPC64 = 92 // R_POWERPC_GOT_DTPREL16_LO_DS
R_PPC64_GOT_DTPREL16_HI R_PPC64 = 93 // R_POWERPC_GOT_DTPREL16_HI
R_PPC64_GOT_DTPREL16_HA R_PPC64 = 94 // R_POWERPC_GOT_DTPREL16_HA
R_PPC64_TPREL16_DS R_PPC64 = 95
R_PPC64_TPREL16_LO_DS R_PPC64 = 96
R_PPC64_TPREL16_HIGHER R_PPC64 = 97
R_PPC64_TPREL16_HIGHERA R_PPC64 = 98
R_PPC64_TPREL16_HIGHEST R_PPC64 = 99
R_PPC64_TPREL16_HIGHESTA R_PPC64 = 100
R_PPC64_DTPREL16_DS R_PPC64 = 101
R_PPC64_DTPREL16_LO_DS R_PPC64 = 102
R_PPC64_DTPREL16_HIGHER R_PPC64 = 103
R_PPC64_DTPREL16_HIGHERA R_PPC64 = 104
R_PPC64_DTPREL16_HIGHEST R_PPC64 = 105
R_PPC64_DTPREL16_HIGHESTA R_PPC64 = 106
R_PPC64_TLSGD R_PPC64 = 107
R_PPC64_TLSLD R_PPC64 = 108
R_PPC64_TOCSAVE R_PPC64 = 109
R_PPC64_ADDR16_HIGH R_PPC64 = 110
R_PPC64_ADDR16_HIGHA R_PPC64 = 111
R_PPC64_TPREL16_HIGH R_PPC64 = 112
R_PPC64_TPREL16_HIGHA R_PPC64 = 113
R_PPC64_DTPREL16_HIGH R_PPC64 = 114
R_PPC64_DTPREL16_HIGHA R_PPC64 = 115
R_PPC64_REL24_NOTOC R_PPC64 = 116
R_PPC64_ADDR64_LOCAL R_PPC64 = 117
R_PPC64_ENTRY R_PPC64 = 118
R_PPC64_PLTSEQ R_PPC64 = 119
R_PPC64_PLTCALL R_PPC64 = 120
R_PPC64_PLTSEQ_NOTOC R_PPC64 = 121
R_PPC64_PLTCALL_NOTOC R_PPC64 = 122
R_PPC64_PCREL_OPT R_PPC64 = 123
R_PPC64_REL24_P9NOTOC R_PPC64 = 124
R_PPC64_D34 R_PPC64 = 128
R_PPC64_D34_LO R_PPC64 = 129
R_PPC64_D34_HI30 R_PPC64 = 130
R_PPC64_D34_HA30 R_PPC64 = 131
R_PPC64_PCREL34 R_PPC64 = 132
R_PPC64_GOT_PCREL34 R_PPC64 = 133
R_PPC64_PLT_PCREL34 R_PPC64 = 134
R_PPC64_PLT_PCREL34_NOTOC R_PPC64 = 135
R_PPC64_ADDR16_HIGHER34 R_PPC64 = 136
R_PPC64_ADDR16_HIGHERA34 R_PPC64 = 137
R_PPC64_ADDR16_HIGHEST34 R_PPC64 = 138
R_PPC64_ADDR16_HIGHESTA34 R_PPC64 = 139
R_PPC64_REL16_HIGHER34 R_PPC64 = 140
R_PPC64_REL16_HIGHERA34 R_PPC64 = 141
R_PPC64_REL16_HIGHEST34 R_PPC64 = 142
R_PPC64_REL16_HIGHESTA34 R_PPC64 = 143
R_PPC64_D28 R_PPC64 = 144
R_PPC64_PCREL28 R_PPC64 = 145
R_PPC64_TPREL34 R_PPC64 = 146
R_PPC64_DTPREL34 R_PPC64 = 147
R_PPC64_GOT_TLSGD_PCREL34 R_PPC64 = 148
R_PPC64_GOT_TLSLD_PCREL34 R_PPC64 = 149
R_PPC64_GOT_TPREL_PCREL34 R_PPC64 = 150
R_PPC64_GOT_DTPREL_PCREL34 R_PPC64 = 151
R_PPC64_REL16_HIGH R_PPC64 = 240
R_PPC64_REL16_HIGHA R_PPC64 = 241
R_PPC64_REL16_HIGHER R_PPC64 = 242
R_PPC64_REL16_HIGHERA R_PPC64 = 243
R_PPC64_REL16_HIGHEST R_PPC64 = 244
R_PPC64_REL16_HIGHESTA R_PPC64 = 245
R_PPC64_REL16DX_HA R_PPC64 = 246 // R_POWERPC_REL16DX_HA
R_PPC64_JMP_IREL R_PPC64 = 247
R_PPC64_IRELATIVE R_PPC64 = 248 // R_POWERPC_IRELATIVE
R_PPC64_REL16 R_PPC64 = 249 // R_POWERPC_REL16
R_PPC64_REL16_LO R_PPC64 = 250 // R_POWERPC_REL16_LO
R_PPC64_REL16_HI R_PPC64 = 251 // R_POWERPC_REL16_HI
R_PPC64_REL16_HA R_PPC64 = 252 // R_POWERPC_REL16_HA
R_PPC64_GNU_VTINHERIT R_PPC64 = 253
R_PPC64_GNU_VTENTRY R_PPC64 = 254
)
var rppc64Strings = []intName{
{0, "R_PPC64_NONE"},
{1, "R_PPC64_ADDR32"},
{2, "R_PPC64_ADDR24"},
{3, "R_PPC64_ADDR16"},
{4, "R_PPC64_ADDR16_LO"},
{5, "R_PPC64_ADDR16_HI"},
{6, "R_PPC64_ADDR16_HA"},
{7, "R_PPC64_ADDR14"},
{8, "R_PPC64_ADDR14_BRTAKEN"},
{9, "R_PPC64_ADDR14_BRNTAKEN"},
{10, "R_PPC64_REL24"},
{11, "R_PPC64_REL14"},
{12, "R_PPC64_REL14_BRTAKEN"},
{13, "R_PPC64_REL14_BRNTAKEN"},
{14, "R_PPC64_GOT16"},
{15, "R_PPC64_GOT16_LO"},
{16, "R_PPC64_GOT16_HI"},
{17, "R_PPC64_GOT16_HA"},
{19, "R_PPC64_COPY"},
{20, "R_PPC64_GLOB_DAT"},
{21, "R_PPC64_JMP_SLOT"},
{22, "R_PPC64_RELATIVE"},
{24, "R_PPC64_UADDR32"},
{25, "R_PPC64_UADDR16"},
{26, "R_PPC64_REL32"},
{27, "R_PPC64_PLT32"},
{28, "R_PPC64_PLTREL32"},
{29, "R_PPC64_PLT16_LO"},
{30, "R_PPC64_PLT16_HI"},
{31, "R_PPC64_PLT16_HA"},
{33, "R_PPC64_SECTOFF"},
{34, "R_PPC64_SECTOFF_LO"},
{35, "R_PPC64_SECTOFF_HI"},
{36, "R_PPC64_SECTOFF_HA"},
{37, "R_PPC64_REL30"},
{38, "R_PPC64_ADDR64"},
{39, "R_PPC64_ADDR16_HIGHER"},
{40, "R_PPC64_ADDR16_HIGHERA"},
{41, "R_PPC64_ADDR16_HIGHEST"},
{42, "R_PPC64_ADDR16_HIGHESTA"},
{43, "R_PPC64_UADDR64"},
{44, "R_PPC64_REL64"},
{45, "R_PPC64_PLT64"},
{46, "R_PPC64_PLTREL64"},
{47, "R_PPC64_TOC16"},
{48, "R_PPC64_TOC16_LO"},
{49, "R_PPC64_TOC16_HI"},
{50, "R_PPC64_TOC16_HA"},
{51, "R_PPC64_TOC"},
{52, "R_PPC64_PLTGOT16"},
{53, "R_PPC64_PLTGOT16_LO"},
{54, "R_PPC64_PLTGOT16_HI"},
{55, "R_PPC64_PLTGOT16_HA"},
{56, "R_PPC64_ADDR16_DS"},
{57, "R_PPC64_ADDR16_LO_DS"},
{58, "R_PPC64_GOT16_DS"},
{59, "R_PPC64_GOT16_LO_DS"},
{60, "R_PPC64_PLT16_LO_DS"},
{61, "R_PPC64_SECTOFF_DS"},
{62, "R_PPC64_SECTOFF_LO_DS"},
{63, "R_PPC64_TOC16_DS"},
{64, "R_PPC64_TOC16_LO_DS"},
{65, "R_PPC64_PLTGOT16_DS"},
{66, "R_PPC64_PLTGOT_LO_DS"},
{67, "R_PPC64_TLS"},
{68, "R_PPC64_DTPMOD64"},
{69, "R_PPC64_TPREL16"},
{70, "R_PPC64_TPREL16_LO"},
{71, "R_PPC64_TPREL16_HI"},
{72, "R_PPC64_TPREL16_HA"},
{73, "R_PPC64_TPREL64"},
{74, "R_PPC64_DTPREL16"},
{75, "R_PPC64_DTPREL16_LO"},
{76, "R_PPC64_DTPREL16_HI"},
{77, "R_PPC64_DTPREL16_HA"},
{78, "R_PPC64_DTPREL64"},
{79, "R_PPC64_GOT_TLSGD16"},
{80, "R_PPC64_GOT_TLSGD16_LO"},
{81, "R_PPC64_GOT_TLSGD16_HI"},
{82, "R_PPC64_GOT_TLSGD16_HA"},
{83, "R_PPC64_GOT_TLSLD16"},
{84, "R_PPC64_GOT_TLSLD16_LO"},
{85, "R_PPC64_GOT_TLSLD16_HI"},
{86, "R_PPC64_GOT_TLSLD16_HA"},
{87, "R_PPC64_GOT_TPREL16_DS"},
{88, "R_PPC64_GOT_TPREL16_LO_DS"},
{89, "R_PPC64_GOT_TPREL16_HI"},
{90, "R_PPC64_GOT_TPREL16_HA"},
{91, "R_PPC64_GOT_DTPREL16_DS"},
{92, "R_PPC64_GOT_DTPREL16_LO_DS"},
{93, "R_PPC64_GOT_DTPREL16_HI"},
{94, "R_PPC64_GOT_DTPREL16_HA"},
{95, "R_PPC64_TPREL16_DS"},
{96, "R_PPC64_TPREL16_LO_DS"},
{97, "R_PPC64_TPREL16_HIGHER"},
{98, "R_PPC64_TPREL16_HIGHERA"},
{99, "R_PPC64_TPREL16_HIGHEST"},
{100, "R_PPC64_TPREL16_HIGHESTA"},
{101, "R_PPC64_DTPREL16_DS"},
{102, "R_PPC64_DTPREL16_LO_DS"},
{103, "R_PPC64_DTPREL16_HIGHER"},
{104, "R_PPC64_DTPREL16_HIGHERA"},
{105, "R_PPC64_DTPREL16_HIGHEST"},
{106, "R_PPC64_DTPREL16_HIGHESTA"},
{107, "R_PPC64_TLSGD"},
{108, "R_PPC64_TLSLD"},
{109, "R_PPC64_TOCSAVE"},
{110, "R_PPC64_ADDR16_HIGH"},
{111, "R_PPC64_ADDR16_HIGHA"},
{112, "R_PPC64_TPREL16_HIGH"},
{113, "R_PPC64_TPREL16_HIGHA"},
{114, "R_PPC64_DTPREL16_HIGH"},
{115, "R_PPC64_DTPREL16_HIGHA"},
{116, "R_PPC64_REL24_NOTOC"},
{117, "R_PPC64_ADDR64_LOCAL"},
{118, "R_PPC64_ENTRY"},
{119, "R_PPC64_PLTSEQ"},
{120, "R_PPC64_PLTCALL"},
{121, "R_PPC64_PLTSEQ_NOTOC"},
{122, "R_PPC64_PLTCALL_NOTOC"},
{123, "R_PPC64_PCREL_OPT"},
{124, "R_PPC64_REL24_P9NOTOC"},
{128, "R_PPC64_D34"},
{129, "R_PPC64_D34_LO"},
{130, "R_PPC64_D34_HI30"},
{131, "R_PPC64_D34_HA30"},
{132, "R_PPC64_PCREL34"},
{133, "R_PPC64_GOT_PCREL34"},
{134, "R_PPC64_PLT_PCREL34"},
{135, "R_PPC64_PLT_PCREL34_NOTOC"},
{136, "R_PPC64_ADDR16_HIGHER34"},
{137, "R_PPC64_ADDR16_HIGHERA34"},
{138, "R_PPC64_ADDR16_HIGHEST34"},
{139, "R_PPC64_ADDR16_HIGHESTA34"},
{140, "R_PPC64_REL16_HIGHER34"},
{141, "R_PPC64_REL16_HIGHERA34"},
{142, "R_PPC64_REL16_HIGHEST34"},
{143, "R_PPC64_REL16_HIGHESTA34"},
{144, "R_PPC64_D28"},
{145, "R_PPC64_PCREL28"},
{146, "R_PPC64_TPREL34"},
{147, "R_PPC64_DTPREL34"},
{148, "R_PPC64_GOT_TLSGD_PCREL34"},
{149, "R_PPC64_GOT_TLSLD_PCREL34"},
{150, "R_PPC64_GOT_TPREL_PCREL34"},
{151, "R_PPC64_GOT_DTPREL_PCREL34"},
{240, "R_PPC64_REL16_HIGH"},
{241, "R_PPC64_REL16_HIGHA"},
{242, "R_PPC64_REL16_HIGHER"},
{243, "R_PPC64_REL16_HIGHERA"},
{244, "R_PPC64_REL16_HIGHEST"},
{245, "R_PPC64_REL16_HIGHESTA"},
{246, "R_PPC64_REL16DX_HA"},
{247, "R_PPC64_JMP_IREL"},
{248, "R_PPC64_IRELATIVE"},
{249, "R_PPC64_REL16"},
{250, "R_PPC64_REL16_LO"},
{251, "R_PPC64_REL16_HI"},
{252, "R_PPC64_REL16_HA"},
{253, "R_PPC64_GNU_VTINHERIT"},
{254, "R_PPC64_GNU_VTENTRY"},
}
func (i R_PPC64) String() string { return stringName(uint32(i), rppc64Strings, false) }
func (i R_PPC64) GoString() string { return stringName(uint32(i), rppc64Strings, true) }
// Relocation types for RISC-V processors.
type R_RISCV int
const (
R_RISCV_NONE R_RISCV = 0 /* No relocation. */
R_RISCV_32 R_RISCV = 1 /* Add 32 bit zero extended symbol value */
R_RISCV_64 R_RISCV = 2 /* Add 64 bit symbol value. */
R_RISCV_RELATIVE R_RISCV = 3 /* Add load address of shared object. */
R_RISCV_COPY R_RISCV = 4 /* Copy data from shared object. */
R_RISCV_JUMP_SLOT R_RISCV = 5 /* Set GOT entry to code address. */
R_RISCV_TLS_DTPMOD32 R_RISCV = 6 /* 32 bit ID of module containing symbol */
R_RISCV_TLS_DTPMOD64 R_RISCV = 7 /* ID of module containing symbol */
R_RISCV_TLS_DTPREL32 R_RISCV = 8 /* 32 bit relative offset in TLS block */
R_RISCV_TLS_DTPREL64 R_RISCV = 9 /* Relative offset in TLS block */
R_RISCV_TLS_TPREL32 R_RISCV = 10 /* 32 bit relative offset in static TLS block */
R_RISCV_TLS_TPREL64 R_RISCV = 11 /* Relative offset in static TLS block */
R_RISCV_BRANCH R_RISCV = 16 /* PC-relative branch */
R_RISCV_JAL R_RISCV = 17 /* PC-relative jump */
R_RISCV_CALL R_RISCV = 18 /* PC-relative call */
R_RISCV_CALL_PLT R_RISCV = 19 /* PC-relative call (PLT) */
R_RISCV_GOT_HI20 R_RISCV = 20 /* PC-relative GOT reference */
R_RISCV_TLS_GOT_HI20 R_RISCV = 21 /* PC-relative TLS IE GOT offset */
R_RISCV_TLS_GD_HI20 R_RISCV = 22 /* PC-relative TLS GD reference */
R_RISCV_PCREL_HI20 R_RISCV = 23 /* PC-relative reference */
R_RISCV_PCREL_LO12_I R_RISCV = 24 /* PC-relative reference */
R_RISCV_PCREL_LO12_S R_RISCV = 25 /* PC-relative reference */
R_RISCV_HI20 R_RISCV = 26 /* Absolute address */
R_RISCV_LO12_I R_RISCV = 27 /* Absolute address */
R_RISCV_LO12_S R_RISCV = 28 /* Absolute address */
R_RISCV_TPREL_HI20 R_RISCV = 29 /* TLS LE thread offset */
R_RISCV_TPREL_LO12_I R_RISCV = 30 /* TLS LE thread offset */
R_RISCV_TPREL_LO12_S R_RISCV = 31 /* TLS LE thread offset */
R_RISCV_TPREL_ADD R_RISCV = 32 /* TLS LE thread usage */
R_RISCV_ADD8 R_RISCV = 33 /* 8-bit label addition */
R_RISCV_ADD16 R_RISCV = 34 /* 16-bit label addition */
R_RISCV_ADD32 R_RISCV = 35 /* 32-bit label addition */
R_RISCV_ADD64 R_RISCV = 36 /* 64-bit label addition */
R_RISCV_SUB8 R_RISCV = 37 /* 8-bit label subtraction */
R_RISCV_SUB16 R_RISCV = 38 /* 16-bit label subtraction */
R_RISCV_SUB32 R_RISCV = 39 /* 32-bit label subtraction */
R_RISCV_SUB64 R_RISCV = 40 /* 64-bit label subtraction */
R_RISCV_GNU_VTINHERIT R_RISCV = 41 /* GNU C++ vtable hierarchy */
R_RISCV_GNU_VTENTRY R_RISCV = 42 /* GNU C++ vtable member usage */
R_RISCV_ALIGN R_RISCV = 43 /* Alignment statement */
R_RISCV_RVC_BRANCH R_RISCV = 44 /* PC-relative branch offset */
R_RISCV_RVC_JUMP R_RISCV = 45 /* PC-relative jump offset */
R_RISCV_RVC_LUI R_RISCV = 46 /* Absolute address */
R_RISCV_GPREL_I R_RISCV = 47 /* GP-relative reference */
R_RISCV_GPREL_S R_RISCV = 48 /* GP-relative reference */
R_RISCV_TPREL_I R_RISCV = 49 /* TP-relative TLS LE load */
R_RISCV_TPREL_S R_RISCV = 50 /* TP-relative TLS LE store */
R_RISCV_RELAX R_RISCV = 51 /* Instruction pair can be relaxed */
R_RISCV_SUB6 R_RISCV = 52 /* Local label subtraction */
R_RISCV_SET6 R_RISCV = 53 /* Local label subtraction */
R_RISCV_SET8 R_RISCV = 54 /* Local label subtraction */
R_RISCV_SET16 R_RISCV = 55 /* Local label subtraction */
R_RISCV_SET32 R_RISCV = 56 /* Local label subtraction */
R_RISCV_32_PCREL R_RISCV = 57 /* 32-bit PC relative */
)
var rriscvStrings = []intName{
{0, "R_RISCV_NONE"},
{1, "R_RISCV_32"},
{2, "R_RISCV_64"},
{3, "R_RISCV_RELATIVE"},
{4, "R_RISCV_COPY"},
{5, "R_RISCV_JUMP_SLOT"},
{6, "R_RISCV_TLS_DTPMOD32"},
{7, "R_RISCV_TLS_DTPMOD64"},
{8, "R_RISCV_TLS_DTPREL32"},
{9, "R_RISCV_TLS_DTPREL64"},
{10, "R_RISCV_TLS_TPREL32"},
{11, "R_RISCV_TLS_TPREL64"},
{16, "R_RISCV_BRANCH"},
{17, "R_RISCV_JAL"},
{18, "R_RISCV_CALL"},
{19, "R_RISCV_CALL_PLT"},
{20, "R_RISCV_GOT_HI20"},
{21, "R_RISCV_TLS_GOT_HI20"},
{22, "R_RISCV_TLS_GD_HI20"},
{23, "R_RISCV_PCREL_HI20"},
{24, "R_RISCV_PCREL_LO12_I"},
{25, "R_RISCV_PCREL_LO12_S"},
{26, "R_RISCV_HI20"},
{27, "R_RISCV_LO12_I"},
{28, "R_RISCV_LO12_S"},
{29, "R_RISCV_TPREL_HI20"},
{30, "R_RISCV_TPREL_LO12_I"},
{31, "R_RISCV_TPREL_LO12_S"},
{32, "R_RISCV_TPREL_ADD"},
{33, "R_RISCV_ADD8"},
{34, "R_RISCV_ADD16"},
{35, "R_RISCV_ADD32"},
{36, "R_RISCV_ADD64"},
{37, "R_RISCV_SUB8"},
{38, "R_RISCV_SUB16"},
{39, "R_RISCV_SUB32"},
{40, "R_RISCV_SUB64"},
{41, "R_RISCV_GNU_VTINHERIT"},
{42, "R_RISCV_GNU_VTENTRY"},
{43, "R_RISCV_ALIGN"},
{44, "R_RISCV_RVC_BRANCH"},
{45, "R_RISCV_RVC_JUMP"},
{46, "R_RISCV_RVC_LUI"},
{47, "R_RISCV_GPREL_I"},
{48, "R_RISCV_GPREL_S"},
{49, "R_RISCV_TPREL_I"},
{50, "R_RISCV_TPREL_S"},
{51, "R_RISCV_RELAX"},
{52, "R_RISCV_SUB6"},
{53, "R_RISCV_SET6"},
{54, "R_RISCV_SET8"},
{55, "R_RISCV_SET16"},
{56, "R_RISCV_SET32"},
{57, "R_RISCV_32_PCREL"},
}
func (i R_RISCV) String() string { return stringName(uint32(i), rriscvStrings, false) }
func (i R_RISCV) GoString() string { return stringName(uint32(i), rriscvStrings, true) }
// Relocation types for s390x processors.
type R_390 int
const (
R_390_NONE R_390 = 0
R_390_8 R_390 = 1
R_390_12 R_390 = 2
R_390_16 R_390 = 3
R_390_32 R_390 = 4
R_390_PC32 R_390 = 5
R_390_GOT12 R_390 = 6
R_390_GOT32 R_390 = 7
R_390_PLT32 R_390 = 8
R_390_COPY R_390 = 9
R_390_GLOB_DAT R_390 = 10
R_390_JMP_SLOT R_390 = 11
R_390_RELATIVE R_390 = 12
R_390_GOTOFF R_390 = 13
R_390_GOTPC R_390 = 14
R_390_GOT16 R_390 = 15
R_390_PC16 R_390 = 16
R_390_PC16DBL R_390 = 17
R_390_PLT16DBL R_390 = 18
R_390_PC32DBL R_390 = 19
R_390_PLT32DBL R_390 = 20
R_390_GOTPCDBL R_390 = 21
R_390_64 R_390 = 22
R_390_PC64 R_390 = 23
R_390_GOT64 R_390 = 24
R_390_PLT64 R_390 = 25
R_390_GOTENT R_390 = 26
R_390_GOTOFF16 R_390 = 27
R_390_GOTOFF64 R_390 = 28
R_390_GOTPLT12 R_390 = 29
R_390_GOTPLT16 R_390 = 30
R_390_GOTPLT32 R_390 = 31
R_390_GOTPLT64 R_390 = 32
R_390_GOTPLTENT R_390 = 33
R_390_GOTPLTOFF16 R_390 = 34
R_390_GOTPLTOFF32 R_390 = 35
R_390_GOTPLTOFF64 R_390 = 36
R_390_TLS_LOAD R_390 = 37
R_390_TLS_GDCALL R_390 = 38
R_390_TLS_LDCALL R_390 = 39
R_390_TLS_GD32 R_390 = 40
R_390_TLS_GD64 R_390 = 41
R_390_TLS_GOTIE12 R_390 = 42
R_390_TLS_GOTIE32 R_390 = 43
R_390_TLS_GOTIE64 R_390 = 44
R_390_TLS_LDM32 R_390 = 45
R_390_TLS_LDM64 R_390 = 46
R_390_TLS_IE32 R_390 = 47
R_390_TLS_IE64 R_390 = 48
R_390_TLS_IEENT R_390 = 49
R_390_TLS_LE32 R_390 = 50
R_390_TLS_LE64 R_390 = 51
R_390_TLS_LDO32 R_390 = 52
R_390_TLS_LDO64 R_390 = 53
R_390_TLS_DTPMOD R_390 = 54
R_390_TLS_DTPOFF R_390 = 55
R_390_TLS_TPOFF R_390 = 56
R_390_20 R_390 = 57
R_390_GOT20 R_390 = 58
R_390_GOTPLT20 R_390 = 59
R_390_TLS_GOTIE20 R_390 = 60
)
var r390Strings = []intName{
{0, "R_390_NONE"},
{1, "R_390_8"},
{2, "R_390_12"},
{3, "R_390_16"},
{4, "R_390_32"},
{5, "R_390_PC32"},
{6, "R_390_GOT12"},
{7, "R_390_GOT32"},
{8, "R_390_PLT32"},
{9, "R_390_COPY"},
{10, "R_390_GLOB_DAT"},
{11, "R_390_JMP_SLOT"},
{12, "R_390_RELATIVE"},
{13, "R_390_GOTOFF"},
{14, "R_390_GOTPC"},
{15, "R_390_GOT16"},
{16, "R_390_PC16"},
{17, "R_390_PC16DBL"},
{18, "R_390_PLT16DBL"},
{19, "R_390_PC32DBL"},
{20, "R_390_PLT32DBL"},
{21, "R_390_GOTPCDBL"},
{22, "R_390_64"},
{23, "R_390_PC64"},
{24, "R_390_GOT64"},
{25, "R_390_PLT64"},
{26, "R_390_GOTENT"},
{27, "R_390_GOTOFF16"},
{28, "R_390_GOTOFF64"},
{29, "R_390_GOTPLT12"},
{30, "R_390_GOTPLT16"},
{31, "R_390_GOTPLT32"},
{32, "R_390_GOTPLT64"},
{33, "R_390_GOTPLTENT"},
{34, "R_390_GOTPLTOFF16"},
{35, "R_390_GOTPLTOFF32"},
{36, "R_390_GOTPLTOFF64"},
{37, "R_390_TLS_LOAD"},
{38, "R_390_TLS_GDCALL"},
{39, "R_390_TLS_LDCALL"},
{40, "R_390_TLS_GD32"},
{41, "R_390_TLS_GD64"},
{42, "R_390_TLS_GOTIE12"},
{43, "R_390_TLS_GOTIE32"},
{44, "R_390_TLS_GOTIE64"},
{45, "R_390_TLS_LDM32"},
{46, "R_390_TLS_LDM64"},
{47, "R_390_TLS_IE32"},
{48, "R_390_TLS_IE64"},
{49, "R_390_TLS_IEENT"},
{50, "R_390_TLS_LE32"},
{51, "R_390_TLS_LE64"},
{52, "R_390_TLS_LDO32"},
{53, "R_390_TLS_LDO64"},
{54, "R_390_TLS_DTPMOD"},
{55, "R_390_TLS_DTPOFF"},
{56, "R_390_TLS_TPOFF"},
{57, "R_390_20"},
{58, "R_390_GOT20"},
{59, "R_390_GOTPLT20"},
{60, "R_390_TLS_GOTIE20"},
}
func (i R_390) String() string { return stringName(uint32(i), r390Strings, false) }
func (i R_390) GoString() string { return stringName(uint32(i), r390Strings, true) }
// Relocation types for SPARC.
type R_SPARC int
const (
R_SPARC_NONE R_SPARC = 0
R_SPARC_8 R_SPARC = 1
R_SPARC_16 R_SPARC = 2
R_SPARC_32 R_SPARC = 3
R_SPARC_DISP8 R_SPARC = 4
R_SPARC_DISP16 R_SPARC = 5
R_SPARC_DISP32 R_SPARC = 6
R_SPARC_WDISP30 R_SPARC = 7
R_SPARC_WDISP22 R_SPARC = 8
R_SPARC_HI22 R_SPARC = 9
R_SPARC_22 R_SPARC = 10
R_SPARC_13 R_SPARC = 11
R_SPARC_LO10 R_SPARC = 12
R_SPARC_GOT10 R_SPARC = 13
R_SPARC_GOT13 R_SPARC = 14
R_SPARC_GOT22 R_SPARC = 15
R_SPARC_PC10 R_SPARC = 16
R_SPARC_PC22 R_SPARC = 17
R_SPARC_WPLT30 R_SPARC = 18
R_SPARC_COPY R_SPARC = 19
R_SPARC_GLOB_DAT R_SPARC = 20
R_SPARC_JMP_SLOT R_SPARC = 21
R_SPARC_RELATIVE R_SPARC = 22
R_SPARC_UA32 R_SPARC = 23
R_SPARC_PLT32 R_SPARC = 24
R_SPARC_HIPLT22 R_SPARC = 25
R_SPARC_LOPLT10 R_SPARC = 26
R_SPARC_PCPLT32 R_SPARC = 27
R_SPARC_PCPLT22 R_SPARC = 28
R_SPARC_PCPLT10 R_SPARC = 29
R_SPARC_10 R_SPARC = 30
R_SPARC_11 R_SPARC = 31
R_SPARC_64 R_SPARC = 32
R_SPARC_OLO10 R_SPARC = 33
R_SPARC_HH22 R_SPARC = 34
R_SPARC_HM10 R_SPARC = 35
R_SPARC_LM22 R_SPARC = 36
R_SPARC_PC_HH22 R_SPARC = 37
R_SPARC_PC_HM10 R_SPARC = 38
R_SPARC_PC_LM22 R_SPARC = 39
R_SPARC_WDISP16 R_SPARC = 40
R_SPARC_WDISP19 R_SPARC = 41
R_SPARC_GLOB_JMP R_SPARC = 42
R_SPARC_7 R_SPARC = 43
R_SPARC_5 R_SPARC = 44
R_SPARC_6 R_SPARC = 45
R_SPARC_DISP64 R_SPARC = 46
R_SPARC_PLT64 R_SPARC = 47
R_SPARC_HIX22 R_SPARC = 48
R_SPARC_LOX10 R_SPARC = 49
R_SPARC_H44 R_SPARC = 50
R_SPARC_M44 R_SPARC = 51
R_SPARC_L44 R_SPARC = 52
R_SPARC_REGISTER R_SPARC = 53
R_SPARC_UA64 R_SPARC = 54
R_SPARC_UA16 R_SPARC = 55
)
var rsparcStrings = []intName{
{0, "R_SPARC_NONE"},
{1, "R_SPARC_8"},
{2, "R_SPARC_16"},
{3, "R_SPARC_32"},
{4, "R_SPARC_DISP8"},
{5, "R_SPARC_DISP16"},
{6, "R_SPARC_DISP32"},
{7, "R_SPARC_WDISP30"},
{8, "R_SPARC_WDISP22"},
{9, "R_SPARC_HI22"},
{10, "R_SPARC_22"},
{11, "R_SPARC_13"},
{12, "R_SPARC_LO10"},
{13, "R_SPARC_GOT10"},
{14, "R_SPARC_GOT13"},
{15, "R_SPARC_GOT22"},
{16, "R_SPARC_PC10"},
{17, "R_SPARC_PC22"},
{18, "R_SPARC_WPLT30"},
{19, "R_SPARC_COPY"},
{20, "R_SPARC_GLOB_DAT"},
{21, "R_SPARC_JMP_SLOT"},
{22, "R_SPARC_RELATIVE"},
{23, "R_SPARC_UA32"},
{24, "R_SPARC_PLT32"},
{25, "R_SPARC_HIPLT22"},
{26, "R_SPARC_LOPLT10"},
{27, "R_SPARC_PCPLT32"},
{28, "R_SPARC_PCPLT22"},
{29, "R_SPARC_PCPLT10"},
{30, "R_SPARC_10"},
{31, "R_SPARC_11"},
{32, "R_SPARC_64"},
{33, "R_SPARC_OLO10"},
{34, "R_SPARC_HH22"},
{35, "R_SPARC_HM10"},
{36, "R_SPARC_LM22"},
{37, "R_SPARC_PC_HH22"},
{38, "R_SPARC_PC_HM10"},
{39, "R_SPARC_PC_LM22"},
{40, "R_SPARC_WDISP16"},
{41, "R_SPARC_WDISP19"},
{42, "R_SPARC_GLOB_JMP"},
{43, "R_SPARC_7"},
{44, "R_SPARC_5"},
{45, "R_SPARC_6"},
{46, "R_SPARC_DISP64"},
{47, "R_SPARC_PLT64"},
{48, "R_SPARC_HIX22"},
{49, "R_SPARC_LOX10"},
{50, "R_SPARC_H44"},
{51, "R_SPARC_M44"},
{52, "R_SPARC_L44"},
{53, "R_SPARC_REGISTER"},
{54, "R_SPARC_UA64"},
{55, "R_SPARC_UA16"},
}
func (i R_SPARC) String() string { return stringName(uint32(i), rsparcStrings, false) }
func (i R_SPARC) GoString() string { return stringName(uint32(i), rsparcStrings, true) }
// Magic number for the elf trampoline, chosen wisely to be an immediate value.
const ARM_MAGIC_TRAMP_NUMBER = 0x5c000003
// ELF32 File header.
type Header32 struct {
Ident [EI_NIDENT]byte /* File identification. */
Type uint16 /* File type. */
Machine uint16 /* Machine architecture. */
Version uint32 /* ELF format version. */
Entry uint32 /* Entry point. */
Phoff uint32 /* Program header file offset. */
Shoff uint32 /* Section header file offset. */
Flags uint32 /* Architecture-specific flags. */
Ehsize uint16 /* Size of ELF header in bytes. */
Phentsize uint16 /* Size of program header entry. */
Phnum uint16 /* Number of program header entries. */
Shentsize uint16 /* Size of section header entry. */
Shnum uint16 /* Number of section header entries. */
Shstrndx uint16 /* Section name strings section. */
}
// ELF32 Section header.
type Section32 struct {
Name uint32 /* Section name (index into the section header string table). */
Type uint32 /* Section type. */
Flags uint32 /* Section flags. */
Addr uint32 /* Address in memory image. */
Off uint32 /* Offset in file. */
Size uint32 /* Size in bytes. */
Link uint32 /* Index of a related section. */
Info uint32 /* Depends on section type. */
Addralign uint32 /* Alignment in bytes. */
Entsize uint32 /* Size of each entry in section. */
}
// ELF32 Program header.
type Prog32 struct {
Type uint32 /* Entry type. */
Off uint32 /* File offset of contents. */
Vaddr uint32 /* Virtual address in memory image. */
Paddr uint32 /* Physical address (not used). */
Filesz uint32 /* Size of contents in file. */
Memsz uint32 /* Size of contents in memory. */
Flags uint32 /* Access permission flags. */
Align uint32 /* Alignment in memory and file. */
}
// ELF32 Dynamic structure. The ".dynamic" section contains an array of them.
type Dyn32 struct {
Tag int32 /* Entry type. */
Val uint32 /* Integer/Address value. */
}
// ELF32 Compression header.
type Chdr32 struct {
Type uint32
Size uint32
Addralign uint32
}
/*
* Relocation entries.
*/
// ELF32 Relocations that don't need an addend field.
type Rel32 struct {
Off uint32 /* Location to be relocated. */
Info uint32 /* Relocation type and symbol index. */
}
// ELF32 Relocations that need an addend field.
type Rela32 struct {
Off uint32 /* Location to be relocated. */
Info uint32 /* Relocation type and symbol index. */
Addend int32 /* Addend. */
}
func R_SYM32(info uint32) uint32 { return info >> 8 }
func R_TYPE32(info uint32) uint32 { return info & 0xff }
func R_INFO32(sym, typ uint32) uint32 { return sym<<8 | typ }
// ELF32 Symbol.
type Sym32 struct {
Name uint32
Value uint32
Size uint32
Info uint8
Other uint8
Shndx uint16
}
const Sym32Size = 16
func ST_BIND(info uint8) SymBind { return SymBind(info >> 4) }
func ST_TYPE(info uint8) SymType { return SymType(info & 0xF) }
func ST_INFO(bind SymBind, typ SymType) uint8 {
return uint8(bind)<<4 | uint8(typ)&0xf
}
func ST_VISIBILITY(other uint8) SymVis { return SymVis(other & 3) }
/*
* ELF64
*/
// ELF64 file header.
type Header64 struct {
Ident [EI_NIDENT]byte /* File identification. */
Type uint16 /* File type. */
Machine uint16 /* Machine architecture. */
Version uint32 /* ELF format version. */
Entry uint64 /* Entry point. */
Phoff uint64 /* Program header file offset. */
Shoff uint64 /* Section header file offset. */
Flags uint32 /* Architecture-specific flags. */
Ehsize uint16 /* Size of ELF header in bytes. */
Phentsize uint16 /* Size of program header entry. */
Phnum uint16 /* Number of program header entries. */
Shentsize uint16 /* Size of section header entry. */
Shnum uint16 /* Number of section header entries. */
Shstrndx uint16 /* Section name strings section. */
}
// ELF64 Section header.
type Section64 struct {
Name uint32 /* Section name (index into the section header string table). */
Type uint32 /* Section type. */
Flags uint64 /* Section flags. */
Addr uint64 /* Address in memory image. */
Off uint64 /* Offset in file. */
Size uint64 /* Size in bytes. */
Link uint32 /* Index of a related section. */
Info uint32 /* Depends on section type. */
Addralign uint64 /* Alignment in bytes. */
Entsize uint64 /* Size of each entry in section. */
}
// ELF64 Program header.
type Prog64 struct {
Type uint32 /* Entry type. */
Flags uint32 /* Access permission flags. */
Off uint64 /* File offset of contents. */
Vaddr uint64 /* Virtual address in memory image. */
Paddr uint64 /* Physical address (not used). */
Filesz uint64 /* Size of contents in file. */
Memsz uint64 /* Size of contents in memory. */
Align uint64 /* Alignment in memory and file. */
}
// ELF64 Dynamic structure. The ".dynamic" section contains an array of them.
type Dyn64 struct {
Tag int64 /* Entry type. */
Val uint64 /* Integer/address value */
}
// ELF64 Compression header.
type Chdr64 struct {
Type uint32
_ uint32 /* Reserved. */
Size uint64
Addralign uint64
}
/*
* Relocation entries.
*/
/* ELF64 relocations that don't need an addend field. */
type Rel64 struct {
Off uint64 /* Location to be relocated. */
Info uint64 /* Relocation type and symbol index. */
}
/* ELF64 relocations that need an addend field. */
type Rela64 struct {
Off uint64 /* Location to be relocated. */
Info uint64 /* Relocation type and symbol index. */
Addend int64 /* Addend. */
}
func R_SYM64(info uint64) uint32 { return uint32(info >> 32) }
func R_TYPE64(info uint64) uint32 { return uint32(info) }
func R_INFO(sym, typ uint32) uint64 { return uint64(sym)<<32 | uint64(typ) }
// ELF64 symbol table entries.
type Sym64 struct {
Name uint32 /* String table index of name. */
Info uint8 /* Type and binding information. */
Other uint8 /* Reserved (not used). */
Shndx uint16 /* Section index of symbol. */
Value uint64 /* Symbol value. */
Size uint64 /* Size of associated object. */
}
const Sym64Size = 24
type intName struct {
i uint32
s string
}
func stringName(i uint32, names []intName, goSyntax bool) string {
for _, n := range names {
if n.i == i {
if goSyntax {
return "elf." + n.s
}
return n.s
}
}
// second pass - look for smaller to add with.
// assume sorted already
for j := len(names) - 1; j >= 0; j-- {
n := names[j]
if n.i < i {
s := n.s
if goSyntax {
s = "elf." + s
}
return s + "+" + strconv.FormatUint(uint64(i-n.i), 10)
}
}
return strconv.FormatUint(uint64(i), 10)
}
func flagName(i uint32, names []intName, goSyntax bool) string {
s := ""
for _, n := range names {
if n.i&i == n.i {
if len(s) > 0 {
s += "+"
}
if goSyntax {
s += "elf."
}
s += n.s
i -= n.i
}
}
if len(s) == 0 {
return "0x" + strconv.FormatUint(uint64(i), 16)
}
if i != 0 {
s += "+0x" + strconv.FormatUint(uint64(i), 16)
}
return s
}
| go/src/debug/elf/elf.go/0 | {
"file_path": "go/src/debug/elf/elf.go",
"repo_id": "go",
"token_count": 73510
} | 235 |
// Copyright 2022 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package pe
import (
"fmt"
"testing"
)
type testpoint struct {
name string
ok bool
err string
auxstr string
}
func TestReadCOFFSymbolAuxInfo(t *testing.T) {
testpoints := map[int]testpoint{
39: testpoint{
name: ".rdata$.refptr.__native_startup_lock",
ok: true,
auxstr: "{Size:8 NumRelocs:1 NumLineNumbers:0 Checksum:0 SecNum:16 Selection:2 _:[0 0 0]}",
},
81: testpoint{
name: ".debug_line",
ok: true,
auxstr: "{Size:994 NumRelocs:1 NumLineNumbers:0 Checksum:1624223678 SecNum:32 Selection:0 _:[0 0 0]}",
},
155: testpoint{
name: ".file",
ok: false,
err: "incorrect symbol storage class",
},
}
// The testdata PE object file below was selected from a release
// build from https://github.com/mstorsjo/llvm-mingw/releases; it
// corresponds to the mingw "crt2.o" object. The object itself was
// built using an x86_64 HOST=linux TARGET=windows clang cross
// compiler based on LLVM 13. More build details can be found at
// https://github.com/mstorsjo/llvm-mingw/releases.
f, err := Open("testdata/llvm-mingw-20211002-msvcrt-x86_64-crt2")
if err != nil {
t.Errorf("open failed with %v", err)
}
defer f.Close()
for k := range f.COFFSymbols {
tp, ok := testpoints[k]
if !ok {
continue
}
sym := &f.COFFSymbols[k]
if sym.NumberOfAuxSymbols == 0 {
t.Errorf("expected aux symbols for sym %d", k)
continue
}
name, nerr := sym.FullName(f.StringTable)
if nerr != nil {
t.Errorf("FullName(%d) failed with %v", k, nerr)
continue
}
if name != tp.name {
t.Errorf("name check for %d, got %s want %s", k, name, tp.name)
continue
}
ap, err := f.COFFSymbolReadSectionDefAux(k)
if tp.ok {
if err != nil {
t.Errorf("unexpected failure on %d, got error %v", k, err)
continue
}
got := fmt.Sprintf("%+v", *ap)
if got != tp.auxstr {
t.Errorf("COFFSymbolReadSectionDefAux on %d bad return, got:\n%s\nwant:\n%s\n", k, got, tp.auxstr)
continue
}
} else {
if err == nil {
t.Errorf("unexpected non-failure on %d", k)
continue
}
got := fmt.Sprintf("%v", err)
if got != tp.err {
t.Errorf("COFFSymbolReadSectionDefAux %d wrong error, got %q want %q", k, got, tp.err)
continue
}
}
}
}
| go/src/debug/pe/symbols_test.go/0 | {
"file_path": "go/src/debug/pe/symbols_test.go",
"repo_id": "go",
"token_count": 1054
} | 236 |
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package ascii85 implements the ascii85 data encoding
// as used in the btoa tool and Adobe's PostScript and PDF document formats.
package ascii85
import (
"io"
"strconv"
)
/*
* Encoder
*/
// Encode encodes src into at most [MaxEncodedLen](len(src))
// bytes of dst, returning the actual number of bytes written.
//
// The encoding handles 4-byte chunks, using a special encoding
// for the last fragment, so Encode is not appropriate for use on
// individual blocks of a large data stream. Use [NewEncoder] instead.
//
// Often, ascii85-encoded data is wrapped in <~ and ~> symbols.
// Encode does not add these.
func Encode(dst, src []byte) int {
if len(src) == 0 {
return 0
}
n := 0
for len(src) > 0 {
dst[0] = 0
dst[1] = 0
dst[2] = 0
dst[3] = 0
dst[4] = 0
// Unpack 4 bytes into uint32 to repack into base 85 5-byte.
var v uint32
switch len(src) {
default:
v |= uint32(src[3])
fallthrough
case 3:
v |= uint32(src[2]) << 8
fallthrough
case 2:
v |= uint32(src[1]) << 16
fallthrough
case 1:
v |= uint32(src[0]) << 24
}
// Special case: zero (!!!!!) shortens to z.
if v == 0 && len(src) >= 4 {
dst[0] = 'z'
dst = dst[1:]
src = src[4:]
n++
continue
}
// Otherwise, 5 base 85 digits starting at !.
for i := 4; i >= 0; i-- {
dst[i] = '!' + byte(v%85)
v /= 85
}
// If src was short, discard the low destination bytes.
m := 5
if len(src) < 4 {
m -= 4 - len(src)
src = nil
} else {
src = src[4:]
}
dst = dst[m:]
n += m
}
return n
}
// MaxEncodedLen returns the maximum length of an encoding of n source bytes.
func MaxEncodedLen(n int) int { return (n + 3) / 4 * 5 }
// NewEncoder returns a new ascii85 stream encoder. Data written to
// the returned writer will be encoded and then written to w.
// Ascii85 encodings operate in 32-bit blocks; when finished
// writing, the caller must Close the returned encoder to flush any
// trailing partial block.
func NewEncoder(w io.Writer) io.WriteCloser { return &encoder{w: w} }
type encoder struct {
err error
w io.Writer
buf [4]byte // buffered data waiting to be encoded
nbuf int // number of bytes in buf
out [1024]byte // output buffer
}
func (e *encoder) Write(p []byte) (n int, err error) {
if e.err != nil {
return 0, e.err
}
// Leading fringe.
if e.nbuf > 0 {
var i int
for i = 0; i < len(p) && e.nbuf < 4; i++ {
e.buf[e.nbuf] = p[i]
e.nbuf++
}
n += i
p = p[i:]
if e.nbuf < 4 {
return
}
nout := Encode(e.out[0:], e.buf[0:])
if _, e.err = e.w.Write(e.out[0:nout]); e.err != nil {
return n, e.err
}
e.nbuf = 0
}
// Large interior chunks.
for len(p) >= 4 {
nn := len(e.out) / 5 * 4
if nn > len(p) {
nn = len(p)
}
nn -= nn % 4
if nn > 0 {
nout := Encode(e.out[0:], p[0:nn])
if _, e.err = e.w.Write(e.out[0:nout]); e.err != nil {
return n, e.err
}
}
n += nn
p = p[nn:]
}
// Trailing fringe.
copy(e.buf[:], p)
e.nbuf = len(p)
n += len(p)
return
}
// Close flushes any pending output from the encoder.
// It is an error to call Write after calling Close.
func (e *encoder) Close() error {
// If there's anything left in the buffer, flush it out
if e.err == nil && e.nbuf > 0 {
nout := Encode(e.out[0:], e.buf[0:e.nbuf])
e.nbuf = 0
_, e.err = e.w.Write(e.out[0:nout])
}
return e.err
}
/*
* Decoder
*/
type CorruptInputError int64
func (e CorruptInputError) Error() string {
return "illegal ascii85 data at input byte " + strconv.FormatInt(int64(e), 10)
}
// Decode decodes src into dst, returning both the number
// of bytes written to dst and the number consumed from src.
// If src contains invalid ascii85 data, Decode will return the
// number of bytes successfully written and a [CorruptInputError].
// Decode ignores space and control characters in src.
// Often, ascii85-encoded data is wrapped in <~ and ~> symbols.
// Decode expects these to have been stripped by the caller.
//
// If flush is true, Decode assumes that src represents the
// end of the input stream and processes it completely rather
// than wait for the completion of another 32-bit block.
//
// [NewDecoder] wraps an [io.Reader] interface around Decode.
func Decode(dst, src []byte, flush bool) (ndst, nsrc int, err error) {
var v uint32
var nb int
for i, b := range src {
if len(dst)-ndst < 4 {
return
}
switch {
case b <= ' ':
continue
case b == 'z' && nb == 0:
nb = 5
v = 0
case '!' <= b && b <= 'u':
v = v*85 + uint32(b-'!')
nb++
default:
return 0, 0, CorruptInputError(i)
}
if nb == 5 {
nsrc = i + 1
dst[ndst] = byte(v >> 24)
dst[ndst+1] = byte(v >> 16)
dst[ndst+2] = byte(v >> 8)
dst[ndst+3] = byte(v)
ndst += 4
nb = 0
v = 0
}
}
if flush {
nsrc = len(src)
if nb > 0 {
// The number of output bytes in the last fragment
// is the number of leftover input bytes - 1:
// the extra byte provides enough bits to cover
// the inefficiency of the encoding for the block.
if nb == 1 {
return 0, 0, CorruptInputError(len(src))
}
for i := nb; i < 5; i++ {
// The short encoding truncated the output value.
// We have to assume the worst case values (digit 84)
// in order to ensure that the top bits are correct.
v = v*85 + 84
}
for i := 0; i < nb-1; i++ {
dst[ndst] = byte(v >> 24)
v <<= 8
ndst++
}
}
}
return
}
// NewDecoder constructs a new ascii85 stream decoder.
func NewDecoder(r io.Reader) io.Reader { return &decoder{r: r} }
type decoder struct {
err error
readErr error
r io.Reader
buf [1024]byte // leftover input
nbuf int
out []byte // leftover decoded output
outbuf [1024]byte
}
func (d *decoder) Read(p []byte) (n int, err error) {
if len(p) == 0 {
return 0, nil
}
if d.err != nil {
return 0, d.err
}
for {
// Copy leftover output from last decode.
if len(d.out) > 0 {
n = copy(p, d.out)
d.out = d.out[n:]
return
}
// Decode leftover input from last read.
var nn, nsrc, ndst int
if d.nbuf > 0 {
ndst, nsrc, d.err = Decode(d.outbuf[0:], d.buf[0:d.nbuf], d.readErr != nil)
if ndst > 0 {
d.out = d.outbuf[0:ndst]
d.nbuf = copy(d.buf[0:], d.buf[nsrc:d.nbuf])
continue // copy out and return
}
if ndst == 0 && d.err == nil {
// Special case: input buffer is mostly filled with non-data bytes.
// Filter out such bytes to make room for more input.
off := 0
for i := 0; i < d.nbuf; i++ {
if d.buf[i] > ' ' {
d.buf[off] = d.buf[i]
off++
}
}
d.nbuf = off
}
}
// Out of input, out of decoded output. Check errors.
if d.err != nil {
return 0, d.err
}
if d.readErr != nil {
d.err = d.readErr
return 0, d.err
}
// Read more data.
nn, d.readErr = d.r.Read(d.buf[d.nbuf:])
d.nbuf += nn
}
}
| go/src/encoding/ascii85/ascii85.go/0 | {
"file_path": "go/src/encoding/ascii85/ascii85.go",
"repo_id": "go",
"token_count": 3012
} | 237 |
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package gob
import (
"bufio"
"errors"
"internal/saferio"
"io"
"reflect"
"sync"
)
// tooBig provides a sanity check for sizes; used in several places. Upper limit
// of is 1GB on 32-bit systems, 8GB on 64-bit, allowing room to grow a little
// without overflow.
const tooBig = (1 << 30) << (^uint(0) >> 62)
// A Decoder manages the receipt of type and data information read from the
// remote side of a connection. It is safe for concurrent use by multiple
// goroutines.
//
// The Decoder does only basic sanity checking on decoded input sizes,
// and its limits are not configurable. Take caution when decoding gob data
// from untrusted sources.
type Decoder struct {
mutex sync.Mutex // each item must be received atomically
r io.Reader // source of the data
buf decBuffer // buffer for more efficient i/o from r
wireType map[typeId]*wireType // map from remote ID to local description
decoderCache map[reflect.Type]map[typeId]**decEngine // cache of compiled engines
ignorerCache map[typeId]**decEngine // ditto for ignored objects
freeList *decoderState // list of free decoderStates; avoids reallocation
countBuf []byte // used for decoding integers while parsing messages
err error
}
// NewDecoder returns a new decoder that reads from the [io.Reader].
// If r does not also implement [io.ByteReader], it will be wrapped in a
// [bufio.Reader].
func NewDecoder(r io.Reader) *Decoder {
dec := new(Decoder)
// We use the ability to read bytes as a plausible surrogate for buffering.
if _, ok := r.(io.ByteReader); !ok {
r = bufio.NewReader(r)
}
dec.r = r
dec.wireType = make(map[typeId]*wireType)
dec.decoderCache = make(map[reflect.Type]map[typeId]**decEngine)
dec.ignorerCache = make(map[typeId]**decEngine)
dec.countBuf = make([]byte, 9) // counts may be uint64s (unlikely!), require 9 bytes
return dec
}
// recvType loads the definition of a type.
func (dec *Decoder) recvType(id typeId) {
// Have we already seen this type? That's an error
if id < firstUserId || dec.wireType[id] != nil {
dec.err = errors.New("gob: duplicate type received")
return
}
// Type:
wire := new(wireType)
dec.decodeValue(tWireType, reflect.ValueOf(wire))
if dec.err != nil {
return
}
// Remember we've seen this type.
dec.wireType[id] = wire
}
var errBadCount = errors.New("invalid message length")
// recvMessage reads the next count-delimited item from the input. It is the converse
// of Encoder.writeMessage. It returns false on EOF or other error reading the message.
func (dec *Decoder) recvMessage() bool {
// Read a count.
nbytes, _, err := decodeUintReader(dec.r, dec.countBuf)
if err != nil {
dec.err = err
return false
}
if nbytes >= tooBig {
dec.err = errBadCount
return false
}
dec.readMessage(int(nbytes))
return dec.err == nil
}
// readMessage reads the next nbytes bytes from the input.
func (dec *Decoder) readMessage(nbytes int) {
if dec.buf.Len() != 0 {
// The buffer should always be empty now.
panic("non-empty decoder buffer")
}
// Read the data
var buf []byte
buf, dec.err = saferio.ReadData(dec.r, uint64(nbytes))
dec.buf.SetBytes(buf)
if dec.err == io.EOF {
dec.err = io.ErrUnexpectedEOF
}
}
// toInt turns an encoded uint64 into an int, according to the marshaling rules.
func toInt(x uint64) int64 {
i := int64(x >> 1)
if x&1 != 0 {
i = ^i
}
return i
}
func (dec *Decoder) nextInt() int64 {
n, _, err := decodeUintReader(&dec.buf, dec.countBuf)
if err != nil {
dec.err = err
}
return toInt(n)
}
func (dec *Decoder) nextUint() uint64 {
n, _, err := decodeUintReader(&dec.buf, dec.countBuf)
if err != nil {
dec.err = err
}
return n
}
// decodeTypeSequence parses:
// TypeSequence
//
// (TypeDefinition DelimitedTypeDefinition*)?
//
// and returns the type id of the next value. It returns -1 at
// EOF. Upon return, the remainder of dec.buf is the value to be
// decoded. If this is an interface value, it can be ignored by
// resetting that buffer.
func (dec *Decoder) decodeTypeSequence(isInterface bool) typeId {
firstMessage := true
for dec.err == nil {
if dec.buf.Len() == 0 {
if !dec.recvMessage() {
// We can only return io.EOF if the input was empty.
// If we read one or more type spec messages,
// require a data item message to follow.
// If we hit an EOF before that, then give ErrUnexpectedEOF.
if !firstMessage && dec.err == io.EOF {
dec.err = io.ErrUnexpectedEOF
}
break
}
}
// Receive a type id.
id := typeId(dec.nextInt())
if id >= 0 {
// Value follows.
return id
}
// Type definition for (-id) follows.
dec.recvType(-id)
if dec.err != nil {
break
}
// When decoding an interface, after a type there may be a
// DelimitedValue still in the buffer. Skip its count.
// (Alternatively, the buffer is empty and the byte count
// will be absorbed by recvMessage.)
if dec.buf.Len() > 0 {
if !isInterface {
dec.err = errors.New("extra data in buffer")
break
}
dec.nextUint()
}
firstMessage = false
}
return -1
}
// Decode reads the next value from the input stream and stores
// it in the data represented by the empty interface value.
// If e is nil, the value will be discarded. Otherwise,
// the value underlying e must be a pointer to the
// correct type for the next data item received.
// If the input is at EOF, Decode returns [io.EOF] and
// does not modify e.
func (dec *Decoder) Decode(e any) error {
if e == nil {
return dec.DecodeValue(reflect.Value{})
}
value := reflect.ValueOf(e)
// If e represents a value as opposed to a pointer, the answer won't
// get back to the caller. Make sure it's a pointer.
if value.Type().Kind() != reflect.Pointer {
dec.err = errors.New("gob: attempt to decode into a non-pointer")
return dec.err
}
return dec.DecodeValue(value)
}
// DecodeValue reads the next value from the input stream.
// If v is the zero reflect.Value (v.Kind() == Invalid), DecodeValue discards the value.
// Otherwise, it stores the value into v. In that case, v must represent
// a non-nil pointer to data or be an assignable reflect.Value (v.CanSet())
// If the input is at EOF, DecodeValue returns [io.EOF] and
// does not modify v.
func (dec *Decoder) DecodeValue(v reflect.Value) error {
if v.IsValid() {
if v.Kind() == reflect.Pointer && !v.IsNil() {
// That's okay, we'll store through the pointer.
} else if !v.CanSet() {
return errors.New("gob: DecodeValue of unassignable value")
}
}
// Make sure we're single-threaded through here.
dec.mutex.Lock()
defer dec.mutex.Unlock()
dec.buf.Reset() // In case data lingers from previous invocation.
dec.err = nil
id := dec.decodeTypeSequence(false)
if dec.err == nil {
dec.decodeValue(id, v)
}
return dec.err
}
// If debug.go is compiled into the program, debugFunc prints a human-readable
// representation of the gob data read from r by calling that file's Debug function.
// Otherwise it is nil.
var debugFunc func(io.Reader)
| go/src/encoding/gob/decoder.go/0 | {
"file_path": "go/src/encoding/gob/decoder.go",
"repo_id": "go",
"token_count": 2668
} | 238 |
// Copyright 2016 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 hex_test
import (
"encoding/hex"
"fmt"
"log"
"os"
)
func ExampleEncode() {
src := []byte("Hello Gopher!")
dst := make([]byte, hex.EncodedLen(len(src)))
hex.Encode(dst, src)
fmt.Printf("%s\n", dst)
// Output:
// 48656c6c6f20476f7068657221
}
func ExampleDecode() {
src := []byte("48656c6c6f20476f7068657221")
dst := make([]byte, hex.DecodedLen(len(src)))
n, err := hex.Decode(dst, src)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s\n", dst[:n])
// Output:
// Hello Gopher!
}
func ExampleDecodeString() {
const s = "48656c6c6f20476f7068657221"
decoded, err := hex.DecodeString(s)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s\n", decoded)
// Output:
// Hello Gopher!
}
func ExampleDump() {
content := []byte("Go is an open source programming language.")
fmt.Printf("%s", hex.Dump(content))
// Output:
// 00000000 47 6f 20 69 73 20 61 6e 20 6f 70 65 6e 20 73 6f |Go is an open so|
// 00000010 75 72 63 65 20 70 72 6f 67 72 61 6d 6d 69 6e 67 |urce programming|
// 00000020 20 6c 61 6e 67 75 61 67 65 2e | language.|
}
func ExampleDumper() {
lines := []string{
"Go is an open source programming language.",
"\n",
"We encourage all Go users to subscribe to golang-announce.",
}
stdoutDumper := hex.Dumper(os.Stdout)
defer stdoutDumper.Close()
for _, line := range lines {
stdoutDumper.Write([]byte(line))
}
// Output:
// 00000000 47 6f 20 69 73 20 61 6e 20 6f 70 65 6e 20 73 6f |Go is an open so|
// 00000010 75 72 63 65 20 70 72 6f 67 72 61 6d 6d 69 6e 67 |urce programming|
// 00000020 20 6c 61 6e 67 75 61 67 65 2e 0a 57 65 20 65 6e | language..We en|
// 00000030 63 6f 75 72 61 67 65 20 61 6c 6c 20 47 6f 20 75 |courage all Go u|
// 00000040 73 65 72 73 20 74 6f 20 73 75 62 73 63 72 69 62 |sers to subscrib|
// 00000050 65 20 74 6f 20 67 6f 6c 61 6e 67 2d 61 6e 6e 6f |e to golang-anno|
// 00000060 75 6e 63 65 2e |unce.|
}
func ExampleEncodeToString() {
src := []byte("Hello")
encodedStr := hex.EncodeToString(src)
fmt.Printf("%s\n", encodedStr)
// Output:
// 48656c6c6f
}
| go/src/encoding/hex/example_test.go/0 | {
"file_path": "go/src/encoding/hex/example_test.go",
"repo_id": "go",
"token_count": 987
} | 239 |
// Copyright 2010 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 json
// JSON value parser state machine.
// Just about at the limit of what is reasonable to write by hand.
// Some parts are a bit tedious, but overall it nicely factors out the
// otherwise common code from the multiple scanning functions
// in this package (Compact, Indent, checkValid, etc).
//
// This file starts with two simple examples using the scanner
// before diving into the scanner itself.
import (
"strconv"
"sync"
)
// Valid reports whether data is a valid JSON encoding.
func Valid(data []byte) bool {
scan := newScanner()
defer freeScanner(scan)
return checkValid(data, scan) == nil
}
// checkValid verifies that data is valid JSON-encoded data.
// scan is passed in for use by checkValid to avoid an allocation.
// checkValid returns nil or a SyntaxError.
func checkValid(data []byte, scan *scanner) error {
scan.reset()
for _, c := range data {
scan.bytes++
if scan.step(scan, c) == scanError {
return scan.err
}
}
if scan.eof() == scanError {
return scan.err
}
return nil
}
// A SyntaxError is a description of a JSON syntax error.
// [Unmarshal] will return a SyntaxError if the JSON can't be parsed.
type SyntaxError struct {
msg string // description of error
Offset int64 // error occurred after reading Offset bytes
}
func (e *SyntaxError) Error() string { return e.msg }
// A scanner is a JSON scanning state machine.
// Callers call scan.reset and then pass bytes in one at a time
// by calling scan.step(&scan, c) for each byte.
// The return value, referred to as an opcode, tells the
// caller about significant parsing events like beginning
// and ending literals, objects, and arrays, so that the
// caller can follow along if it wishes.
// The return value scanEnd indicates that a single top-level
// JSON value has been completed, *before* the byte that
// just got passed in. (The indication must be delayed in order
// to recognize the end of numbers: is 123 a whole value or
// the beginning of 12345e+6?).
type scanner struct {
// The step is a func to be called to execute the next transition.
// Also tried using an integer constant and a single func
// with a switch, but using the func directly was 10% faster
// on a 64-bit Mac Mini, and it's nicer to read.
step func(*scanner, byte) int
// Reached end of top-level value.
endTop bool
// Stack of what we're in the middle of - array values, object keys, object values.
parseState []int
// Error that happened, if any.
err error
// total bytes consumed, updated by decoder.Decode (and deliberately
// not set to zero by scan.reset)
bytes int64
}
var scannerPool = sync.Pool{
New: func() any {
return &scanner{}
},
}
func newScanner() *scanner {
scan := scannerPool.Get().(*scanner)
// scan.reset by design doesn't set bytes to zero
scan.bytes = 0
scan.reset()
return scan
}
func freeScanner(scan *scanner) {
// Avoid hanging on to too much memory in extreme cases.
if len(scan.parseState) > 1024 {
scan.parseState = nil
}
scannerPool.Put(scan)
}
// These values are returned by the state transition functions
// assigned to scanner.state and the method scanner.eof.
// They give details about the current state of the scan that
// callers might be interested to know about.
// It is okay to ignore the return value of any particular
// call to scanner.state: if one call returns scanError,
// every subsequent call will return scanError too.
const (
// Continue.
scanContinue = iota // uninteresting byte
scanBeginLiteral // end implied by next result != scanContinue
scanBeginObject // begin object
scanObjectKey // just finished object key (string)
scanObjectValue // just finished non-last object value
scanEndObject // end object (implies scanObjectValue if possible)
scanBeginArray // begin array
scanArrayValue // just finished array value
scanEndArray // end array (implies scanArrayValue if possible)
scanSkipSpace // space byte; can skip; known to be last "continue" result
// Stop.
scanEnd // top-level value ended *before* this byte; known to be first "stop" result
scanError // hit an error, scanner.err.
)
// These values are stored in the parseState stack.
// They give the current state of a composite value
// being scanned. If the parser is inside a nested value
// the parseState describes the nested state, outermost at entry 0.
const (
parseObjectKey = iota // parsing object key (before colon)
parseObjectValue // parsing object value (after colon)
parseArrayValue // parsing array value
)
// This limits the max nesting depth to prevent stack overflow.
// This is permitted by https://tools.ietf.org/html/rfc7159#section-9
const maxNestingDepth = 10000
// reset prepares the scanner for use.
// It must be called before calling s.step.
func (s *scanner) reset() {
s.step = stateBeginValue
s.parseState = s.parseState[0:0]
s.err = nil
s.endTop = false
}
// eof tells the scanner that the end of input has been reached.
// It returns a scan status just as s.step does.
func (s *scanner) eof() int {
if s.err != nil {
return scanError
}
if s.endTop {
return scanEnd
}
s.step(s, ' ')
if s.endTop {
return scanEnd
}
if s.err == nil {
s.err = &SyntaxError{"unexpected end of JSON input", s.bytes}
}
return scanError
}
// pushParseState pushes a new parse state p onto the parse stack.
// an error state is returned if maxNestingDepth was exceeded, otherwise successState is returned.
func (s *scanner) pushParseState(c byte, newParseState int, successState int) int {
s.parseState = append(s.parseState, newParseState)
if len(s.parseState) <= maxNestingDepth {
return successState
}
return s.error(c, "exceeded max depth")
}
// popParseState pops a parse state (already obtained) off the stack
// and updates s.step accordingly.
func (s *scanner) popParseState() {
n := len(s.parseState) - 1
s.parseState = s.parseState[0:n]
if n == 0 {
s.step = stateEndTop
s.endTop = true
} else {
s.step = stateEndValue
}
}
func isSpace(c byte) bool {
return c <= ' ' && (c == ' ' || c == '\t' || c == '\r' || c == '\n')
}
// stateBeginValueOrEmpty is the state after reading `[`.
func stateBeginValueOrEmpty(s *scanner, c byte) int {
if isSpace(c) {
return scanSkipSpace
}
if c == ']' {
return stateEndValue(s, c)
}
return stateBeginValue(s, c)
}
// stateBeginValue is the state at the beginning of the input.
func stateBeginValue(s *scanner, c byte) int {
if isSpace(c) {
return scanSkipSpace
}
switch c {
case '{':
s.step = stateBeginStringOrEmpty
return s.pushParseState(c, parseObjectKey, scanBeginObject)
case '[':
s.step = stateBeginValueOrEmpty
return s.pushParseState(c, parseArrayValue, scanBeginArray)
case '"':
s.step = stateInString
return scanBeginLiteral
case '-':
s.step = stateNeg
return scanBeginLiteral
case '0': // beginning of 0.123
s.step = state0
return scanBeginLiteral
case 't': // beginning of true
s.step = stateT
return scanBeginLiteral
case 'f': // beginning of false
s.step = stateF
return scanBeginLiteral
case 'n': // beginning of null
s.step = stateN
return scanBeginLiteral
}
if '1' <= c && c <= '9' { // beginning of 1234.5
s.step = state1
return scanBeginLiteral
}
return s.error(c, "looking for beginning of value")
}
// stateBeginStringOrEmpty is the state after reading `{`.
func stateBeginStringOrEmpty(s *scanner, c byte) int {
if isSpace(c) {
return scanSkipSpace
}
if c == '}' {
n := len(s.parseState)
s.parseState[n-1] = parseObjectValue
return stateEndValue(s, c)
}
return stateBeginString(s, c)
}
// stateBeginString is the state after reading `{"key": value,`.
func stateBeginString(s *scanner, c byte) int {
if isSpace(c) {
return scanSkipSpace
}
if c == '"' {
s.step = stateInString
return scanBeginLiteral
}
return s.error(c, "looking for beginning of object key string")
}
// stateEndValue is the state after completing a value,
// such as after reading `{}` or `true` or `["x"`.
func stateEndValue(s *scanner, c byte) int {
n := len(s.parseState)
if n == 0 {
// Completed top-level before the current byte.
s.step = stateEndTop
s.endTop = true
return stateEndTop(s, c)
}
if isSpace(c) {
s.step = stateEndValue
return scanSkipSpace
}
ps := s.parseState[n-1]
switch ps {
case parseObjectKey:
if c == ':' {
s.parseState[n-1] = parseObjectValue
s.step = stateBeginValue
return scanObjectKey
}
return s.error(c, "after object key")
case parseObjectValue:
if c == ',' {
s.parseState[n-1] = parseObjectKey
s.step = stateBeginString
return scanObjectValue
}
if c == '}' {
s.popParseState()
return scanEndObject
}
return s.error(c, "after object key:value pair")
case parseArrayValue:
if c == ',' {
s.step = stateBeginValue
return scanArrayValue
}
if c == ']' {
s.popParseState()
return scanEndArray
}
return s.error(c, "after array element")
}
return s.error(c, "")
}
// stateEndTop is the state after finishing the top-level value,
// such as after reading `{}` or `[1,2,3]`.
// Only space characters should be seen now.
func stateEndTop(s *scanner, c byte) int {
if !isSpace(c) {
// Complain about non-space byte on next call.
s.error(c, "after top-level value")
}
return scanEnd
}
// stateInString is the state after reading `"`.
func stateInString(s *scanner, c byte) int {
if c == '"' {
s.step = stateEndValue
return scanContinue
}
if c == '\\' {
s.step = stateInStringEsc
return scanContinue
}
if c < 0x20 {
return s.error(c, "in string literal")
}
return scanContinue
}
// stateInStringEsc is the state after reading `"\` during a quoted string.
func stateInStringEsc(s *scanner, c byte) int {
switch c {
case 'b', 'f', 'n', 'r', 't', '\\', '/', '"':
s.step = stateInString
return scanContinue
case 'u':
s.step = stateInStringEscU
return scanContinue
}
return s.error(c, "in string escape code")
}
// stateInStringEscU is the state after reading `"\u` during a quoted string.
func stateInStringEscU(s *scanner, c byte) int {
if '0' <= c && c <= '9' || 'a' <= c && c <= 'f' || 'A' <= c && c <= 'F' {
s.step = stateInStringEscU1
return scanContinue
}
// numbers
return s.error(c, "in \\u hexadecimal character escape")
}
// stateInStringEscU1 is the state after reading `"\u1` during a quoted string.
func stateInStringEscU1(s *scanner, c byte) int {
if '0' <= c && c <= '9' || 'a' <= c && c <= 'f' || 'A' <= c && c <= 'F' {
s.step = stateInStringEscU12
return scanContinue
}
// numbers
return s.error(c, "in \\u hexadecimal character escape")
}
// stateInStringEscU12 is the state after reading `"\u12` during a quoted string.
func stateInStringEscU12(s *scanner, c byte) int {
if '0' <= c && c <= '9' || 'a' <= c && c <= 'f' || 'A' <= c && c <= 'F' {
s.step = stateInStringEscU123
return scanContinue
}
// numbers
return s.error(c, "in \\u hexadecimal character escape")
}
// stateInStringEscU123 is the state after reading `"\u123` during a quoted string.
func stateInStringEscU123(s *scanner, c byte) int {
if '0' <= c && c <= '9' || 'a' <= c && c <= 'f' || 'A' <= c && c <= 'F' {
s.step = stateInString
return scanContinue
}
// numbers
return s.error(c, "in \\u hexadecimal character escape")
}
// stateNeg is the state after reading `-` during a number.
func stateNeg(s *scanner, c byte) int {
if c == '0' {
s.step = state0
return scanContinue
}
if '1' <= c && c <= '9' {
s.step = state1
return scanContinue
}
return s.error(c, "in numeric literal")
}
// state1 is the state after reading a non-zero integer during a number,
// such as after reading `1` or `100` but not `0`.
func state1(s *scanner, c byte) int {
if '0' <= c && c <= '9' {
s.step = state1
return scanContinue
}
return state0(s, c)
}
// state0 is the state after reading `0` during a number.
func state0(s *scanner, c byte) int {
if c == '.' {
s.step = stateDot
return scanContinue
}
if c == 'e' || c == 'E' {
s.step = stateE
return scanContinue
}
return stateEndValue(s, c)
}
// stateDot is the state after reading the integer and decimal point in a number,
// such as after reading `1.`.
func stateDot(s *scanner, c byte) int {
if '0' <= c && c <= '9' {
s.step = stateDot0
return scanContinue
}
return s.error(c, "after decimal point in numeric literal")
}
// stateDot0 is the state after reading the integer, decimal point, and subsequent
// digits of a number, such as after reading `3.14`.
func stateDot0(s *scanner, c byte) int {
if '0' <= c && c <= '9' {
return scanContinue
}
if c == 'e' || c == 'E' {
s.step = stateE
return scanContinue
}
return stateEndValue(s, c)
}
// stateE is the state after reading the mantissa and e in a number,
// such as after reading `314e` or `0.314e`.
func stateE(s *scanner, c byte) int {
if c == '+' || c == '-' {
s.step = stateESign
return scanContinue
}
return stateESign(s, c)
}
// stateESign is the state after reading the mantissa, e, and sign in a number,
// such as after reading `314e-` or `0.314e+`.
func stateESign(s *scanner, c byte) int {
if '0' <= c && c <= '9' {
s.step = stateE0
return scanContinue
}
return s.error(c, "in exponent of numeric literal")
}
// stateE0 is the state after reading the mantissa, e, optional sign,
// and at least one digit of the exponent in a number,
// such as after reading `314e-2` or `0.314e+1` or `3.14e0`.
func stateE0(s *scanner, c byte) int {
if '0' <= c && c <= '9' {
return scanContinue
}
return stateEndValue(s, c)
}
// stateT is the state after reading `t`.
func stateT(s *scanner, c byte) int {
if c == 'r' {
s.step = stateTr
return scanContinue
}
return s.error(c, "in literal true (expecting 'r')")
}
// stateTr is the state after reading `tr`.
func stateTr(s *scanner, c byte) int {
if c == 'u' {
s.step = stateTru
return scanContinue
}
return s.error(c, "in literal true (expecting 'u')")
}
// stateTru is the state after reading `tru`.
func stateTru(s *scanner, c byte) int {
if c == 'e' {
s.step = stateEndValue
return scanContinue
}
return s.error(c, "in literal true (expecting 'e')")
}
// stateF is the state after reading `f`.
func stateF(s *scanner, c byte) int {
if c == 'a' {
s.step = stateFa
return scanContinue
}
return s.error(c, "in literal false (expecting 'a')")
}
// stateFa is the state after reading `fa`.
func stateFa(s *scanner, c byte) int {
if c == 'l' {
s.step = stateFal
return scanContinue
}
return s.error(c, "in literal false (expecting 'l')")
}
// stateFal is the state after reading `fal`.
func stateFal(s *scanner, c byte) int {
if c == 's' {
s.step = stateFals
return scanContinue
}
return s.error(c, "in literal false (expecting 's')")
}
// stateFals is the state after reading `fals`.
func stateFals(s *scanner, c byte) int {
if c == 'e' {
s.step = stateEndValue
return scanContinue
}
return s.error(c, "in literal false (expecting 'e')")
}
// stateN is the state after reading `n`.
func stateN(s *scanner, c byte) int {
if c == 'u' {
s.step = stateNu
return scanContinue
}
return s.error(c, "in literal null (expecting 'u')")
}
// stateNu is the state after reading `nu`.
func stateNu(s *scanner, c byte) int {
if c == 'l' {
s.step = stateNul
return scanContinue
}
return s.error(c, "in literal null (expecting 'l')")
}
// stateNul is the state after reading `nul`.
func stateNul(s *scanner, c byte) int {
if c == 'l' {
s.step = stateEndValue
return scanContinue
}
return s.error(c, "in literal null (expecting 'l')")
}
// stateError is the state after reaching a syntax error,
// such as after reading `[1}` or `5.1.2`.
func stateError(s *scanner, c byte) int {
return scanError
}
// error records an error and switches to the error state.
func (s *scanner) error(c byte, context string) int {
s.step = stateError
s.err = &SyntaxError{"invalid character " + quoteChar(c) + " " + context, s.bytes}
return scanError
}
// quoteChar formats c as a quoted character literal.
func quoteChar(c byte) string {
// special cases - different from quoted strings
if c == '\'' {
return `'\''`
}
if c == '"' {
return `'"'`
}
// use quoted string with different quotation marks
s := strconv.Quote(string(c))
return "'" + s[1:len(s)-1] + "'"
}
| go/src/encoding/json/scanner.go/0 | {
"file_path": "go/src/encoding/json/scanner.go",
"repo_id": "go",
"token_count": 5859
} | 240 |
// Copyright 2011 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 xml
import (
"bufio"
"bytes"
"encoding"
"errors"
"fmt"
"io"
"reflect"
"strconv"
"strings"
)
const (
// Header is a generic XML header suitable for use with the output of [Marshal].
// This is not automatically added to any output of this package,
// it is provided as a convenience.
Header = `<?xml version="1.0" encoding="UTF-8"?>` + "\n"
)
// Marshal returns the XML encoding of v.
//
// Marshal handles an array or slice by marshaling each of the elements.
// Marshal handles a pointer by marshaling the value it points at or, if the
// pointer is nil, by writing nothing. Marshal handles an interface value by
// marshaling the value it contains or, if the interface value is nil, by
// writing nothing. Marshal handles all other data by writing one or more XML
// elements containing the data.
//
// The name for the XML elements is taken from, in order of preference:
// - the tag on the XMLName field, if the data is a struct
// - the value of the XMLName field of type [Name]
// - the tag of the struct field used to obtain the data
// - the name of the struct field used to obtain the data
// - the name of the marshaled type
//
// The XML element for a struct contains marshaled elements for each of the
// exported fields of the struct, with these exceptions:
// - the XMLName field, described above, is omitted.
// - a field with tag "-" is omitted.
// - a field with tag "name,attr" becomes an attribute with
// the given name in the XML element.
// - a field with tag ",attr" becomes an attribute with the
// field name in the XML element.
// - a field with tag ",chardata" is written as character data,
// not as an XML element.
// - a field with tag ",cdata" is written as character data
// wrapped in one or more <![CDATA[ ... ]]> tags, not as an XML element.
// - a field with tag ",innerxml" is written verbatim, not subject
// to the usual marshaling procedure.
// - a field with tag ",comment" is written as an XML comment, not
// subject to the usual marshaling procedure. It must not contain
// the "--" string within it.
// - a field with a tag including the "omitempty" option is omitted
// if the field value is empty. The empty values are false, 0, any
// nil pointer or interface value, and any array, slice, map, or
// string of length zero.
// - an anonymous struct field is handled as if the fields of its
// value were part of the outer struct.
// - a field implementing [Marshaler] is written by calling its MarshalXML
// method.
// - a field implementing [encoding.TextMarshaler] is written by encoding the
// result of its MarshalText method as text.
//
// If a field uses a tag "a>b>c", then the element c will be nested inside
// parent elements a and b. Fields that appear next to each other that name
// the same parent will be enclosed in one XML element.
//
// If the XML name for a struct field is defined by both the field tag and the
// struct's XMLName field, the names must match.
//
// See [MarshalIndent] for an example.
//
// Marshal will return an error if asked to marshal a channel, function, or map.
func Marshal(v any) ([]byte, error) {
var b bytes.Buffer
enc := NewEncoder(&b)
if err := enc.Encode(v); err != nil {
return nil, err
}
if err := enc.Close(); err != nil {
return nil, err
}
return b.Bytes(), nil
}
// Marshaler is the interface implemented by objects that can marshal
// themselves into valid XML elements.
//
// MarshalXML encodes the receiver as zero or more XML elements.
// By convention, arrays or slices are typically encoded as a sequence
// of elements, one per entry.
// Using start as the element tag is not required, but doing so
// will enable [Unmarshal] to match the XML elements to the correct
// struct field.
// One common implementation strategy is to construct a separate
// value with a layout corresponding to the desired XML and then
// to encode it using e.EncodeElement.
// Another common strategy is to use repeated calls to e.EncodeToken
// to generate the XML output one token at a time.
// The sequence of encoded tokens must make up zero or more valid
// XML elements.
type Marshaler interface {
MarshalXML(e *Encoder, start StartElement) error
}
// MarshalerAttr is the interface implemented by objects that can marshal
// themselves into valid XML attributes.
//
// MarshalXMLAttr returns an XML attribute with the encoded value of the receiver.
// Using name as the attribute name is not required, but doing so
// will enable [Unmarshal] to match the attribute to the correct
// struct field.
// If MarshalXMLAttr returns the zero attribute [Attr]{}, no attribute
// will be generated in the output.
// MarshalXMLAttr is used only for struct fields with the
// "attr" option in the field tag.
type MarshalerAttr interface {
MarshalXMLAttr(name Name) (Attr, error)
}
// MarshalIndent works like [Marshal], but each XML element begins on a new
// indented line that starts with prefix and is followed by one or more
// copies of indent according to the nesting depth.
func MarshalIndent(v any, prefix, indent string) ([]byte, error) {
var b bytes.Buffer
enc := NewEncoder(&b)
enc.Indent(prefix, indent)
if err := enc.Encode(v); err != nil {
return nil, err
}
if err := enc.Close(); err != nil {
return nil, err
}
return b.Bytes(), nil
}
// An Encoder writes XML data to an output stream.
type Encoder struct {
p printer
}
// NewEncoder returns a new encoder that writes to w.
func NewEncoder(w io.Writer) *Encoder {
e := &Encoder{printer{w: bufio.NewWriter(w)}}
e.p.encoder = e
return e
}
// Indent sets the encoder to generate XML in which each element
// begins on a new indented line that starts with prefix and is followed by
// one or more copies of indent according to the nesting depth.
func (enc *Encoder) Indent(prefix, indent string) {
enc.p.prefix = prefix
enc.p.indent = indent
}
// Encode writes the XML encoding of v to the stream.
//
// See the documentation for [Marshal] for details about the conversion
// of Go values to XML.
//
// Encode calls [Encoder.Flush] before returning.
func (enc *Encoder) Encode(v any) error {
err := enc.p.marshalValue(reflect.ValueOf(v), nil, nil)
if err != nil {
return err
}
return enc.p.w.Flush()
}
// EncodeElement writes the XML encoding of v to the stream,
// using start as the outermost tag in the encoding.
//
// See the documentation for [Marshal] for details about the conversion
// of Go values to XML.
//
// EncodeElement calls [Encoder.Flush] before returning.
func (enc *Encoder) EncodeElement(v any, start StartElement) error {
err := enc.p.marshalValue(reflect.ValueOf(v), nil, &start)
if err != nil {
return err
}
return enc.p.w.Flush()
}
var (
begComment = []byte("<!--")
endComment = []byte("-->")
endProcInst = []byte("?>")
)
// EncodeToken writes the given XML token to the stream.
// It returns an error if [StartElement] and [EndElement] tokens are not properly matched.
//
// EncodeToken does not call [Encoder.Flush], because usually it is part of a larger operation
// such as [Encoder.Encode] or [Encoder.EncodeElement] (or a custom [Marshaler]'s MarshalXML invoked
// during those), and those will call Flush when finished.
// Callers that create an Encoder and then invoke EncodeToken directly, without
// using Encode or EncodeElement, need to call Flush when finished to ensure
// that the XML is written to the underlying writer.
//
// EncodeToken allows writing a [ProcInst] with Target set to "xml" only as the first token
// in the stream.
func (enc *Encoder) EncodeToken(t Token) error {
p := &enc.p
switch t := t.(type) {
case StartElement:
if err := p.writeStart(&t); err != nil {
return err
}
case EndElement:
if err := p.writeEnd(t.Name); err != nil {
return err
}
case CharData:
escapeText(p, t, false)
case Comment:
if bytes.Contains(t, endComment) {
return fmt.Errorf("xml: EncodeToken of Comment containing --> marker")
}
p.WriteString("<!--")
p.Write(t)
p.WriteString("-->")
return p.cachedWriteError()
case ProcInst:
// First token to be encoded which is also a ProcInst with target of xml
// is the xml declaration. The only ProcInst where target of xml is allowed.
if t.Target == "xml" && p.w.Buffered() != 0 {
return fmt.Errorf("xml: EncodeToken of ProcInst xml target only valid for xml declaration, first token encoded")
}
if !isNameString(t.Target) {
return fmt.Errorf("xml: EncodeToken of ProcInst with invalid Target")
}
if bytes.Contains(t.Inst, endProcInst) {
return fmt.Errorf("xml: EncodeToken of ProcInst containing ?> marker")
}
p.WriteString("<?")
p.WriteString(t.Target)
if len(t.Inst) > 0 {
p.WriteByte(' ')
p.Write(t.Inst)
}
p.WriteString("?>")
case Directive:
if !isValidDirective(t) {
return fmt.Errorf("xml: EncodeToken of Directive containing wrong < or > markers")
}
p.WriteString("<!")
p.Write(t)
p.WriteString(">")
default:
return fmt.Errorf("xml: EncodeToken of invalid token type")
}
return p.cachedWriteError()
}
// isValidDirective reports whether dir is a valid directive text,
// meaning angle brackets are matched, ignoring comments and strings.
func isValidDirective(dir Directive) bool {
var (
depth int
inquote uint8
incomment bool
)
for i, c := range dir {
switch {
case incomment:
if c == '>' {
if n := 1 + i - len(endComment); n >= 0 && bytes.Equal(dir[n:i+1], endComment) {
incomment = false
}
}
// Just ignore anything in comment
case inquote != 0:
if c == inquote {
inquote = 0
}
// Just ignore anything within quotes
case c == '\'' || c == '"':
inquote = c
case c == '<':
if i+len(begComment) < len(dir) && bytes.Equal(dir[i:i+len(begComment)], begComment) {
incomment = true
} else {
depth++
}
case c == '>':
if depth == 0 {
return false
}
depth--
}
}
return depth == 0 && inquote == 0 && !incomment
}
// Flush flushes any buffered XML to the underlying writer.
// See the [Encoder.EncodeToken] documentation for details about when it is necessary.
func (enc *Encoder) Flush() error {
return enc.p.w.Flush()
}
// Close the Encoder, indicating that no more data will be written. It flushes
// any buffered XML to the underlying writer and returns an error if the
// written XML is invalid (e.g. by containing unclosed elements).
func (enc *Encoder) Close() error {
return enc.p.Close()
}
type printer struct {
w *bufio.Writer
encoder *Encoder
seq int
indent string
prefix string
depth int
indentedIn bool
putNewline bool
attrNS map[string]string // map prefix -> name space
attrPrefix map[string]string // map name space -> prefix
prefixes []string
tags []Name
closed bool
err error
}
// createAttrPrefix finds the name space prefix attribute to use for the given name space,
// defining a new prefix if necessary. It returns the prefix.
func (p *printer) createAttrPrefix(url string) string {
if prefix := p.attrPrefix[url]; prefix != "" {
return prefix
}
// The "http://www.w3.org/XML/1998/namespace" name space is predefined as "xml"
// and must be referred to that way.
// (The "http://www.w3.org/2000/xmlns/" name space is also predefined as "xmlns",
// but users should not be trying to use that one directly - that's our job.)
if url == xmlURL {
return xmlPrefix
}
// Need to define a new name space.
if p.attrPrefix == nil {
p.attrPrefix = make(map[string]string)
p.attrNS = make(map[string]string)
}
// Pick a name. We try to use the final element of the path
// but fall back to _.
prefix := strings.TrimRight(url, "/")
if i := strings.LastIndex(prefix, "/"); i >= 0 {
prefix = prefix[i+1:]
}
if prefix == "" || !isName([]byte(prefix)) || strings.Contains(prefix, ":") {
prefix = "_"
}
// xmlanything is reserved and any variant of it regardless of
// case should be matched, so:
// (('X'|'x') ('M'|'m') ('L'|'l'))
// See Section 2.3 of https://www.w3.org/TR/REC-xml/
if len(prefix) >= 3 && strings.EqualFold(prefix[:3], "xml") {
prefix = "_" + prefix
}
if p.attrNS[prefix] != "" {
// Name is taken. Find a better one.
for p.seq++; ; p.seq++ {
if id := prefix + "_" + strconv.Itoa(p.seq); p.attrNS[id] == "" {
prefix = id
break
}
}
}
p.attrPrefix[url] = prefix
p.attrNS[prefix] = url
p.WriteString(`xmlns:`)
p.WriteString(prefix)
p.WriteString(`="`)
EscapeText(p, []byte(url))
p.WriteString(`" `)
p.prefixes = append(p.prefixes, prefix)
return prefix
}
// deleteAttrPrefix removes an attribute name space prefix.
func (p *printer) deleteAttrPrefix(prefix string) {
delete(p.attrPrefix, p.attrNS[prefix])
delete(p.attrNS, prefix)
}
func (p *printer) markPrefix() {
p.prefixes = append(p.prefixes, "")
}
func (p *printer) popPrefix() {
for len(p.prefixes) > 0 {
prefix := p.prefixes[len(p.prefixes)-1]
p.prefixes = p.prefixes[:len(p.prefixes)-1]
if prefix == "" {
break
}
p.deleteAttrPrefix(prefix)
}
}
var (
marshalerType = reflect.TypeFor[Marshaler]()
marshalerAttrType = reflect.TypeFor[MarshalerAttr]()
textMarshalerType = reflect.TypeFor[encoding.TextMarshaler]()
)
// marshalValue writes one or more XML elements representing val.
// If val was obtained from a struct field, finfo must have its details.
func (p *printer) marshalValue(val reflect.Value, finfo *fieldInfo, startTemplate *StartElement) error {
if startTemplate != nil && startTemplate.Name.Local == "" {
return fmt.Errorf("xml: EncodeElement of StartElement with missing name")
}
if !val.IsValid() {
return nil
}
if finfo != nil && finfo.flags&fOmitEmpty != 0 && isEmptyValue(val) {
return nil
}
// Drill into interfaces and pointers.
// This can turn into an infinite loop given a cyclic chain,
// but it matches the Go 1 behavior.
for val.Kind() == reflect.Interface || val.Kind() == reflect.Pointer {
if val.IsNil() {
return nil
}
val = val.Elem()
}
kind := val.Kind()
typ := val.Type()
// Check for marshaler.
if val.CanInterface() && typ.Implements(marshalerType) {
return p.marshalInterface(val.Interface().(Marshaler), defaultStart(typ, finfo, startTemplate))
}
if val.CanAddr() {
pv := val.Addr()
if pv.CanInterface() && pv.Type().Implements(marshalerType) {
return p.marshalInterface(pv.Interface().(Marshaler), defaultStart(pv.Type(), finfo, startTemplate))
}
}
// Check for text marshaler.
if val.CanInterface() && typ.Implements(textMarshalerType) {
return p.marshalTextInterface(val.Interface().(encoding.TextMarshaler), defaultStart(typ, finfo, startTemplate))
}
if val.CanAddr() {
pv := val.Addr()
if pv.CanInterface() && pv.Type().Implements(textMarshalerType) {
return p.marshalTextInterface(pv.Interface().(encoding.TextMarshaler), defaultStart(pv.Type(), finfo, startTemplate))
}
}
// Slices and arrays iterate over the elements. They do not have an enclosing tag.
if (kind == reflect.Slice || kind == reflect.Array) && typ.Elem().Kind() != reflect.Uint8 {
for i, n := 0, val.Len(); i < n; i++ {
if err := p.marshalValue(val.Index(i), finfo, startTemplate); err != nil {
return err
}
}
return nil
}
tinfo, err := getTypeInfo(typ)
if err != nil {
return err
}
// Create start element.
// Precedence for the XML element name is:
// 0. startTemplate
// 1. XMLName field in underlying struct;
// 2. field name/tag in the struct field; and
// 3. type name
var start StartElement
if startTemplate != nil {
start.Name = startTemplate.Name
start.Attr = append(start.Attr, startTemplate.Attr...)
} else if tinfo.xmlname != nil {
xmlname := tinfo.xmlname
if xmlname.name != "" {
start.Name.Space, start.Name.Local = xmlname.xmlns, xmlname.name
} else {
fv := xmlname.value(val, dontInitNilPointers)
if v, ok := fv.Interface().(Name); ok && v.Local != "" {
start.Name = v
}
}
}
if start.Name.Local == "" && finfo != nil {
start.Name.Space, start.Name.Local = finfo.xmlns, finfo.name
}
if start.Name.Local == "" {
name := typ.Name()
if i := strings.IndexByte(name, '['); i >= 0 {
// Truncate generic instantiation name. See issue 48318.
name = name[:i]
}
if name == "" {
return &UnsupportedTypeError{typ}
}
start.Name.Local = name
}
// Attributes
for i := range tinfo.fields {
finfo := &tinfo.fields[i]
if finfo.flags&fAttr == 0 {
continue
}
fv := finfo.value(val, dontInitNilPointers)
if finfo.flags&fOmitEmpty != 0 && (!fv.IsValid() || isEmptyValue(fv)) {
continue
}
if fv.Kind() == reflect.Interface && fv.IsNil() {
continue
}
name := Name{Space: finfo.xmlns, Local: finfo.name}
if err := p.marshalAttr(&start, name, fv); err != nil {
return err
}
}
// If an empty name was found, namespace is overridden with an empty space
if tinfo.xmlname != nil && start.Name.Space == "" &&
tinfo.xmlname.xmlns == "" && tinfo.xmlname.name == "" &&
len(p.tags) != 0 && p.tags[len(p.tags)-1].Space != "" {
start.Attr = append(start.Attr, Attr{Name{"", xmlnsPrefix}, ""})
}
if err := p.writeStart(&start); err != nil {
return err
}
if val.Kind() == reflect.Struct {
err = p.marshalStruct(tinfo, val)
} else {
s, b, err1 := p.marshalSimple(typ, val)
if err1 != nil {
err = err1
} else if b != nil {
EscapeText(p, b)
} else {
p.EscapeString(s)
}
}
if err != nil {
return err
}
if err := p.writeEnd(start.Name); err != nil {
return err
}
return p.cachedWriteError()
}
// marshalAttr marshals an attribute with the given name and value, adding to start.Attr.
func (p *printer) marshalAttr(start *StartElement, name Name, val reflect.Value) error {
if val.CanInterface() && val.Type().Implements(marshalerAttrType) {
attr, err := val.Interface().(MarshalerAttr).MarshalXMLAttr(name)
if err != nil {
return err
}
if attr.Name.Local != "" {
start.Attr = append(start.Attr, attr)
}
return nil
}
if val.CanAddr() {
pv := val.Addr()
if pv.CanInterface() && pv.Type().Implements(marshalerAttrType) {
attr, err := pv.Interface().(MarshalerAttr).MarshalXMLAttr(name)
if err != nil {
return err
}
if attr.Name.Local != "" {
start.Attr = append(start.Attr, attr)
}
return nil
}
}
if val.CanInterface() && val.Type().Implements(textMarshalerType) {
text, err := val.Interface().(encoding.TextMarshaler).MarshalText()
if err != nil {
return err
}
start.Attr = append(start.Attr, Attr{name, string(text)})
return nil
}
if val.CanAddr() {
pv := val.Addr()
if pv.CanInterface() && pv.Type().Implements(textMarshalerType) {
text, err := pv.Interface().(encoding.TextMarshaler).MarshalText()
if err != nil {
return err
}
start.Attr = append(start.Attr, Attr{name, string(text)})
return nil
}
}
// Dereference or skip nil pointer, interface values.
switch val.Kind() {
case reflect.Pointer, reflect.Interface:
if val.IsNil() {
return nil
}
val = val.Elem()
}
// Walk slices.
if val.Kind() == reflect.Slice && val.Type().Elem().Kind() != reflect.Uint8 {
n := val.Len()
for i := 0; i < n; i++ {
if err := p.marshalAttr(start, name, val.Index(i)); err != nil {
return err
}
}
return nil
}
if val.Type() == attrType {
start.Attr = append(start.Attr, val.Interface().(Attr))
return nil
}
s, b, err := p.marshalSimple(val.Type(), val)
if err != nil {
return err
}
if b != nil {
s = string(b)
}
start.Attr = append(start.Attr, Attr{name, s})
return nil
}
// defaultStart returns the default start element to use,
// given the reflect type, field info, and start template.
func defaultStart(typ reflect.Type, finfo *fieldInfo, startTemplate *StartElement) StartElement {
var start StartElement
// Precedence for the XML element name is as above,
// except that we do not look inside structs for the first field.
if startTemplate != nil {
start.Name = startTemplate.Name
start.Attr = append(start.Attr, startTemplate.Attr...)
} else if finfo != nil && finfo.name != "" {
start.Name.Local = finfo.name
start.Name.Space = finfo.xmlns
} else if typ.Name() != "" {
start.Name.Local = typ.Name()
} else {
// Must be a pointer to a named type,
// since it has the Marshaler methods.
start.Name.Local = typ.Elem().Name()
}
return start
}
// marshalInterface marshals a Marshaler interface value.
func (p *printer) marshalInterface(val Marshaler, start StartElement) error {
// Push a marker onto the tag stack so that MarshalXML
// cannot close the XML tags that it did not open.
p.tags = append(p.tags, Name{})
n := len(p.tags)
err := val.MarshalXML(p.encoder, start)
if err != nil {
return err
}
// Make sure MarshalXML closed all its tags. p.tags[n-1] is the mark.
if len(p.tags) > n {
return fmt.Errorf("xml: %s.MarshalXML wrote invalid XML: <%s> not closed", receiverType(val), p.tags[len(p.tags)-1].Local)
}
p.tags = p.tags[:n-1]
return nil
}
// marshalTextInterface marshals a TextMarshaler interface value.
func (p *printer) marshalTextInterface(val encoding.TextMarshaler, start StartElement) error {
if err := p.writeStart(&start); err != nil {
return err
}
text, err := val.MarshalText()
if err != nil {
return err
}
EscapeText(p, text)
return p.writeEnd(start.Name)
}
// writeStart writes the given start element.
func (p *printer) writeStart(start *StartElement) error {
if start.Name.Local == "" {
return fmt.Errorf("xml: start tag with no name")
}
p.tags = append(p.tags, start.Name)
p.markPrefix()
p.writeIndent(1)
p.WriteByte('<')
p.WriteString(start.Name.Local)
if start.Name.Space != "" {
p.WriteString(` xmlns="`)
p.EscapeString(start.Name.Space)
p.WriteByte('"')
}
// Attributes
for _, attr := range start.Attr {
name := attr.Name
if name.Local == "" {
continue
}
p.WriteByte(' ')
if name.Space != "" {
p.WriteString(p.createAttrPrefix(name.Space))
p.WriteByte(':')
}
p.WriteString(name.Local)
p.WriteString(`="`)
p.EscapeString(attr.Value)
p.WriteByte('"')
}
p.WriteByte('>')
return nil
}
func (p *printer) writeEnd(name Name) error {
if name.Local == "" {
return fmt.Errorf("xml: end tag with no name")
}
if len(p.tags) == 0 || p.tags[len(p.tags)-1].Local == "" {
return fmt.Errorf("xml: end tag </%s> without start tag", name.Local)
}
if top := p.tags[len(p.tags)-1]; top != name {
if top.Local != name.Local {
return fmt.Errorf("xml: end tag </%s> does not match start tag <%s>", name.Local, top.Local)
}
return fmt.Errorf("xml: end tag </%s> in namespace %s does not match start tag <%s> in namespace %s", name.Local, name.Space, top.Local, top.Space)
}
p.tags = p.tags[:len(p.tags)-1]
p.writeIndent(-1)
p.WriteByte('<')
p.WriteByte('/')
p.WriteString(name.Local)
p.WriteByte('>')
p.popPrefix()
return nil
}
func (p *printer) marshalSimple(typ reflect.Type, val reflect.Value) (string, []byte, error) {
switch val.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return strconv.FormatInt(val.Int(), 10), nil, nil
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
return strconv.FormatUint(val.Uint(), 10), nil, nil
case reflect.Float32, reflect.Float64:
return strconv.FormatFloat(val.Float(), 'g', -1, val.Type().Bits()), nil, nil
case reflect.String:
return val.String(), nil, nil
case reflect.Bool:
return strconv.FormatBool(val.Bool()), nil, nil
case reflect.Array:
if typ.Elem().Kind() != reflect.Uint8 {
break
}
// [...]byte
var bytes []byte
if val.CanAddr() {
bytes = val.Bytes()
} else {
bytes = make([]byte, val.Len())
reflect.Copy(reflect.ValueOf(bytes), val)
}
return "", bytes, nil
case reflect.Slice:
if typ.Elem().Kind() != reflect.Uint8 {
break
}
// []byte
return "", val.Bytes(), nil
}
return "", nil, &UnsupportedTypeError{typ}
}
var ddBytes = []byte("--")
// indirect drills into interfaces and pointers, returning the pointed-at value.
// If it encounters a nil interface or pointer, indirect returns that nil value.
// This can turn into an infinite loop given a cyclic chain,
// but it matches the Go 1 behavior.
func indirect(vf reflect.Value) reflect.Value {
for vf.Kind() == reflect.Interface || vf.Kind() == reflect.Pointer {
if vf.IsNil() {
return vf
}
vf = vf.Elem()
}
return vf
}
func (p *printer) marshalStruct(tinfo *typeInfo, val reflect.Value) error {
s := parentStack{p: p}
for i := range tinfo.fields {
finfo := &tinfo.fields[i]
if finfo.flags&fAttr != 0 {
continue
}
vf := finfo.value(val, dontInitNilPointers)
if !vf.IsValid() {
// The field is behind an anonymous struct field that's
// nil. Skip it.
continue
}
switch finfo.flags & fMode {
case fCDATA, fCharData:
emit := EscapeText
if finfo.flags&fMode == fCDATA {
emit = emitCDATA
}
if err := s.trim(finfo.parents); err != nil {
return err
}
if vf.CanInterface() && vf.Type().Implements(textMarshalerType) {
data, err := vf.Interface().(encoding.TextMarshaler).MarshalText()
if err != nil {
return err
}
if err := emit(p, data); err != nil {
return err
}
continue
}
if vf.CanAddr() {
pv := vf.Addr()
if pv.CanInterface() && pv.Type().Implements(textMarshalerType) {
data, err := pv.Interface().(encoding.TextMarshaler).MarshalText()
if err != nil {
return err
}
if err := emit(p, data); err != nil {
return err
}
continue
}
}
var scratch [64]byte
vf = indirect(vf)
switch vf.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
if err := emit(p, strconv.AppendInt(scratch[:0], vf.Int(), 10)); err != nil {
return err
}
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
if err := emit(p, strconv.AppendUint(scratch[:0], vf.Uint(), 10)); err != nil {
return err
}
case reflect.Float32, reflect.Float64:
if err := emit(p, strconv.AppendFloat(scratch[:0], vf.Float(), 'g', -1, vf.Type().Bits())); err != nil {
return err
}
case reflect.Bool:
if err := emit(p, strconv.AppendBool(scratch[:0], vf.Bool())); err != nil {
return err
}
case reflect.String:
if err := emit(p, []byte(vf.String())); err != nil {
return err
}
case reflect.Slice:
if elem, ok := vf.Interface().([]byte); ok {
if err := emit(p, elem); err != nil {
return err
}
}
}
continue
case fComment:
if err := s.trim(finfo.parents); err != nil {
return err
}
vf = indirect(vf)
k := vf.Kind()
if !(k == reflect.String || k == reflect.Slice && vf.Type().Elem().Kind() == reflect.Uint8) {
return fmt.Errorf("xml: bad type for comment field of %s", val.Type())
}
if vf.Len() == 0 {
continue
}
p.writeIndent(0)
p.WriteString("<!--")
dashDash := false
dashLast := false
switch k {
case reflect.String:
s := vf.String()
dashDash = strings.Contains(s, "--")
dashLast = s[len(s)-1] == '-'
if !dashDash {
p.WriteString(s)
}
case reflect.Slice:
b := vf.Bytes()
dashDash = bytes.Contains(b, ddBytes)
dashLast = b[len(b)-1] == '-'
if !dashDash {
p.Write(b)
}
default:
panic("can't happen")
}
if dashDash {
return fmt.Errorf(`xml: comments must not contain "--"`)
}
if dashLast {
// "--->" is invalid grammar. Make it "- -->"
p.WriteByte(' ')
}
p.WriteString("-->")
continue
case fInnerXML:
vf = indirect(vf)
iface := vf.Interface()
switch raw := iface.(type) {
case []byte:
p.Write(raw)
continue
case string:
p.WriteString(raw)
continue
}
case fElement, fElement | fAny:
if err := s.trim(finfo.parents); err != nil {
return err
}
if len(finfo.parents) > len(s.stack) {
if vf.Kind() != reflect.Pointer && vf.Kind() != reflect.Interface || !vf.IsNil() {
if err := s.push(finfo.parents[len(s.stack):]); err != nil {
return err
}
}
}
}
if err := p.marshalValue(vf, finfo, nil); err != nil {
return err
}
}
s.trim(nil)
return p.cachedWriteError()
}
// Write implements io.Writer
func (p *printer) Write(b []byte) (n int, err error) {
if p.closed && p.err == nil {
p.err = errors.New("use of closed Encoder")
}
if p.err == nil {
n, p.err = p.w.Write(b)
}
return n, p.err
}
// WriteString implements io.StringWriter
func (p *printer) WriteString(s string) (n int, err error) {
if p.closed && p.err == nil {
p.err = errors.New("use of closed Encoder")
}
if p.err == nil {
n, p.err = p.w.WriteString(s)
}
return n, p.err
}
// WriteByte implements io.ByteWriter
func (p *printer) WriteByte(c byte) error {
if p.closed && p.err == nil {
p.err = errors.New("use of closed Encoder")
}
if p.err == nil {
p.err = p.w.WriteByte(c)
}
return p.err
}
// Close the Encoder, indicating that no more data will be written. It flushes
// any buffered XML to the underlying writer and returns an error if the
// written XML is invalid (e.g. by containing unclosed elements).
func (p *printer) Close() error {
if p.closed {
return nil
}
p.closed = true
if err := p.w.Flush(); err != nil {
return err
}
if len(p.tags) > 0 {
return fmt.Errorf("unclosed tag <%s>", p.tags[len(p.tags)-1].Local)
}
return nil
}
// return the bufio Writer's cached write error
func (p *printer) cachedWriteError() error {
_, err := p.Write(nil)
return err
}
func (p *printer) writeIndent(depthDelta int) {
if len(p.prefix) == 0 && len(p.indent) == 0 {
return
}
if depthDelta < 0 {
p.depth--
if p.indentedIn {
p.indentedIn = false
return
}
p.indentedIn = false
}
if p.putNewline {
p.WriteByte('\n')
} else {
p.putNewline = true
}
if len(p.prefix) > 0 {
p.WriteString(p.prefix)
}
if len(p.indent) > 0 {
for i := 0; i < p.depth; i++ {
p.WriteString(p.indent)
}
}
if depthDelta > 0 {
p.depth++
p.indentedIn = true
}
}
type parentStack struct {
p *printer
stack []string
}
// trim updates the XML context to match the longest common prefix of the stack
// and the given parents. A closing tag will be written for every parent
// popped. Passing a zero slice or nil will close all the elements.
func (s *parentStack) trim(parents []string) error {
split := 0
for ; split < len(parents) && split < len(s.stack); split++ {
if parents[split] != s.stack[split] {
break
}
}
for i := len(s.stack) - 1; i >= split; i-- {
if err := s.p.writeEnd(Name{Local: s.stack[i]}); err != nil {
return err
}
}
s.stack = s.stack[:split]
return nil
}
// push adds parent elements to the stack and writes open tags.
func (s *parentStack) push(parents []string) error {
for i := 0; i < len(parents); i++ {
if err := s.p.writeStart(&StartElement{Name: Name{Local: parents[i]}}); err != nil {
return err
}
}
s.stack = append(s.stack, parents...)
return nil
}
// UnsupportedTypeError is returned when [Marshal] encounters a type
// that cannot be converted into XML.
type UnsupportedTypeError struct {
Type reflect.Type
}
func (e *UnsupportedTypeError) Error() string {
return "xml: unsupported type: " + e.Type.String()
}
func isEmptyValue(v reflect.Value) bool {
switch v.Kind() {
case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
return v.Len() == 0
case reflect.Bool,
reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr,
reflect.Float32, reflect.Float64,
reflect.Interface, reflect.Pointer:
return v.IsZero()
}
return false
}
| go/src/encoding/xml/marshal.go/0 | {
"file_path": "go/src/encoding/xml/marshal.go",
"repo_id": "go",
"token_count": 11965
} | 241 |
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package flag_test
import (
"flag"
"fmt"
"time"
)
func ExampleFlagSet() {
start := func(args []string) {
// A real program (not an example) would use flag.ExitOnError.
fs := flag.NewFlagSet("start", flag.ContinueOnError)
addr := fs.String("addr", ":8080", "`address` to listen on")
if err := fs.Parse(args); err != nil {
fmt.Printf("error: %s", err)
return
}
fmt.Printf("starting server on %s\n", *addr)
}
stop := func(args []string) {
fs := flag.NewFlagSet("stop", flag.ContinueOnError)
timeout := fs.Duration("timeout", time.Second, "stop timeout duration")
if err := fs.Parse(args); err != nil {
fmt.Printf("error: %s", err)
return
}
fmt.Printf("stopping server (timeout=%v)\n", *timeout)
}
main := func(args []string) {
subArgs := args[2:] // Drop program name and command.
switch args[1] {
case "start":
start(subArgs)
case "stop":
stop(subArgs)
default:
fmt.Printf("error: unknown command - %q\n", args[1])
// In a real program (not an example) print to os.Stderr and exit the program with non-zero value.
}
}
main([]string{"httpd", "start", "-addr", ":9999"})
main([]string{"httpd", "stop"})
main([]string{"http", "start", "-log-level", "verbose"})
// Output:
// starting server on :9999
// stopping server (timeout=1s)
// error: flag provided but not defined: -log-level
}
| go/src/flag/example_flagset_test.go/0 | {
"file_path": "go/src/flag/example_flagset_test.go",
"repo_id": "go",
"token_count": 570
} | 242 |
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package fmt
import (
"internal/fmtsort"
"io"
"os"
"reflect"
"strconv"
"sync"
"unicode/utf8"
)
// Strings for use with buffer.WriteString.
// This is less overhead than using buffer.Write with byte arrays.
const (
commaSpaceString = ", "
nilAngleString = "<nil>"
nilParenString = "(nil)"
nilString = "nil"
mapString = "map["
percentBangString = "%!"
missingString = "(MISSING)"
badIndexString = "(BADINDEX)"
panicString = "(PANIC="
extraString = "%!(EXTRA "
badWidthString = "%!(BADWIDTH)"
badPrecString = "%!(BADPREC)"
noVerbString = "%!(NOVERB)"
invReflectString = "<invalid reflect.Value>"
)
// State represents the printer state passed to custom formatters.
// It provides access to the [io.Writer] interface plus information about
// the flags and options for the operand's format specifier.
type State interface {
// Write is the function to call to emit formatted output to be printed.
Write(b []byte) (n int, err error)
// Width returns the value of the width option and whether it has been set.
Width() (wid int, ok bool)
// Precision returns the value of the precision option and whether it has been set.
Precision() (prec int, ok bool)
// Flag reports whether the flag c, a character, has been set.
Flag(c int) bool
}
// Formatter is implemented by any value that has a Format method.
// The implementation controls how [State] and rune are interpreted,
// and may call [Sprint] or [Fprint](f) etc. to generate its output.
type Formatter interface {
Format(f State, verb rune)
}
// Stringer is implemented by any value that has a String method,
// which defines the “native” format for that value.
// The String method is used to print values passed as an operand
// to any format that accepts a string or to an unformatted printer
// such as [Print].
type Stringer interface {
String() string
}
// GoStringer is implemented by any value that has a GoString method,
// which defines the Go syntax for that value.
// The GoString method is used to print values passed as an operand
// to a %#v format.
type GoStringer interface {
GoString() string
}
// FormatString returns a string representing the fully qualified formatting
// directive captured by the [State], followed by the argument verb. ([State] does not
// itself contain the verb.) The result has a leading percent sign followed by any
// flags, the width, and the precision. Missing flags, width, and precision are
// omitted. This function allows a [Formatter] to reconstruct the original
// directive triggering the call to Format.
func FormatString(state State, verb rune) string {
var tmp [16]byte // Use a local buffer.
b := append(tmp[:0], '%')
for _, c := range " +-#0" { // All known flags
if state.Flag(int(c)) { // The argument is an int for historical reasons.
b = append(b, byte(c))
}
}
if w, ok := state.Width(); ok {
b = strconv.AppendInt(b, int64(w), 10)
}
if p, ok := state.Precision(); ok {
b = append(b, '.')
b = strconv.AppendInt(b, int64(p), 10)
}
b = utf8.AppendRune(b, verb)
return string(b)
}
// Use simple []byte instead of bytes.Buffer to avoid large dependency.
type buffer []byte
func (b *buffer) write(p []byte) {
*b = append(*b, p...)
}
func (b *buffer) writeString(s string) {
*b = append(*b, s...)
}
func (b *buffer) writeByte(c byte) {
*b = append(*b, c)
}
func (b *buffer) writeRune(r rune) {
*b = utf8.AppendRune(*b, r)
}
// pp is used to store a printer's state and is reused with sync.Pool to avoid allocations.
type pp struct {
buf buffer
// arg holds the current item, as an interface{}.
arg any
// value is used instead of arg for reflect values.
value reflect.Value
// fmt is used to format basic items such as integers or strings.
fmt fmt
// reordered records whether the format string used argument reordering.
reordered bool
// goodArgNum records whether the most recent reordering directive was valid.
goodArgNum bool
// panicking is set by catchPanic to avoid infinite panic, recover, panic, ... recursion.
panicking bool
// erroring is set when printing an error string to guard against calling handleMethods.
erroring bool
// wrapErrs is set when the format string may contain a %w verb.
wrapErrs bool
// wrappedErrs records the targets of the %w verb.
wrappedErrs []int
}
var ppFree = sync.Pool{
New: func() any { return new(pp) },
}
// newPrinter allocates a new pp struct or grabs a cached one.
func newPrinter() *pp {
p := ppFree.Get().(*pp)
p.panicking = false
p.erroring = false
p.wrapErrs = false
p.fmt.init(&p.buf)
return p
}
// free saves used pp structs in ppFree; avoids an allocation per invocation.
func (p *pp) free() {
// Proper usage of a sync.Pool requires each entry to have approximately
// the same memory cost. To obtain this property when the stored type
// contains a variably-sized buffer, we add a hard limit on the maximum
// buffer to place back in the pool. If the buffer is larger than the
// limit, we drop the buffer and recycle just the printer.
//
// See https://golang.org/issue/23199.
if cap(p.buf) > 64*1024 {
p.buf = nil
} else {
p.buf = p.buf[:0]
}
if cap(p.wrappedErrs) > 8 {
p.wrappedErrs = nil
}
p.arg = nil
p.value = reflect.Value{}
p.wrappedErrs = p.wrappedErrs[:0]
ppFree.Put(p)
}
func (p *pp) Width() (wid int, ok bool) { return p.fmt.wid, p.fmt.widPresent }
func (p *pp) Precision() (prec int, ok bool) { return p.fmt.prec, p.fmt.precPresent }
func (p *pp) Flag(b int) bool {
switch b {
case '-':
return p.fmt.minus
case '+':
return p.fmt.plus || p.fmt.plusV
case '#':
return p.fmt.sharp || p.fmt.sharpV
case ' ':
return p.fmt.space
case '0':
return p.fmt.zero
}
return false
}
// Implement Write so we can call [Fprintf] on a pp (through [State]), for
// recursive use in custom verbs.
func (p *pp) Write(b []byte) (ret int, err error) {
p.buf.write(b)
return len(b), nil
}
// Implement WriteString so that we can call [io.WriteString]
// on a pp (through state), for efficiency.
func (p *pp) WriteString(s string) (ret int, err error) {
p.buf.writeString(s)
return len(s), nil
}
// These routines end in 'f' and take a format string.
// Fprintf formats according to a format specifier and writes to w.
// It returns the number of bytes written and any write error encountered.
func Fprintf(w io.Writer, format string, a ...any) (n int, err error) {
p := newPrinter()
p.doPrintf(format, a)
n, err = w.Write(p.buf)
p.free()
return
}
// Printf formats according to a format specifier and writes to standard output.
// It returns the number of bytes written and any write error encountered.
func Printf(format string, a ...any) (n int, err error) {
return Fprintf(os.Stdout, format, a...)
}
// Sprintf formats according to a format specifier and returns the resulting string.
func Sprintf(format string, a ...any) string {
p := newPrinter()
p.doPrintf(format, a)
s := string(p.buf)
p.free()
return s
}
// Appendf formats according to a format specifier, appends the result to the byte
// slice, and returns the updated slice.
func Appendf(b []byte, format string, a ...any) []byte {
p := newPrinter()
p.doPrintf(format, a)
b = append(b, p.buf...)
p.free()
return b
}
// These routines do not take a format string
// Fprint formats using the default formats for its operands and writes to w.
// Spaces are added between operands when neither is a string.
// It returns the number of bytes written and any write error encountered.
func Fprint(w io.Writer, a ...any) (n int, err error) {
p := newPrinter()
p.doPrint(a)
n, err = w.Write(p.buf)
p.free()
return
}
// Print formats using the default formats for its operands and writes to standard output.
// Spaces are added between operands when neither is a string.
// It returns the number of bytes written and any write error encountered.
func Print(a ...any) (n int, err error) {
return Fprint(os.Stdout, a...)
}
// Sprint formats using the default formats for its operands and returns the resulting string.
// Spaces are added between operands when neither is a string.
func Sprint(a ...any) string {
p := newPrinter()
p.doPrint(a)
s := string(p.buf)
p.free()
return s
}
// Append formats using the default formats for its operands, appends the result to
// the byte slice, and returns the updated slice.
func Append(b []byte, a ...any) []byte {
p := newPrinter()
p.doPrint(a)
b = append(b, p.buf...)
p.free()
return b
}
// These routines end in 'ln', do not take a format string,
// always add spaces between operands, and add a newline
// after the last operand.
// Fprintln formats using the default formats for its operands and writes to w.
// Spaces are always added between operands and a newline is appended.
// It returns the number of bytes written and any write error encountered.
func Fprintln(w io.Writer, a ...any) (n int, err error) {
p := newPrinter()
p.doPrintln(a)
n, err = w.Write(p.buf)
p.free()
return
}
// Println formats using the default formats for its operands and writes to standard output.
// Spaces are always added between operands and a newline is appended.
// It returns the number of bytes written and any write error encountered.
func Println(a ...any) (n int, err error) {
return Fprintln(os.Stdout, a...)
}
// Sprintln formats using the default formats for its operands and returns the resulting string.
// Spaces are always added between operands and a newline is appended.
func Sprintln(a ...any) string {
p := newPrinter()
p.doPrintln(a)
s := string(p.buf)
p.free()
return s
}
// Appendln formats using the default formats for its operands, appends the result
// to the byte slice, and returns the updated slice. Spaces are always added
// between operands and a newline is appended.
func Appendln(b []byte, a ...any) []byte {
p := newPrinter()
p.doPrintln(a)
b = append(b, p.buf...)
p.free()
return b
}
// getField gets the i'th field of the struct value.
// If the field itself is a non-nil interface, return a value for
// the thing inside the interface, not the interface itself.
func getField(v reflect.Value, i int) reflect.Value {
val := v.Field(i)
if val.Kind() == reflect.Interface && !val.IsNil() {
val = val.Elem()
}
return val
}
// tooLarge reports whether the magnitude of the integer is
// too large to be used as a formatting width or precision.
func tooLarge(x int) bool {
const max int = 1e6
return x > max || x < -max
}
// parsenum converts ASCII to integer. num is 0 (and isnum is false) if no number present.
func parsenum(s string, start, end int) (num int, isnum bool, newi int) {
if start >= end {
return 0, false, end
}
for newi = start; newi < end && '0' <= s[newi] && s[newi] <= '9'; newi++ {
if tooLarge(num) {
return 0, false, end // Overflow; crazy long number most likely.
}
num = num*10 + int(s[newi]-'0')
isnum = true
}
return
}
func (p *pp) unknownType(v reflect.Value) {
if !v.IsValid() {
p.buf.writeString(nilAngleString)
return
}
p.buf.writeByte('?')
p.buf.writeString(v.Type().String())
p.buf.writeByte('?')
}
func (p *pp) badVerb(verb rune) {
p.erroring = true
p.buf.writeString(percentBangString)
p.buf.writeRune(verb)
p.buf.writeByte('(')
switch {
case p.arg != nil:
p.buf.writeString(reflect.TypeOf(p.arg).String())
p.buf.writeByte('=')
p.printArg(p.arg, 'v')
case p.value.IsValid():
p.buf.writeString(p.value.Type().String())
p.buf.writeByte('=')
p.printValue(p.value, 'v', 0)
default:
p.buf.writeString(nilAngleString)
}
p.buf.writeByte(')')
p.erroring = false
}
func (p *pp) fmtBool(v bool, verb rune) {
switch verb {
case 't', 'v':
p.fmt.fmtBoolean(v)
default:
p.badVerb(verb)
}
}
// fmt0x64 formats a uint64 in hexadecimal and prefixes it with 0x or
// not, as requested, by temporarily setting the sharp flag.
func (p *pp) fmt0x64(v uint64, leading0x bool) {
sharp := p.fmt.sharp
p.fmt.sharp = leading0x
p.fmt.fmtInteger(v, 16, unsigned, 'v', ldigits)
p.fmt.sharp = sharp
}
// fmtInteger formats a signed or unsigned integer.
func (p *pp) fmtInteger(v uint64, isSigned bool, verb rune) {
switch verb {
case 'v':
if p.fmt.sharpV && !isSigned {
p.fmt0x64(v, true)
} else {
p.fmt.fmtInteger(v, 10, isSigned, verb, ldigits)
}
case 'd':
p.fmt.fmtInteger(v, 10, isSigned, verb, ldigits)
case 'b':
p.fmt.fmtInteger(v, 2, isSigned, verb, ldigits)
case 'o', 'O':
p.fmt.fmtInteger(v, 8, isSigned, verb, ldigits)
case 'x':
p.fmt.fmtInteger(v, 16, isSigned, verb, ldigits)
case 'X':
p.fmt.fmtInteger(v, 16, isSigned, verb, udigits)
case 'c':
p.fmt.fmtC(v)
case 'q':
p.fmt.fmtQc(v)
case 'U':
p.fmt.fmtUnicode(v)
default:
p.badVerb(verb)
}
}
// fmtFloat formats a float. The default precision for each verb
// is specified as last argument in the call to fmt_float.
func (p *pp) fmtFloat(v float64, size int, verb rune) {
switch verb {
case 'v':
p.fmt.fmtFloat(v, size, 'g', -1)
case 'b', 'g', 'G', 'x', 'X':
p.fmt.fmtFloat(v, size, verb, -1)
case 'f', 'e', 'E':
p.fmt.fmtFloat(v, size, verb, 6)
case 'F':
p.fmt.fmtFloat(v, size, 'f', 6)
default:
p.badVerb(verb)
}
}
// fmtComplex formats a complex number v with
// r = real(v) and j = imag(v) as (r+ji) using
// fmtFloat for r and j formatting.
func (p *pp) fmtComplex(v complex128, size int, verb rune) {
// Make sure any unsupported verbs are found before the
// calls to fmtFloat to not generate an incorrect error string.
switch verb {
case 'v', 'b', 'g', 'G', 'x', 'X', 'f', 'F', 'e', 'E':
oldPlus := p.fmt.plus
p.buf.writeByte('(')
p.fmtFloat(real(v), size/2, verb)
// Imaginary part always has a sign.
p.fmt.plus = true
p.fmtFloat(imag(v), size/2, verb)
p.buf.writeString("i)")
p.fmt.plus = oldPlus
default:
p.badVerb(verb)
}
}
func (p *pp) fmtString(v string, verb rune) {
switch verb {
case 'v':
if p.fmt.sharpV {
p.fmt.fmtQ(v)
} else {
p.fmt.fmtS(v)
}
case 's':
p.fmt.fmtS(v)
case 'x':
p.fmt.fmtSx(v, ldigits)
case 'X':
p.fmt.fmtSx(v, udigits)
case 'q':
p.fmt.fmtQ(v)
default:
p.badVerb(verb)
}
}
func (p *pp) fmtBytes(v []byte, verb rune, typeString string) {
switch verb {
case 'v', 'd':
if p.fmt.sharpV {
p.buf.writeString(typeString)
if v == nil {
p.buf.writeString(nilParenString)
return
}
p.buf.writeByte('{')
for i, c := range v {
if i > 0 {
p.buf.writeString(commaSpaceString)
}
p.fmt0x64(uint64(c), true)
}
p.buf.writeByte('}')
} else {
p.buf.writeByte('[')
for i, c := range v {
if i > 0 {
p.buf.writeByte(' ')
}
p.fmt.fmtInteger(uint64(c), 10, unsigned, verb, ldigits)
}
p.buf.writeByte(']')
}
case 's':
p.fmt.fmtBs(v)
case 'x':
p.fmt.fmtBx(v, ldigits)
case 'X':
p.fmt.fmtBx(v, udigits)
case 'q':
p.fmt.fmtQ(string(v))
default:
p.printValue(reflect.ValueOf(v), verb, 0)
}
}
func (p *pp) fmtPointer(value reflect.Value, verb rune) {
var u uintptr
switch value.Kind() {
case reflect.Chan, reflect.Func, reflect.Map, reflect.Pointer, reflect.Slice, reflect.UnsafePointer:
u = uintptr(value.UnsafePointer())
default:
p.badVerb(verb)
return
}
switch verb {
case 'v':
if p.fmt.sharpV {
p.buf.writeByte('(')
p.buf.writeString(value.Type().String())
p.buf.writeString(")(")
if u == 0 {
p.buf.writeString(nilString)
} else {
p.fmt0x64(uint64(u), true)
}
p.buf.writeByte(')')
} else {
if u == 0 {
p.fmt.padString(nilAngleString)
} else {
p.fmt0x64(uint64(u), !p.fmt.sharp)
}
}
case 'p':
p.fmt0x64(uint64(u), !p.fmt.sharp)
case 'b', 'o', 'd', 'x', 'X':
p.fmtInteger(uint64(u), unsigned, verb)
default:
p.badVerb(verb)
}
}
func (p *pp) catchPanic(arg any, verb rune, method string) {
if err := recover(); err != nil {
// If it's a nil pointer, just say "<nil>". The likeliest causes are a
// Stringer that fails to guard against nil or a nil pointer for a
// value receiver, and in either case, "<nil>" is a nice result.
if v := reflect.ValueOf(arg); v.Kind() == reflect.Pointer && v.IsNil() {
p.buf.writeString(nilAngleString)
return
}
// Otherwise print a concise panic message. Most of the time the panic
// value will print itself nicely.
if p.panicking {
// Nested panics; the recursion in printArg cannot succeed.
panic(err)
}
oldFlags := p.fmt.fmtFlags
// For this output we want default behavior.
p.fmt.clearflags()
p.buf.writeString(percentBangString)
p.buf.writeRune(verb)
p.buf.writeString(panicString)
p.buf.writeString(method)
p.buf.writeString(" method: ")
p.panicking = true
p.printArg(err, 'v')
p.panicking = false
p.buf.writeByte(')')
p.fmt.fmtFlags = oldFlags
}
}
func (p *pp) handleMethods(verb rune) (handled bool) {
if p.erroring {
return
}
if verb == 'w' {
// It is invalid to use %w other than with Errorf or with a non-error arg.
_, ok := p.arg.(error)
if !ok || !p.wrapErrs {
p.badVerb(verb)
return true
}
// If the arg is a Formatter, pass 'v' as the verb to it.
verb = 'v'
}
// Is it a Formatter?
if formatter, ok := p.arg.(Formatter); ok {
handled = true
defer p.catchPanic(p.arg, verb, "Format")
formatter.Format(p, verb)
return
}
// If we're doing Go syntax and the argument knows how to supply it, take care of it now.
if p.fmt.sharpV {
if stringer, ok := p.arg.(GoStringer); ok {
handled = true
defer p.catchPanic(p.arg, verb, "GoString")
// Print the result of GoString unadorned.
p.fmt.fmtS(stringer.GoString())
return
}
} else {
// If a string is acceptable according to the format, see if
// the value satisfies one of the string-valued interfaces.
// Println etc. set verb to %v, which is "stringable".
switch verb {
case 'v', 's', 'x', 'X', 'q':
// Is it an error or Stringer?
// The duplication in the bodies is necessary:
// setting handled and deferring catchPanic
// must happen before calling the method.
switch v := p.arg.(type) {
case error:
handled = true
defer p.catchPanic(p.arg, verb, "Error")
p.fmtString(v.Error(), verb)
return
case Stringer:
handled = true
defer p.catchPanic(p.arg, verb, "String")
p.fmtString(v.String(), verb)
return
}
}
}
return false
}
func (p *pp) printArg(arg any, verb rune) {
p.arg = arg
p.value = reflect.Value{}
if arg == nil {
switch verb {
case 'T', 'v':
p.fmt.padString(nilAngleString)
default:
p.badVerb(verb)
}
return
}
// Special processing considerations.
// %T (the value's type) and %p (its address) are special; we always do them first.
switch verb {
case 'T':
p.fmt.fmtS(reflect.TypeOf(arg).String())
return
case 'p':
p.fmtPointer(reflect.ValueOf(arg), 'p')
return
}
// Some types can be done without reflection.
switch f := arg.(type) {
case bool:
p.fmtBool(f, verb)
case float32:
p.fmtFloat(float64(f), 32, verb)
case float64:
p.fmtFloat(f, 64, verb)
case complex64:
p.fmtComplex(complex128(f), 64, verb)
case complex128:
p.fmtComplex(f, 128, verb)
case int:
p.fmtInteger(uint64(f), signed, verb)
case int8:
p.fmtInteger(uint64(f), signed, verb)
case int16:
p.fmtInteger(uint64(f), signed, verb)
case int32:
p.fmtInteger(uint64(f), signed, verb)
case int64:
p.fmtInteger(uint64(f), signed, verb)
case uint:
p.fmtInteger(uint64(f), unsigned, verb)
case uint8:
p.fmtInteger(uint64(f), unsigned, verb)
case uint16:
p.fmtInteger(uint64(f), unsigned, verb)
case uint32:
p.fmtInteger(uint64(f), unsigned, verb)
case uint64:
p.fmtInteger(f, unsigned, verb)
case uintptr:
p.fmtInteger(uint64(f), unsigned, verb)
case string:
p.fmtString(f, verb)
case []byte:
p.fmtBytes(f, verb, "[]byte")
case reflect.Value:
// Handle extractable values with special methods
// since printValue does not handle them at depth 0.
if f.IsValid() && f.CanInterface() {
p.arg = f.Interface()
if p.handleMethods(verb) {
return
}
}
p.printValue(f, verb, 0)
default:
// If the type is not simple, it might have methods.
if !p.handleMethods(verb) {
// Need to use reflection, since the type had no
// interface methods that could be used for formatting.
p.printValue(reflect.ValueOf(f), verb, 0)
}
}
}
// printValue is similar to printArg but starts with a reflect value, not an interface{} value.
// It does not handle 'p' and 'T' verbs because these should have been already handled by printArg.
func (p *pp) printValue(value reflect.Value, verb rune, depth int) {
// Handle values with special methods if not already handled by printArg (depth == 0).
if depth > 0 && value.IsValid() && value.CanInterface() {
p.arg = value.Interface()
if p.handleMethods(verb) {
return
}
}
p.arg = nil
p.value = value
switch f := value; value.Kind() {
case reflect.Invalid:
if depth == 0 {
p.buf.writeString(invReflectString)
} else {
switch verb {
case 'v':
p.buf.writeString(nilAngleString)
default:
p.badVerb(verb)
}
}
case reflect.Bool:
p.fmtBool(f.Bool(), verb)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
p.fmtInteger(uint64(f.Int()), signed, verb)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
p.fmtInteger(f.Uint(), unsigned, verb)
case reflect.Float32:
p.fmtFloat(f.Float(), 32, verb)
case reflect.Float64:
p.fmtFloat(f.Float(), 64, verb)
case reflect.Complex64:
p.fmtComplex(f.Complex(), 64, verb)
case reflect.Complex128:
p.fmtComplex(f.Complex(), 128, verb)
case reflect.String:
p.fmtString(f.String(), verb)
case reflect.Map:
if p.fmt.sharpV {
p.buf.writeString(f.Type().String())
if f.IsNil() {
p.buf.writeString(nilParenString)
return
}
p.buf.writeByte('{')
} else {
p.buf.writeString(mapString)
}
sorted := fmtsort.Sort(f)
for i, m := range sorted {
if i > 0 {
if p.fmt.sharpV {
p.buf.writeString(commaSpaceString)
} else {
p.buf.writeByte(' ')
}
}
p.printValue(m.Key, verb, depth+1)
p.buf.writeByte(':')
p.printValue(m.Value, verb, depth+1)
}
if p.fmt.sharpV {
p.buf.writeByte('}')
} else {
p.buf.writeByte(']')
}
case reflect.Struct:
if p.fmt.sharpV {
p.buf.writeString(f.Type().String())
}
p.buf.writeByte('{')
for i := 0; i < f.NumField(); i++ {
if i > 0 {
if p.fmt.sharpV {
p.buf.writeString(commaSpaceString)
} else {
p.buf.writeByte(' ')
}
}
if p.fmt.plusV || p.fmt.sharpV {
if name := f.Type().Field(i).Name; name != "" {
p.buf.writeString(name)
p.buf.writeByte(':')
}
}
p.printValue(getField(f, i), verb, depth+1)
}
p.buf.writeByte('}')
case reflect.Interface:
value := f.Elem()
if !value.IsValid() {
if p.fmt.sharpV {
p.buf.writeString(f.Type().String())
p.buf.writeString(nilParenString)
} else {
p.buf.writeString(nilAngleString)
}
} else {
p.printValue(value, verb, depth+1)
}
case reflect.Array, reflect.Slice:
switch verb {
case 's', 'q', 'x', 'X':
// Handle byte and uint8 slices and arrays special for the above verbs.
t := f.Type()
if t.Elem().Kind() == reflect.Uint8 {
var bytes []byte
if f.Kind() == reflect.Slice || f.CanAddr() {
bytes = f.Bytes()
} else {
// We have an array, but we cannot Bytes() a non-addressable array,
// so we build a slice by hand. This is a rare case but it would be nice
// if reflection could help a little more.
bytes = make([]byte, f.Len())
for i := range bytes {
bytes[i] = byte(f.Index(i).Uint())
}
}
p.fmtBytes(bytes, verb, t.String())
return
}
}
if p.fmt.sharpV {
p.buf.writeString(f.Type().String())
if f.Kind() == reflect.Slice && f.IsNil() {
p.buf.writeString(nilParenString)
return
}
p.buf.writeByte('{')
for i := 0; i < f.Len(); i++ {
if i > 0 {
p.buf.writeString(commaSpaceString)
}
p.printValue(f.Index(i), verb, depth+1)
}
p.buf.writeByte('}')
} else {
p.buf.writeByte('[')
for i := 0; i < f.Len(); i++ {
if i > 0 {
p.buf.writeByte(' ')
}
p.printValue(f.Index(i), verb, depth+1)
}
p.buf.writeByte(']')
}
case reflect.Pointer:
// pointer to array or slice or struct? ok at top level
// but not embedded (avoid loops)
if depth == 0 && f.UnsafePointer() != nil {
switch a := f.Elem(); a.Kind() {
case reflect.Array, reflect.Slice, reflect.Struct, reflect.Map:
p.buf.writeByte('&')
p.printValue(a, verb, depth+1)
return
}
}
fallthrough
case reflect.Chan, reflect.Func, reflect.UnsafePointer:
p.fmtPointer(f, verb)
default:
p.unknownType(f)
}
}
// intFromArg gets the argNumth element of a. On return, isInt reports whether the argument has integer type.
func intFromArg(a []any, argNum int) (num int, isInt bool, newArgNum int) {
newArgNum = argNum
if argNum < len(a) {
num, isInt = a[argNum].(int) // Almost always OK.
if !isInt {
// Work harder.
switch v := reflect.ValueOf(a[argNum]); v.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
n := v.Int()
if int64(int(n)) == n {
num = int(n)
isInt = true
}
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
n := v.Uint()
if int64(n) >= 0 && uint64(int(n)) == n {
num = int(n)
isInt = true
}
default:
// Already 0, false.
}
}
newArgNum = argNum + 1
if tooLarge(num) {
num = 0
isInt = false
}
}
return
}
// parseArgNumber returns the value of the bracketed number, minus 1
// (explicit argument numbers are one-indexed but we want zero-indexed).
// The opening bracket is known to be present at format[0].
// The returned values are the index, the number of bytes to consume
// up to the closing paren, if present, and whether the number parsed
// ok. The bytes to consume will be 1 if no closing paren is present.
func parseArgNumber(format string) (index int, wid int, ok bool) {
// There must be at least 3 bytes: [n].
if len(format) < 3 {
return 0, 1, false
}
// Find closing bracket.
for i := 1; i < len(format); i++ {
if format[i] == ']' {
width, ok, newi := parsenum(format, 1, i)
if !ok || newi != i {
return 0, i + 1, false
}
return width - 1, i + 1, true // arg numbers are one-indexed and skip paren.
}
}
return 0, 1, false
}
// argNumber returns the next argument to evaluate, which is either the value of the passed-in
// argNum or the value of the bracketed integer that begins format[i:]. It also returns
// the new value of i, that is, the index of the next byte of the format to process.
func (p *pp) argNumber(argNum int, format string, i int, numArgs int) (newArgNum, newi int, found bool) {
if len(format) <= i || format[i] != '[' {
return argNum, i, false
}
p.reordered = true
index, wid, ok := parseArgNumber(format[i:])
if ok && 0 <= index && index < numArgs {
return index, i + wid, true
}
p.goodArgNum = false
return argNum, i + wid, ok
}
func (p *pp) badArgNum(verb rune) {
p.buf.writeString(percentBangString)
p.buf.writeRune(verb)
p.buf.writeString(badIndexString)
}
func (p *pp) missingArg(verb rune) {
p.buf.writeString(percentBangString)
p.buf.writeRune(verb)
p.buf.writeString(missingString)
}
func (p *pp) doPrintf(format string, a []any) {
end := len(format)
argNum := 0 // we process one argument per non-trivial format
afterIndex := false // previous item in format was an index like [3].
p.reordered = false
formatLoop:
for i := 0; i < end; {
p.goodArgNum = true
lasti := i
for i < end && format[i] != '%' {
i++
}
if i > lasti {
p.buf.writeString(format[lasti:i])
}
if i >= end {
// done processing format string
break
}
// Process one verb
i++
// Do we have flags?
p.fmt.clearflags()
simpleFormat:
for ; i < end; i++ {
c := format[i]
switch c {
case '#':
p.fmt.sharp = true
case '0':
p.fmt.zero = true
case '+':
p.fmt.plus = true
case '-':
p.fmt.minus = true
case ' ':
p.fmt.space = true
default:
// Fast path for common case of ascii lower case simple verbs
// without precision or width or argument indices.
if 'a' <= c && c <= 'z' && argNum < len(a) {
switch c {
case 'w':
p.wrappedErrs = append(p.wrappedErrs, argNum)
fallthrough
case 'v':
// Go syntax
p.fmt.sharpV = p.fmt.sharp
p.fmt.sharp = false
// Struct-field syntax
p.fmt.plusV = p.fmt.plus
p.fmt.plus = false
}
p.printArg(a[argNum], rune(c))
argNum++
i++
continue formatLoop
}
// Format is more complex than simple flags and a verb or is malformed.
break simpleFormat
}
}
// Do we have an explicit argument index?
argNum, i, afterIndex = p.argNumber(argNum, format, i, len(a))
// Do we have width?
if i < end && format[i] == '*' {
i++
p.fmt.wid, p.fmt.widPresent, argNum = intFromArg(a, argNum)
if !p.fmt.widPresent {
p.buf.writeString(badWidthString)
}
// We have a negative width, so take its value and ensure
// that the minus flag is set
if p.fmt.wid < 0 {
p.fmt.wid = -p.fmt.wid
p.fmt.minus = true
p.fmt.zero = false // Do not pad with zeros to the right.
}
afterIndex = false
} else {
p.fmt.wid, p.fmt.widPresent, i = parsenum(format, i, end)
if afterIndex && p.fmt.widPresent { // "%[3]2d"
p.goodArgNum = false
}
}
// Do we have precision?
if i+1 < end && format[i] == '.' {
i++
if afterIndex { // "%[3].2d"
p.goodArgNum = false
}
argNum, i, afterIndex = p.argNumber(argNum, format, i, len(a))
if i < end && format[i] == '*' {
i++
p.fmt.prec, p.fmt.precPresent, argNum = intFromArg(a, argNum)
// Negative precision arguments don't make sense
if p.fmt.prec < 0 {
p.fmt.prec = 0
p.fmt.precPresent = false
}
if !p.fmt.precPresent {
p.buf.writeString(badPrecString)
}
afterIndex = false
} else {
p.fmt.prec, p.fmt.precPresent, i = parsenum(format, i, end)
if !p.fmt.precPresent {
p.fmt.prec = 0
p.fmt.precPresent = true
}
}
}
if !afterIndex {
argNum, i, afterIndex = p.argNumber(argNum, format, i, len(a))
}
if i >= end {
p.buf.writeString(noVerbString)
break
}
verb, size := rune(format[i]), 1
if verb >= utf8.RuneSelf {
verb, size = utf8.DecodeRuneInString(format[i:])
}
i += size
switch {
case verb == '%': // Percent does not absorb operands and ignores f.wid and f.prec.
p.buf.writeByte('%')
case !p.goodArgNum:
p.badArgNum(verb)
case argNum >= len(a): // No argument left over to print for the current verb.
p.missingArg(verb)
case verb == 'w':
p.wrappedErrs = append(p.wrappedErrs, argNum)
fallthrough
case verb == 'v':
// Go syntax
p.fmt.sharpV = p.fmt.sharp
p.fmt.sharp = false
// Struct-field syntax
p.fmt.plusV = p.fmt.plus
p.fmt.plus = false
fallthrough
default:
p.printArg(a[argNum], verb)
argNum++
}
}
// Check for extra arguments unless the call accessed the arguments
// out of order, in which case it's too expensive to detect if they've all
// been used and arguably OK if they're not.
if !p.reordered && argNum < len(a) {
p.fmt.clearflags()
p.buf.writeString(extraString)
for i, arg := range a[argNum:] {
if i > 0 {
p.buf.writeString(commaSpaceString)
}
if arg == nil {
p.buf.writeString(nilAngleString)
} else {
p.buf.writeString(reflect.TypeOf(arg).String())
p.buf.writeByte('=')
p.printArg(arg, 'v')
}
}
p.buf.writeByte(')')
}
}
func (p *pp) doPrint(a []any) {
prevString := false
for argNum, arg := range a {
isString := arg != nil && reflect.TypeOf(arg).Kind() == reflect.String
// Add a space between two non-string arguments.
if argNum > 0 && !isString && !prevString {
p.buf.writeByte(' ')
}
p.printArg(arg, 'v')
prevString = isString
}
}
// doPrintln is like doPrint but always adds a space between arguments
// and a newline after the last argument.
func (p *pp) doPrintln(a []any) {
for argNum, arg := range a {
if argNum > 0 {
p.buf.writeByte(' ')
}
p.printArg(arg, 'v')
}
p.buf.writeByte('\n')
}
| go/src/fmt/print.go/0 | {
"file_path": "go/src/fmt/print.go",
"repo_id": "go",
"token_count": 13127
} | 243 |
// Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package ast_test
import (
"go/ast"
"go/parser"
"go/token"
"testing"
)
func TestIssue33649(t *testing.T) {
for _, src := range []string{
`package p; func _()`,
`package p; func _() {`,
`package p; func _() { _ = 0`,
`package p; func _() { _ = 0 }`,
} {
fset := token.NewFileSet()
f, _ := parser.ParseFile(fset, "", src, parser.AllErrors)
if f == nil {
panic("invalid test setup: parser didn't return an AST")
}
// find corresponding token.File
var tf *token.File
fset.Iterate(func(f *token.File) bool {
tf = f
return true
})
tfEnd := tf.Base() + tf.Size()
fd := f.Decls[len(f.Decls)-1].(*ast.FuncDecl)
fdEnd := int(fd.End())
if fdEnd != tfEnd {
t.Errorf("%q: got fdEnd = %d; want %d (base = %d, size = %d)", src, fdEnd, tfEnd, tf.Base(), tf.Size())
}
}
}
// TestIssue28089 exercises the IsGenerated function.
func TestIssue28089(t *testing.T) {
for i, test := range []struct {
src string
want bool
}{
// No file comments.
{`package p`, false},
// Irrelevant file comments.
{`// Package p doc.
package p`, false},
// Special comment misplaced after package decl.
{`// Package p doc.
package p
// Code generated by gen. DO NOT EDIT.
`, false},
// Special comment appears inside string literal.
{`// Package p doc.
package p
const c = "` + "`" + `
// Code generated by gen. DO NOT EDIT.
` + "`" + `
`, false},
// Special comment appears properly.
{`// Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package p doc comment goes here.
//
// Code generated by gen. DO NOT EDIT.
package p
... `, true},
// Special comment is indented.
//
// Strictly, the indent should cause IsGenerated to
// yield false, but we cannot detect the indent
// without either source text or a token.File.
// In other words, the function signature cannot
// implement the spec. Let's brush this under the
// rug since well-formatted code has no indent.
{`// Package p doc comment goes here.
//
// Code generated by gen. DO NOT EDIT.
package p
... `, true},
// Special comment has unwanted spaces after "DO NOT EDIT."
{`// Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package p doc comment goes here.
//
// Code generated by gen. DO NOT EDIT.
package p
... `, false},
// Special comment has rogue interior space.
{`// Code generated by gen. DO NOT EDIT.
package p
`, false},
// Special comment lacks the middle portion.
{`// Code generated DO NOT EDIT.
package p
`, false},
// Special comment (incl. "//") appears within a /* block */ comment,
// an obscure corner case of the spec.
{`/* start of a general comment
// Code generated by tool; DO NOT EDIT.
end of a general comment */
// +build !dev
// Package comment.
package p
// Does match even though it's inside general comment (/*-style).
`, true},
} {
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "", test.src, parser.PackageClauseOnly|parser.ParseComments)
if f == nil {
t.Fatalf("parse %d failed to return AST: %v", i, err)
}
got := ast.IsGenerated(f)
if got != test.want {
t.Errorf("%d: IsGenerated on <<%s>> returned %t", i, test.src, got)
}
}
}
| go/src/go/ast/issues_test.go/0 | {
"file_path": "go/src/go/ast/issues_test.go",
"repo_id": "go",
"token_count": 1236
} | 244 |
// Doc from xtests
package doc_test
| go/src/go/build/testdata/doc/a_test.go/0 | {
"file_path": "go/src/go/build/testdata/doc/a_test.go",
"repo_id": "go",
"token_count": 12
} | 245 |
// 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 constant_test
import (
"fmt"
"go/constant"
"go/token"
"math"
"slices"
)
func Example_complexNumbers() {
// Create the complex number 2.3 + 5i.
ar := constant.MakeFloat64(2.3)
ai := constant.MakeImag(constant.MakeInt64(5))
a := constant.BinaryOp(ar, token.ADD, ai)
// Compute (2.3 + 5i) * 11.
b := constant.MakeUint64(11)
c := constant.BinaryOp(a, token.MUL, b)
// Convert c into a complex128.
Ar, exact := constant.Float64Val(constant.Real(c))
if !exact {
fmt.Printf("Could not represent real part %s exactly as float64\n", constant.Real(c))
}
Ai, exact := constant.Float64Val(constant.Imag(c))
if !exact {
fmt.Printf("Could not represent imaginary part %s as exactly as float64\n", constant.Imag(c))
}
C := complex(Ar, Ai)
fmt.Println("literal", 25.3+55i)
fmt.Println("go/constant", c)
fmt.Println("complex128", C)
// Output:
//
// Could not represent real part 25.3 exactly as float64
// literal (25.3+55i)
// go/constant (25.3 + 55i)
// complex128 (25.299999999999997+55i)
}
func ExampleBinaryOp() {
// 11 / 0.5
a := constant.MakeUint64(11)
b := constant.MakeFloat64(0.5)
c := constant.BinaryOp(a, token.QUO, b)
fmt.Println(c)
// Output: 22
}
func ExampleUnaryOp() {
vs := []constant.Value{
constant.MakeBool(true),
constant.MakeFloat64(2.7),
constant.MakeUint64(42),
}
for i, v := range vs {
switch v.Kind() {
case constant.Bool:
vs[i] = constant.UnaryOp(token.NOT, v, 0)
case constant.Float:
vs[i] = constant.UnaryOp(token.SUB, v, 0)
case constant.Int:
// Use 16-bit precision.
// This would be equivalent to ^uint16(v).
vs[i] = constant.UnaryOp(token.XOR, v, 16)
}
}
for _, v := range vs {
fmt.Println(v)
}
// Output:
//
// false
// -2.7
// 65493
}
func ExampleCompare() {
vs := []constant.Value{
constant.MakeString("Z"),
constant.MakeString("bacon"),
constant.MakeString("go"),
constant.MakeString("Frame"),
constant.MakeString("defer"),
constant.MakeFromLiteral(`"a"`, token.STRING, 0),
}
slices.SortFunc(vs, func(a, b constant.Value) int {
if constant.Compare(a, token.LSS, b) {
return -1
}
if constant.Compare(a, token.GTR, b) {
return +1
}
return 0
})
for _, v := range vs {
fmt.Println(constant.StringVal(v))
}
// Output:
//
// Frame
// Z
// a
// bacon
// defer
// go
}
func ExampleSign() {
zero := constant.MakeInt64(0)
one := constant.MakeInt64(1)
negOne := constant.MakeInt64(-1)
mkComplex := func(a, b constant.Value) constant.Value {
b = constant.MakeImag(b)
return constant.BinaryOp(a, token.ADD, b)
}
vs := []constant.Value{
negOne,
mkComplex(zero, negOne),
mkComplex(one, negOne),
mkComplex(negOne, one),
mkComplex(negOne, negOne),
zero,
mkComplex(zero, zero),
one,
mkComplex(zero, one),
mkComplex(one, one),
}
for _, v := range vs {
fmt.Printf("% d %s\n", constant.Sign(v), v)
}
// Output:
//
// -1 -1
// -1 (0 + -1i)
// -1 (1 + -1i)
// -1 (-1 + 1i)
// -1 (-1 + -1i)
// 0 0
// 0 (0 + 0i)
// 1 1
// 1 (0 + 1i)
// 1 (1 + 1i)
}
func ExampleVal() {
maxint := constant.MakeInt64(math.MaxInt64)
fmt.Printf("%v\n", constant.Val(maxint))
e := constant.MakeFloat64(math.E)
fmt.Printf("%v\n", constant.Val(e))
b := constant.MakeBool(true)
fmt.Printf("%v\n", constant.Val(b))
b = constant.Make(false)
fmt.Printf("%v\n", constant.Val(b))
// Output:
//
// 9223372036854775807
// 6121026514868073/2251799813685248
// true
// false
}
| go/src/go/constant/example_test.go/0 | {
"file_path": "go/src/go/constant/example_test.go",
"repo_id": "go",
"token_count": 1597
} | 246 |
This directory contains test files (*.txt) for the comment parser.
The files are in [txtar format](https://pkg.go.dev/golang.org/x/tools/txtar).
Consider this example:
-- input --
Hello.
-- gofmt --
Hello.
-- html --
<p>Hello.
-- markdown --
Hello.
-- text --
Hello.
Each `-- name --` line introduces a new file with the given name.
The file named “input” must be first and contains the input to
[comment.Parser](https://pkg.go.dev/go/doc/comment/#Parser).
The remaining files contain the expected output for the named format generated by
[comment.Printer](https://pkg.go.dev/go/doc/comment/#Printer):
“gofmt” for Printer.Comment (Go comment format, as used by gofmt),
“html” for Printer.HTML, “markdown” for Printer.Markdown, and “text” for Printer.Text.
The format can also be “dump” for a textual dump of the raw data structures.
The text before the `-- input --` line, if present, is JSON to be unmarshaled
to initialize a comment.Printer. For example, this test case sets the Printer's
TextWidth field to 20:
{"TextWidth": 20}
-- input --
Package gob manages streams of gobs - binary values exchanged between an
Encoder (transmitter) and a Decoder (receiver).
-- text --
Package gob
manages streams
of gobs - binary
values exchanged
between an Encoder
(transmitter) and a
Decoder (receiver).
| go/src/go/doc/comment/testdata/README.md/0 | {
"file_path": "go/src/go/doc/comment/testdata/README.md",
"repo_id": "go",
"token_count": 422
} | 247 |
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package doc
import "go/ast"
type Filter func(string) bool
func matchFields(fields *ast.FieldList, f Filter) bool {
if fields != nil {
for _, field := range fields.List {
for _, name := range field.Names {
if f(name.Name) {
return true
}
}
}
}
return false
}
func matchDecl(d *ast.GenDecl, f Filter) bool {
for _, d := range d.Specs {
switch v := d.(type) {
case *ast.ValueSpec:
for _, name := range v.Names {
if f(name.Name) {
return true
}
}
case *ast.TypeSpec:
if f(v.Name.Name) {
return true
}
// We don't match ordinary parameters in filterFuncs, so by analogy don't
// match type parameters here.
switch t := v.Type.(type) {
case *ast.StructType:
if matchFields(t.Fields, f) {
return true
}
case *ast.InterfaceType:
if matchFields(t.Methods, f) {
return true
}
}
}
}
return false
}
func filterValues(a []*Value, f Filter) []*Value {
w := 0
for _, vd := range a {
if matchDecl(vd.Decl, f) {
a[w] = vd
w++
}
}
return a[0:w]
}
func filterFuncs(a []*Func, f Filter) []*Func {
w := 0
for _, fd := range a {
if f(fd.Name) {
a[w] = fd
w++
}
}
return a[0:w]
}
func filterTypes(a []*Type, f Filter) []*Type {
w := 0
for _, td := range a {
n := 0 // number of matches
if matchDecl(td.Decl, f) {
n = 1
} else {
// type name doesn't match, but we may have matching consts, vars, factories or methods
td.Consts = filterValues(td.Consts, f)
td.Vars = filterValues(td.Vars, f)
td.Funcs = filterFuncs(td.Funcs, f)
td.Methods = filterFuncs(td.Methods, f)
n += len(td.Consts) + len(td.Vars) + len(td.Funcs) + len(td.Methods)
}
if n > 0 {
a[w] = td
w++
}
}
return a[0:w]
}
// Filter eliminates documentation for names that don't pass through the filter f.
// TODO(gri): Recognize "Type.Method" as a name.
func (p *Package) Filter(f Filter) {
p.Consts = filterValues(p.Consts, f)
p.Vars = filterValues(p.Vars, f)
p.Types = filterTypes(p.Types, f)
p.Funcs = filterFuncs(p.Funcs, f)
p.Doc = "" // don't show top-level package doc
}
| go/src/go/doc/filter.go/0 | {
"file_path": "go/src/go/doc/filter.go",
"repo_id": "go",
"token_count": 994
} | 248 |
// Package blank is a go/doc test for the handling of _. See issue ...
PACKAGE blank
IMPORTPATH
testdata/blank
IMPORTS
os
FILENAMES
testdata/blank.go
CONSTANTS
// T constants counting from unexported constants.
const (
tweedledee T = iota
tweedledum
C1
C2
alice
C3
redQueen int = iota
C4
)
// Constants with a single type that is not propagated.
const (
zero os.FileMode = 0
Default = 0644
Useless = 0312
WideOpen = 0777
)
// Constants with an imported type that is propagated.
const (
zero os.FileMode = 0
M1
M2
M3
)
// Package constants.
const (
_ int = iota
I1
I2
)
// Unexported constants counting from blank iota. See issue 9615.
const (
_ = iota
one = iota + 1
)
VARIABLES
//
var _ = T(55)
FUNCTIONS
//
func _()
TYPES
// S has a padding field.
type S struct {
H uint32
_ uint8
A uint8
}
//
type T int
// T constants counting from a blank constant.
const (
_ T = iota
T1
T2
)
| go/src/go/doc/testdata/blank.1.golden/0 | {
"file_path": "go/src/go/doc/testdata/blank.1.golden",
"repo_id": "go",
"token_count": 462
} | 249 |
// The package e is a go/doc test for embedded methods.
PACKAGE e
IMPORTPATH
testdata/e
FILENAMES
testdata/e.go
TYPES
// T1 has no embedded (level 1) M method due to conflict.
type T1 struct {
// contains filtered or unexported fields
}
// T2 has only M as top-level method.
type T2 struct {
// contains filtered or unexported fields
}
// T2.M should appear as method of T2.
func (T2) M()
// T3 has only M as top-level method.
type T3 struct {
// contains filtered or unexported fields
}
// T3.M should appear as method of T3.
func (T3) M()
//
type T4 struct{}
// T4.M should appear as method of T5 only if AllMethods is set.
func (*T4) M()
//
type T5 struct {
T4
}
//
type U1 struct {
*U1
}
// U1.M should appear as method of U1.
func (*U1) M()
//
type U2 struct {
*U3
}
// U2.M should appear as method of U2 and as method of U3 only if ...
func (*U2) M()
//
type U3 struct {
*U2
}
// U3.N should appear as method of U3 and as method of U2 only if ...
func (*U3) N()
//
type U4 struct {
// contains filtered or unexported fields
}
// U4.M should appear as method of U4.
func (*U4) M()
//
type V1 struct {
*V2
*V5
}
//
type V2 struct {
*V3
}
//
type V3 struct {
*V4
}
//
type V4 struct {
*V5
}
// V4.M should appear as method of V2 and V3 if AllMethods is set.
func (*V4) M()
//
type V5 struct {
*V6
}
//
type V6 struct{}
// V6.M should appear as method of V1 and V5 if AllMethods is set.
func (*V6) M()
| go/src/go/doc/testdata/e.0.golden/0 | {
"file_path": "go/src/go/doc/testdata/e.0.golden",
"repo_id": "go",
"token_count": 654
} | 250 |
// Copyright 2021 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package p_test
import (
"fmt"
"time"
)
type C1 interface {
string | int
}
type C2 interface {
M(time.Time)
}
type G[T C1] int
func g[T C2](x T) {}
type Tm int
func (Tm) M(time.Time) {}
type Foo int
func Example() {
fmt.Println("hello")
}
func ExampleGeneric() {
var x G[string]
g(Tm(3))
fmt.Println(x)
}
| go/src/go/doc/testdata/examples/generic_constraints.go/0 | {
"file_path": "go/src/go/doc/testdata/examples/generic_constraints.go",
"repo_id": "go",
"token_count": 196
} | 251 |
// 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.
// This file provides a simple framework to add benchmarks
// based on generated input (source) files.
package format_test
import (
"bytes"
"flag"
"fmt"
"go/format"
"os"
"testing"
)
var debug = flag.Bool("debug", false, "write .src files containing formatting input; for debugging")
// array1 generates an array literal with n elements of the form:
//
// var _ = [...]byte{
//
// // 0
// 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
// 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
// 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
// 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
// 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27,
// // 40
// 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
// 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
// ...
func array1(buf *bytes.Buffer, n int) {
buf.WriteString("var _ = [...]byte{\n")
for i := 0; i < n; {
if i%10 == 0 {
fmt.Fprintf(buf, "\t// %d\n", i)
}
buf.WriteByte('\t')
for j := 0; j < 8; j++ {
fmt.Fprintf(buf, "0x%02x, ", byte(i))
i++
}
buf.WriteString("\n")
}
buf.WriteString("}\n")
}
var tests = []struct {
name string
gen func(*bytes.Buffer, int)
n int
}{
{"array1", array1, 10000},
// add new test cases here as needed
}
func BenchmarkFormat(b *testing.B) {
var src bytes.Buffer
for _, t := range tests {
src.Reset()
src.WriteString("package p\n")
t.gen(&src, t.n)
data := src.Bytes()
if *debug {
filename := t.name + ".src"
err := os.WriteFile(filename, data, 0660)
if err != nil {
b.Fatalf("couldn't write %s: %v", filename, err)
}
}
b.Run(fmt.Sprintf("%s-%d", t.name, t.n), func(b *testing.B) {
b.SetBytes(int64(len(data)))
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
var err error
sink, err = format.Source(data)
if err != nil {
b.Fatal(err)
}
}
})
}
}
var sink []byte
| go/src/go/format/benchmark_test.go/0 | {
"file_path": "go/src/go/format/benchmark_test.go",
"repo_id": "go",
"token_count": 977
} | 252 |
// Copyright 2015 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.
// This file implements support functionality for iimport.go.
package gcimporter
import (
"fmt"
"go/token"
"go/types"
"internal/pkgbits"
"sync"
)
func assert(b bool) {
if !b {
panic("assertion failed")
}
}
func errorf(format string, args ...any) {
panic(fmt.Sprintf(format, args...))
}
// deltaNewFile is a magic line delta offset indicating a new file.
// We use -64 because it is rare; see issue 20080 and CL 41619.
// -64 is the smallest int that fits in a single byte as a varint.
const deltaNewFile = -64
// Synthesize a token.Pos
type fakeFileSet struct {
fset *token.FileSet
files map[string]*fileInfo
}
type fileInfo struct {
file *token.File
lastline int
}
const maxlines = 64 * 1024
func (s *fakeFileSet) pos(file string, line, column int) token.Pos {
// TODO(mdempsky): Make use of column.
// Since we don't know the set of needed file positions, we reserve
// maxlines positions per file. We delay calling token.File.SetLines until
// all positions have been calculated (by way of fakeFileSet.setLines), so
// that we can avoid setting unnecessary lines. See also golang/go#46586.
f := s.files[file]
if f == nil {
f = &fileInfo{file: s.fset.AddFile(file, -1, maxlines)}
s.files[file] = f
}
if line > maxlines {
line = 1
}
if line > f.lastline {
f.lastline = line
}
// Return a fake position assuming that f.file consists only of newlines.
return token.Pos(f.file.Base() + line - 1)
}
func (s *fakeFileSet) setLines() {
fakeLinesOnce.Do(func() {
fakeLines = make([]int, maxlines)
for i := range fakeLines {
fakeLines[i] = i
}
})
for _, f := range s.files {
f.file.SetLines(fakeLines[:f.lastline])
}
}
var (
fakeLines []int
fakeLinesOnce sync.Once
)
func chanDir(d int) types.ChanDir {
// tag values must match the constants in cmd/compile/internal/gc/go.go
switch d {
case 1 /* Crecv */ :
return types.RecvOnly
case 2 /* Csend */ :
return types.SendOnly
case 3 /* Cboth */ :
return types.SendRecv
default:
errorf("unexpected channel dir %d", d)
return 0
}
}
var predeclared = []types.Type{
// basic types
types.Typ[types.Bool],
types.Typ[types.Int],
types.Typ[types.Int8],
types.Typ[types.Int16],
types.Typ[types.Int32],
types.Typ[types.Int64],
types.Typ[types.Uint],
types.Typ[types.Uint8],
types.Typ[types.Uint16],
types.Typ[types.Uint32],
types.Typ[types.Uint64],
types.Typ[types.Uintptr],
types.Typ[types.Float32],
types.Typ[types.Float64],
types.Typ[types.Complex64],
types.Typ[types.Complex128],
types.Typ[types.String],
// basic type aliases
types.Universe.Lookup("byte").Type(),
types.Universe.Lookup("rune").Type(),
// error
types.Universe.Lookup("error").Type(),
// untyped types
types.Typ[types.UntypedBool],
types.Typ[types.UntypedInt],
types.Typ[types.UntypedRune],
types.Typ[types.UntypedFloat],
types.Typ[types.UntypedComplex],
types.Typ[types.UntypedString],
types.Typ[types.UntypedNil],
// package unsafe
types.Typ[types.UnsafePointer],
// invalid type
types.Typ[types.Invalid], // only appears in packages with errors
// used internally by gc; never used by this package or in .a files
// not to be confused with the universe any
anyType{},
// comparable
types.Universe.Lookup("comparable").Type(),
// "any" has special handling: see usage of predeclared.
}
type anyType struct{}
func (t anyType) Underlying() types.Type { return t }
func (t anyType) String() string { return "any" }
// See cmd/compile/internal/noder.derivedInfo.
type derivedInfo struct {
idx pkgbits.Index
needed bool
}
// See cmd/compile/internal/noder.typeInfo.
type typeInfo struct {
idx pkgbits.Index
derived bool
}
// See cmd/compile/internal/types.SplitVargenSuffix.
func splitVargenSuffix(name string) (base, suffix string) {
i := len(name)
for i > 0 && name[i-1] >= '0' && name[i-1] <= '9' {
i--
}
const dot = "·"
if i >= len(dot) && name[i-len(dot):i] == dot {
i -= len(dot)
return name[:i], name[i:]
}
return name, ""
}
| go/src/go/internal/gcimporter/support.go/0 | {
"file_path": "go/src/go/internal/gcimporter/support.go",
"repo_id": "go",
"token_count": 1574
} | 253 |
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package parser
import (
"fmt"
"go/ast"
"go/token"
"io/fs"
"strings"
"testing"
)
var validFiles = []string{
"parser.go",
"parser_test.go",
"error_test.go",
"short_test.go",
}
func TestParse(t *testing.T) {
for _, filename := range validFiles {
_, err := ParseFile(token.NewFileSet(), filename, nil, DeclarationErrors)
if err != nil {
t.Fatalf("ParseFile(%s): %v", filename, err)
}
}
}
func nameFilter(filename string) bool {
switch filename {
case "parser.go", "interface.go", "parser_test.go":
return true
case "parser.go.orig":
return true // permit but should be ignored by ParseDir
}
return false
}
func dirFilter(f fs.FileInfo) bool { return nameFilter(f.Name()) }
func TestParseFile(t *testing.T) {
src := "package p\nvar _=s[::]+\ns[::]+\ns[::]+\ns[::]+\ns[::]+\ns[::]+\ns[::]+\ns[::]+\ns[::]+\ns[::]+\ns[::]+\ns[::]"
_, err := ParseFile(token.NewFileSet(), "", src, 0)
if err == nil {
t.Errorf("ParseFile(%s) succeeded unexpectedly", src)
}
}
func TestParseExprFrom(t *testing.T) {
src := "s[::]+\ns[::]+\ns[::]+\ns[::]+\ns[::]+\ns[::]+\ns[::]+\ns[::]+\ns[::]+\ns[::]+\ns[::]+\ns[::]"
_, err := ParseExprFrom(token.NewFileSet(), "", src, 0)
if err == nil {
t.Errorf("ParseExprFrom(%s) succeeded unexpectedly", src)
}
}
func TestParseDir(t *testing.T) {
path := "."
pkgs, err := ParseDir(token.NewFileSet(), path, dirFilter, 0)
if err != nil {
t.Fatalf("ParseDir(%s): %v", path, err)
}
if n := len(pkgs); n != 1 {
t.Errorf("got %d packages; want 1", n)
}
pkg := pkgs["parser"]
if pkg == nil {
t.Errorf(`package "parser" not found`)
return
}
if n := len(pkg.Files); n != 3 {
t.Errorf("got %d package files; want 3", n)
}
for filename := range pkg.Files {
if !nameFilter(filename) {
t.Errorf("unexpected package file: %s", filename)
}
}
}
func TestIssue42951(t *testing.T) {
path := "./testdata/issue42951"
_, err := ParseDir(token.NewFileSet(), path, nil, 0)
if err != nil {
t.Errorf("ParseDir(%s): %v", path, err)
}
}
func TestParseExpr(t *testing.T) {
// just kicking the tires:
// a valid arithmetic expression
src := "a + b"
x, err := ParseExpr(src)
if err != nil {
t.Errorf("ParseExpr(%q): %v", src, err)
}
// sanity check
if _, ok := x.(*ast.BinaryExpr); !ok {
t.Errorf("ParseExpr(%q): got %T, want *ast.BinaryExpr", src, x)
}
// a valid type expression
src = "struct{x *int}"
x, err = ParseExpr(src)
if err != nil {
t.Errorf("ParseExpr(%q): %v", src, err)
}
// sanity check
if _, ok := x.(*ast.StructType); !ok {
t.Errorf("ParseExpr(%q): got %T, want *ast.StructType", src, x)
}
// an invalid expression
src = "a + *"
x, err = ParseExpr(src)
if err == nil {
t.Errorf("ParseExpr(%q): got no error", src)
}
if x == nil {
t.Errorf("ParseExpr(%q): got no (partial) result", src)
}
if _, ok := x.(*ast.BinaryExpr); !ok {
t.Errorf("ParseExpr(%q): got %T, want *ast.BinaryExpr", src, x)
}
// a valid expression followed by extra tokens is invalid
src = "a[i] := x"
if _, err := ParseExpr(src); err == nil {
t.Errorf("ParseExpr(%q): got no error", src)
}
// a semicolon is not permitted unless automatically inserted
src = "a + b\n"
if _, err := ParseExpr(src); err != nil {
t.Errorf("ParseExpr(%q): got error %s", src, err)
}
src = "a + b;"
if _, err := ParseExpr(src); err == nil {
t.Errorf("ParseExpr(%q): got no error", src)
}
// various other stuff following a valid expression
const validExpr = "a + b"
const anything = "dh3*#D)#_"
for _, c := range "!)]};," {
src := validExpr + string(c) + anything
if _, err := ParseExpr(src); err == nil {
t.Errorf("ParseExpr(%q): got no error", src)
}
}
// ParseExpr must not crash
for _, src := range valids {
ParseExpr(src)
}
}
func TestColonEqualsScope(t *testing.T) {
f, err := ParseFile(token.NewFileSet(), "", `package p; func f() { x, y, z := x, y, z }`, 0)
if err != nil {
t.Fatal(err)
}
// RHS refers to undefined globals; LHS does not.
as := f.Decls[0].(*ast.FuncDecl).Body.List[0].(*ast.AssignStmt)
for _, v := range as.Rhs {
id := v.(*ast.Ident)
if id.Obj != nil {
t.Errorf("rhs %s has Obj, should not", id.Name)
}
}
for _, v := range as.Lhs {
id := v.(*ast.Ident)
if id.Obj == nil {
t.Errorf("lhs %s does not have Obj, should", id.Name)
}
}
}
func TestVarScope(t *testing.T) {
f, err := ParseFile(token.NewFileSet(), "", `package p; func f() { var x, y, z = x, y, z }`, 0)
if err != nil {
t.Fatal(err)
}
// RHS refers to undefined globals; LHS does not.
as := f.Decls[0].(*ast.FuncDecl).Body.List[0].(*ast.DeclStmt).Decl.(*ast.GenDecl).Specs[0].(*ast.ValueSpec)
for _, v := range as.Values {
id := v.(*ast.Ident)
if id.Obj != nil {
t.Errorf("rhs %s has Obj, should not", id.Name)
}
}
for _, id := range as.Names {
if id.Obj == nil {
t.Errorf("lhs %s does not have Obj, should", id.Name)
}
}
}
func TestObjects(t *testing.T) {
const src = `
package p
import fmt "fmt"
const pi = 3.14
type T struct{}
var x int
func f() { L: }
`
f, err := ParseFile(token.NewFileSet(), "", src, 0)
if err != nil {
t.Fatal(err)
}
objects := map[string]ast.ObjKind{
"p": ast.Bad, // not in a scope
"fmt": ast.Bad, // not resolved yet
"pi": ast.Con,
"T": ast.Typ,
"x": ast.Var,
"int": ast.Bad, // not resolved yet
"f": ast.Fun,
"L": ast.Lbl,
}
ast.Inspect(f, func(n ast.Node) bool {
if ident, ok := n.(*ast.Ident); ok {
obj := ident.Obj
if obj == nil {
if objects[ident.Name] != ast.Bad {
t.Errorf("no object for %s", ident.Name)
}
return true
}
if obj.Name != ident.Name {
t.Errorf("names don't match: obj.Name = %s, ident.Name = %s", obj.Name, ident.Name)
}
kind := objects[ident.Name]
if obj.Kind != kind {
t.Errorf("%s: obj.Kind = %s; want %s", ident.Name, obj.Kind, kind)
}
}
return true
})
}
func TestUnresolved(t *testing.T) {
f, err := ParseFile(token.NewFileSet(), "", `
package p
//
func f1a(int)
func f2a(byte, int, float)
func f3a(a, b int, c float)
func f4a(...complex)
func f5a(a s1a, b ...complex)
//
func f1b(*int)
func f2b([]byte, (int), *float)
func f3b(a, b *int, c []float)
func f4b(...*complex)
func f5b(a s1a, b ...[]complex)
//
type s1a struct { int }
type s2a struct { byte; int; s1a }
type s3a struct { a, b int; c float }
//
type s1b struct { *int }
type s2b struct { byte; int; *float }
type s3b struct { a, b *s3b; c []float }
`, 0)
if err != nil {
t.Fatal(err)
}
want := "int " + // f1a
"byte int float " + // f2a
"int float " + // f3a
"complex " + // f4a
"complex " + // f5a
//
"int " + // f1b
"byte int float " + // f2b
"int float " + // f3b
"complex " + // f4b
"complex " + // f5b
//
"int " + // s1a
"byte int " + // s2a
"int float " + // s3a
//
"int " + // s1a
"byte int float " + // s2a
"float " // s3a
// collect unresolved identifiers
var buf strings.Builder
for _, u := range f.Unresolved {
buf.WriteString(u.Name)
buf.WriteByte(' ')
}
got := buf.String()
if got != want {
t.Errorf("\ngot: %s\nwant: %s", got, want)
}
}
func TestCommentGroups(t *testing.T) {
f, err := ParseFile(token.NewFileSet(), "", `
package p /* 1a */ /* 1b */ /* 1c */ // 1d
/* 2a
*/
// 2b
const pi = 3.1415
/* 3a */ // 3b
/* 3c */ const e = 2.7182
// Example from go.dev/issue/3139
func ExampleCount() {
fmt.Println(strings.Count("cheese", "e"))
fmt.Println(strings.Count("five", "")) // before & after each rune
// Output:
// 3
// 5
}
`, ParseComments)
if err != nil {
t.Fatal(err)
}
expected := [][]string{
{"/* 1a */", "/* 1b */", "/* 1c */", "// 1d"},
{"/* 2a\n*/", "// 2b"},
{"/* 3a */", "// 3b", "/* 3c */"},
{"// Example from go.dev/issue/3139"},
{"// before & after each rune"},
{"// Output:", "// 3", "// 5"},
}
if len(f.Comments) != len(expected) {
t.Fatalf("got %d comment groups; expected %d", len(f.Comments), len(expected))
}
for i, exp := range expected {
got := f.Comments[i].List
if len(got) != len(exp) {
t.Errorf("got %d comments in group %d; expected %d", len(got), i, len(exp))
continue
}
for j, exp := range exp {
got := got[j].Text
if got != exp {
t.Errorf("got %q in group %d; expected %q", got, i, exp)
}
}
}
}
func getField(file *ast.File, fieldname string) *ast.Field {
parts := strings.Split(fieldname, ".")
for _, d := range file.Decls {
if d, ok := d.(*ast.GenDecl); ok && d.Tok == token.TYPE {
for _, s := range d.Specs {
if s, ok := s.(*ast.TypeSpec); ok && s.Name.Name == parts[0] {
if s, ok := s.Type.(*ast.StructType); ok {
for _, f := range s.Fields.List {
for _, name := range f.Names {
if name.Name == parts[1] {
return f
}
}
}
}
}
}
}
}
return nil
}
// Don't use ast.CommentGroup.Text() - we want to see exact comment text.
func commentText(c *ast.CommentGroup) string {
var buf strings.Builder
if c != nil {
for _, c := range c.List {
buf.WriteString(c.Text)
}
}
return buf.String()
}
func checkFieldComments(t *testing.T, file *ast.File, fieldname, lead, line string) {
f := getField(file, fieldname)
if f == nil {
t.Fatalf("field not found: %s", fieldname)
}
if got := commentText(f.Doc); got != lead {
t.Errorf("got lead comment %q; expected %q", got, lead)
}
if got := commentText(f.Comment); got != line {
t.Errorf("got line comment %q; expected %q", got, line)
}
}
func TestLeadAndLineComments(t *testing.T) {
f, err := ParseFile(token.NewFileSet(), "", `
package p
type T struct {
/* F1 lead comment */
//
F1 int /* F1 */ // line comment
// F2 lead
// comment
F2 int // F2 line comment
// f3 lead comment
f3 int // f3 line comment
f4 int /* not a line comment */ ;
f5 int ; // f5 line comment
f6 int ; /* f6 line comment */
f7 int ; /*f7a*/ /*f7b*/ //f7c
}
`, ParseComments)
if err != nil {
t.Fatal(err)
}
checkFieldComments(t, f, "T.F1", "/* F1 lead comment *///", "/* F1 */// line comment")
checkFieldComments(t, f, "T.F2", "// F2 lead// comment", "// F2 line comment")
checkFieldComments(t, f, "T.f3", "// f3 lead comment", "// f3 line comment")
checkFieldComments(t, f, "T.f4", "", "")
checkFieldComments(t, f, "T.f5", "", "// f5 line comment")
checkFieldComments(t, f, "T.f6", "", "/* f6 line comment */")
checkFieldComments(t, f, "T.f7", "", "/*f7a*//*f7b*///f7c")
ast.FileExports(f)
checkFieldComments(t, f, "T.F1", "/* F1 lead comment *///", "/* F1 */// line comment")
checkFieldComments(t, f, "T.F2", "// F2 lead// comment", "// F2 line comment")
if getField(f, "T.f3") != nil {
t.Error("not expected to find T.f3")
}
}
// TestIssue9979 verifies that empty statements are contained within their enclosing blocks.
func TestIssue9979(t *testing.T) {
for _, src := range []string{
"package p; func f() {;}",
"package p; func f() {L:}",
"package p; func f() {L:;}",
"package p; func f() {L:\n}",
"package p; func f() {L:\n;}",
"package p; func f() { ; }",
"package p; func f() { L: }",
"package p; func f() { L: ; }",
"package p; func f() { L: \n}",
"package p; func f() { L: \n; }",
} {
fset := token.NewFileSet()
f, err := ParseFile(fset, "", src, 0)
if err != nil {
t.Fatal(err)
}
var pos, end token.Pos
ast.Inspect(f, func(x ast.Node) bool {
switch s := x.(type) {
case *ast.BlockStmt:
pos, end = s.Pos()+1, s.End()-1 // exclude "{", "}"
case *ast.LabeledStmt:
pos, end = s.Pos()+2, s.End() // exclude "L:"
case *ast.EmptyStmt:
// check containment
if s.Pos() < pos || s.End() > end {
t.Errorf("%s: %T[%d, %d] not inside [%d, %d]", src, s, s.Pos(), s.End(), pos, end)
}
// check semicolon
offs := fset.Position(s.Pos()).Offset
if ch := src[offs]; ch != ';' != s.Implicit {
want := "want ';'"
if s.Implicit {
want = "but ';' is implicit"
}
t.Errorf("%s: found %q at offset %d; %s", src, ch, offs, want)
}
}
return true
})
}
}
func TestFileStartEndPos(t *testing.T) {
const src = `// Copyright
//+build tag
// Package p doc comment.
package p
var lastDecl int
/* end of file */
`
fset := token.NewFileSet()
f, err := ParseFile(fset, "file.go", src, 0)
if err != nil {
t.Fatal(err)
}
// File{Start,End} spans the entire file, not just the declarations.
if got, want := fset.Position(f.FileStart).String(), "file.go:1:1"; got != want {
t.Errorf("for File.FileStart, got %s, want %s", got, want)
}
// The end position is the newline at the end of the /* end of file */ line.
if got, want := fset.Position(f.FileEnd).String(), "file.go:10:19"; got != want {
t.Errorf("for File.FileEnd, got %s, want %s", got, want)
}
}
// TestIncompleteSelection ensures that an incomplete selector
// expression is parsed as a (blank) *ast.SelectorExpr, not a
// *ast.BadExpr.
func TestIncompleteSelection(t *testing.T) {
for _, src := range []string{
"package p; var _ = fmt.", // at EOF
"package p; var _ = fmt.\ntype X int", // not at EOF
} {
fset := token.NewFileSet()
f, err := ParseFile(fset, "", src, 0)
if err == nil {
t.Errorf("ParseFile(%s) succeeded unexpectedly", src)
continue
}
const wantErr = "expected selector or type assertion"
if !strings.Contains(err.Error(), wantErr) {
t.Errorf("ParseFile returned wrong error %q, want %q", err, wantErr)
}
var sel *ast.SelectorExpr
ast.Inspect(f, func(n ast.Node) bool {
if n, ok := n.(*ast.SelectorExpr); ok {
sel = n
}
return true
})
if sel == nil {
t.Error("found no *ast.SelectorExpr")
continue
}
const wantSel = "&{fmt _}"
if fmt.Sprint(sel) != wantSel {
t.Errorf("found selector %s, want %s", sel, wantSel)
continue
}
}
}
func TestLastLineComment(t *testing.T) {
const src = `package main
type x int // comment
`
fset := token.NewFileSet()
f, err := ParseFile(fset, "", src, ParseComments)
if err != nil {
t.Fatal(err)
}
comment := f.Decls[0].(*ast.GenDecl).Specs[0].(*ast.TypeSpec).Comment.List[0].Text
if comment != "// comment" {
t.Errorf("got %q, want %q", comment, "// comment")
}
}
var parseDepthTests = []struct {
name string
format string
// parseMultiplier is used when a single statement may result in more than one
// change in the depth level, for instance "1+(..." produces a BinaryExpr
// followed by a UnaryExpr, which increments the depth twice. The test
// case comment explains which nodes are triggering the multiple depth
// changes.
parseMultiplier int
// scope is true if we should also test the statement for the resolver scope
// depth limit.
scope bool
// scopeMultiplier does the same as parseMultiplier, but for the scope
// depths.
scopeMultiplier int
}{
// The format expands the part inside « » many times.
// A second set of brackets nested inside the first stops the repetition,
// so that for example «(«1»)» expands to (((...((((1))))...))).
{name: "array", format: "package main; var x «[1]»int"},
{name: "slice", format: "package main; var x «[]»int"},
{name: "struct", format: "package main; var x «struct { X «int» }»", scope: true},
{name: "pointer", format: "package main; var x «*»int"},
{name: "func", format: "package main; var x «func()»int", scope: true},
{name: "chan", format: "package main; var x «chan »int"},
{name: "chan2", format: "package main; var x «<-chan »int"},
{name: "interface", format: "package main; var x «interface { M() «int» }»", scope: true, scopeMultiplier: 2}, // Scopes: InterfaceType, FuncType
{name: "map", format: "package main; var x «map[int]»int"},
{name: "slicelit", format: "package main; var x = «[]any{«»}»", parseMultiplier: 2}, // Parser nodes: UnaryExpr, CompositeLit
{name: "arraylit", format: "package main; var x = «[1]any{«nil»}»", parseMultiplier: 2}, // Parser nodes: UnaryExpr, CompositeLit
{name: "structlit", format: "package main; var x = «struct{x any}{«nil»}»", parseMultiplier: 2}, // Parser nodes: UnaryExpr, CompositeLit
{name: "maplit", format: "package main; var x = «map[int]any{1:«nil»}»", parseMultiplier: 2}, // Parser nodes: CompositeLit, KeyValueExpr
{name: "dot", format: "package main; var x = «x.»x"},
{name: "index", format: "package main; var x = x«[1]»"},
{name: "slice", format: "package main; var x = x«[1:2]»"},
{name: "slice3", format: "package main; var x = x«[1:2:3]»"},
{name: "dottype", format: "package main; var x = x«.(any)»"},
{name: "callseq", format: "package main; var x = x«()»"},
{name: "methseq", format: "package main; var x = x«.m()»", parseMultiplier: 2}, // Parser nodes: SelectorExpr, CallExpr
{name: "binary", format: "package main; var x = «1+»1"},
{name: "binaryparen", format: "package main; var x = «1+(«1»)»", parseMultiplier: 2}, // Parser nodes: BinaryExpr, ParenExpr
{name: "unary", format: "package main; var x = «^»1"},
{name: "addr", format: "package main; var x = «& »x"},
{name: "star", format: "package main; var x = «*»x"},
{name: "recv", format: "package main; var x = «<-»x"},
{name: "call", format: "package main; var x = «f(«1»)»", parseMultiplier: 2}, // Parser nodes: Ident, CallExpr
{name: "conv", format: "package main; var x = «(*T)(«1»)»", parseMultiplier: 2}, // Parser nodes: ParenExpr, CallExpr
{name: "label", format: "package main; func main() { «Label:» }"},
{name: "if", format: "package main; func main() { «if true { «» }»}", parseMultiplier: 2, scope: true, scopeMultiplier: 2}, // Parser nodes: IfStmt, BlockStmt. Scopes: IfStmt, BlockStmt
{name: "ifelse", format: "package main; func main() { «if true {} else » {} }", scope: true},
{name: "switch", format: "package main; func main() { «switch { default: «» }»}", scope: true, scopeMultiplier: 2}, // Scopes: TypeSwitchStmt, CaseClause
{name: "typeswitch", format: "package main; func main() { «switch x.(type) { default: «» }» }", scope: true, scopeMultiplier: 2}, // Scopes: TypeSwitchStmt, CaseClause
{name: "for0", format: "package main; func main() { «for { «» }» }", scope: true, scopeMultiplier: 2}, // Scopes: ForStmt, BlockStmt
{name: "for1", format: "package main; func main() { «for x { «» }» }", scope: true, scopeMultiplier: 2}, // Scopes: ForStmt, BlockStmt
{name: "for3", format: "package main; func main() { «for f(); g(); h() { «» }» }", scope: true, scopeMultiplier: 2}, // Scopes: ForStmt, BlockStmt
{name: "forrange0", format: "package main; func main() { «for range x { «» }» }", scope: true, scopeMultiplier: 2}, // Scopes: RangeStmt, BlockStmt
{name: "forrange1", format: "package main; func main() { «for x = range z { «» }» }", scope: true, scopeMultiplier: 2}, // Scopes: RangeStmt, BlockStmt
{name: "forrange2", format: "package main; func main() { «for x, y = range z { «» }» }", scope: true, scopeMultiplier: 2}, // Scopes: RangeStmt, BlockStmt
{name: "go", format: "package main; func main() { «go func() { «» }()» }", parseMultiplier: 2, scope: true}, // Parser nodes: GoStmt, FuncLit
{name: "defer", format: "package main; func main() { «defer func() { «» }()» }", parseMultiplier: 2, scope: true}, // Parser nodes: DeferStmt, FuncLit
{name: "select", format: "package main; func main() { «select { default: «» }» }", scope: true},
}
// split splits pre«mid»post into pre, mid, post.
// If the string does not have that form, split returns x, "", "".
func split(x string) (pre, mid, post string) {
start, end := strings.Index(x, "«"), strings.LastIndex(x, "»")
if start < 0 || end < 0 {
return x, "", ""
}
return x[:start], x[start+len("«") : end], x[end+len("»"):]
}
func TestParseDepthLimit(t *testing.T) {
if testing.Short() {
t.Skip("test requires significant memory")
}
for _, tt := range parseDepthTests {
for _, size := range []string{"small", "big"} {
t.Run(tt.name+"/"+size, func(t *testing.T) {
n := maxNestLev + 1
if tt.parseMultiplier > 0 {
n /= tt.parseMultiplier
}
if size == "small" {
// Decrease the number of statements by 10, in order to check
// that we do not fail when under the limit. 10 is used to
// provide some wiggle room for cases where the surrounding
// scaffolding syntax adds some noise to the depth that changes
// on a per testcase basis.
n -= 10
}
pre, mid, post := split(tt.format)
if strings.Contains(mid, "«") {
left, base, right := split(mid)
mid = strings.Repeat(left, n) + base + strings.Repeat(right, n)
} else {
mid = strings.Repeat(mid, n)
}
input := pre + mid + post
fset := token.NewFileSet()
_, err := ParseFile(fset, "", input, ParseComments|SkipObjectResolution)
if size == "small" {
if err != nil {
t.Errorf("ParseFile(...): %v (want success)", err)
}
} else {
expected := "exceeded max nesting depth"
if err == nil || !strings.HasSuffix(err.Error(), expected) {
t.Errorf("ParseFile(...) = _, %v, want %q", err, expected)
}
}
})
}
}
}
func TestScopeDepthLimit(t *testing.T) {
for _, tt := range parseDepthTests {
if !tt.scope {
continue
}
for _, size := range []string{"small", "big"} {
t.Run(tt.name+"/"+size, func(t *testing.T) {
n := maxScopeDepth + 1
if tt.scopeMultiplier > 0 {
n /= tt.scopeMultiplier
}
if size == "small" {
// Decrease the number of statements by 10, in order to check
// that we do not fail when under the limit. 10 is used to
// provide some wiggle room for cases where the surrounding
// scaffolding syntax adds some noise to the depth that changes
// on a per testcase basis.
n -= 10
}
pre, mid, post := split(tt.format)
if strings.Contains(mid, "«") {
left, base, right := split(mid)
mid = strings.Repeat(left, n) + base + strings.Repeat(right, n)
} else {
mid = strings.Repeat(mid, n)
}
input := pre + mid + post
fset := token.NewFileSet()
_, err := ParseFile(fset, "", input, DeclarationErrors)
if size == "small" {
if err != nil {
t.Errorf("ParseFile(...): %v (want success)", err)
}
} else {
expected := "exceeded max scope depth during object resolution"
if err == nil || !strings.HasSuffix(err.Error(), expected) {
t.Errorf("ParseFile(...) = _, %v, want %q", err, expected)
}
}
})
}
}
}
// proposal go.dev/issue/50429
func TestRangePos(t *testing.T) {
testcases := []string{
"package p; func _() { for range x {} }",
"package p; func _() { for i = range x {} }",
"package p; func _() { for i := range x {} }",
"package p; func _() { for k, v = range x {} }",
"package p; func _() { for k, v := range x {} }",
}
for _, src := range testcases {
fset := token.NewFileSet()
f, err := ParseFile(fset, src, src, 0)
if err != nil {
t.Fatal(err)
}
ast.Inspect(f, func(x ast.Node) bool {
switch s := x.(type) {
case *ast.RangeStmt:
pos := fset.Position(s.Range)
if pos.Offset != strings.Index(src, "range") {
t.Errorf("%s: got offset %v, want %v", src, pos.Offset, strings.Index(src, "range"))
}
}
return true
})
}
}
// TestIssue59180 tests that line number overflow doesn't cause an infinite loop.
func TestIssue59180(t *testing.T) {
testcases := []string{
"package p\n//line :9223372036854775806\n\n//",
"package p\n//line :1:9223372036854775806\n\n//",
"package p\n//line file:9223372036854775806\n\n//",
}
for _, src := range testcases {
_, err := ParseFile(token.NewFileSet(), "", src, ParseComments)
if err == nil {
t.Errorf("ParseFile(%s) succeeded unexpectedly", src)
}
}
}
func TestGoVersion(t *testing.T) {
fset := token.NewFileSet()
pkgs, err := ParseDir(fset, "./testdata/goversion", nil, 0)
if err != nil {
t.Fatal(err)
}
for _, p := range pkgs {
want := strings.ReplaceAll(p.Name, "_", ".")
if want == "none" {
want = ""
}
for _, f := range p.Files {
if f.GoVersion != want {
t.Errorf("%s: GoVersion = %q, want %q", fset.Position(f.Pos()), f.GoVersion, want)
}
}
}
}
func TestIssue57490(t *testing.T) {
src := `package p; func f() { var x struct` // program not correctly terminated
fset := token.NewFileSet()
file, err := ParseFile(fset, "", src, 0)
if err == nil {
t.Fatalf("syntax error expected, but no error reported")
}
// Because of the syntax error, the end position of the function declaration
// is past the end of the file's position range.
funcEnd := file.Decls[0].End()
// Offset(funcEnd) must not panic (to test panic, set debug=true in token package)
// (panic: offset 35 out of bounds [0, 34] (position 36 out of bounds [1, 35]))
tokFile := fset.File(file.Pos())
offset := tokFile.Offset(funcEnd)
if offset != tokFile.Size() {
t.Fatalf("offset = %d, want %d", offset, tokFile.Size())
}
}
| go/src/go/parser/parser_test.go/0 | {
"file_path": "go/src/go/parser/parser_test.go",
"repo_id": "go",
"token_count": 10558
} | 254 |
// Copyright 2012 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.
// Test case for go.dev/issue/3106: Better synchronization of
// parser after certain syntax errors.
package main
func f() {
var m Mutex
c := MakeCond(&m)
percent := 0
const step = 10
for i := 0; i < 5; i++ {
go func() {
for {
// Emulates some useful work.
time.Sleep(1e8)
m.Lock()
defer
if /* ERROR "expected ';', found 'if'" */ percent == 100 {
m.Unlock()
break
}
percent++
if percent % step == 0 {
//c.Signal()
}
m.Unlock()
}
}()
}
for {
m.Lock()
if percent == 0 || percent % step != 0 {
c.Wait()
}
fmt.Print(",")
if percent == 100 {
m.Unlock()
break
}
m.Unlock()
}
}
| go/src/go/parser/testdata/issue3106.src/0 | {
"file_path": "go/src/go/parser/testdata/issue3106.src",
"repo_id": "go",
"token_count": 362
} | 255 |
// Package set implements sets of any type.
package set
type Set[Elem comparable] map[Elem]struct{}
func Make[Elem comparable]() Set[Elem] {
return make(Set(Elem))
}
func (s Set[Elem]) Add(v Elem) {
s[v] = struct{}{}
}
func (s Set[Elem]) Delete(v Elem) {
delete(s, v)
}
func (s Set[Elem]) Contains(v Elem) bool {
_, ok := s[v]
return ok
}
func (s Set[Elem]) Len() int {
return len(s)
}
func (s Set[Elem]) Iterate(f func(Elem)) {
for v := range s {
f(v)
}
}
| go/src/go/parser/testdata/set.go2/0 | {
"file_path": "go/src/go/parser/testdata/set.go2",
"repo_id": "go",
"token_count": 212
} | 256 |
// This is a package for testing comment placement by go/printer.
package main
// The SZ struct; it is empty.
type SZ struct{}
// The S0 struct; no field is exported.
type S0 struct {
// contains filtered or unexported fields
}
// The S1 struct; some fields are not exported.
type S1 struct {
S0
A, B, C float // 3 exported fields
D int // 2 unexported fields
// contains filtered or unexported fields
}
// The S2 struct; all fields are exported.
type S2 struct {
S1
A, B, C float // 3 exported fields
}
// The IZ interface; it is empty.
type SZ interface{}
// The I0 interface; no method is exported.
type I0 interface {
// contains filtered or unexported methods
}
// The I1 interface; some methods are not exported.
type I1 interface {
I0
F(x float) float // exported methods
// contains filtered or unexported methods
}
// The I2 interface; all methods are exported.
type I2 interface {
I0
F(x float) float // exported method
G(x float) float // exported method
}
// The S3 struct; all comments except for the last one must appear in the export.
type S3 struct {
// lead comment for F1
F1 int // line comment for F1
// lead comment for F2
F2 int // line comment for F2
// contains filtered or unexported fields
}
| go/src/go/printer/testdata/comments.x/0 | {
"file_path": "go/src/go/printer/testdata/comments.x",
"repo_id": "go",
"token_count": 392
} | 257 |
// Copyright 2011 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 token
type serializedFile struct {
// fields correspond 1:1 to fields with same (lower-case) name in File
Name string
Base int
Size int
Lines []int
Infos []lineInfo
}
type serializedFileSet struct {
Base int
Files []serializedFile
}
// Read calls decode to deserialize a file set into s; s must not be nil.
func (s *FileSet) Read(decode func(any) error) error {
var ss serializedFileSet
if err := decode(&ss); err != nil {
return err
}
s.mutex.Lock()
s.base = ss.Base
files := make([]*File, len(ss.Files))
for i := 0; i < len(ss.Files); i++ {
f := &ss.Files[i]
files[i] = &File{
name: f.Name,
base: f.Base,
size: f.Size,
lines: f.Lines,
infos: f.Infos,
}
}
s.files = files
s.last.Store(nil)
s.mutex.Unlock()
return nil
}
// Write calls encode to serialize the file set s.
func (s *FileSet) Write(encode func(any) error) error {
var ss serializedFileSet
s.mutex.Lock()
ss.Base = s.base
files := make([]serializedFile, len(s.files))
for i, f := range s.files {
f.mutex.Lock()
files[i] = serializedFile{
Name: f.name,
Base: f.base,
Size: f.size,
Lines: append([]int(nil), f.lines...),
Infos: append([]lineInfo(nil), f.infos...),
}
f.mutex.Unlock()
}
ss.Files = files
s.mutex.Unlock()
return encode(ss)
}
| go/src/go/token/serialize.go/0 | {
"file_path": "go/src/go/token/serialize.go",
"repo_id": "go",
"token_count": 595
} | 258 |
// Copyright 2011 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.
// This file implements the Check function, which drives type-checking.
package types
import (
"fmt"
"go/ast"
"go/constant"
"go/token"
"internal/godebug"
. "internal/types/errors"
"strings"
"sync/atomic"
)
// nopos, noposn indicate an unknown position
var nopos token.Pos
var noposn = atPos(nopos)
// debugging/development support
const debug = false // leave on during development
// gotypesalias controls the use of Alias types.
// As of Apr 16 2024 they are used by default.
// To disable their use, set GODEBUG to gotypesalias=0.
// This GODEBUG flag will be removed in the near future (tentatively Go 1.24).
var gotypesalias = godebug.New("gotypesalias")
// _aliasAny changes the behavior of [Scope.Lookup] for "any" in the
// [Universe] scope.
//
// This is necessary because while Alias creation is controlled by
// [Config._EnableAlias], based on the gotypealias variable, the representation
// of "any" is a global. In [Scope.Lookup], we select this global
// representation based on the result of [aliasAny], but as a result need to
// guard against this behavior changing during the type checking pass.
// Therefore we implement the following rule: any number of goroutines can type
// check concurrently with the same EnableAlias value, but if any goroutine
// tries to type check concurrently with a different EnableAlias value, we
// panic.
//
// To achieve this, _aliasAny is a state machine:
//
// 0: no type checking is occurring
// negative: type checking is occurring without _EnableAlias set
// positive: type checking is occurring with _EnableAlias set
var _aliasAny int32
func aliasAny() bool {
v := gotypesalias.Value()
useAlias := v != "0"
inuse := atomic.LoadInt32(&_aliasAny)
if inuse != 0 && useAlias != (inuse > 0) {
panic(fmt.Sprintf("gotypealias mutated during type checking, gotypesalias=%s, inuse=%d", v, inuse))
}
return useAlias
}
// exprInfo stores information about an untyped expression.
type exprInfo struct {
isLhs bool // expression is lhs operand of a shift with delayed type-check
mode operandMode
typ *Basic
val constant.Value // constant value; or nil (if not a constant)
}
// An environment represents the environment within which an object is
// type-checked.
type environment struct {
decl *declInfo // package-level declaration whose init expression/function body is checked
scope *Scope // top-most scope for lookups
pos token.Pos // if valid, identifiers are looked up as if at position pos (used by Eval)
iota constant.Value // value of iota in a constant declaration; nil otherwise
errpos positioner // if set, identifier position of a constant with inherited initializer
inTParamList bool // set if inside a type parameter list
sig *Signature // function signature if inside a function; nil otherwise
isPanic map[*ast.CallExpr]bool // set of panic call expressions (used for termination check)
hasLabel bool // set if a function makes use of labels (only ~1% of functions); unused outside functions
hasCallOrRecv bool // set if an expression contains a function call or channel receive operation
}
// lookup looks up name in the current environment and returns the matching object, or nil.
func (env *environment) lookup(name string) Object {
_, obj := env.scope.LookupParent(name, env.pos)
return obj
}
// An importKey identifies an imported package by import path and source directory
// (directory containing the file containing the import). In practice, the directory
// may always be the same, or may not matter. Given an (import path, directory), an
// importer must always return the same package (but given two different import paths,
// an importer may still return the same package by mapping them to the same package
// paths).
type importKey struct {
path, dir string
}
// A dotImportKey describes a dot-imported object in the given scope.
type dotImportKey struct {
scope *Scope
name string
}
// An action describes a (delayed) action.
type action struct {
f func() // action to be executed
desc *actionDesc // action description; may be nil, requires debug to be set
}
// If debug is set, describef sets a printf-formatted description for action a.
// Otherwise, it is a no-op.
func (a *action) describef(pos positioner, format string, args ...any) {
if debug {
a.desc = &actionDesc{pos, format, args}
}
}
// An actionDesc provides information on an action.
// For debugging only.
type actionDesc struct {
pos positioner
format string
args []any
}
// A Checker maintains the state of the type checker.
// It must be created with [NewChecker].
type Checker struct {
// package information
// (initialized by NewChecker, valid for the life-time of checker)
conf *Config
ctxt *Context // context for de-duplicating instances
fset *token.FileSet
pkg *Package
*Info
version goVersion // accepted language version
nextID uint64 // unique Id for type parameters (first valid Id is 1)
objMap map[Object]*declInfo // maps package-level objects and (non-interface) methods to declaration info
impMap map[importKey]*Package // maps (import path, source directory) to (complete or fake) package
// see TODO in validtype.go
// valids instanceLookup // valid *Named (incl. instantiated) types per the validType check
// pkgPathMap maps package names to the set of distinct import paths we've
// seen for that name, anywhere in the import graph. It is used for
// disambiguating package names in error messages.
//
// pkgPathMap is allocated lazily, so that we don't pay the price of building
// it on the happy path. seenPkgMap tracks the packages that we've already
// walked.
pkgPathMap map[string]map[string]bool
seenPkgMap map[*Package]bool
// information collected during type-checking of a set of package files
// (initialized by Files, valid only for the duration of check.Files;
// maps and lists are allocated on demand)
files []*ast.File // package files
versions map[*ast.File]string // maps files to version strings (each file has an entry); shared with Info.FileVersions if present
imports []*PkgName // list of imported packages
dotImportMap map[dotImportKey]*PkgName // maps dot-imported objects to the package they were dot-imported through
brokenAliases map[*TypeName]bool // set of aliases with broken (not yet determined) types
unionTypeSets map[*Union]*_TypeSet // computed type sets for union types
mono monoGraph // graph for detecting non-monomorphizable instantiation loops
firstErr error // first error encountered
methods map[*TypeName][]*Func // maps package scope type names to associated non-blank (non-interface) methods
untyped map[ast.Expr]exprInfo // map of expressions without final type
delayed []action // stack of delayed action segments; segments are processed in FIFO order
objPath []Object // path of object dependencies during type inference (for cycle reporting)
cleaners []cleaner // list of types that may need a final cleanup at the end of type-checking
// environment within which the current object is type-checked (valid only
// for the duration of type-checking a specific object)
environment
// debugging
indent int // indentation for tracing
}
// addDeclDep adds the dependency edge (check.decl -> to) if check.decl exists
func (check *Checker) addDeclDep(to Object) {
from := check.decl
if from == nil {
return // not in a package-level init expression
}
if _, found := check.objMap[to]; !found {
return // to is not a package-level object
}
from.addDep(to)
}
// Note: The following three alias-related functions are only used
// when Alias types are not enabled.
// brokenAlias records that alias doesn't have a determined type yet.
// It also sets alias.typ to Typ[Invalid].
// Not used if check.conf._EnableAlias is set.
func (check *Checker) brokenAlias(alias *TypeName) {
assert(!check.conf._EnableAlias)
if check.brokenAliases == nil {
check.brokenAliases = make(map[*TypeName]bool)
}
check.brokenAliases[alias] = true
alias.typ = Typ[Invalid]
}
// validAlias records that alias has the valid type typ (possibly Typ[Invalid]).
func (check *Checker) validAlias(alias *TypeName, typ Type) {
assert(!check.conf._EnableAlias)
delete(check.brokenAliases, alias)
alias.typ = typ
}
// isBrokenAlias reports whether alias doesn't have a determined type yet.
func (check *Checker) isBrokenAlias(alias *TypeName) bool {
assert(!check.conf._EnableAlias)
return check.brokenAliases[alias]
}
func (check *Checker) rememberUntyped(e ast.Expr, lhs bool, mode operandMode, typ *Basic, val constant.Value) {
m := check.untyped
if m == nil {
m = make(map[ast.Expr]exprInfo)
check.untyped = m
}
m[e] = exprInfo{lhs, mode, typ, val}
}
// later pushes f on to the stack of actions that will be processed later;
// either at the end of the current statement, or in case of a local constant
// or variable declaration, before the constant or variable is in scope
// (so that f still sees the scope before any new declarations).
// later returns the pushed action so one can provide a description
// via action.describef for debugging, if desired.
func (check *Checker) later(f func()) *action {
i := len(check.delayed)
check.delayed = append(check.delayed, action{f: f})
return &check.delayed[i]
}
// push pushes obj onto the object path and returns its index in the path.
func (check *Checker) push(obj Object) int {
check.objPath = append(check.objPath, obj)
return len(check.objPath) - 1
}
// pop pops and returns the topmost object from the object path.
func (check *Checker) pop() Object {
i := len(check.objPath) - 1
obj := check.objPath[i]
check.objPath[i] = nil
check.objPath = check.objPath[:i]
return obj
}
type cleaner interface {
cleanup()
}
// needsCleanup records objects/types that implement the cleanup method
// which will be called at the end of type-checking.
func (check *Checker) needsCleanup(c cleaner) {
check.cleaners = append(check.cleaners, c)
}
// NewChecker returns a new [Checker] instance for a given package.
// [Package] files may be added incrementally via checker.Files.
func NewChecker(conf *Config, fset *token.FileSet, pkg *Package, info *Info) *Checker {
// make sure we have a configuration
if conf == nil {
conf = new(Config)
}
// make sure we have an info struct
if info == nil {
info = new(Info)
}
// Note: clients may call NewChecker with the Unsafe package, which is
// globally shared and must not be mutated. Therefore NewChecker must not
// mutate *pkg.
//
// (previously, pkg.goVersion was mutated here: go.dev/issue/61212)
// In go/types, conf._EnableAlias is controlled by gotypesalias.
conf._EnableAlias = gotypesalias.Value() != "0"
return &Checker{
conf: conf,
ctxt: conf.Context,
fset: fset,
pkg: pkg,
Info: info,
version: asGoVersion(conf.GoVersion),
objMap: make(map[Object]*declInfo),
impMap: make(map[importKey]*Package),
}
}
// initFiles initializes the files-specific portion of checker.
// The provided files must all belong to the same package.
func (check *Checker) initFiles(files []*ast.File) {
// start with a clean slate (check.Files may be called multiple times)
check.files = nil
check.imports = nil
check.dotImportMap = nil
check.firstErr = nil
check.methods = nil
check.untyped = nil
check.delayed = nil
check.objPath = nil
check.cleaners = nil
// determine package name and collect valid files
pkg := check.pkg
for _, file := range files {
switch name := file.Name.Name; pkg.name {
case "":
if name != "_" {
pkg.name = name
} else {
check.error(file.Name, BlankPkgName, "invalid package name _")
}
fallthrough
case name:
check.files = append(check.files, file)
default:
check.errorf(atPos(file.Package), MismatchedPkgName, "package %s; expected package %s", name, pkg.name)
// ignore this file
}
}
// reuse Info.FileVersions if provided
versions := check.Info.FileVersions
if versions == nil {
versions = make(map[*ast.File]string)
}
check.versions = versions
pkgVersionOk := check.version.isValid()
if pkgVersionOk && len(files) > 0 && check.version.cmp(go_current) > 0 {
check.errorf(files[0], TooNew, "package requires newer Go version %v (application built with %v)",
check.version, go_current)
}
downgradeOk := check.version.cmp(go1_21) >= 0
// determine Go version for each file
for _, file := range check.files {
// use unaltered Config.GoVersion by default
// (This version string may contain dot-release numbers as in go1.20.1,
// unlike file versions which are Go language versions only, if valid.)
v := check.conf.GoVersion
fileVersion := asGoVersion(file.GoVersion)
if fileVersion.isValid() {
// use the file version, if applicable
// (file versions are either the empty string or of the form go1.dd)
if pkgVersionOk {
cmp := fileVersion.cmp(check.version)
// Go 1.21 introduced the feature of setting the go.mod
// go line to an early version of Go and allowing //go:build lines
// to “upgrade” (cmp > 0) the Go version in a given file.
// We can do that backwards compatibly.
//
// Go 1.21 also introduced the feature of allowing //go:build lines
// to “downgrade” (cmp < 0) the Go version in a given file.
// That can't be done compatibly in general, since before the
// build lines were ignored and code got the module's Go version.
// To work around this, downgrades are only allowed when the
// module's Go version is Go 1.21 or later.
//
// If there is no valid check.version, then we don't really know what
// Go version to apply.
// Legacy tools may do this, and they historically have accepted everything.
// Preserve that behavior by ignoring //go:build constraints entirely in that
// case (!pkgVersionOk).
if cmp > 0 || cmp < 0 && downgradeOk {
v = file.GoVersion
}
}
// Report a specific error for each tagged file that's too new.
// (Normally the build system will have filtered files by version,
// but clients can present arbitrary files to the type checker.)
if fileVersion.cmp(go_current) > 0 {
// Use position of 'package [p]' for types/types2 consistency.
// (Ideally we would use the //build tag itself.)
check.errorf(file.Name, TooNew, "file requires newer Go version %v (application built with %v)", fileVersion, go_current)
}
}
versions[file] = v
}
}
// A bailout panic is used for early termination.
type bailout struct{}
func (check *Checker) handleBailout(err *error) {
switch p := recover().(type) {
case nil, bailout:
// normal return or early exit
*err = check.firstErr
default:
// re-panic
panic(p)
}
}
// Files checks the provided files as part of the checker's package.
func (check *Checker) Files(files []*ast.File) (err error) {
if check.pkg == Unsafe {
// Defensive handling for Unsafe, which cannot be type checked, and must
// not be mutated. See https://go.dev/issue/61212 for an example of where
// Unsafe is passed to NewChecker.
return nil
}
// Avoid early returns here! Nearly all errors can be
// localized to a piece of syntax and needn't prevent
// type-checking of the rest of the package.
defer check.handleBailout(&err)
check.checkFiles(files)
return
}
// checkFiles type-checks the specified files. Errors are reported as
// a side effect, not by returning early, to ensure that well-formed
// syntax is properly type annotated even in a package containing
// errors.
func (check *Checker) checkFiles(files []*ast.File) {
// Ensure that _EnableAlias is consistent among concurrent type checking
// operations. See the documentation of [_aliasAny] for details.
if check.conf._EnableAlias {
if atomic.AddInt32(&_aliasAny, 1) <= 0 {
panic("EnableAlias set while !EnableAlias type checking is ongoing")
}
defer atomic.AddInt32(&_aliasAny, -1)
} else {
if atomic.AddInt32(&_aliasAny, -1) >= 0 {
panic("!EnableAlias set while EnableAlias type checking is ongoing")
}
defer atomic.AddInt32(&_aliasAny, 1)
}
print := func(msg string) {
if check.conf._Trace {
fmt.Println()
fmt.Println(msg)
}
}
print("== initFiles ==")
check.initFiles(files)
print("== collectObjects ==")
check.collectObjects()
print("== packageObjects ==")
check.packageObjects()
print("== processDelayed ==")
check.processDelayed(0) // incl. all functions
print("== cleanup ==")
check.cleanup()
print("== initOrder ==")
check.initOrder()
if !check.conf.DisableUnusedImportCheck {
print("== unusedImports ==")
check.unusedImports()
}
print("== recordUntyped ==")
check.recordUntyped()
if check.firstErr == nil {
// TODO(mdempsky): Ensure monomorph is safe when errors exist.
check.monomorph()
}
check.pkg.goVersion = check.conf.GoVersion
check.pkg.complete = true
// no longer needed - release memory
check.imports = nil
check.dotImportMap = nil
check.pkgPathMap = nil
check.seenPkgMap = nil
check.brokenAliases = nil
check.unionTypeSets = nil
check.ctxt = nil
// TODO(rFindley) There's more memory we should release at this point.
}
// processDelayed processes all delayed actions pushed after top.
func (check *Checker) processDelayed(top int) {
// If each delayed action pushes a new action, the
// stack will continue to grow during this loop.
// However, it is only processing functions (which
// are processed in a delayed fashion) that may
// add more actions (such as nested functions), so
// this is a sufficiently bounded process.
for i := top; i < len(check.delayed); i++ {
a := &check.delayed[i]
if check.conf._Trace {
if a.desc != nil {
check.trace(a.desc.pos.Pos(), "-- "+a.desc.format, a.desc.args...)
} else {
check.trace(nopos, "-- delayed %p", a.f)
}
}
a.f() // may append to check.delayed
if check.conf._Trace {
fmt.Println()
}
}
assert(top <= len(check.delayed)) // stack must not have shrunk
check.delayed = check.delayed[:top]
}
// cleanup runs cleanup for all collected cleaners.
func (check *Checker) cleanup() {
// Don't use a range clause since Named.cleanup may add more cleaners.
for i := 0; i < len(check.cleaners); i++ {
check.cleaners[i].cleanup()
}
check.cleaners = nil
}
func (check *Checker) record(x *operand) {
// convert x into a user-friendly set of values
// TODO(gri) this code can be simplified
var typ Type
var val constant.Value
switch x.mode {
case invalid:
typ = Typ[Invalid]
case novalue:
typ = (*Tuple)(nil)
case constant_:
typ = x.typ
val = x.val
default:
typ = x.typ
}
assert(x.expr != nil && typ != nil)
if isUntyped(typ) {
// delay type and value recording until we know the type
// or until the end of type checking
check.rememberUntyped(x.expr, false, x.mode, typ.(*Basic), val)
} else {
check.recordTypeAndValue(x.expr, x.mode, typ, val)
}
}
func (check *Checker) recordUntyped() {
if !debug && check.Types == nil {
return // nothing to do
}
for x, info := range check.untyped {
if debug && isTyped(info.typ) {
check.dump("%v: %s (type %s) is typed", x.Pos(), x, info.typ)
panic("unreachable")
}
check.recordTypeAndValue(x, info.mode, info.typ, info.val)
}
}
func (check *Checker) recordTypeAndValue(x ast.Expr, mode operandMode, typ Type, val constant.Value) {
assert(x != nil)
assert(typ != nil)
if mode == invalid {
return // omit
}
if mode == constant_ {
assert(val != nil)
// We check allBasic(typ, IsConstType) here as constant expressions may be
// recorded as type parameters.
assert(!isValid(typ) || allBasic(typ, IsConstType))
}
if m := check.Types; m != nil {
m[x] = TypeAndValue{mode, typ, val}
}
}
func (check *Checker) recordBuiltinType(f ast.Expr, sig *Signature) {
// f must be a (possibly parenthesized, possibly qualified)
// identifier denoting a built-in (including unsafe's non-constant
// functions Add and Slice): record the signature for f and possible
// children.
for {
check.recordTypeAndValue(f, builtin, sig, nil)
switch p := f.(type) {
case *ast.Ident, *ast.SelectorExpr:
return // we're done
case *ast.ParenExpr:
f = p.X
default:
panic("unreachable")
}
}
}
// recordCommaOkTypes updates recorded types to reflect that x is used in a commaOk context
// (and therefore has tuple type).
func (check *Checker) recordCommaOkTypes(x ast.Expr, a []*operand) {
assert(x != nil)
assert(len(a) == 2)
if a[0].mode == invalid {
return
}
t0, t1 := a[0].typ, a[1].typ
assert(isTyped(t0) && isTyped(t1) && (allBoolean(t1) || t1 == universeError))
if m := check.Types; m != nil {
for {
tv := m[x]
assert(tv.Type != nil) // should have been recorded already
pos := x.Pos()
tv.Type = NewTuple(
NewVar(pos, check.pkg, "", t0),
NewVar(pos, check.pkg, "", t1),
)
m[x] = tv
// if x is a parenthesized expression (p.X), update p.X
p, _ := x.(*ast.ParenExpr)
if p == nil {
break
}
x = p.X
}
}
}
// recordInstance records instantiation information into check.Info, if the
// Instances map is non-nil. The given expr must be an ident, selector, or
// index (list) expr with ident or selector operand.
//
// TODO(rfindley): the expr parameter is fragile. See if we can access the
// instantiated identifier in some other way.
func (check *Checker) recordInstance(expr ast.Expr, targs []Type, typ Type) {
ident := instantiatedIdent(expr)
assert(ident != nil)
assert(typ != nil)
if m := check.Instances; m != nil {
m[ident] = Instance{newTypeList(targs), typ}
}
}
func instantiatedIdent(expr ast.Expr) *ast.Ident {
var selOrIdent ast.Expr
switch e := expr.(type) {
case *ast.IndexExpr:
selOrIdent = e.X
case *ast.IndexListExpr:
selOrIdent = e.X
case *ast.SelectorExpr, *ast.Ident:
selOrIdent = e
}
switch x := selOrIdent.(type) {
case *ast.Ident:
return x
case *ast.SelectorExpr:
return x.Sel
}
// extra debugging of #63933
var buf strings.Builder
buf.WriteString("instantiated ident not found; please report: ")
ast.Fprint(&buf, token.NewFileSet(), expr, ast.NotNilFilter)
panic(buf.String())
}
func (check *Checker) recordDef(id *ast.Ident, obj Object) {
assert(id != nil)
if m := check.Defs; m != nil {
m[id] = obj
}
}
func (check *Checker) recordUse(id *ast.Ident, obj Object) {
assert(id != nil)
assert(obj != nil)
if m := check.Uses; m != nil {
m[id] = obj
}
}
func (check *Checker) recordImplicit(node ast.Node, obj Object) {
assert(node != nil)
assert(obj != nil)
if m := check.Implicits; m != nil {
m[node] = obj
}
}
func (check *Checker) recordSelection(x *ast.SelectorExpr, kind SelectionKind, recv Type, obj Object, index []int, indirect bool) {
assert(obj != nil && (recv == nil || len(index) > 0))
check.recordUse(x.Sel, obj)
if m := check.Selections; m != nil {
m[x] = &Selection{kind, recv, obj, index, indirect}
}
}
func (check *Checker) recordScope(node ast.Node, scope *Scope) {
assert(node != nil)
assert(scope != nil)
if m := check.Scopes; m != nil {
m[node] = scope
}
}
| go/src/go/types/check.go/0 | {
"file_path": "go/src/go/types/check.go",
"repo_id": "go",
"token_count": 7954
} | 259 |
// Copyright 2013 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.
// This file implements printing of expressions.
package types
import (
"bytes"
"fmt"
"go/ast"
"go/internal/typeparams"
)
// ExprString returns the (possibly shortened) string representation for x.
// Shortened representations are suitable for user interfaces but may not
// necessarily follow Go syntax.
func ExprString(x ast.Expr) string {
var buf bytes.Buffer
WriteExpr(&buf, x)
return buf.String()
}
// WriteExpr writes the (possibly shortened) string representation for x to buf.
// Shortened representations are suitable for user interfaces but may not
// necessarily follow Go syntax.
func WriteExpr(buf *bytes.Buffer, x ast.Expr) {
// The AST preserves source-level parentheses so there is
// no need to introduce them here to correct for different
// operator precedences. (This assumes that the AST was
// generated by a Go parser.)
switch x := x.(type) {
default:
fmt.Fprintf(buf, "(ast: %T)", x) // nil, ast.BadExpr, ast.KeyValueExpr
case *ast.Ident:
buf.WriteString(x.Name)
case *ast.Ellipsis:
buf.WriteString("...")
if x.Elt != nil {
WriteExpr(buf, x.Elt)
}
case *ast.BasicLit:
buf.WriteString(x.Value)
case *ast.FuncLit:
buf.WriteByte('(')
WriteExpr(buf, x.Type)
buf.WriteString(" literal)") // shortened
case *ast.CompositeLit:
WriteExpr(buf, x.Type)
buf.WriteByte('{')
if len(x.Elts) > 0 {
buf.WriteString("…")
}
buf.WriteByte('}')
case *ast.ParenExpr:
buf.WriteByte('(')
WriteExpr(buf, x.X)
buf.WriteByte(')')
case *ast.SelectorExpr:
WriteExpr(buf, x.X)
buf.WriteByte('.')
buf.WriteString(x.Sel.Name)
case *ast.IndexExpr, *ast.IndexListExpr:
ix := typeparams.UnpackIndexExpr(x)
WriteExpr(buf, ix.X)
buf.WriteByte('[')
writeExprList(buf, ix.Indices)
buf.WriteByte(']')
case *ast.SliceExpr:
WriteExpr(buf, x.X)
buf.WriteByte('[')
if x.Low != nil {
WriteExpr(buf, x.Low)
}
buf.WriteByte(':')
if x.High != nil {
WriteExpr(buf, x.High)
}
if x.Slice3 {
buf.WriteByte(':')
if x.Max != nil {
WriteExpr(buf, x.Max)
}
}
buf.WriteByte(']')
case *ast.TypeAssertExpr:
WriteExpr(buf, x.X)
buf.WriteString(".(")
WriteExpr(buf, x.Type)
buf.WriteByte(')')
case *ast.CallExpr:
WriteExpr(buf, x.Fun)
buf.WriteByte('(')
writeExprList(buf, x.Args)
if hasDots(x) {
buf.WriteString("...")
}
buf.WriteByte(')')
case *ast.StarExpr:
buf.WriteByte('*')
WriteExpr(buf, x.X)
case *ast.UnaryExpr:
buf.WriteString(x.Op.String())
WriteExpr(buf, x.X)
case *ast.BinaryExpr:
WriteExpr(buf, x.X)
buf.WriteByte(' ')
buf.WriteString(x.Op.String())
buf.WriteByte(' ')
WriteExpr(buf, x.Y)
case *ast.ArrayType:
buf.WriteByte('[')
if x.Len != nil {
WriteExpr(buf, x.Len)
}
buf.WriteByte(']')
WriteExpr(buf, x.Elt)
case *ast.StructType:
buf.WriteString("struct{")
writeFieldList(buf, x.Fields.List, "; ", false)
buf.WriteByte('}')
case *ast.FuncType:
buf.WriteString("func")
writeSigExpr(buf, x)
case *ast.InterfaceType:
buf.WriteString("interface{")
writeFieldList(buf, x.Methods.List, "; ", true)
buf.WriteByte('}')
case *ast.MapType:
buf.WriteString("map[")
WriteExpr(buf, x.Key)
buf.WriteByte(']')
WriteExpr(buf, x.Value)
case *ast.ChanType:
var s string
switch x.Dir {
case ast.SEND:
s = "chan<- "
case ast.RECV:
s = "<-chan "
default:
s = "chan "
}
buf.WriteString(s)
WriteExpr(buf, x.Value)
}
}
func writeSigExpr(buf *bytes.Buffer, sig *ast.FuncType) {
buf.WriteByte('(')
writeFieldList(buf, sig.Params.List, ", ", false)
buf.WriteByte(')')
res := sig.Results
n := res.NumFields()
if n == 0 {
// no result
return
}
buf.WriteByte(' ')
if n == 1 && len(res.List[0].Names) == 0 {
// single unnamed result
WriteExpr(buf, res.List[0].Type)
return
}
// multiple or named result(s)
buf.WriteByte('(')
writeFieldList(buf, res.List, ", ", false)
buf.WriteByte(')')
}
func writeFieldList(buf *bytes.Buffer, list []*ast.Field, sep string, iface bool) {
for i, f := range list {
if i > 0 {
buf.WriteString(sep)
}
// field list names
writeIdentList(buf, f.Names)
// types of interface methods consist of signatures only
if sig, _ := f.Type.(*ast.FuncType); sig != nil && iface {
writeSigExpr(buf, sig)
continue
}
// named fields are separated with a blank from the field type
if len(f.Names) > 0 {
buf.WriteByte(' ')
}
WriteExpr(buf, f.Type)
// ignore tag
}
}
func writeIdentList(buf *bytes.Buffer, list []*ast.Ident) {
for i, x := range list {
if i > 0 {
buf.WriteString(", ")
}
buf.WriteString(x.Name)
}
}
func writeExprList(buf *bytes.Buffer, list []ast.Expr) {
for i, x := range list {
if i > 0 {
buf.WriteString(", ")
}
WriteExpr(buf, x)
}
}
| go/src/go/types/exprstring.go/0 | {
"file_path": "go/src/go/types/exprstring.go",
"repo_id": "go",
"token_count": 2086
} | 260 |
// Copyright 2013 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 types
import (
"go/ast"
"go/token"
. "internal/types/errors"
)
// labels checks correct label use in body.
func (check *Checker) labels(body *ast.BlockStmt) {
// set of all labels in this body
all := NewScope(nil, body.Pos(), body.End(), "label")
fwdJumps := check.blockBranches(all, nil, nil, body.List)
// If there are any forward jumps left, no label was found for
// the corresponding goto statements. Either those labels were
// never defined, or they are inside blocks and not reachable
// for the respective gotos.
for _, jmp := range fwdJumps {
var msg string
var code Code
name := jmp.Label.Name
if alt := all.Lookup(name); alt != nil {
msg = "goto %s jumps into block"
code = JumpIntoBlock
alt.(*Label).used = true // avoid another error
} else {
msg = "label %s not declared"
code = UndeclaredLabel
}
check.errorf(jmp.Label, code, msg, name)
}
// spec: "It is illegal to define a label that is never used."
for name, obj := range all.elems {
obj = resolve(name, obj)
if lbl := obj.(*Label); !lbl.used {
check.softErrorf(lbl, UnusedLabel, "label %s declared and not used", lbl.name)
}
}
}
// A block tracks label declarations in a block and its enclosing blocks.
type block struct {
parent *block // enclosing block
lstmt *ast.LabeledStmt // labeled statement to which this block belongs, or nil
labels map[string]*ast.LabeledStmt // allocated lazily
}
// insert records a new label declaration for the current block.
// The label must not have been declared before in any block.
func (b *block) insert(s *ast.LabeledStmt) {
name := s.Label.Name
if debug {
assert(b.gotoTarget(name) == nil)
}
labels := b.labels
if labels == nil {
labels = make(map[string]*ast.LabeledStmt)
b.labels = labels
}
labels[name] = s
}
// gotoTarget returns the labeled statement in the current
// or an enclosing block with the given label name, or nil.
func (b *block) gotoTarget(name string) *ast.LabeledStmt {
for s := b; s != nil; s = s.parent {
if t := s.labels[name]; t != nil {
return t
}
}
return nil
}
// enclosingTarget returns the innermost enclosing labeled
// statement with the given label name, or nil.
func (b *block) enclosingTarget(name string) *ast.LabeledStmt {
for s := b; s != nil; s = s.parent {
if t := s.lstmt; t != nil && t.Label.Name == name {
return t
}
}
return nil
}
// blockBranches processes a block's statement list and returns the set of outgoing forward jumps.
// all is the scope of all declared labels, parent the set of labels declared in the immediately
// enclosing block, and lstmt is the labeled statement this block is associated with (or nil).
func (check *Checker) blockBranches(all *Scope, parent *block, lstmt *ast.LabeledStmt, list []ast.Stmt) []*ast.BranchStmt {
b := &block{parent: parent, lstmt: lstmt}
var (
varDeclPos token.Pos
fwdJumps, badJumps []*ast.BranchStmt
)
// All forward jumps jumping over a variable declaration are possibly
// invalid (they may still jump out of the block and be ok).
// recordVarDecl records them for the given position.
recordVarDecl := func(pos token.Pos) {
varDeclPos = pos
badJumps = append(badJumps[:0], fwdJumps...) // copy fwdJumps to badJumps
}
jumpsOverVarDecl := func(jmp *ast.BranchStmt) bool {
if varDeclPos.IsValid() {
for _, bad := range badJumps {
if jmp == bad {
return true
}
}
}
return false
}
blockBranches := func(lstmt *ast.LabeledStmt, list []ast.Stmt) {
// Unresolved forward jumps inside the nested block
// become forward jumps in the current block.
fwdJumps = append(fwdJumps, check.blockBranches(all, b, lstmt, list)...)
}
var stmtBranches func(ast.Stmt)
stmtBranches = func(s ast.Stmt) {
switch s := s.(type) {
case *ast.DeclStmt:
if d, _ := s.Decl.(*ast.GenDecl); d != nil && d.Tok == token.VAR {
recordVarDecl(d.Pos())
}
case *ast.LabeledStmt:
// declare non-blank label
if name := s.Label.Name; name != "_" {
lbl := NewLabel(s.Label.Pos(), check.pkg, name)
if alt := all.Insert(lbl); alt != nil {
err := check.newError(DuplicateLabel)
err.soft = true
err.addf(lbl, "label %s already declared", name)
err.addAltDecl(alt)
err.report()
// ok to continue
} else {
b.insert(s)
check.recordDef(s.Label, lbl)
}
// resolve matching forward jumps and remove them from fwdJumps
i := 0
for _, jmp := range fwdJumps {
if jmp.Label.Name == name {
// match
lbl.used = true
check.recordUse(jmp.Label, lbl)
if jumpsOverVarDecl(jmp) {
check.softErrorf(
jmp.Label,
JumpOverDecl,
"goto %s jumps over variable declaration at line %d",
name,
check.fset.Position(varDeclPos).Line,
)
// ok to continue
}
} else {
// no match - record new forward jump
fwdJumps[i] = jmp
i++
}
}
fwdJumps = fwdJumps[:i]
lstmt = s
}
stmtBranches(s.Stmt)
case *ast.BranchStmt:
if s.Label == nil {
return // checked in 1st pass (check.stmt)
}
// determine and validate target
name := s.Label.Name
switch s.Tok {
case token.BREAK:
// spec: "If there is a label, it must be that of an enclosing
// "for", "switch", or "select" statement, and that is the one
// whose execution terminates."
valid := false
if t := b.enclosingTarget(name); t != nil {
switch t.Stmt.(type) {
case *ast.SwitchStmt, *ast.TypeSwitchStmt, *ast.SelectStmt, *ast.ForStmt, *ast.RangeStmt:
valid = true
}
}
if !valid {
check.errorf(s.Label, MisplacedLabel, "invalid break label %s", name)
return
}
case token.CONTINUE:
// spec: "If there is a label, it must be that of an enclosing
// "for" statement, and that is the one whose execution advances."
valid := false
if t := b.enclosingTarget(name); t != nil {
switch t.Stmt.(type) {
case *ast.ForStmt, *ast.RangeStmt:
valid = true
}
}
if !valid {
check.errorf(s.Label, MisplacedLabel, "invalid continue label %s", name)
return
}
case token.GOTO:
if b.gotoTarget(name) == nil {
// label may be declared later - add branch to forward jumps
fwdJumps = append(fwdJumps, s)
return
}
default:
check.errorf(s, InvalidSyntaxTree, "branch statement: %s %s", s.Tok, name)
return
}
// record label use
obj := all.Lookup(name)
obj.(*Label).used = true
check.recordUse(s.Label, obj)
case *ast.AssignStmt:
if s.Tok == token.DEFINE {
recordVarDecl(s.Pos())
}
case *ast.BlockStmt:
blockBranches(lstmt, s.List)
case *ast.IfStmt:
stmtBranches(s.Body)
if s.Else != nil {
stmtBranches(s.Else)
}
case *ast.CaseClause:
blockBranches(nil, s.Body)
case *ast.SwitchStmt:
stmtBranches(s.Body)
case *ast.TypeSwitchStmt:
stmtBranches(s.Body)
case *ast.CommClause:
blockBranches(nil, s.Body)
case *ast.SelectStmt:
stmtBranches(s.Body)
case *ast.ForStmt:
stmtBranches(s.Body)
case *ast.RangeStmt:
stmtBranches(s.Body)
}
}
for _, s := range list {
stmtBranches(s)
}
return fwdJumps
}
| go/src/go/types/labels.go/0 | {
"file_path": "go/src/go/types/labels.go",
"repo_id": "go",
"token_count": 3040
} | 261 |
// Code generated by "go test -run=Generate -write=all"; DO NOT EDIT.
// Source: ../../cmd/compile/internal/types2/pointer.go
// Copyright 2011 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 types
// A Pointer represents a pointer type.
type Pointer struct {
base Type // element type
}
// NewPointer returns a new pointer type for the given element (base) type.
func NewPointer(elem Type) *Pointer { return &Pointer{base: elem} }
// Elem returns the element type for the given pointer p.
func (p *Pointer) Elem() Type { return p.base }
func (p *Pointer) Underlying() Type { return p }
func (p *Pointer) String() string { return TypeString(p, nil) }
| go/src/go/types/pointer.go/0 | {
"file_path": "go/src/go/types/pointer.go",
"repo_id": "go",
"token_count": 231
} | 262 |
// Code generated by "go test -run=Generate -write=all"; DO NOT EDIT.
// Source: ../../cmd/compile/internal/types2/subst.go
// 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.
// This file implements type parameter substitution.
package types
import (
"go/token"
)
type substMap map[*TypeParam]Type
// makeSubstMap creates a new substitution map mapping tpars[i] to targs[i].
// If targs[i] is nil, tpars[i] is not substituted.
func makeSubstMap(tpars []*TypeParam, targs []Type) substMap {
assert(len(tpars) == len(targs))
proj := make(substMap, len(tpars))
for i, tpar := range tpars {
proj[tpar] = targs[i]
}
return proj
}
// makeRenameMap is like makeSubstMap, but creates a map used to rename type
// parameters in from with the type parameters in to.
func makeRenameMap(from, to []*TypeParam) substMap {
assert(len(from) == len(to))
proj := make(substMap, len(from))
for i, tpar := range from {
proj[tpar] = to[i]
}
return proj
}
func (m substMap) empty() bool {
return len(m) == 0
}
func (m substMap) lookup(tpar *TypeParam) Type {
if t := m[tpar]; t != nil {
return t
}
return tpar
}
// subst returns the type typ with its type parameters tpars replaced by the
// corresponding type arguments targs, recursively. subst doesn't modify the
// incoming type. If a substitution took place, the result type is different
// from the incoming type.
//
// If expanding is non-nil, it is the instance type currently being expanded.
// One of expanding or ctxt must be non-nil.
func (check *Checker) subst(pos token.Pos, typ Type, smap substMap, expanding *Named, ctxt *Context) Type {
assert(expanding != nil || ctxt != nil)
if smap.empty() {
return typ
}
// common cases
switch t := typ.(type) {
case *Basic:
return typ // nothing to do
case *TypeParam:
return smap.lookup(t)
}
// general case
subst := subster{
pos: pos,
smap: smap,
check: check,
expanding: expanding,
ctxt: ctxt,
}
return subst.typ(typ)
}
type subster struct {
pos token.Pos
smap substMap
check *Checker // nil if called via Instantiate
expanding *Named // if non-nil, the instance that is being expanded
ctxt *Context
}
func (subst *subster) typ(typ Type) Type {
switch t := typ.(type) {
case nil:
// Call typOrNil if it's possible that typ is nil.
panic("nil typ")
case *Basic:
// nothing to do
case *Alias:
// This code follows the code for *Named types closely.
// TODO(gri) try to factor better
orig := t.Origin()
n := orig.TypeParams().Len()
if n == 0 {
return t // type is not parameterized
}
// TODO(gri) do we need this for Alias types?
if t.TypeArgs().Len() != n {
return Typ[Invalid] // error reported elsewhere
}
// already instantiated
// For each (existing) type argument determine if it needs
// to be substituted; i.e., if it is or contains a type parameter
// that has a type argument for it.
if targs := substList(t.TypeArgs().list(), subst.typ); targs != nil {
return subst.check.newAliasInstance(subst.pos, t.orig, targs, subst.expanding, subst.ctxt)
}
case *Array:
elem := subst.typOrNil(t.elem)
if elem != t.elem {
return &Array{len: t.len, elem: elem}
}
case *Slice:
elem := subst.typOrNil(t.elem)
if elem != t.elem {
return &Slice{elem: elem}
}
case *Struct:
if fields := substList(t.fields, subst.var_); fields != nil {
s := &Struct{fields: fields, tags: t.tags}
s.markComplete()
return s
}
case *Pointer:
base := subst.typ(t.base)
if base != t.base {
return &Pointer{base: base}
}
case *Tuple:
return subst.tuple(t)
case *Signature:
// Preserve the receiver: it is handled during *Interface and *Named type
// substitution.
//
// Naively doing the substitution here can lead to an infinite recursion in
// the case where the receiver is an interface. For example, consider the
// following declaration:
//
// type T[A any] struct { f interface{ m() } }
//
// In this case, the type of f is an interface that is itself the receiver
// type of all of its methods. Because we have no type name to break
// cycles, substituting in the recv results in an infinite loop of
// recv->interface->recv->interface->...
recv := t.recv
params := subst.tuple(t.params)
results := subst.tuple(t.results)
if params != t.params || results != t.results {
return &Signature{
rparams: t.rparams,
// TODO(gri) why can't we nil out tparams here, rather than in instantiate?
tparams: t.tparams,
// instantiated signatures have a nil scope
recv: recv,
params: params,
results: results,
variadic: t.variadic,
}
}
case *Union:
if terms := substList(t.terms, subst.term); terms != nil {
// term list substitution may introduce duplicate terms (unlikely but possible).
// This is ok; lazy type set computation will determine the actual type set
// in normal form.
return &Union{terms}
}
case *Interface:
methods := substList(t.methods, subst.func_)
embeddeds := substList(t.embeddeds, subst.typ)
if methods != nil || embeddeds != nil {
if methods == nil {
methods = t.methods
}
if embeddeds == nil {
embeddeds = t.embeddeds
}
iface := subst.check.newInterface()
iface.embeddeds = embeddeds
iface.embedPos = t.embedPos
iface.implicit = t.implicit
assert(t.complete) // otherwise we are copying incomplete data
iface.complete = t.complete
// If we've changed the interface type, we may need to replace its
// receiver if the receiver type is the original interface. Receivers of
// *Named type are replaced during named type expansion.
//
// Notably, it's possible to reach here and not create a new *Interface,
// even though the receiver type may be parameterized. For example:
//
// type T[P any] interface{ m() }
//
// In this case the interface will not be substituted here, because its
// method signatures do not depend on the type parameter P, but we still
// need to create new interface methods to hold the instantiated
// receiver. This is handled by Named.expandUnderlying.
iface.methods, _ = replaceRecvType(methods, t, iface)
// If check != nil, check.newInterface will have saved the interface for later completion.
if subst.check == nil { // golang/go#61561: all newly created interfaces must be completed
iface.typeSet()
}
return iface
}
case *Map:
key := subst.typ(t.key)
elem := subst.typ(t.elem)
if key != t.key || elem != t.elem {
return &Map{key: key, elem: elem}
}
case *Chan:
elem := subst.typ(t.elem)
if elem != t.elem {
return &Chan{dir: t.dir, elem: elem}
}
case *Named:
// subst is called during expansion, so in this function we need to be
// careful not to call any methods that would cause t to be expanded: doing
// so would result in deadlock.
//
// So we call t.Origin().TypeParams() rather than t.TypeParams().
orig := t.Origin()
n := orig.TypeParams().Len()
if n == 0 {
return t // type is not parameterized
}
if t.TypeArgs().Len() != n {
return Typ[Invalid] // error reported elsewhere
}
// already instantiated
// For each (existing) type argument determine if it needs
// to be substituted; i.e., if it is or contains a type parameter
// that has a type argument for it.
if targs := substList(t.TypeArgs().list(), subst.typ); targs != nil {
// Create a new instance and populate the context to avoid endless
// recursion. The position used here is irrelevant because validation only
// occurs on t (we don't call validType on named), but we use subst.pos to
// help with debugging.
return subst.check.instance(subst.pos, orig, targs, subst.expanding, subst.ctxt)
}
case *TypeParam:
return subst.smap.lookup(t)
default:
panic("unreachable")
}
return typ
}
// typOrNil is like typ but if the argument is nil it is replaced with Typ[Invalid].
// A nil type may appear in pathological cases such as type T[P any] []func(_ T([]_))
// where an array/slice element is accessed before it is set up.
func (subst *subster) typOrNil(typ Type) Type {
if typ == nil {
return Typ[Invalid]
}
return subst.typ(typ)
}
func (subst *subster) var_(v *Var) *Var {
if v != nil {
if typ := subst.typ(v.typ); typ != v.typ {
return cloneVar(v, typ)
}
}
return v
}
func cloneVar(v *Var, typ Type) *Var {
copy := *v
copy.typ = typ
copy.origin = v.Origin()
return ©
}
func (subst *subster) tuple(t *Tuple) *Tuple {
if t != nil {
if vars := substList(t.vars, subst.var_); vars != nil {
return &Tuple{vars: vars}
}
}
return t
}
// substList applies subst to each element of the incoming slice.
// If at least one element changes, the result is a new slice with
// all the (possibly updated) elements of the incoming slice;
// otherwise the result it nil. The incoming slice is unchanged.
func substList[T comparable](in []T, subst func(T) T) (out []T) {
for i, t := range in {
if u := subst(t); u != t {
if out == nil {
// lazily allocate a new slice on first substitution
out = make([]T, len(in))
copy(out, in)
}
out[i] = u
}
}
return
}
func (subst *subster) func_(f *Func) *Func {
if f != nil {
if typ := subst.typ(f.typ); typ != f.typ {
return cloneFunc(f, typ)
}
}
return f
}
func cloneFunc(f *Func, typ Type) *Func {
copy := *f
copy.typ = typ
copy.origin = f.Origin()
return ©
}
func (subst *subster) term(t *Term) *Term {
if typ := subst.typ(t.typ); typ != t.typ {
return NewTerm(t.tilde, typ)
}
return t
}
// replaceRecvType updates any function receivers that have type old to have
// type new. It does not modify the input slice; if modifications are required,
// the input slice and any affected signatures will be copied before mutating.
//
// The resulting out slice contains the updated functions, and copied reports
// if anything was modified.
func replaceRecvType(in []*Func, old, new Type) (out []*Func, copied bool) {
out = in
for i, method := range in {
sig := method.Signature()
if sig.recv != nil && sig.recv.Type() == old {
if !copied {
// Allocate a new methods slice before mutating for the first time.
// This is defensive, as we may share methods across instantiations of
// a given interface type if they do not get substituted.
out = make([]*Func, len(in))
copy(out, in)
copied = true
}
newsig := *sig
newsig.recv = cloneVar(sig.recv, new)
out[i] = cloneFunc(method, &newsig)
}
}
return
}
| go/src/go/types/subst.go/0 | {
"file_path": "go/src/go/types/subst.go",
"repo_id": "go",
"token_count": 3861
} | 263 |
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
#include "textflag.h"
// castagnoliSSE42 updates the (non-inverted) crc with the given buffer.
//
// func castagnoliSSE42(crc uint32, p []byte) uint32
TEXT ·castagnoliSSE42(SB),NOSPLIT,$0
MOVL crc+0(FP), AX // CRC value
MOVQ p+8(FP), SI // data pointer
MOVQ p_len+16(FP), CX // len(p)
// If there are fewer than 8 bytes to process, skip alignment.
CMPQ CX, $8
JL less_than_8
MOVQ SI, BX
ANDQ $7, BX
JZ aligned
// Process the first few bytes to 8-byte align the input.
// BX = 8 - BX. We need to process this many bytes to align.
SUBQ $1, BX
XORQ $7, BX
BTQ $0, BX
JNC align_2
CRC32B (SI), AX
DECQ CX
INCQ SI
align_2:
BTQ $1, BX
JNC align_4
CRC32W (SI), AX
SUBQ $2, CX
ADDQ $2, SI
align_4:
BTQ $2, BX
JNC aligned
CRC32L (SI), AX
SUBQ $4, CX
ADDQ $4, SI
aligned:
// The input is now 8-byte aligned and we can process 8-byte chunks.
CMPQ CX, $8
JL less_than_8
CRC32Q (SI), AX
ADDQ $8, SI
SUBQ $8, CX
JMP aligned
less_than_8:
// We may have some bytes left over; process 4 bytes, then 2, then 1.
BTQ $2, CX
JNC less_than_4
CRC32L (SI), AX
ADDQ $4, SI
less_than_4:
BTQ $1, CX
JNC less_than_2
CRC32W (SI), AX
ADDQ $2, SI
less_than_2:
BTQ $0, CX
JNC done
CRC32B (SI), AX
done:
MOVL AX, ret+32(FP)
RET
// castagnoliSSE42Triple updates three (non-inverted) crcs with (24*rounds)
// bytes from each buffer.
//
// func castagnoliSSE42Triple(
// crc1, crc2, crc3 uint32,
// a, b, c []byte,
// rounds uint32,
// ) (retA uint32, retB uint32, retC uint32)
TEXT ·castagnoliSSE42Triple(SB),NOSPLIT,$0
MOVL crcA+0(FP), AX
MOVL crcB+4(FP), CX
MOVL crcC+8(FP), DX
MOVQ a+16(FP), R8 // data pointer
MOVQ b+40(FP), R9 // data pointer
MOVQ c+64(FP), R10 // data pointer
MOVL rounds+88(FP), R11
loop:
CRC32Q (R8), AX
CRC32Q (R9), CX
CRC32Q (R10), DX
CRC32Q 8(R8), AX
CRC32Q 8(R9), CX
CRC32Q 8(R10), DX
CRC32Q 16(R8), AX
CRC32Q 16(R9), CX
CRC32Q 16(R10), DX
ADDQ $24, R8
ADDQ $24, R9
ADDQ $24, R10
DECQ R11
JNZ loop
MOVL AX, retA+96(FP)
MOVL CX, retB+100(FP)
MOVL DX, retC+104(FP)
RET
// CRC32 polynomial data
//
// These constants are lifted from the
// Linux kernel, since they avoid the costly
// PSHUFB 16 byte reversal proposed in the
// original Intel paper.
DATA r2r1<>+0(SB)/8, $0x154442bd4
DATA r2r1<>+8(SB)/8, $0x1c6e41596
DATA r4r3<>+0(SB)/8, $0x1751997d0
DATA r4r3<>+8(SB)/8, $0x0ccaa009e
DATA rupoly<>+0(SB)/8, $0x1db710641
DATA rupoly<>+8(SB)/8, $0x1f7011641
DATA r5<>+0(SB)/8, $0x163cd6124
GLOBL r2r1<>(SB),RODATA,$16
GLOBL r4r3<>(SB),RODATA,$16
GLOBL rupoly<>(SB),RODATA,$16
GLOBL r5<>(SB),RODATA,$8
// Based on https://www.intel.com/content/dam/www/public/us/en/documents/white-papers/fast-crc-computation-generic-polynomials-pclmulqdq-paper.pdf
// len(p) must be at least 64, and must be a multiple of 16.
// func ieeeCLMUL(crc uint32, p []byte) uint32
TEXT ·ieeeCLMUL(SB),NOSPLIT,$0
MOVL crc+0(FP), X0 // Initial CRC value
MOVQ p+8(FP), SI // data pointer
MOVQ p_len+16(FP), CX // len(p)
MOVOU (SI), X1
MOVOU 16(SI), X2
MOVOU 32(SI), X3
MOVOU 48(SI), X4
PXOR X0, X1
ADDQ $64, SI // buf+=64
SUBQ $64, CX // len-=64
CMPQ CX, $64 // Less than 64 bytes left
JB remain64
MOVOA r2r1<>+0(SB), X0
loopback64:
MOVOA X1, X5
MOVOA X2, X6
MOVOA X3, X7
MOVOA X4, X8
PCLMULQDQ $0, X0, X1
PCLMULQDQ $0, X0, X2
PCLMULQDQ $0, X0, X3
PCLMULQDQ $0, X0, X4
/* Load next early */
MOVOU (SI), X11
MOVOU 16(SI), X12
MOVOU 32(SI), X13
MOVOU 48(SI), X14
PCLMULQDQ $0x11, X0, X5
PCLMULQDQ $0x11, X0, X6
PCLMULQDQ $0x11, X0, X7
PCLMULQDQ $0x11, X0, X8
PXOR X5, X1
PXOR X6, X2
PXOR X7, X3
PXOR X8, X4
PXOR X11, X1
PXOR X12, X2
PXOR X13, X3
PXOR X14, X4
ADDQ $0x40, DI
ADDQ $64, SI // buf+=64
SUBQ $64, CX // len-=64
CMPQ CX, $64 // Less than 64 bytes left?
JGE loopback64
/* Fold result into a single register (X1) */
remain64:
MOVOA r4r3<>+0(SB), X0
MOVOA X1, X5
PCLMULQDQ $0, X0, X1
PCLMULQDQ $0x11, X0, X5
PXOR X5, X1
PXOR X2, X1
MOVOA X1, X5
PCLMULQDQ $0, X0, X1
PCLMULQDQ $0x11, X0, X5
PXOR X5, X1
PXOR X3, X1
MOVOA X1, X5
PCLMULQDQ $0, X0, X1
PCLMULQDQ $0x11, X0, X5
PXOR X5, X1
PXOR X4, X1
/* If there is less than 16 bytes left we are done */
CMPQ CX, $16
JB finish
/* Encode 16 bytes */
remain16:
MOVOU (SI), X10
MOVOA X1, X5
PCLMULQDQ $0, X0, X1
PCLMULQDQ $0x11, X0, X5
PXOR X5, X1
PXOR X10, X1
SUBQ $16, CX
ADDQ $16, SI
CMPQ CX, $16
JGE remain16
finish:
/* Fold final result into 32 bits and return it */
PCMPEQB X3, X3
PCLMULQDQ $1, X1, X0
PSRLDQ $8, X1
PXOR X0, X1
MOVOA X1, X2
MOVQ r5<>+0(SB), X0
/* Creates 32 bit mask. Note that we don't care about upper half. */
PSRLQ $32, X3
PSRLDQ $4, X2
PAND X3, X1
PCLMULQDQ $0, X0, X1
PXOR X2, X1
MOVOA rupoly<>+0(SB), X0
MOVOA X1, X2
PAND X3, X1
PCLMULQDQ $0x10, X0, X1
PAND X3, X1
PCLMULQDQ $0, X0, X1
PXOR X2, X1
PEXTRD $1, X1, AX
MOVL AX, ret+32(FP)
RET
| go/src/hash/crc32/crc32_amd64.s/0 | {
"file_path": "go/src/hash/crc32/crc32_amd64.s",
"repo_id": "go",
"token_count": 3153
} | 264 |
// Copyright 2017 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 hash_test
import (
"bytes"
"crypto/sha256"
"encoding"
"fmt"
"log"
)
func Example_binaryMarshaler() {
const (
input1 = "The tunneling gopher digs downwards, "
input2 = "unaware of what he will find."
)
first := sha256.New()
first.Write([]byte(input1))
marshaler, ok := first.(encoding.BinaryMarshaler)
if !ok {
log.Fatal("first does not implement encoding.BinaryMarshaler")
}
state, err := marshaler.MarshalBinary()
if err != nil {
log.Fatal("unable to marshal hash:", err)
}
second := sha256.New()
unmarshaler, ok := second.(encoding.BinaryUnmarshaler)
if !ok {
log.Fatal("second does not implement encoding.BinaryUnmarshaler")
}
if err := unmarshaler.UnmarshalBinary(state); err != nil {
log.Fatal("unable to unmarshal hash:", err)
}
first.Write([]byte(input2))
second.Write([]byte(input2))
fmt.Printf("%x\n", first.Sum(nil))
fmt.Println(bytes.Equal(first.Sum(nil), second.Sum(nil)))
// Output:
// 57d51a066f3a39942649cd9a76c77e97ceab246756ff3888659e6aa5a07f4a52
// true
}
| go/src/hash/example_test.go/0 | {
"file_path": "go/src/hash/example_test.go",
"repo_id": "go",
"token_count": 466
} | 265 |
// Copyright 2013 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 html
import (
"strings"
"testing"
)
type unescapeTest struct {
// A short description of the test case.
desc string
// The HTML text.
html string
// The unescaped text.
unescaped string
}
var unescapeTests = []unescapeTest{
// Handle no entities.
{
"copy",
"A\ttext\nstring",
"A\ttext\nstring",
},
// Handle simple named entities.
{
"simple",
"& > <",
"& > <",
},
// Handle hitting the end of the string.
{
"stringEnd",
"& &",
"& &",
},
// Handle entities with two codepoints.
{
"multiCodepoint",
"text ⋛︀ blah",
"text \u22db\ufe00 blah",
},
// Handle decimal numeric entities.
{
"decimalEntity",
"Delta = Δ ",
"Delta = Δ ",
},
// Handle hexadecimal numeric entities.
{
"hexadecimalEntity",
"Lambda = λ = λ ",
"Lambda = λ = λ ",
},
// Handle numeric early termination.
{
"numericEnds",
"&# &#x €43 © = ©f = ©",
"&# &#x €43 © = ©f = ©",
},
// Handle numeric ISO-8859-1 entity replacements.
{
"numericReplacements",
"Footnote‡",
"Footnote‡",
},
// Handle single ampersand.
{
"copySingleAmpersand",
"&",
"&",
},
// Handle ampersand followed by non-entity.
{
"copyAmpersandNonEntity",
"text &test",
"text &test",
},
// Handle "&#".
{
"copyAmpersandHash",
"text &#",
"text &#",
},
}
func TestUnescape(t *testing.T) {
for _, tt := range unescapeTests {
unescaped := UnescapeString(tt.html)
if unescaped != tt.unescaped {
t.Errorf("TestUnescape %s: want %q, got %q", tt.desc, tt.unescaped, unescaped)
}
}
}
func TestUnescapeEscape(t *testing.T) {
ss := []string{
``,
`abc def`,
`a & b`,
`a&b`,
`a & b`,
`"`,
`"`,
`"<&>"`,
`"<&>"`,
`3&5==1 && 0<1, "0<1", a+acute=á`,
`The special characters are: <, >, &, ' and "`,
}
for _, s := range ss {
if got := UnescapeString(EscapeString(s)); got != s {
t.Errorf("got %q want %q", got, s)
}
}
}
var (
benchEscapeData = strings.Repeat("AAAAA < BBBBB > CCCCC & DDDDD ' EEEEE \" ", 100)
benchEscapeNone = strings.Repeat("AAAAA x BBBBB x CCCCC x DDDDD x EEEEE x ", 100)
benchUnescapeSparse = strings.Repeat(strings.Repeat("AAAAA x BBBBB x CCCCC x DDDDD x EEEEE x ", 10)+"&", 10)
benchUnescapeDense = strings.Repeat("&< & <", 100)
)
func BenchmarkEscape(b *testing.B) {
n := 0
for i := 0; i < b.N; i++ {
n += len(EscapeString(benchEscapeData))
}
}
func BenchmarkEscapeNone(b *testing.B) {
n := 0
for i := 0; i < b.N; i++ {
n += len(EscapeString(benchEscapeNone))
}
}
func BenchmarkUnescape(b *testing.B) {
s := EscapeString(benchEscapeData)
n := 0
for i := 0; i < b.N; i++ {
n += len(UnescapeString(s))
}
}
func BenchmarkUnescapeNone(b *testing.B) {
s := EscapeString(benchEscapeNone)
n := 0
for i := 0; i < b.N; i++ {
n += len(UnescapeString(s))
}
}
func BenchmarkUnescapeSparse(b *testing.B) {
n := 0
for i := 0; i < b.N; i++ {
n += len(UnescapeString(benchUnescapeSparse))
}
}
func BenchmarkUnescapeDense(b *testing.B) {
n := 0
for i := 0; i < b.N; i++ {
n += len(UnescapeString(benchUnescapeDense))
}
}
| go/src/html/escape_test.go/0 | {
"file_path": "go/src/html/escape_test.go",
"repo_id": "go",
"token_count": 1510
} | 266 |
// Copyright 2011 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 template
import (
"bytes"
"encoding/json"
"fmt"
"os"
"strings"
"testing"
"text/template"
"text/template/parse"
)
type badMarshaler struct{}
func (x *badMarshaler) MarshalJSON() ([]byte, error) {
// Keys in valid JSON must be double quoted as must all strings.
return []byte("{ foo: 'not quite valid JSON' }"), nil
}
type goodMarshaler struct{}
func (x *goodMarshaler) MarshalJSON() ([]byte, error) {
return []byte(`{ "<foo>": "O'Reilly" }`), nil
}
func TestEscape(t *testing.T) {
data := struct {
F, T bool
C, G, H, I string
A, E []string
B, M json.Marshaler
N int
U any // untyped nil
Z *int // typed nil
W HTML
}{
F: false,
T: true,
C: "<Cincinnati>",
G: "<Goodbye>",
H: "<Hello>",
A: []string{"<a>", "<b>"},
E: []string{},
N: 42,
B: &badMarshaler{},
M: &goodMarshaler{},
U: nil,
Z: nil,
W: HTML(`¡<b class="foo">Hello</b>, <textarea>O'World</textarea>!`),
I: "${ asd `` }",
}
pdata := &data
tests := []struct {
name string
input string
output string
}{
{
"if",
"{{if .T}}Hello{{end}}, {{.C}}!",
"Hello, <Cincinnati>!",
},
{
"else",
"{{if .F}}{{.H}}{{else}}{{.G}}{{end}}!",
"<Goodbye>!",
},
{
"overescaping1",
"Hello, {{.C | html}}!",
"Hello, <Cincinnati>!",
},
{
"overescaping2",
"Hello, {{html .C}}!",
"Hello, <Cincinnati>!",
},
{
"overescaping3",
"{{with .C}}{{$msg := .}}Hello, {{$msg}}!{{end}}",
"Hello, <Cincinnati>!",
},
{
"assignment",
"{{if $x := .H}}{{$x}}{{end}}",
"<Hello>",
},
{
"withBody",
"{{with .H}}{{.}}{{end}}",
"<Hello>",
},
{
"withElse",
"{{with .E}}{{.}}{{else}}{{.H}}{{end}}",
"<Hello>",
},
{
"rangeBody",
"{{range .A}}{{.}}{{end}}",
"<a><b>",
},
{
"rangeElse",
"{{range .E}}{{.}}{{else}}{{.H}}{{end}}",
"<Hello>",
},
{
"nonStringValue",
"{{.T}}",
"true",
},
{
"untypedNilValue",
"{{.U}}",
"",
},
{
"typedNilValue",
"{{.Z}}",
"<nil>",
},
{
"constant",
`<a href="/search?q={{"'a<b'"}}">`,
`<a href="/search?q=%27a%3cb%27">`,
},
{
"multipleAttrs",
"<a b=1 c={{.H}}>",
"<a b=1 c=<Hello>>",
},
{
"urlStartRel",
`<a href='{{"/foo/bar?a=b&c=d"}}'>`,
`<a href='/foo/bar?a=b&c=d'>`,
},
{
"urlStartAbsOk",
`<a href='{{"http://example.com/foo/bar?a=b&c=d"}}'>`,
`<a href='http://example.com/foo/bar?a=b&c=d'>`,
},
{
"protocolRelativeURLStart",
`<a href='{{"//example.com:8000/foo/bar?a=b&c=d"}}'>`,
`<a href='//example.com:8000/foo/bar?a=b&c=d'>`,
},
{
"pathRelativeURLStart",
`<a href="{{"/javascript:80/foo/bar"}}">`,
`<a href="/javascript:80/foo/bar">`,
},
{
"dangerousURLStart",
`<a href='{{"javascript:alert(%22pwned%22)"}}'>`,
`<a href='#ZgotmplZ'>`,
},
{
"dangerousURLStart2",
`<a href=' {{"javascript:alert(%22pwned%22)"}}'>`,
`<a href=' #ZgotmplZ'>`,
},
{
"nonHierURL",
`<a href={{"mailto:Muhammed \"The Greatest\" Ali <m.ali@example.com>"}}>`,
`<a href=mailto:Muhammed%20%22The%20Greatest%22%20Ali%20%3cm.ali@example.com%3e>`,
},
{
"urlPath",
`<a href='http://{{"javascript:80"}}/foo'>`,
`<a href='http://javascript:80/foo'>`,
},
{
"urlQuery",
`<a href='/search?q={{.H}}'>`,
`<a href='/search?q=%3cHello%3e'>`,
},
{
"urlFragment",
`<a href='/faq#{{.H}}'>`,
`<a href='/faq#%3cHello%3e'>`,
},
{
"urlBranch",
`<a href="{{if .F}}/foo?a=b{{else}}/bar{{end}}">`,
`<a href="/bar">`,
},
{
"urlBranchConflictMoot",
`<a href="{{if .T}}/foo?a={{else}}/bar#{{end}}{{.C}}">`,
`<a href="/foo?a=%3cCincinnati%3e">`,
},
{
"jsStrValue",
"<button onclick='alert({{.H}})'>",
`<button onclick='alert("\u003cHello\u003e")'>`,
},
{
"jsNumericValue",
"<button onclick='alert({{.N}})'>",
`<button onclick='alert( 42 )'>`,
},
{
"jsBoolValue",
"<button onclick='alert({{.T}})'>",
`<button onclick='alert( true )'>`,
},
{
"jsNilValueTyped",
"<button onclick='alert(typeof{{.Z}})'>",
`<button onclick='alert(typeof null )'>`,
},
{
"jsNilValueUntyped",
"<button onclick='alert(typeof{{.U}})'>",
`<button onclick='alert(typeof null )'>`,
},
{
"jsObjValue",
"<button onclick='alert({{.A}})'>",
`<button onclick='alert(["\u003ca\u003e","\u003cb\u003e"])'>`,
},
{
"jsObjValueScript",
"<script>alert({{.A}})</script>",
`<script>alert(["\u003ca\u003e","\u003cb\u003e"])</script>`,
},
{
"jsObjValueNotOverEscaped",
"<button onclick='alert({{.A | html}})'>",
`<button onclick='alert(["\u003ca\u003e","\u003cb\u003e"])'>`,
},
{
"jsStr",
"<button onclick='alert("{{.H}}")'>",
`<button onclick='alert("\u003cHello\u003e")'>`,
},
{
"badMarshaler",
`<button onclick='alert(1/{{.B}}in numbers)'>`,
`<button onclick='alert(1/ /* json: error calling MarshalJSON for type *template.badMarshaler: invalid character 'f' looking for beginning of object key string */null in numbers)'>`,
},
{
"jsMarshaler",
`<button onclick='alert({{.M}})'>`,
`<button onclick='alert({"\u003cfoo\u003e":"O'Reilly"})'>`,
},
{
"jsStrNotUnderEscaped",
"<button onclick='alert({{.C | urlquery}})'>",
// URL escaped, then quoted for JS.
`<button onclick='alert("%3CCincinnati%3E")'>`,
},
{
"jsRe",
`<button onclick='alert(/{{"foo+bar"}}/.test(""))'>`,
`<button onclick='alert(/foo\u002bbar/.test(""))'>`,
},
{
"jsReBlank",
`<script>alert(/{{""}}/.test(""));</script>`,
`<script>alert(/(?:)/.test(""));</script>`,
},
{
"jsReAmbigOk",
`<script>{{if true}}var x = 1{{end}}</script>`,
// The {if} ends in an ambiguous jsCtx but there is
// no slash following so we shouldn't care.
`<script>var x = 1</script>`,
},
{
"styleBidiKeywordPassed",
`<p style="dir: {{"ltr"}}">`,
`<p style="dir: ltr">`,
},
{
"styleBidiPropNamePassed",
`<p style="border-{{"left"}}: 0; border-{{"right"}}: 1in">`,
`<p style="border-left: 0; border-right: 1in">`,
},
{
"styleExpressionBlocked",
`<p style="width: {{"expression(alert(1337))"}}">`,
`<p style="width: ZgotmplZ">`,
},
{
"styleTagSelectorPassed",
`<style>{{"p"}} { color: pink }</style>`,
`<style>p { color: pink }</style>`,
},
{
"styleIDPassed",
`<style>p{{"#my-ID"}} { font: Arial }</style>`,
`<style>p#my-ID { font: Arial }</style>`,
},
{
"styleClassPassed",
`<style>p{{".my_class"}} { font: Arial }</style>`,
`<style>p.my_class { font: Arial }</style>`,
},
{
"styleQuantityPassed",
`<a style="left: {{"2em"}}; top: {{0}}">`,
`<a style="left: 2em; top: 0">`,
},
{
"stylePctPassed",
`<table style=width:{{"100%"}}>`,
`<table style=width:100%>`,
},
{
"styleColorPassed",
`<p style="color: {{"#8ff"}}; background: {{"#000"}}">`,
`<p style="color: #8ff; background: #000">`,
},
{
"styleObfuscatedExpressionBlocked",
`<p style="width: {{" e\\78preS\x00Sio/**/n(alert(1337))"}}">`,
`<p style="width: ZgotmplZ">`,
},
{
"styleMozBindingBlocked",
`<p style="{{"-moz-binding(alert(1337))"}}: ...">`,
`<p style="ZgotmplZ: ...">`,
},
{
"styleObfuscatedMozBindingBlocked",
`<p style="{{" -mo\\7a-B\x00I/**/nding(alert(1337))"}}: ...">`,
`<p style="ZgotmplZ: ...">`,
},
{
"styleFontNameString",
`<p style='font-family: "{{"Times New Roman"}}"'>`,
`<p style='font-family: "Times New Roman"'>`,
},
{
"styleFontNameString",
`<p style='font-family: "{{"Times New Roman"}}", "{{"sans-serif"}}"'>`,
`<p style='font-family: "Times New Roman", "sans-serif"'>`,
},
{
"styleFontNameUnquoted",
`<p style='font-family: {{"Times New Roman"}}'>`,
`<p style='font-family: Times New Roman'>`,
},
{
"styleURLQueryEncoded",
`<p style="background: url(/img?name={{"O'Reilly Animal(1)<2>.png"}})">`,
`<p style="background: url(/img?name=O%27Reilly%20Animal%281%29%3c2%3e.png)">`,
},
{
"styleQuotedURLQueryEncoded",
`<p style="background: url('/img?name={{"O'Reilly Animal(1)<2>.png"}}')">`,
`<p style="background: url('/img?name=O%27Reilly%20Animal%281%29%3c2%3e.png')">`,
},
{
"styleStrQueryEncoded",
`<p style="background: '/img?name={{"O'Reilly Animal(1)<2>.png"}}'">`,
`<p style="background: '/img?name=O%27Reilly%20Animal%281%29%3c2%3e.png'">`,
},
{
"styleURLBadProtocolBlocked",
`<a style="background: url('{{"javascript:alert(1337)"}}')">`,
`<a style="background: url('#ZgotmplZ')">`,
},
{
"styleStrBadProtocolBlocked",
`<a style="background: '{{"vbscript:alert(1337)"}}'">`,
`<a style="background: '#ZgotmplZ'">`,
},
{
"styleStrEncodedProtocolEncoded",
`<a style="background: '{{"javascript\\3a alert(1337)"}}'">`,
// The CSS string 'javascript\\3a alert(1337)' does not contain a colon.
`<a style="background: 'javascript\\3a alert\28 1337\29 '">`,
},
{
"styleURLGoodProtocolPassed",
`<a style="background: url('{{"http://oreilly.com/O'Reilly Animals(1)<2>;{}.html"}}')">`,
`<a style="background: url('http://oreilly.com/O%27Reilly%20Animals%281%29%3c2%3e;%7b%7d.html')">`,
},
{
"styleStrGoodProtocolPassed",
`<a style="background: '{{"http://oreilly.com/O'Reilly Animals(1)<2>;{}.html"}}'">`,
`<a style="background: 'http\3a\2f\2foreilly.com\2fO\27Reilly Animals\28 1\29\3c 2\3e\3b\7b\7d.html'">`,
},
{
"styleURLEncodedForHTMLInAttr",
`<a style="background: url('{{"/search?img=foo&size=icon"}}')">`,
`<a style="background: url('/search?img=foo&size=icon')">`,
},
{
"styleURLNotEncodedForHTMLInCdata",
`<style>body { background: url('{{"/search?img=foo&size=icon"}}') }</style>`,
`<style>body { background: url('/search?img=foo&size=icon') }</style>`,
},
{
"styleURLMixedCase",
`<p style="background: URL(#{{.H}})">`,
`<p style="background: URL(#%3cHello%3e)">`,
},
{
"stylePropertyPairPassed",
`<a style='{{"color: red"}}'>`,
`<a style='color: red'>`,
},
{
"styleStrSpecialsEncoded",
`<a style="font-family: '{{"/**/'\";:// \\"}}', "{{"/**/'\";:// \\"}}"">`,
`<a style="font-family: '\2f**\2f\27\22\3b\3a\2f\2f \\', "\2f**\2f\27\22\3b\3a\2f\2f \\"">`,
},
{
"styleURLSpecialsEncoded",
`<a style="border-image: url({{"/**/'\";:// \\"}}), url("{{"/**/'\";:// \\"}}"), url('{{"/**/'\";:// \\"}}'), 'http://www.example.com/?q={{"/**/'\";:// \\"}}''">`,
`<a style="border-image: url(/**/%27%22;://%20%5c), url("/**/%27%22;://%20%5c"), url('/**/%27%22;://%20%5c'), 'http://www.example.com/?q=%2f%2a%2a%2f%27%22%3b%3a%2f%2f%20%5c''">`,
},
{
"HTML comment",
"<b>Hello, <!-- name of world -->{{.C}}</b>",
"<b>Hello, <Cincinnati></b>",
},
{
"HTML comment not first < in text node.",
"<<!-- -->!--",
"<!--",
},
{
"HTML normalization 1",
"a < b",
"a < b",
},
{
"HTML normalization 2",
"a << b",
"a << b",
},
{
"HTML normalization 3",
"a<<!-- --><!-- -->b",
"a<b",
},
{
"HTML doctype not normalized",
"<!DOCTYPE html>Hello, World!",
"<!DOCTYPE html>Hello, World!",
},
{
"HTML doctype not case-insensitive",
"<!doCtYPE htMl>Hello, World!",
"<!doCtYPE htMl>Hello, World!",
},
{
"No doctype injection",
`<!{{"DOCTYPE"}}`,
"<!DOCTYPE",
},
{
"Split HTML comment",
"<b>Hello, <!-- name of {{if .T}}city -->{{.C}}{{else}}world -->{{.W}}{{end}}</b>",
"<b>Hello, <Cincinnati></b>",
},
{
"JS line comment",
"<script>for (;;) { if (c()) break// foo not a label\n" +
"foo({{.T}});}</script>",
"<script>for (;;) { if (c()) break\n" +
"foo( true );}</script>",
},
{
"JS multiline block comment",
"<script>for (;;) { if (c()) break/* foo not a label\n" +
" */foo({{.T}});}</script>",
// Newline separates break from call. If newline
// removed, then break will consume label leaving
// code invalid.
"<script>for (;;) { if (c()) break\n" +
"foo( true );}</script>",
},
{
"JS single-line block comment",
"<script>for (;;) {\n" +
"if (c()) break/* foo a label */foo;" +
"x({{.T}});}</script>",
// Newline separates break from call. If newline
// removed, then break will consume label leaving
// code invalid.
"<script>for (;;) {\n" +
"if (c()) break foo;" +
"x( true );}</script>",
},
{
"JS block comment flush with mathematical division",
"<script>var a/*b*//c\nd</script>",
"<script>var a /c\nd</script>",
},
{
"JS mixed comments",
"<script>var a/*b*///c\nd</script>",
"<script>var a \nd</script>",
},
{
"JS HTML-like comments",
"<script>before <!-- beep\nbetween\nbefore-->boop\n</script>",
"<script>before \nbetween\nbefore\n</script>",
},
{
"JS hashbang comment",
"<script>#! beep\n</script>",
"<script>\n</script>",
},
{
"Special tags in <script> string literals",
`<script>var a = "asd < 123 <!-- 456 < fgh <script jkl < 789 </script"</script>`,
`<script>var a = "asd < 123 \x3C!-- 456 < fgh \x3Cscript jkl < 789 \x3C/script"</script>`,
},
{
"Special tags in <script> string literals (mixed case)",
`<script>var a = "<!-- <ScripT </ScripT"</script>`,
`<script>var a = "\x3C!-- \x3CScripT \x3C/ScripT"</script>`,
},
{
"Special tags in <script> regex literals (mixed case)",
`<script>var a = /<!-- <ScripT </ScripT/</script>`,
`<script>var a = /\x3C!-- \x3CScripT \x3C/ScripT/</script>`,
},
{
"CSS comments",
"<style>p// paragraph\n" +
`{border: 1px/* color */{{"#00f"}}}</style>`,
"<style>p\n" +
"{border: 1px #00f}</style>",
},
{
"JS attr block comment",
`<a onclick="f(""); /* alert({{.H}}) */">`,
// Attribute comment tests should pass if the comments
// are successfully elided.
`<a onclick="f(""); /* alert() */">`,
},
{
"JS attr line comment",
`<a onclick="// alert({{.G}})">`,
`<a onclick="// alert()">`,
},
{
"CSS attr block comment",
`<a style="/* color: {{.H}} */">`,
`<a style="/* color: */">`,
},
{
"CSS attr line comment",
`<a style="// color: {{.G}}">`,
`<a style="// color: ">`,
},
{
"HTML substitution commented out",
"<p><!-- {{.H}} --></p>",
"<p></p>",
},
{
"Comment ends flush with start",
"<!--{{.}}--><script>/*{{.}}*///{{.}}\n</script><style>/*{{.}}*///{{.}}\n</style><a onclick='/*{{.}}*///{{.}}' style='/*{{.}}*///{{.}}'>",
"<script> \n</script><style> \n</style><a onclick='/**///' style='/**///'>",
},
{
"typed HTML in text",
`{{.W}}`,
`¡<b class="foo">Hello</b>, <textarea>O'World</textarea>!`,
},
{
"typed HTML in attribute",
`<div title="{{.W}}">`,
`<div title="¡Hello, O'World!">`,
},
{
"typed HTML in script",
`<button onclick="alert({{.W}})">`,
`<button onclick="alert("\u0026iexcl;\u003cb class=\"foo\"\u003eHello\u003c/b\u003e, \u003ctextarea\u003eO'World\u003c/textarea\u003e!")">`,
},
{
"typed HTML in RCDATA",
`<textarea>{{.W}}</textarea>`,
`<textarea>¡<b class="foo">Hello</b>, <textarea>O'World</textarea>!</textarea>`,
},
{
"range in textarea",
"<textarea>{{range .A}}{{.}}{{end}}</textarea>",
"<textarea><a><b></textarea>",
},
{
"No tag injection",
`{{"10$"}}<{{"script src,evil.org/pwnd.js"}}...`,
`10$<script src,evil.org/pwnd.js...`,
},
{
"No comment injection",
`<{{"!--"}}`,
`<!--`,
},
{
"No RCDATA end tag injection",
`<textarea><{{"/textarea "}}...</textarea>`,
`<textarea></textarea ...</textarea>`,
},
{
"optional attrs",
`<img class="{{"iconClass"}}"` +
`{{if .T}} id="{{"<iconId>"}}"{{end}}` +
// Double quotes inside if/else.
` src=` +
`{{if .T}}"?{{"<iconPath>"}}"` +
`{{else}}"images/cleardot.gif"{{end}}` +
// Missing space before title, but it is not a
// part of the src attribute.
`{{if .T}}title="{{"<title>"}}"{{end}}` +
// Quotes outside if/else.
` alt="` +
`{{if .T}}{{"<alt>"}}` +
`{{else}}{{if .F}}{{"<title>"}}{{end}}` +
`{{end}}"` +
`>`,
`<img class="iconClass" id="<iconId>" src="?%3ciconPath%3e"title="<title>" alt="<alt>">`,
},
{
"conditional valueless attr name",
`<input{{if .T}} checked{{end}} name=n>`,
`<input checked name=n>`,
},
{
"conditional dynamic valueless attr name 1",
`<input{{if .T}} {{"checked"}}{{end}} name=n>`,
`<input checked name=n>`,
},
{
"conditional dynamic valueless attr name 2",
`<input {{if .T}}{{"checked"}} {{end}}name=n>`,
`<input checked name=n>`,
},
{
"dynamic attribute name",
`<img on{{"load"}}="alert({{"loaded"}})">`,
// Treated as JS since quotes are inserted.
`<img onload="alert("loaded")">`,
},
{
"bad dynamic attribute name 1",
// Allow checked, selected, disabled, but not JS or
// CSS attributes.
`<input {{"onchange"}}="{{"doEvil()"}}">`,
`<input ZgotmplZ="doEvil()">`,
},
{
"bad dynamic attribute name 2",
`<div {{"sTyle"}}="{{"color: expression(alert(1337))"}}">`,
`<div ZgotmplZ="color: expression(alert(1337))">`,
},
{
"bad dynamic attribute name 3",
// Allow title or alt, but not a URL.
`<img {{"src"}}="{{"javascript:doEvil()"}}">`,
`<img ZgotmplZ="javascript:doEvil()">`,
},
{
"bad dynamic attribute name 4",
// Structure preservation requires values to associate
// with a consistent attribute.
`<input checked {{""}}="Whose value am I?">`,
`<input checked ZgotmplZ="Whose value am I?">`,
},
{
"dynamic element name",
`<h{{3}}><table><t{{"head"}}>...</h{{3}}>`,
`<h3><table><thead>...</h3>`,
},
{
"bad dynamic element name",
// Dynamic element names are typically used to switch
// between (thead, tfoot, tbody), (ul, ol), (th, td),
// and other replaceable sets.
// We do not currently easily support (ul, ol).
// If we do change to support that, this test should
// catch failures to filter out special tag names which
// would violate the structure preservation property --
// if any special tag name could be substituted, then
// the content could be raw text/RCDATA for some inputs
// and regular HTML content for others.
`<{{"script"}}>{{"doEvil()"}}</{{"script"}}>`,
`<script>doEvil()</script>`,
},
{
"srcset bad URL in second position",
`<img srcset="{{"/not-an-image#,javascript:alert(1)"}}">`,
// The second URL is also filtered.
`<img srcset="/not-an-image#,#ZgotmplZ">`,
},
{
"srcset buffer growth",
`<img srcset={{",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,"}}>`,
`<img srcset=,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,>`,
},
{
"unquoted empty attribute value (plaintext)",
"<p name={{.U}}>",
"<p name=ZgotmplZ>",
},
{
"unquoted empty attribute value (url)",
"<p href={{.U}}>",
"<p href=ZgotmplZ>",
},
{
"quoted empty attribute value",
"<p name=\"{{.U}}\">",
"<p name=\"\">",
},
{
"JS template lit special characters",
"<script>var a = `{{.I}}`</script>",
"<script>var a = `\\u0024\\u007b asd \\u0060\\u0060 \\u007d`</script>",
},
{
"JS template lit special characters, nested lit",
"<script>var a = `${ `{{.I}}` }`</script>",
"<script>var a = `${ `\\u0024\\u007b asd \\u0060\\u0060 \\u007d` }`</script>",
},
{
"JS template lit, nested JS",
"<script>var a = `${ var a = \"{{\"a \\\" d\"}}\" }`</script>",
"<script>var a = `${ var a = \"a \\u0022 d\" }`</script>",
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
tmpl := New(test.name)
tmpl = Must(tmpl.Parse(test.input))
// Check for bug 6459: Tree field was not set in Parse.
if tmpl.Tree != tmpl.text.Tree {
t.Fatalf("%s: tree not set properly", test.name)
}
b := new(strings.Builder)
if err := tmpl.Execute(b, data); err != nil {
t.Fatalf("%s: template execution failed: %s", test.name, err)
}
if w, g := test.output, b.String(); w != g {
t.Fatalf("%s: escaped output: want\n\t%q\ngot\n\t%q", test.name, w, g)
}
b.Reset()
if err := tmpl.Execute(b, pdata); err != nil {
t.Fatalf("%s: template execution failed for pointer: %s", test.name, err)
}
if w, g := test.output, b.String(); w != g {
t.Fatalf("%s: escaped output for pointer: want\n\t%q\ngot\n\t%q", test.name, w, g)
}
if tmpl.Tree != tmpl.text.Tree {
t.Fatalf("%s: tree mismatch", test.name)
}
})
}
}
func TestEscapeMap(t *testing.T) {
data := map[string]string{
"html": `<h1>Hi!</h1>`,
"urlquery": `http://www.foo.com/index.html?title=main`,
}
for _, test := range [...]struct {
desc, input, output string
}{
// covering issue 20323
{
"field with predefined escaper name 1",
`{{.html | print}}`,
`<h1>Hi!</h1>`,
},
// covering issue 20323
{
"field with predefined escaper name 2",
`{{.urlquery | print}}`,
`http://www.foo.com/index.html?title=main`,
},
} {
tmpl := Must(New("").Parse(test.input))
b := new(strings.Builder)
if err := tmpl.Execute(b, data); err != nil {
t.Errorf("%s: template execution failed: %s", test.desc, err)
continue
}
if w, g := test.output, b.String(); w != g {
t.Errorf("%s: escaped output: want\n\t%q\ngot\n\t%q", test.desc, w, g)
continue
}
}
}
func TestEscapeSet(t *testing.T) {
type dataItem struct {
Children []*dataItem
X string
}
data := dataItem{
Children: []*dataItem{
{X: "foo"},
{X: "<bar>"},
{
Children: []*dataItem{
{X: "baz"},
},
},
},
}
tests := []struct {
inputs map[string]string
want string
}{
// The trivial set.
{
map[string]string{
"main": ``,
},
``,
},
// A template called in the start context.
{
map[string]string{
"main": `Hello, {{template "helper"}}!`,
// Not a valid top level HTML template.
// "<b" is not a full tag.
"helper": `{{"<World>"}}`,
},
`Hello, <World>!`,
},
// A template called in a context other than the start.
{
map[string]string{
"main": `<a onclick='a = {{template "helper"}};'>`,
// Not a valid top level HTML template.
// "<b" is not a full tag.
"helper": `{{"<a>"}}<b`,
},
`<a onclick='a = "\u003ca\u003e"<b;'>`,
},
// A recursive template that ends in its start context.
{
map[string]string{
"main": `{{range .Children}}{{template "main" .}}{{else}}{{.X}} {{end}}`,
},
`foo <bar> baz `,
},
// A recursive helper template that ends in its start context.
{
map[string]string{
"main": `{{template "helper" .}}`,
"helper": `{{if .Children}}<ul>{{range .Children}}<li>{{template "main" .}}</li>{{end}}</ul>{{else}}{{.X}}{{end}}`,
},
`<ul><li>foo</li><li><bar></li><li><ul><li>baz</li></ul></li></ul>`,
},
// Co-recursive templates that end in its start context.
{
map[string]string{
"main": `<blockquote>{{range .Children}}{{template "helper" .}}{{end}}</blockquote>`,
"helper": `{{if .Children}}{{template "main" .}}{{else}}{{.X}}<br>{{end}}`,
},
`<blockquote>foo<br><bar><br><blockquote>baz<br></blockquote></blockquote>`,
},
// A template that is called in two different contexts.
{
map[string]string{
"main": `<button onclick="title='{{template "helper"}}'; ...">{{template "helper"}}</button>`,
"helper": `{{11}} of {{"<100>"}}`,
},
`<button onclick="title='11 of \u003c100\u003e'; ...">11 of <100></button>`,
},
// A non-recursive template that ends in a different context.
// helper starts in jsCtxRegexp and ends in jsCtxDivOp.
{
map[string]string{
"main": `<script>var x={{template "helper"}}/{{"42"}};</script>`,
"helper": "{{126}}",
},
`<script>var x= 126 /"42";</script>`,
},
// A recursive template that ends in a similar context.
{
map[string]string{
"main": `<script>var x=[{{template "countdown" 4}}];</script>`,
"countdown": `{{.}}{{if .}},{{template "countdown" . | pred}}{{end}}`,
},
`<script>var x=[ 4 , 3 , 2 , 1 , 0 ];</script>`,
},
// A recursive template that ends in a different context.
/*
{
map[string]string{
"main": `<a href="/foo{{template "helper" .}}">`,
"helper": `{{if .Children}}{{range .Children}}{{template "helper" .}}{{end}}{{else}}?x={{.X}}{{end}}`,
},
`<a href="/foo?x=foo?x=%3cbar%3e?x=baz">`,
},
*/
}
// pred is a template function that returns the predecessor of a
// natural number for testing recursive templates.
fns := FuncMap{"pred": func(a ...any) (any, error) {
if len(a) == 1 {
if i, _ := a[0].(int); i > 0 {
return i - 1, nil
}
}
return nil, fmt.Errorf("undefined pred(%v)", a)
}}
for _, test := range tests {
source := ""
for name, body := range test.inputs {
source += fmt.Sprintf("{{define %q}}%s{{end}} ", name, body)
}
tmpl, err := New("root").Funcs(fns).Parse(source)
if err != nil {
t.Errorf("error parsing %q: %v", source, err)
continue
}
var b strings.Builder
if err := tmpl.ExecuteTemplate(&b, "main", data); err != nil {
t.Errorf("%q executing %v", err.Error(), tmpl.Lookup("main"))
continue
}
if got := b.String(); test.want != got {
t.Errorf("want\n\t%q\ngot\n\t%q", test.want, got)
}
}
}
func TestErrors(t *testing.T) {
tests := []struct {
input string
err string
}{
// Non-error cases.
{
"{{if .Cond}}<a>{{else}}<b>{{end}}",
"",
},
{
"{{if .Cond}}<a>{{end}}",
"",
},
{
"{{if .Cond}}{{else}}<b>{{end}}",
"",
},
{
"{{with .Cond}}<div>{{end}}",
"",
},
{
"{{range .Items}}<a>{{end}}",
"",
},
{
"<a href='/foo?{{range .Items}}&{{.K}}={{.V}}{{end}}'>",
"",
},
{
"{{range .Items}}<a{{if .X}}{{end}}>{{end}}",
"",
},
{
"{{range .Items}}<a{{if .X}}{{end}}>{{continue}}{{end}}",
"",
},
{
"{{range .Items}}<a{{if .X}}{{end}}>{{break}}{{end}}",
"",
},
{
"{{range .Items}}<a{{if .X}}{{end}}>{{if .X}}{{break}}{{end}}{{end}}",
"",
},
{
"<script>var a = `${a+b}`</script>`",
"",
},
{
"<script>var tmpl = `asd`;</script>",
``,
},
{
"<script>var tmpl = `${1}`;</script>",
``,
},
{
"<script>var tmpl = `${return ``}`;</script>",
``,
},
{
"<script>var tmpl = `${return {{.}} }`;</script>",
``,
},
{
"<script>var tmpl = `${ let a = {1:1} {{.}} }`;</script>",
``,
},
{
"<script>var tmpl = `asd ${return \"{\"}`;</script>",
``,
},
// Error cases.
{
"{{if .Cond}}<a{{end}}",
"z:1:5: {{if}} branches",
},
{
"{{if .Cond}}\n{{else}}\n<a{{end}}",
"z:1:5: {{if}} branches",
},
{
// Missing quote in the else branch.
`{{if .Cond}}<a href="foo">{{else}}<a href="bar>{{end}}`,
"z:1:5: {{if}} branches",
},
{
// Different kind of attribute: href implies a URL.
"<a {{if .Cond}}href='{{else}}title='{{end}}{{.X}}'>",
"z:1:8: {{if}} branches",
},
{
"\n{{with .X}}<a{{end}}",
"z:2:7: {{with}} branches",
},
{
"\n{{with .X}}<a>{{else}}<a{{end}}",
"z:2:7: {{with}} branches",
},
{
"{{range .Items}}<a{{end}}",
`z:1: on range loop re-entry: "<" in attribute name: "<a"`,
},
{
"\n{{range .Items}} x='<a{{end}}",
"z:2:8: on range loop re-entry: {{range}} branches",
},
{
"{{range .Items}}<a{{if .X}}{{break}}{{end}}>{{end}}",
"z:1:29: at range loop break: {{range}} branches end in different contexts",
},
{
"{{range .Items}}<a{{if .X}}{{continue}}{{end}}>{{end}}",
"z:1:29: at range loop continue: {{range}} branches end in different contexts",
},
{
"<a b=1 c={{.H}}",
"z: ends in a non-text context: {stateAttr delimSpaceOrTagEnd",
},
{
"<script>foo();",
"z: ends in a non-text context: {stateJS",
},
{
`<a href="{{if .F}}/foo?a={{else}}/bar/{{end}}{{.H}}">`,
"z:1:47: {{.H}} appears in an ambiguous context within a URL",
},
{
`<a onclick="alert('Hello \`,
`unfinished escape sequence in JS string: "Hello \\"`,
},
{
`<a onclick='alert("Hello\, World\`,
`unfinished escape sequence in JS string: "Hello\\, World\\"`,
},
{
`<a onclick='alert(/x+\`,
`unfinished escape sequence in JS string: "x+\\"`,
},
{
`<a onclick="/foo[\]/`,
`unfinished JS regexp charset: "foo[\\]/"`,
},
{
// It is ambiguous whether 1.5 should be 1\.5 or 1.5.
// Either `var x = 1/- 1.5 /i.test(x)`
// where `i.test(x)` is a method call of reference i,
// or `/-1\.5/i.test(x)` which is a method call on a
// case insensitive regular expression.
`<script>{{if false}}var x = 1{{end}}/-{{"1.5"}}/i.test(x)</script>`,
`'/' could start a division or regexp: "/-"`,
},
{
`{{template "foo"}}`,
"z:1:11: no such template \"foo\"",
},
{
`<div{{template "y"}}>` +
// Illegal starting in stateTag but not in stateText.
`{{define "y"}} foo<b{{end}}`,
`"<" in attribute name: " foo<b"`,
},
{
`<script>reverseList = [{{template "t"}}]</script>` +
// Missing " after recursive call.
`{{define "t"}}{{if .Tail}}{{template "t" .Tail}}{{end}}{{.Head}}",{{end}}`,
`: cannot compute output context for template t$htmltemplate_stateJS_elementScript`,
},
{
`<input type=button value=onclick=>`,
`html/template:z: "=" in unquoted attr: "onclick="`,
},
{
`<input type=button value= onclick=>`,
`html/template:z: "=" in unquoted attr: "onclick="`,
},
{
`<input type=button value= 1+1=2>`,
`html/template:z: "=" in unquoted attr: "1+1=2"`,
},
{
"<a class=`foo>",
"html/template:z: \"`\" in unquoted attr: \"`foo\"",
},
{
`<a style=font:'Arial'>`,
`html/template:z: "'" in unquoted attr: "font:'Arial'"`,
},
{
`<a=foo>`,
`: expected space, attr name, or end of tag, but got "=foo>"`,
},
{
`Hello, {{. | urlquery | print}}!`,
// urlquery is disallowed if it is not the last command in the pipeline.
`predefined escaper "urlquery" disallowed in template`,
},
{
`Hello, {{. | html | print}}!`,
// html is disallowed if it is not the last command in the pipeline.
`predefined escaper "html" disallowed in template`,
},
{
`Hello, {{html . | print}}!`,
// A direct call to html is disallowed if it is not the last command in the pipeline.
`predefined escaper "html" disallowed in template`,
},
{
`<div class={{. | html}}>Hello<div>`,
// html is disallowed in a pipeline that is in an unquoted attribute context,
// even if it is the last command in the pipeline.
`predefined escaper "html" disallowed in template`,
},
{
`Hello, {{. | urlquery | html}}!`,
// html is allowed since it is the last command in the pipeline, but urlquery is not.
`predefined escaper "urlquery" disallowed in template`,
},
}
for _, test := range tests {
buf := new(bytes.Buffer)
tmpl, err := New("z").Parse(test.input)
if err != nil {
t.Errorf("input=%q: unexpected parse error %s\n", test.input, err)
continue
}
err = tmpl.Execute(buf, nil)
var got string
if err != nil {
got = err.Error()
}
if test.err == "" {
if got != "" {
t.Errorf("input=%q: unexpected error %q", test.input, got)
}
continue
}
if !strings.Contains(got, test.err) {
t.Errorf("input=%q: error\n\t%q\ndoes not contain expected string\n\t%q", test.input, got, test.err)
continue
}
// Check that we get the same error if we call Execute again.
if err := tmpl.Execute(buf, nil); err == nil || err.Error() != got {
t.Errorf("input=%q: unexpected error on second call %q", test.input, err)
}
}
}
func TestEscapeText(t *testing.T) {
tests := []struct {
input string
output context
}{
{
``,
context{},
},
{
`Hello, World!`,
context{},
},
{
// An orphaned "<" is OK.
`I <3 Ponies!`,
context{},
},
{
`<a`,
context{state: stateTag},
},
{
`<a `,
context{state: stateTag},
},
{
`<a>`,
context{state: stateText},
},
{
`<a href`,
context{state: stateAttrName, attr: attrURL},
},
{
`<a on`,
context{state: stateAttrName, attr: attrScript},
},
{
`<a href `,
context{state: stateAfterName, attr: attrURL},
},
{
`<a style = `,
context{state: stateBeforeValue, attr: attrStyle},
},
{
`<a href=`,
context{state: stateBeforeValue, attr: attrURL},
},
{
`<a href=x`,
context{state: stateURL, delim: delimSpaceOrTagEnd, urlPart: urlPartPreQuery, attr: attrURL},
},
{
`<a href=x `,
context{state: stateTag},
},
{
`<a href=>`,
context{state: stateText},
},
{
`<a href=x>`,
context{state: stateText},
},
{
`<a href ='`,
context{state: stateURL, delim: delimSingleQuote, attr: attrURL},
},
{
`<a href=''`,
context{state: stateTag},
},
{
`<a href= "`,
context{state: stateURL, delim: delimDoubleQuote, attr: attrURL},
},
{
`<a href=""`,
context{state: stateTag},
},
{
`<a title="`,
context{state: stateAttr, delim: delimDoubleQuote},
},
{
`<a HREF='http:`,
context{state: stateURL, delim: delimSingleQuote, urlPart: urlPartPreQuery, attr: attrURL},
},
{
`<a Href='/`,
context{state: stateURL, delim: delimSingleQuote, urlPart: urlPartPreQuery, attr: attrURL},
},
{
`<a href='"`,
context{state: stateURL, delim: delimSingleQuote, urlPart: urlPartPreQuery, attr: attrURL},
},
{
`<a href="'`,
context{state: stateURL, delim: delimDoubleQuote, urlPart: urlPartPreQuery, attr: attrURL},
},
{
`<a href=''`,
context{state: stateURL, delim: delimSingleQuote, urlPart: urlPartPreQuery, attr: attrURL},
},
{
`<a href=""`,
context{state: stateURL, delim: delimDoubleQuote, urlPart: urlPartPreQuery, attr: attrURL},
},
{
`<a href=""`,
context{state: stateURL, delim: delimDoubleQuote, urlPart: urlPartPreQuery, attr: attrURL},
},
{
`<a href="`,
context{state: stateURL, delim: delimSpaceOrTagEnd, urlPart: urlPartPreQuery, attr: attrURL},
},
{
`<img alt="1">`,
context{state: stateText},
},
{
`<img alt="1>"`,
context{state: stateTag},
},
{
`<img alt="1>">`,
context{state: stateText},
},
{
`<input checked type="checkbox"`,
context{state: stateTag},
},
{
`<a onclick="`,
context{state: stateJS, delim: delimDoubleQuote, attr: attrScript},
},
{
`<a onclick="//foo`,
context{state: stateJSLineCmt, delim: delimDoubleQuote, attr: attrScript},
},
{
"<a onclick='//\n",
context{state: stateJS, delim: delimSingleQuote, attr: attrScript},
},
{
"<a onclick='//\r\n",
context{state: stateJS, delim: delimSingleQuote, attr: attrScript},
},
{
"<a onclick='//\u2028",
context{state: stateJS, delim: delimSingleQuote, attr: attrScript},
},
{
`<a onclick="/*`,
context{state: stateJSBlockCmt, delim: delimDoubleQuote, attr: attrScript},
},
{
`<a onclick="/*/`,
context{state: stateJSBlockCmt, delim: delimDoubleQuote, attr: attrScript},
},
{
`<a onclick="/**/`,
context{state: stateJS, delim: delimDoubleQuote, attr: attrScript},
},
{
`<a onkeypress=""`,
context{state: stateJSDqStr, delim: delimDoubleQuote, attr: attrScript},
},
{
`<a onclick='"foo"`,
context{state: stateJS, delim: delimSingleQuote, jsCtx: jsCtxDivOp, attr: attrScript},
},
{
`<a onclick='foo'`,
context{state: stateJS, delim: delimSpaceOrTagEnd, jsCtx: jsCtxDivOp, attr: attrScript},
},
{
`<a onclick='foo`,
context{state: stateJSSqStr, delim: delimSpaceOrTagEnd, attr: attrScript},
},
{
`<a onclick=""foo'`,
context{state: stateJSDqStr, delim: delimDoubleQuote, attr: attrScript},
},
{
`<a onclick="'foo"`,
context{state: stateJSSqStr, delim: delimDoubleQuote, attr: attrScript},
},
{
"<a onclick=\"`foo",
context{state: stateJSTmplLit, delim: delimDoubleQuote, attr: attrScript},
},
{
`<A ONCLICK="'`,
context{state: stateJSSqStr, delim: delimDoubleQuote, attr: attrScript},
},
{
`<a onclick="/`,
context{state: stateJSRegexp, delim: delimDoubleQuote, attr: attrScript},
},
{
`<a onclick="'foo'`,
context{state: stateJS, delim: delimDoubleQuote, jsCtx: jsCtxDivOp, attr: attrScript},
},
{
`<a onclick="'foo\'`,
context{state: stateJSSqStr, delim: delimDoubleQuote, attr: attrScript},
},
{
`<a onclick="'foo\'`,
context{state: stateJSSqStr, delim: delimDoubleQuote, attr: attrScript},
},
{
`<a onclick="/foo/`,
context{state: stateJS, delim: delimDoubleQuote, jsCtx: jsCtxDivOp, attr: attrScript},
},
{
`<script>/foo/ /=`,
context{state: stateJS, element: elementScript},
},
{
`<a onclick="1 /foo`,
context{state: stateJS, delim: delimDoubleQuote, jsCtx: jsCtxDivOp, attr: attrScript},
},
{
`<a onclick="1 /*c*/ /foo`,
context{state: stateJS, delim: delimDoubleQuote, jsCtx: jsCtxDivOp, attr: attrScript},
},
{
`<a onclick="/foo[/]`,
context{state: stateJSRegexp, delim: delimDoubleQuote, attr: attrScript},
},
{
`<a onclick="/foo\/`,
context{state: stateJSRegexp, delim: delimDoubleQuote, attr: attrScript},
},
{
`<a onclick="/foo/`,
context{state: stateJS, delim: delimDoubleQuote, jsCtx: jsCtxDivOp, attr: attrScript},
},
{
`<input checked style="`,
context{state: stateCSS, delim: delimDoubleQuote, attr: attrStyle},
},
{
`<a style="//`,
context{state: stateCSSLineCmt, delim: delimDoubleQuote, attr: attrStyle},
},
{
`<a style="//</script>`,
context{state: stateCSSLineCmt, delim: delimDoubleQuote, attr: attrStyle},
},
{
"<a style='//\n",
context{state: stateCSS, delim: delimSingleQuote, attr: attrStyle},
},
{
"<a style='//\r",
context{state: stateCSS, delim: delimSingleQuote, attr: attrStyle},
},
{
`<a style="/*`,
context{state: stateCSSBlockCmt, delim: delimDoubleQuote, attr: attrStyle},
},
{
`<a style="/*/`,
context{state: stateCSSBlockCmt, delim: delimDoubleQuote, attr: attrStyle},
},
{
`<a style="/**/`,
context{state: stateCSS, delim: delimDoubleQuote, attr: attrStyle},
},
{
`<a style="background: '`,
context{state: stateCSSSqStr, delim: delimDoubleQuote, attr: attrStyle},
},
{
`<a style="background: "`,
context{state: stateCSSDqStr, delim: delimDoubleQuote, attr: attrStyle},
},
{
`<a style="background: '/foo?img=`,
context{state: stateCSSSqStr, delim: delimDoubleQuote, urlPart: urlPartQueryOrFrag, attr: attrStyle},
},
{
`<a style="background: '/`,
context{state: stateCSSSqStr, delim: delimDoubleQuote, urlPart: urlPartPreQuery, attr: attrStyle},
},
{
`<a style="background: url("/`,
context{state: stateCSSDqURL, delim: delimDoubleQuote, urlPart: urlPartPreQuery, attr: attrStyle},
},
{
`<a style="background: url('/`,
context{state: stateCSSSqURL, delim: delimDoubleQuote, urlPart: urlPartPreQuery, attr: attrStyle},
},
{
`<a style="background: url('/)`,
context{state: stateCSSSqURL, delim: delimDoubleQuote, urlPart: urlPartPreQuery, attr: attrStyle},
},
{
`<a style="background: url('/ `,
context{state: stateCSSSqURL, delim: delimDoubleQuote, urlPart: urlPartPreQuery, attr: attrStyle},
},
{
`<a style="background: url(/`,
context{state: stateCSSURL, delim: delimDoubleQuote, urlPart: urlPartPreQuery, attr: attrStyle},
},
{
`<a style="background: url( `,
context{state: stateCSSURL, delim: delimDoubleQuote, attr: attrStyle},
},
{
`<a style="background: url( /image?name=`,
context{state: stateCSSURL, delim: delimDoubleQuote, urlPart: urlPartQueryOrFrag, attr: attrStyle},
},
{
`<a style="background: url(x)`,
context{state: stateCSS, delim: delimDoubleQuote, attr: attrStyle},
},
{
`<a style="background: url('x'`,
context{state: stateCSS, delim: delimDoubleQuote, attr: attrStyle},
},
{
`<a style="background: url( x `,
context{state: stateCSS, delim: delimDoubleQuote, attr: attrStyle},
},
{
`<!-- foo`,
context{state: stateHTMLCmt},
},
{
`<!-->`,
context{state: stateHTMLCmt},
},
{
`<!--->`,
context{state: stateHTMLCmt},
},
{
`<!-- foo -->`,
context{state: stateText},
},
{
`<script`,
context{state: stateTag, element: elementScript},
},
{
`<script `,
context{state: stateTag, element: elementScript},
},
{
`<script src="foo.js" `,
context{state: stateTag, element: elementScript},
},
{
`<script src='foo.js' `,
context{state: stateTag, element: elementScript},
},
{
`<script type=text/javascript `,
context{state: stateTag, element: elementScript},
},
{
`<script>`,
context{state: stateJS, jsCtx: jsCtxRegexp, element: elementScript},
},
{
`<script>foo`,
context{state: stateJS, jsCtx: jsCtxDivOp, element: elementScript},
},
{
`<script>foo</script>`,
context{state: stateText},
},
{
`<script>foo</script><!--`,
context{state: stateHTMLCmt},
},
{
`<script>document.write("<p>foo</p>");`,
context{state: stateJS, element: elementScript},
},
{
`<script>document.write("<p>foo<\/script>");`,
context{state: stateJS, element: elementScript},
},
{
// <script and </script tags are escaped, so </script> should not
// cause us to exit the JS state.
`<script>document.write("<script>alert(1)</script>");`,
context{state: stateJS, element: elementScript},
},
{
`<script>document.write("<script>`,
context{state: stateJSDqStr, element: elementScript},
},
{
`<script>document.write("<script>alert(1)</script>`,
context{state: stateJSDqStr, element: elementScript},
},
{
`<script>document.write("<script>alert(1)<!--`,
context{state: stateJSDqStr, element: elementScript},
},
{
`<script>document.write("<script>alert(1)</Script>");`,
context{state: stateJS, element: elementScript},
},
{
`<script>document.write("<!--");`,
context{state: stateJS, element: elementScript},
},
{
`<script>let a = /</script`,
context{state: stateJSRegexp, element: elementScript},
},
{
`<script>let a = /</script/`,
context{state: stateJS, element: elementScript, jsCtx: jsCtxDivOp},
},
{
`<script type="text/template">`,
context{state: stateText},
},
// covering issue 19968
{
`<script type="TEXT/JAVASCRIPT">`,
context{state: stateJS, element: elementScript},
},
// covering issue 19965
{
`<script TYPE="text/template">`,
context{state: stateText},
},
{
`<script type="notjs">`,
context{state: stateText},
},
{
`<Script>`,
context{state: stateJS, element: elementScript},
},
{
`<SCRIPT>foo`,
context{state: stateJS, jsCtx: jsCtxDivOp, element: elementScript},
},
{
`<textarea>value`,
context{state: stateRCDATA, element: elementTextarea},
},
{
`<textarea>value</TEXTAREA>`,
context{state: stateText},
},
{
`<textarea name=html><b`,
context{state: stateRCDATA, element: elementTextarea},
},
{
`<title>value`,
context{state: stateRCDATA, element: elementTitle},
},
{
`<style>value`,
context{state: stateCSS, element: elementStyle},
},
{
`<a xlink:href`,
context{state: stateAttrName, attr: attrURL},
},
{
`<a xmlns`,
context{state: stateAttrName, attr: attrURL},
},
{
`<a xmlns:foo`,
context{state: stateAttrName, attr: attrURL},
},
{
`<a xmlnsxyz`,
context{state: stateAttrName},
},
{
`<a data-url`,
context{state: stateAttrName, attr: attrURL},
},
{
`<a data-iconUri`,
context{state: stateAttrName, attr: attrURL},
},
{
`<a data-urlItem`,
context{state: stateAttrName, attr: attrURL},
},
{
`<a g:`,
context{state: stateAttrName},
},
{
`<a g:url`,
context{state: stateAttrName, attr: attrURL},
},
{
`<a g:iconUri`,
context{state: stateAttrName, attr: attrURL},
},
{
`<a g:urlItem`,
context{state: stateAttrName, attr: attrURL},
},
{
`<a g:value`,
context{state: stateAttrName},
},
{
`<a svg:style='`,
context{state: stateCSS, delim: delimSingleQuote, attr: attrStyle},
},
{
`<svg:font-face`,
context{state: stateTag},
},
{
`<svg:a svg:onclick="`,
context{state: stateJS, delim: delimDoubleQuote, attr: attrScript},
},
{
`<svg:a svg:onclick="x()">`,
context{},
},
{
"<script>var a = `",
context{state: stateJSTmplLit, element: elementScript},
},
{
"<script>var a = `${",
context{state: stateJS, element: elementScript},
},
{
"<script>var a = `${}",
context{state: stateJSTmplLit, element: elementScript},
},
{
"<script>var a = `${`",
context{state: stateJSTmplLit, element: elementScript},
},
{
"<script>var a = `${var a = \"",
context{state: stateJSDqStr, element: elementScript},
},
{
"<script>var a = `${var a = \"`",
context{state: stateJSDqStr, element: elementScript},
},
{
"<script>var a = `${var a = \"}",
context{state: stateJSDqStr, element: elementScript},
},
{
"<script>var a = `${``",
context{state: stateJS, element: elementScript},
},
{
"<script>var a = `${`}",
context{state: stateJSTmplLit, element: elementScript},
},
{
"<script>`${ {} } asd`</script><script>`${ {} }",
context{state: stateJSTmplLit, element: elementScript},
},
{
"<script>var foo = `${ (_ => { return \"x\" })() + \"${",
context{state: stateJSDqStr, element: elementScript},
},
{
"<script>var a = `${ {</script><script>var b = `${ x }",
context{state: stateJSTmplLit, element: elementScript, jsCtx: jsCtxDivOp},
},
{
"<script>var foo = `x` + \"${",
context{state: stateJSDqStr, element: elementScript},
},
{
"<script>function f() { var a = `${}`; }",
context{state: stateJS, element: elementScript},
},
{
"<script>{`${}`}",
context{state: stateJS, element: elementScript},
},
{
"<script>`${ function f() { return `${1}` }() }`",
context{state: stateJS, element: elementScript, jsCtx: jsCtxDivOp},
},
{
"<script>function f() {`${ function f() { `${1}` } }`}",
context{state: stateJS, element: elementScript, jsCtx: jsCtxDivOp},
},
{
"<script>`${ { `` }",
context{state: stateJS, element: elementScript},
},
{
"<script>`${ { }`",
context{state: stateJSTmplLit, element: elementScript},
},
{
"<script>var foo = `${ foo({ a: { c: `${",
context{state: stateJS, element: elementScript},
},
{
"<script>var foo = `${ foo({ a: { c: `${ {{.}} }` }, b: ",
context{state: stateJS, element: elementScript},
},
{
"<script>`${ `}",
context{state: stateJSTmplLit, element: elementScript},
},
}
for _, test := range tests {
b, e := []byte(test.input), makeEscaper(nil)
c := e.escapeText(context{}, &parse.TextNode{NodeType: parse.NodeText, Text: b})
if !test.output.eq(c) {
t.Errorf("input %q: want context\n\t%v\ngot\n\t%v", test.input, test.output, c)
continue
}
if test.input != string(b) {
t.Errorf("input %q: text node was modified: want %q got %q", test.input, test.input, b)
continue
}
}
}
func TestEnsurePipelineContains(t *testing.T) {
tests := []struct {
input, output string
ids []string
}{
{
"{{.X}}",
".X",
[]string{},
},
{
"{{.X | html}}",
".X | html",
[]string{},
},
{
"{{.X}}",
".X | html",
[]string{"html"},
},
{
"{{html .X}}",
"_eval_args_ .X | html | urlquery",
[]string{"html", "urlquery"},
},
{
"{{html .X .Y .Z}}",
"_eval_args_ .X .Y .Z | html | urlquery",
[]string{"html", "urlquery"},
},
{
"{{.X | print}}",
".X | print | urlquery",
[]string{"urlquery"},
},
{
"{{.X | print | urlquery}}",
".X | print | urlquery",
[]string{"urlquery"},
},
{
"{{.X | urlquery}}",
".X | html | urlquery",
[]string{"html", "urlquery"},
},
{
"{{.X | print 2 | .f 3}}",
".X | print 2 | .f 3 | urlquery | html",
[]string{"urlquery", "html"},
},
{
// covering issue 10801
"{{.X | println.x }}",
".X | println.x | urlquery | html",
[]string{"urlquery", "html"},
},
{
// covering issue 10801
"{{.X | (print 12 | println).x }}",
".X | (print 12 | println).x | urlquery | html",
[]string{"urlquery", "html"},
},
// The following test cases ensure that the merging of internal escapers
// with the predefined "html" and "urlquery" escapers is correct.
{
"{{.X | urlquery}}",
".X | _html_template_urlfilter | urlquery",
[]string{"_html_template_urlfilter", "_html_template_urlnormalizer"},
},
{
"{{.X | urlquery}}",
".X | urlquery | _html_template_urlfilter | _html_template_cssescaper",
[]string{"_html_template_urlfilter", "_html_template_cssescaper"},
},
{
"{{.X | urlquery}}",
".X | urlquery",
[]string{"_html_template_urlnormalizer"},
},
{
"{{.X | urlquery}}",
".X | urlquery",
[]string{"_html_template_urlescaper"},
},
{
"{{.X | html}}",
".X | html",
[]string{"_html_template_htmlescaper"},
},
{
"{{.X | html}}",
".X | html",
[]string{"_html_template_rcdataescaper"},
},
}
for i, test := range tests {
tmpl := template.Must(template.New("test").Parse(test.input))
action, ok := (tmpl.Tree.Root.Nodes[0].(*parse.ActionNode))
if !ok {
t.Errorf("First node is not an action: %s", test.input)
continue
}
pipe := action.Pipe
originalIDs := make([]string, len(test.ids))
copy(originalIDs, test.ids)
ensurePipelineContains(pipe, test.ids)
got := pipe.String()
if got != test.output {
t.Errorf("#%d: %s, %v: want\n\t%s\ngot\n\t%s", i, test.input, originalIDs, test.output, got)
}
}
}
func TestEscapeMalformedPipelines(t *testing.T) {
tests := []string{
"{{ 0 | $ }}",
"{{ 0 | $ | urlquery }}",
"{{ 0 | (nil) }}",
"{{ 0 | (nil) | html }}",
}
for _, test := range tests {
var b bytes.Buffer
tmpl, err := New("test").Parse(test)
if err != nil {
t.Errorf("failed to parse set: %q", err)
}
err = tmpl.Execute(&b, nil)
if err == nil {
t.Errorf("Expected error for %q", test)
}
}
}
func TestEscapeErrorsNotIgnorable(t *testing.T) {
var b bytes.Buffer
tmpl, _ := New("dangerous").Parse("<a")
err := tmpl.Execute(&b, nil)
if err == nil {
t.Errorf("Expected error")
} else if b.Len() != 0 {
t.Errorf("Emitted output despite escaping failure")
}
}
func TestEscapeSetErrorsNotIgnorable(t *testing.T) {
var b bytes.Buffer
tmpl, err := New("root").Parse(`{{define "t"}}<a{{end}}`)
if err != nil {
t.Errorf("failed to parse set: %q", err)
}
err = tmpl.ExecuteTemplate(&b, "t", nil)
if err == nil {
t.Errorf("Expected error")
} else if b.Len() != 0 {
t.Errorf("Emitted output despite escaping failure")
}
}
func TestRedundantFuncs(t *testing.T) {
inputs := []any{
"\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f" +
"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f" +
` !"#$%&'()*+,-./` +
`0123456789:;<=>?` +
`@ABCDEFGHIJKLMNO` +
`PQRSTUVWXYZ[\]^_` +
"`abcdefghijklmno" +
"pqrstuvwxyz{|}~\x7f" +
"\u00A0\u0100\u2028\u2029\ufeff\ufdec\ufffd\uffff\U0001D11E" +
"&%22\\",
CSS(`a[href =~ "//example.com"]#foo`),
HTML(`Hello, <b>World</b> &tc!`),
HTMLAttr(` dir="ltr"`),
JS(`c && alert("Hello, World!");`),
JSStr(`Hello, World & O'Reilly\x21`),
URL(`greeting=H%69&addressee=(World)`),
}
for n0, m := range redundantFuncs {
f0 := funcMap[n0].(func(...any) string)
for n1 := range m {
f1 := funcMap[n1].(func(...any) string)
for _, input := range inputs {
want := f0(input)
if got := f1(want); want != got {
t.Errorf("%s %s with %T %q: want\n\t%q,\ngot\n\t%q", n0, n1, input, input, want, got)
}
}
}
}
}
func TestIndirectPrint(t *testing.T) {
a := 3
ap := &a
b := "hello"
bp := &b
bpp := &bp
tmpl := Must(New("t").Parse(`{{.}}`))
var buf strings.Builder
err := tmpl.Execute(&buf, ap)
if err != nil {
t.Errorf("Unexpected error: %s", err)
} else if buf.String() != "3" {
t.Errorf(`Expected "3"; got %q`, buf.String())
}
buf.Reset()
err = tmpl.Execute(&buf, bpp)
if err != nil {
t.Errorf("Unexpected error: %s", err)
} else if buf.String() != "hello" {
t.Errorf(`Expected "hello"; got %q`, buf.String())
}
}
// This is a test for issue 3272.
func TestEmptyTemplateHTML(t *testing.T) {
page := Must(New("page").ParseFiles(os.DevNull))
if err := page.ExecuteTemplate(os.Stdout, "page", "nothing"); err == nil {
t.Fatal("expected error")
}
}
type Issue7379 int
func (Issue7379) SomeMethod(x int) string {
return fmt.Sprintf("<%d>", x)
}
// This is a test for issue 7379: type assertion error caused panic, and then
// the code to handle the panic breaks escaping. It's hard to see the second
// problem once the first is fixed, but its fix is trivial so we let that go. See
// the discussion for issue 7379.
func TestPipeToMethodIsEscaped(t *testing.T) {
tmpl := Must(New("x").Parse("<html>{{0 | .SomeMethod}}</html>\n"))
tryExec := func() string {
defer func() {
panicValue := recover()
if panicValue != nil {
t.Errorf("panicked: %v\n", panicValue)
}
}()
var b strings.Builder
tmpl.Execute(&b, Issue7379(0))
return b.String()
}
for i := 0; i < 3; i++ {
str := tryExec()
const expect = "<html><0></html>\n"
if str != expect {
t.Errorf("expected %q got %q", expect, str)
}
}
}
// Unlike text/template, html/template crashed if given an incomplete
// template, that is, a template that had been named but not given any content.
// This is issue #10204.
func TestErrorOnUndefined(t *testing.T) {
tmpl := New("undefined")
err := tmpl.Execute(nil, nil)
if err == nil {
t.Error("expected error")
} else if !strings.Contains(err.Error(), "incomplete") {
t.Errorf("expected error about incomplete template; got %s", err)
}
}
// This covers issue #20842.
func TestIdempotentExecute(t *testing.T) {
tmpl := Must(New("").
Parse(`{{define "main"}}<body>{{template "hello"}}</body>{{end}}`))
Must(tmpl.
Parse(`{{define "hello"}}Hello, {{"Ladies & Gentlemen!"}}{{end}}`))
got := new(strings.Builder)
var err error
// Ensure that "hello" produces the same output when executed twice.
want := "Hello, Ladies & Gentlemen!"
for i := 0; i < 2; i++ {
err = tmpl.ExecuteTemplate(got, "hello", nil)
if err != nil {
t.Errorf("unexpected error: %s", err)
}
if got.String() != want {
t.Errorf("after executing template \"hello\", got:\n\t%q\nwant:\n\t%q\n", got.String(), want)
}
got.Reset()
}
// Ensure that the implicit re-execution of "hello" during the execution of
// "main" does not cause the output of "hello" to change.
err = tmpl.ExecuteTemplate(got, "main", nil)
if err != nil {
t.Errorf("unexpected error: %s", err)
}
// If the HTML escaper is added again to the action {{"Ladies & Gentlemen!"}},
// we would expected to see the ampersand overescaped to "&amp;".
want = "<body>Hello, Ladies & Gentlemen!</body>"
if got.String() != want {
t.Errorf("after executing template \"main\", got:\n\t%q\nwant:\n\t%q\n", got.String(), want)
}
}
func BenchmarkEscapedExecute(b *testing.B) {
tmpl := Must(New("t").Parse(`<a onclick="alert('{{.}}')">{{.}}</a>`))
var buf bytes.Buffer
b.ResetTimer()
for i := 0; i < b.N; i++ {
tmpl.Execute(&buf, "foo & 'bar' & baz")
buf.Reset()
}
}
// Covers issue 22780.
func TestOrphanedTemplate(t *testing.T) {
t1 := Must(New("foo").Parse(`<a href="{{.}}">link1</a>`))
t2 := Must(t1.New("foo").Parse(`bar`))
var b strings.Builder
const wantError = `template: "foo" is an incomplete or empty template`
if err := t1.Execute(&b, "javascript:alert(1)"); err == nil {
t.Fatal("expected error executing t1")
} else if gotError := err.Error(); gotError != wantError {
t.Fatalf("got t1 execution error:\n\t%s\nwant:\n\t%s", gotError, wantError)
}
b.Reset()
if err := t2.Execute(&b, nil); err != nil {
t.Fatalf("error executing t2: %s", err)
}
const want = "bar"
if got := b.String(); got != want {
t.Fatalf("t2 rendered %q, want %q", got, want)
}
}
// Covers issue 21844.
func TestAliasedParseTreeDoesNotOverescape(t *testing.T) {
const (
tmplText = `{{.}}`
data = `<baz>`
want = `<baz>`
)
// Templates "foo" and "bar" both alias the same underlying parse tree.
tpl := Must(New("foo").Parse(tmplText))
if _, err := tpl.AddParseTree("bar", tpl.Tree); err != nil {
t.Fatalf("AddParseTree error: %v", err)
}
var b1, b2 strings.Builder
if err := tpl.ExecuteTemplate(&b1, "foo", data); err != nil {
t.Fatalf(`ExecuteTemplate failed for "foo": %v`, err)
}
if err := tpl.ExecuteTemplate(&b2, "bar", data); err != nil {
t.Fatalf(`ExecuteTemplate failed for "foo": %v`, err)
}
got1, got2 := b1.String(), b2.String()
if got1 != want {
t.Fatalf(`Template "foo" rendered %q, want %q`, got1, want)
}
if got1 != got2 {
t.Fatalf(`Template "foo" and "bar" rendered %q and %q respectively, expected equal values`, got1, got2)
}
}
| go/src/html/template/escape_test.go/0 | {
"file_path": "go/src/html/template/escape_test.go",
"repo_id": "go",
"token_count": 26702
} | 267 |
// Copyright 2011 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 draw
import (
"image"
"image/color"
"reflect"
"testing"
)
const (
dstw, dsth = 640, 480
srcw, srch = 400, 300
)
var palette = color.Palette{
color.Black,
color.White,
}
// bench benchmarks drawing src and mask images onto a dst image with the
// given op and the color models to create those images from.
// The created images' pixels are initialized to non-zero values.
func bench(b *testing.B, dcm, scm, mcm color.Model, op Op) {
b.StopTimer()
var dst Image
switch dcm {
case color.RGBAModel:
dst1 := image.NewRGBA(image.Rect(0, 0, dstw, dsth))
for y := 0; y < dsth; y++ {
for x := 0; x < dstw; x++ {
dst1.SetRGBA(x, y, color.RGBA{
uint8(5 * x % 0x100),
uint8(7 * y % 0x100),
uint8((7*x + 5*y) % 0x100),
0xff,
})
}
}
dst = dst1
case color.RGBA64Model:
dst1 := image.NewRGBA64(image.Rect(0, 0, dstw, dsth))
for y := 0; y < dsth; y++ {
for x := 0; x < dstw; x++ {
dst1.SetRGBA64(x, y, color.RGBA64{
uint16(53 * x % 0x10000),
uint16(59 * y % 0x10000),
uint16((59*x + 53*y) % 0x10000),
0xffff,
})
}
}
dst = dst1
default:
// The == operator isn't defined on a color.Palette (a slice), so we
// use reflection.
if reflect.DeepEqual(dcm, palette) {
dst1 := image.NewPaletted(image.Rect(0, 0, dstw, dsth), palette)
for y := 0; y < dsth; y++ {
for x := 0; x < dstw; x++ {
dst1.SetColorIndex(x, y, uint8(x^y)&1)
}
}
dst = dst1
} else {
b.Fatal("unknown destination color model", dcm)
}
}
var src image.Image
switch scm {
case nil:
src = &image.Uniform{C: color.RGBA{0x11, 0x22, 0x33, 0x44}}
case color.CMYKModel:
src1 := image.NewCMYK(image.Rect(0, 0, srcw, srch))
for y := 0; y < srch; y++ {
for x := 0; x < srcw; x++ {
src1.SetCMYK(x, y, color.CMYK{
uint8(13 * x % 0x100),
uint8(11 * y % 0x100),
uint8((11*x + 13*y) % 0x100),
uint8((31*x + 37*y) % 0x100),
})
}
}
src = src1
case color.GrayModel:
src1 := image.NewGray(image.Rect(0, 0, srcw, srch))
for y := 0; y < srch; y++ {
for x := 0; x < srcw; x++ {
src1.SetGray(x, y, color.Gray{
uint8((11*x + 13*y) % 0x100),
})
}
}
src = src1
case color.RGBAModel:
src1 := image.NewRGBA(image.Rect(0, 0, srcw, srch))
for y := 0; y < srch; y++ {
for x := 0; x < srcw; x++ {
src1.SetRGBA(x, y, color.RGBA{
uint8(13 * x % 0x80),
uint8(11 * y % 0x80),
uint8((11*x + 13*y) % 0x80),
0x7f,
})
}
}
src = src1
case color.RGBA64Model:
src1 := image.NewRGBA64(image.Rect(0, 0, srcw, srch))
for y := 0; y < srch; y++ {
for x := 0; x < srcw; x++ {
src1.SetRGBA64(x, y, color.RGBA64{
uint16(103 * x % 0x8000),
uint16(101 * y % 0x8000),
uint16((101*x + 103*y) % 0x8000),
0x7fff,
})
}
}
src = src1
case color.NRGBAModel:
src1 := image.NewNRGBA(image.Rect(0, 0, srcw, srch))
for y := 0; y < srch; y++ {
for x := 0; x < srcw; x++ {
src1.SetNRGBA(x, y, color.NRGBA{
uint8(13 * x % 0x100),
uint8(11 * y % 0x100),
uint8((11*x + 13*y) % 0x100),
0x7f,
})
}
}
src = src1
case color.YCbCrModel:
yy := make([]uint8, srcw*srch)
cb := make([]uint8, srcw*srch)
cr := make([]uint8, srcw*srch)
for i := range yy {
yy[i] = uint8(3 * i % 0x100)
cb[i] = uint8(5 * i % 0x100)
cr[i] = uint8(7 * i % 0x100)
}
src = &image.YCbCr{
Y: yy,
Cb: cb,
Cr: cr,
YStride: srcw,
CStride: srcw,
SubsampleRatio: image.YCbCrSubsampleRatio444,
Rect: image.Rect(0, 0, srcw, srch),
}
default:
b.Fatal("unknown source color model", scm)
}
var mask image.Image
switch mcm {
case nil:
// No-op.
case color.AlphaModel:
mask1 := image.NewAlpha(image.Rect(0, 0, srcw, srch))
for y := 0; y < srch; y++ {
for x := 0; x < srcw; x++ {
a := uint8((23*x + 29*y) % 0x100)
// Glyph masks are typically mostly zero,
// so we only set a quarter of mask1's pixels.
if a >= 0xc0 {
mask1.SetAlpha(x, y, color.Alpha{a})
}
}
}
mask = mask1
default:
b.Fatal("unknown mask color model", mcm)
}
b.StartTimer()
for i := 0; i < b.N; i++ {
// Scatter the destination rectangle to draw into.
x := 3 * i % (dstw - srcw)
y := 7 * i % (dsth - srch)
DrawMask(dst, dst.Bounds().Add(image.Pt(x, y)), src, image.Point{}, mask, image.Point{}, op)
}
}
// The BenchmarkFoo functions exercise a drawFoo fast-path function in draw.go.
func BenchmarkFillOver(b *testing.B) {
bench(b, color.RGBAModel, nil, nil, Over)
}
func BenchmarkFillSrc(b *testing.B) {
bench(b, color.RGBAModel, nil, nil, Src)
}
func BenchmarkCopyOver(b *testing.B) {
bench(b, color.RGBAModel, color.RGBAModel, nil, Over)
}
func BenchmarkCopySrc(b *testing.B) {
bench(b, color.RGBAModel, color.RGBAModel, nil, Src)
}
func BenchmarkNRGBAOver(b *testing.B) {
bench(b, color.RGBAModel, color.NRGBAModel, nil, Over)
}
func BenchmarkNRGBASrc(b *testing.B) {
bench(b, color.RGBAModel, color.NRGBAModel, nil, Src)
}
func BenchmarkYCbCr(b *testing.B) {
bench(b, color.RGBAModel, color.YCbCrModel, nil, Over)
}
func BenchmarkGray(b *testing.B) {
bench(b, color.RGBAModel, color.GrayModel, nil, Over)
}
func BenchmarkCMYK(b *testing.B) {
bench(b, color.RGBAModel, color.CMYKModel, nil, Over)
}
func BenchmarkGlyphOver(b *testing.B) {
bench(b, color.RGBAModel, nil, color.AlphaModel, Over)
}
func BenchmarkRGBAMaskOver(b *testing.B) {
bench(b, color.RGBAModel, color.RGBAModel, color.AlphaModel, Over)
}
func BenchmarkGrayMaskOver(b *testing.B) {
bench(b, color.RGBAModel, color.GrayModel, color.AlphaModel, Over)
}
func BenchmarkRGBA64ImageMaskOver(b *testing.B) {
bench(b, color.RGBAModel, color.RGBA64Model, color.AlphaModel, Over)
}
func BenchmarkRGBA(b *testing.B) {
bench(b, color.RGBAModel, color.RGBA64Model, nil, Src)
}
func BenchmarkPalettedFill(b *testing.B) {
bench(b, palette, nil, nil, Src)
}
func BenchmarkPalettedRGBA(b *testing.B) {
bench(b, palette, color.RGBAModel, nil, Src)
}
// The BenchmarkGenericFoo functions exercise the generic, slow-path code.
func BenchmarkGenericOver(b *testing.B) {
bench(b, color.RGBA64Model, color.RGBA64Model, nil, Over)
}
func BenchmarkGenericMaskOver(b *testing.B) {
bench(b, color.RGBA64Model, color.RGBA64Model, color.AlphaModel, Over)
}
func BenchmarkGenericSrc(b *testing.B) {
bench(b, color.RGBA64Model, color.RGBA64Model, nil, Src)
}
func BenchmarkGenericMaskSrc(b *testing.B) {
bench(b, color.RGBA64Model, color.RGBA64Model, color.AlphaModel, Src)
}
| go/src/image/draw/bench_test.go/0 | {
"file_path": "go/src/image/draw/bench_test.go",
"repo_id": "go",
"token_count": 3235
} | 268 |
// Copyright 2012 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 png
import (
"bytes"
"math/rand"
"testing"
)
func slowAbs(x int) int {
if x < 0 {
return -x
}
return x
}
// slowPaeth is a slow but simple implementation of the Paeth function.
// It is a straight port of the sample code in the PNG spec, section 9.4.
func slowPaeth(a, b, c uint8) uint8 {
p := int(a) + int(b) - int(c)
pa := slowAbs(p - int(a))
pb := slowAbs(p - int(b))
pc := slowAbs(p - int(c))
if pa <= pb && pa <= pc {
return a
} else if pb <= pc {
return b
}
return c
}
// slowFilterPaeth is a slow but simple implementation of func filterPaeth.
func slowFilterPaeth(cdat, pdat []byte, bytesPerPixel int) {
for i := 0; i < bytesPerPixel; i++ {
cdat[i] += paeth(0, pdat[i], 0)
}
for i := bytesPerPixel; i < len(cdat); i++ {
cdat[i] += paeth(cdat[i-bytesPerPixel], pdat[i], pdat[i-bytesPerPixel])
}
}
func TestPaeth(t *testing.T) {
for a := 0; a < 256; a += 15 {
for b := 0; b < 256; b += 15 {
for c := 0; c < 256; c += 15 {
got := paeth(uint8(a), uint8(b), uint8(c))
want := slowPaeth(uint8(a), uint8(b), uint8(c))
if got != want {
t.Errorf("a, b, c = %d, %d, %d: got %d, want %d", a, b, c, got, want)
}
}
}
}
}
func BenchmarkPaeth(b *testing.B) {
for i := 0; i < b.N; i++ {
paeth(uint8(i>>16), uint8(i>>8), uint8(i))
}
}
func TestPaethDecode(t *testing.T) {
pdat0 := make([]byte, 32)
pdat1 := make([]byte, 32)
pdat2 := make([]byte, 32)
cdat0 := make([]byte, 32)
cdat1 := make([]byte, 32)
cdat2 := make([]byte, 32)
r := rand.New(rand.NewSource(1))
for bytesPerPixel := 1; bytesPerPixel <= 8; bytesPerPixel++ {
for i := 0; i < 100; i++ {
for j := range pdat0 {
pdat0[j] = uint8(r.Uint32())
cdat0[j] = uint8(r.Uint32())
}
copy(pdat1, pdat0)
copy(pdat2, pdat0)
copy(cdat1, cdat0)
copy(cdat2, cdat0)
filterPaeth(cdat1, pdat1, bytesPerPixel)
slowFilterPaeth(cdat2, pdat2, bytesPerPixel)
if !bytes.Equal(cdat1, cdat2) {
t.Errorf("bytesPerPixel: %d\npdat0: % x\ncdat0: % x\ngot: % x\nwant: % x", bytesPerPixel, pdat0, cdat0, cdat1, cdat2)
break
}
}
}
}
| go/src/image/png/paeth_test.go/0 | {
"file_path": "go/src/image/png/paeth_test.go",
"repo_id": "go",
"token_count": 1049
} | 269 |
The *.png and README.original files in this directory are copied from
libpng.org, specifically contrib/pngsuite/* in libpng 1.6.26.
README.original gives the following license for those files:
Permission to use, copy, and distribute these images for any purpose
and without fee is hereby granted.
The files basn0g01-30.png, basn0g02-29.png and basn0g04-31.png are in fact not
part of pngsuite but were created from files in pngsuite. Their non-power-of-2
sizes makes them useful for testing bit-depths smaller than a byte.
basn3a08.png was generated from basn6a08.png using the pngnq tool, which
converted it to the 8-bit paletted image with alpha values in tRNS chunk.
The *.sng files in this directory were generated from the *.png files by the
sng command-line tool and some hand editing. The files basn0g0{1,2,4}.sng and
ftbbn0g0{1,2,4}.sng were actually generated by first converting the PNG to a
bitdepth of 8 and then running sng on them. basn4a08.sng was generated from a
16-bit rgba version of basn4a08.png rather than the original gray + alpha.
| go/src/image/png/testdata/pngsuite/README/0 | {
"file_path": "go/src/image/png/testdata/pngsuite/README",
"repo_id": "go",
"token_count": 330
} | 270 |
// Copyright 2012 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 image
import (
"image/color"
"testing"
)
func TestYCbCr(t *testing.T) {
rects := []Rectangle{
Rect(0, 0, 16, 16),
Rect(1, 0, 16, 16),
Rect(0, 1, 16, 16),
Rect(1, 1, 16, 16),
Rect(1, 1, 15, 16),
Rect(1, 1, 16, 15),
Rect(1, 1, 15, 15),
Rect(2, 3, 14, 15),
Rect(7, 0, 7, 16),
Rect(0, 8, 16, 8),
Rect(0, 0, 10, 11),
Rect(5, 6, 16, 16),
Rect(7, 7, 8, 8),
Rect(7, 8, 8, 9),
Rect(8, 7, 9, 8),
Rect(8, 8, 9, 9),
Rect(7, 7, 17, 17),
Rect(8, 8, 17, 17),
Rect(9, 9, 17, 17),
Rect(10, 10, 17, 17),
}
subsampleRatios := []YCbCrSubsampleRatio{
YCbCrSubsampleRatio444,
YCbCrSubsampleRatio422,
YCbCrSubsampleRatio420,
YCbCrSubsampleRatio440,
YCbCrSubsampleRatio411,
YCbCrSubsampleRatio410,
}
deltas := []Point{
Pt(0, 0),
Pt(1000, 1001),
Pt(5001, -400),
Pt(-701, -801),
}
for _, r := range rects {
for _, subsampleRatio := range subsampleRatios {
for _, delta := range deltas {
testYCbCr(t, r, subsampleRatio, delta)
}
}
if testing.Short() {
break
}
}
}
func testYCbCr(t *testing.T, r Rectangle, subsampleRatio YCbCrSubsampleRatio, delta Point) {
// Create a YCbCr image m, whose bounds are r translated by (delta.X, delta.Y).
r1 := r.Add(delta)
m := NewYCbCr(r1, subsampleRatio)
// Test that the image buffer is reasonably small even if (delta.X, delta.Y) is far from the origin.
if len(m.Y) > 100*100 {
t.Errorf("r=%v, subsampleRatio=%v, delta=%v: image buffer is too large",
r, subsampleRatio, delta)
return
}
// Initialize m's pixels. For 422 and 420 subsampling, some of the Cb and Cr elements
// will be set multiple times. That's OK. We just want to avoid a uniform image.
for y := r1.Min.Y; y < r1.Max.Y; y++ {
for x := r1.Min.X; x < r1.Max.X; x++ {
yi := m.YOffset(x, y)
ci := m.COffset(x, y)
m.Y[yi] = uint8(16*y + x)
m.Cb[ci] = uint8(y + 16*x)
m.Cr[ci] = uint8(y + 16*x)
}
}
// Make various sub-images of m.
for y0 := delta.Y + 3; y0 < delta.Y+7; y0++ {
for y1 := delta.Y + 8; y1 < delta.Y+13; y1++ {
for x0 := delta.X + 3; x0 < delta.X+7; x0++ {
for x1 := delta.X + 8; x1 < delta.X+13; x1++ {
subRect := Rect(x0, y0, x1, y1)
sub := m.SubImage(subRect).(*YCbCr)
// For each point in the sub-image's bounds, check that m.At(x, y) equals sub.At(x, y).
for y := sub.Rect.Min.Y; y < sub.Rect.Max.Y; y++ {
for x := sub.Rect.Min.X; x < sub.Rect.Max.X; x++ {
color0 := m.At(x, y).(color.YCbCr)
color1 := sub.At(x, y).(color.YCbCr)
if color0 != color1 {
t.Errorf("r=%v, subsampleRatio=%v, delta=%v, x=%d, y=%d, color0=%v, color1=%v",
r, subsampleRatio, delta, x, y, color0, color1)
return
}
}
}
}
}
}
}
}
func TestYCbCrSlicesDontOverlap(t *testing.T) {
m := NewYCbCr(Rect(0, 0, 8, 8), YCbCrSubsampleRatio420)
names := []string{"Y", "Cb", "Cr"}
slices := [][]byte{
m.Y[:cap(m.Y)],
m.Cb[:cap(m.Cb)],
m.Cr[:cap(m.Cr)],
}
for i, slice := range slices {
want := uint8(10 + i)
for j := range slice {
slice[j] = want
}
}
for i, slice := range slices {
want := uint8(10 + i)
for j, got := range slice {
if got != want {
t.Fatalf("m.%s[%d]: got %d, want %d", names[i], j, got, want)
}
}
}
}
| go/src/image/ycbcr_test.go/0 | {
"file_path": "go/src/image/ycbcr_test.go",
"repo_id": "go",
"token_count": 1704
} | 271 |
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package abi
// These functions are the build-time version of the Go type data structures.
// Their contents must be kept in sync with their definitions.
// Because the host and target type sizes can differ, the compiler and
// linker cannot use the host information that they might get from
// either unsafe.Sizeof and Alignof, nor runtime, reflect, or reflectlite.
// CommonSize returns sizeof(Type) for a compilation target with a given ptrSize
func CommonSize(ptrSize int) int { return 4*ptrSize + 8 + 8 }
// StructFieldSize returns sizeof(StructField) for a compilation target with a given ptrSize
func StructFieldSize(ptrSize int) int { return 3 * ptrSize }
// UncommonSize returns sizeof(UncommonType). This currently does not depend on ptrSize.
// This exported function is in an internal package, so it may change to depend on ptrSize in the future.
func UncommonSize() uint64 { return 4 + 2 + 2 + 4 + 4 }
// TFlagOff returns the offset of Type.TFlag for a compilation target with a given ptrSize
func TFlagOff(ptrSize int) int { return 2*ptrSize + 4 }
// ITabTypeOff returns the offset of ITab.Type for a compilation target with a given ptrSize
func ITabTypeOff(ptrSize int) int { return ptrSize }
| go/src/internal/abi/compiletype.go/0 | {
"file_path": "go/src/internal/abi/compiletype.go",
"repo_id": "go",
"token_count": 355
} | 272 |
// 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 386 || amd64 || s390x || arm || arm64 || loong64 || ppc64 || ppc64le || mips || mipsle || wasm || mips64 || mips64le || riscv64
package bytealg
import _ "unsafe" // For go:linkname
//go:noescape
func Compare(a, b []byte) int
func CompareString(a, b string) int {
return abigen_runtime_cmpstring(a, b)
}
// The declaration below generates ABI wrappers for functions
// implemented in assembly in this package but declared in another
// package.
//go:linkname abigen_runtime_cmpstring runtime.cmpstring
func abigen_runtime_cmpstring(a, b string) int
| go/src/internal/bytealg/compare_native.go/0 | {
"file_path": "go/src/internal/bytealg/compare_native.go",
"repo_id": "go",
"token_count": 227
} | 273 |
// 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.
#include "go_asm.h"
#include "textflag.h"
// memequal(a, b unsafe.Pointer, size uintptr) bool
TEXT runtime·memequal<ABIInternal>(SB),NOSPLIT|NOFRAME,$0-25
// short path to handle 0-byte case
CBZ R2, equal
// short path to handle equal pointers
CMP R0, R1
BEQ equal
B memeqbody<>(SB)
equal:
MOVD $1, R0
RET
// memequal_varlen(a, b unsafe.Pointer) bool
TEXT runtime·memequal_varlen<ABIInternal>(SB),NOSPLIT,$0-17
CMP R0, R1
BEQ eq
MOVD 8(R26), R2 // compiler stores size at offset 8 in the closure
CBZ R2, eq
B memeqbody<>(SB)
eq:
MOVD $1, R0
RET
// input:
// R0: pointer a
// R1: pointer b
// R2: data len
// at return: result in R0
TEXT memeqbody<>(SB),NOSPLIT,$0
CMP $1, R2
// handle 1-byte special case for better performance
BEQ one
CMP $16, R2
// handle specially if length < 16
BLO tail
BIC $0x3f, R2, R3
CBZ R3, chunk16
// work with 64-byte chunks
ADD R3, R0, R6 // end of chunks
chunk64_loop:
VLD1.P (R0), [V0.D2, V1.D2, V2.D2, V3.D2]
VLD1.P (R1), [V4.D2, V5.D2, V6.D2, V7.D2]
VCMEQ V0.D2, V4.D2, V8.D2
VCMEQ V1.D2, V5.D2, V9.D2
VCMEQ V2.D2, V6.D2, V10.D2
VCMEQ V3.D2, V7.D2, V11.D2
VAND V8.B16, V9.B16, V8.B16
VAND V8.B16, V10.B16, V8.B16
VAND V8.B16, V11.B16, V8.B16
CMP R0, R6
VMOV V8.D[0], R4
VMOV V8.D[1], R5
CBZ R4, not_equal
CBZ R5, not_equal
BNE chunk64_loop
AND $0x3f, R2, R2
CBZ R2, equal
chunk16:
// work with 16-byte chunks
BIC $0xf, R2, R3
CBZ R3, tail
ADD R3, R0, R6 // end of chunks
chunk16_loop:
LDP.P 16(R0), (R4, R5)
LDP.P 16(R1), (R7, R9)
EOR R4, R7
CBNZ R7, not_equal
EOR R5, R9
CBNZ R9, not_equal
CMP R0, R6
BNE chunk16_loop
AND $0xf, R2, R2
CBZ R2, equal
tail:
// special compare of tail with length < 16
TBZ $3, R2, lt_8
MOVD (R0), R4
MOVD (R1), R5
EOR R4, R5
CBNZ R5, not_equal
SUB $8, R2, R6 // offset of the last 8 bytes
MOVD (R0)(R6), R4
MOVD (R1)(R6), R5
EOR R4, R5
CBNZ R5, not_equal
B equal
lt_8:
TBZ $2, R2, lt_4
MOVWU (R0), R4
MOVWU (R1), R5
EOR R4, R5
CBNZ R5, not_equal
SUB $4, R2, R6 // offset of the last 4 bytes
MOVWU (R0)(R6), R4
MOVWU (R1)(R6), R5
EOR R4, R5
CBNZ R5, not_equal
B equal
lt_4:
TBZ $1, R2, lt_2
MOVHU.P 2(R0), R4
MOVHU.P 2(R1), R5
CMP R4, R5
BNE not_equal
lt_2:
TBZ $0, R2, equal
one:
MOVBU (R0), R4
MOVBU (R1), R5
CMP R4, R5
BNE not_equal
equal:
MOVD $1, R0
RET
not_equal:
MOVB ZR, R0
RET
| go/src/internal/bytealg/equal_arm64.s/0 | {
"file_path": "go/src/internal/bytealg/equal_arm64.s",
"repo_id": "go",
"token_count": 1445
} | 274 |
// 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.
#include "go_asm.h"
#include "textflag.h"
TEXT ·IndexByte(SB), NOSPLIT, $0-40
I64Load b_base+0(FP)
I32WrapI64
I32Load8U c+24(FP)
I64Load b_len+8(FP)
I32WrapI64
Call memchr<>(SB)
I64ExtendI32U
Set R0
Get SP
I64Const $-1
Get R0
I64Load b_base+0(FP)
I64Sub
Get R0
I64Eqz $0
Select
I64Store ret+32(FP)
RET
TEXT ·IndexByteString(SB), NOSPLIT, $0-32
Get SP
I64Load s_base+0(FP)
I32WrapI64
I32Load8U c+16(FP)
I64Load s_len+8(FP)
I32WrapI64
Call memchr<>(SB)
I64ExtendI32U
Set R0
I64Const $-1
Get R0
I64Load s_base+0(FP)
I64Sub
Get R0
I64Eqz $0
Select
I64Store ret+24(FP)
RET
// initially compiled with emscripten and then modified over time.
// params:
// R0: s
// R1: c
// R2: len
// ret: index
TEXT memchr<>(SB), NOSPLIT, $0
Get R1
Set R4
Block
Block
Get R2
I32Const $0
I32Ne
Tee R3
Get R0
I32Const $3
I32And
I32Const $0
I32Ne
I32And
If
Loop
Get R0
I32Load8U $0
Get R1
I32Eq
BrIf $2
Get R2
I32Const $-1
I32Add
Tee R2
I32Const $0
I32Ne
Tee R3
Get R0
I32Const $1
I32Add
Tee R0
I32Const $3
I32And
I32Const $0
I32Ne
I32And
BrIf $0
End
End
Get R3
BrIf $0
I32Const $0
Set R1
Br $1
End
Get R0
I32Load8U $0
Get R4
Tee R3
I32Eq
If
Get R2
Set R1
Else
Get R4
I32Const $16843009
I32Mul
Set R4
Block
Block
Get R2
I32Const $3
I32GtU
If
Get R2
Set R1
Loop
Get R0
I32Load $0
Get R4
I32Xor
Tee R2
I32Const $-2139062144
I32And
I32Const $-2139062144
I32Xor
Get R2
I32Const $-16843009
I32Add
I32And
I32Eqz
If
Get R0
I32Const $4
I32Add
Set R0
Get R1
I32Const $-4
I32Add
Tee R1
I32Const $3
I32GtU
BrIf $1
Br $3
End
End
Else
Get R2
Set R1
Br $1
End
Br $1
End
Get R1
I32Eqz
If
I32Const $0
Set R1
Br $3
End
End
Loop
Get R0
I32Load8U $0
Get R3
I32Eq
BrIf $2
Get R0
I32Const $1
I32Add
Set R0
Get R1
I32Const $-1
I32Add
Tee R1
BrIf $0
I32Const $0
Set R1
End
End
End
Get R0
I32Const $0
Get R1
Select
Return
| go/src/internal/bytealg/indexbyte_wasm.s/0 | {
"file_path": "go/src/internal/bytealg/indexbyte_wasm.s",
"repo_id": "go",
"token_count": 1663
} | 275 |
// Copyright 2022 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package cfile implements management of coverage files.
// It provides functionality exported in runtime/coverage as well as
// additional functionality used directly by package testing
// through testing/internal/testdeps.
package cfile
import (
"crypto/md5"
"fmt"
"internal/coverage"
"internal/coverage/encodecounter"
"internal/coverage/encodemeta"
"internal/coverage/rtcov"
"io"
"os"
"path/filepath"
"runtime"
"strconv"
"sync/atomic"
"time"
"unsafe"
)
// This file contains functions that support the writing of data files
// emitted at the end of code coverage testing runs, from instrumented
// executables.
// getCovCounterList returns a list of counter-data blobs registered
// for the currently executing instrumented program. It is defined in the
// runtime.
//
//go:linkname getCovCounterList
func getCovCounterList() []rtcov.CovCounterBlob
// emitState holds useful state information during the emit process.
//
// When an instrumented program finishes execution and starts the
// process of writing out coverage data, it's possible that an
// existing meta-data file already exists in the output directory. In
// this case openOutputFiles() below will leave the 'mf' field below
// as nil. If a new meta-data file is needed, field 'mfname' will be
// the final desired path of the meta file, 'mftmp' will be a
// temporary file, and 'mf' will be an open os.File pointer for
// 'mftmp'. The meta-data file payload will be written to 'mf', the
// temp file will be then closed and renamed (from 'mftmp' to
// 'mfname'), so as to insure that the meta-data file is created
// atomically; we want this so that things work smoothly in cases
// where there are several instances of a given instrumented program
// all terminating at the same time and trying to create meta-data
// files simultaneously.
//
// For counter data files there is less chance of a collision, hence
// the openOutputFiles() stores the counter data file in 'cfname' and
// then places the *io.File into 'cf'.
type emitState struct {
mfname string // path of final meta-data output file
mftmp string // path to meta-data temp file (if needed)
mf *os.File // open os.File for meta-data temp file
cfname string // path of final counter data file
cftmp string // path to counter data temp file
cf *os.File // open os.File for counter data file
outdir string // output directory
// List of meta-data symbols obtained from the runtime
metalist []rtcov.CovMetaBlob
// List of counter-data symbols obtained from the runtime
counterlist []rtcov.CovCounterBlob
// Table to use for remapping hard-coded pkg ids.
pkgmap map[int]int
// emit debug trace output
debug bool
}
var (
// finalHash is computed at init time from the list of meta-data
// symbols registered during init. It is used both for writing the
// meta-data file and counter-data files.
finalHash [16]byte
// Set to true when we've computed finalHash + finalMetaLen.
finalHashComputed bool
// Total meta-data length.
finalMetaLen uint64
// Records whether we've already attempted to write meta-data.
metaDataEmitAttempted bool
// Counter mode for this instrumented program run.
cmode coverage.CounterMode
// Counter granularity for this instrumented program run.
cgran coverage.CounterGranularity
// Cached value of GOCOVERDIR environment variable.
goCoverDir string
// Copy of os.Args made at init time, converted into map format.
capturedOsArgs map[string]string
// Flag used in tests to signal that coverage data already written.
covProfileAlreadyEmitted bool
)
// fileType is used to select between counter-data files and
// meta-data files.
type fileType int
const (
noFile = 1 << iota
metaDataFile
counterDataFile
)
// emitMetaData emits the meta-data output file for this coverage run.
// This entry point is intended to be invoked by the compiler from
// an instrumented program's main package init func.
func emitMetaData() {
if covProfileAlreadyEmitted {
return
}
ml, err := prepareForMetaEmit()
if err != nil {
fmt.Fprintf(os.Stderr, "error: coverage meta-data prep failed: %v\n", err)
if os.Getenv("GOCOVERDEBUG") != "" {
panic("meta-data write failure")
}
}
if len(ml) == 0 {
fmt.Fprintf(os.Stderr, "program not built with -cover\n")
return
}
goCoverDir = os.Getenv("GOCOVERDIR")
if goCoverDir == "" {
fmt.Fprintf(os.Stderr, "warning: GOCOVERDIR not set, no coverage data emitted\n")
return
}
if err := emitMetaDataToDirectory(goCoverDir, ml); err != nil {
fmt.Fprintf(os.Stderr, "error: coverage meta-data emit failed: %v\n", err)
if os.Getenv("GOCOVERDEBUG") != "" {
panic("meta-data write failure")
}
}
}
func modeClash(m coverage.CounterMode) bool {
if m == coverage.CtrModeRegOnly || m == coverage.CtrModeTestMain {
return false
}
if cmode == coverage.CtrModeInvalid {
cmode = m
return false
}
return cmode != m
}
func granClash(g coverage.CounterGranularity) bool {
if cgran == coverage.CtrGranularityInvalid {
cgran = g
return false
}
return cgran != g
}
// prepareForMetaEmit performs preparatory steps needed prior to
// emitting a meta-data file, notably computing a final hash of
// all meta-data blobs and capturing os args.
func prepareForMetaEmit() ([]rtcov.CovMetaBlob, error) {
// Ask the runtime for the list of coverage meta-data symbols.
ml := rtcov.Meta.List
// In the normal case (go build -o prog.exe ... ; ./prog.exe)
// len(ml) will always be non-zero, but we check here since at
// some point this function will be reachable via user-callable
// APIs (for example, to write out coverage data from a server
// program that doesn't ever call os.Exit).
if len(ml) == 0 {
return nil, nil
}
s := &emitState{
metalist: ml,
debug: os.Getenv("GOCOVERDEBUG") != "",
}
// Capture os.Args() now so as to avoid issues if args
// are rewritten during program execution.
capturedOsArgs = captureOsArgs()
if s.debug {
fmt.Fprintf(os.Stderr, "=+= GOCOVERDIR is %s\n", os.Getenv("GOCOVERDIR"))
fmt.Fprintf(os.Stderr, "=+= contents of covmetalist:\n")
for k, b := range ml {
fmt.Fprintf(os.Stderr, "=+= slot: %d path: %s ", k, b.PkgPath)
if b.PkgID != -1 {
fmt.Fprintf(os.Stderr, " hcid: %d", b.PkgID)
}
fmt.Fprintf(os.Stderr, "\n")
}
pm := rtcov.Meta.PkgMap
fmt.Fprintf(os.Stderr, "=+= remap table:\n")
for from, to := range pm {
fmt.Fprintf(os.Stderr, "=+= from %d to %d\n",
uint32(from), uint32(to))
}
}
h := md5.New()
tlen := uint64(unsafe.Sizeof(coverage.MetaFileHeader{}))
for _, entry := range ml {
if _, err := h.Write(entry.Hash[:]); err != nil {
return nil, err
}
tlen += uint64(entry.Len)
ecm := coverage.CounterMode(entry.CounterMode)
if modeClash(ecm) {
return nil, fmt.Errorf("coverage counter mode clash: package %s uses mode=%d, but package %s uses mode=%s\n", ml[0].PkgPath, cmode, entry.PkgPath, ecm)
}
ecg := coverage.CounterGranularity(entry.CounterGranularity)
if granClash(ecg) {
return nil, fmt.Errorf("coverage counter granularity clash: package %s uses gran=%d, but package %s uses gran=%s\n", ml[0].PkgPath, cgran, entry.PkgPath, ecg)
}
}
// Hash mode and granularity as well.
h.Write([]byte(cmode.String()))
h.Write([]byte(cgran.String()))
// Compute final digest.
fh := h.Sum(nil)
copy(finalHash[:], fh)
finalHashComputed = true
finalMetaLen = tlen
return ml, nil
}
// emitMetaDataToDirectory emits the meta-data output file to the specified
// directory, returning an error if something went wrong.
func emitMetaDataToDirectory(outdir string, ml []rtcov.CovMetaBlob) error {
ml, err := prepareForMetaEmit()
if err != nil {
return err
}
if len(ml) == 0 {
return nil
}
metaDataEmitAttempted = true
s := &emitState{
metalist: ml,
debug: os.Getenv("GOCOVERDEBUG") != "",
outdir: outdir,
}
// Open output files.
if err := s.openOutputFiles(finalHash, finalMetaLen, metaDataFile); err != nil {
return err
}
// Emit meta-data file only if needed (may already be present).
if s.needMetaDataFile() {
if err := s.emitMetaDataFile(finalHash, finalMetaLen); err != nil {
return err
}
}
return nil
}
// emitCounterData emits the counter data output file for this coverage run.
// This entry point is intended to be invoked by the runtime when an
// instrumented program is terminating or calling os.Exit().
func emitCounterData() {
if goCoverDir == "" || !finalHashComputed || covProfileAlreadyEmitted {
return
}
if err := emitCounterDataToDirectory(goCoverDir); err != nil {
fmt.Fprintf(os.Stderr, "error: coverage counter data emit failed: %v\n", err)
if os.Getenv("GOCOVERDEBUG") != "" {
panic("counter-data write failure")
}
}
}
// emitCounterDataToDirectory emits the counter-data output file for this coverage run.
func emitCounterDataToDirectory(outdir string) error {
// Ask the runtime for the list of coverage counter symbols.
cl := getCovCounterList()
if len(cl) == 0 {
// no work to do here.
return nil
}
if !finalHashComputed {
return fmt.Errorf("error: meta-data not available (binary not built with -cover?)")
}
// Ask the runtime for the list of coverage counter symbols.
pm := rtcov.Meta.PkgMap
s := &emitState{
counterlist: cl,
pkgmap: pm,
outdir: outdir,
debug: os.Getenv("GOCOVERDEBUG") != "",
}
// Open output file.
if err := s.openOutputFiles(finalHash, finalMetaLen, counterDataFile); err != nil {
return err
}
if s.cf == nil {
return fmt.Errorf("counter data output file open failed (no additional info")
}
// Emit counter data file.
if err := s.emitCounterDataFile(finalHash, s.cf); err != nil {
return err
}
if err := s.cf.Close(); err != nil {
return fmt.Errorf("closing counter data file: %v", err)
}
// Counter file has now been closed. Rename the temp to the
// final desired path.
if err := os.Rename(s.cftmp, s.cfname); err != nil {
return fmt.Errorf("writing %s: rename from %s failed: %v\n", s.cfname, s.cftmp, err)
}
return nil
}
// emitCounterDataToWriter emits counter data for this coverage run to an io.Writer.
func (s *emitState) emitCounterDataToWriter(w io.Writer) error {
if err := s.emitCounterDataFile(finalHash, w); err != nil {
return err
}
return nil
}
// openMetaFile determines whether we need to emit a meta-data output
// file, or whether we can reuse the existing file in the coverage out
// dir. It updates mfname/mftmp/mf fields in 's', returning an error
// if something went wrong. See the comment on the emitState type
// definition above for more on how file opening is managed.
func (s *emitState) openMetaFile(metaHash [16]byte, metaLen uint64) error {
// Open meta-outfile for reading to see if it exists.
fn := fmt.Sprintf("%s.%x", coverage.MetaFilePref, metaHash)
s.mfname = filepath.Join(s.outdir, fn)
fi, err := os.Stat(s.mfname)
if err != nil || fi.Size() != int64(metaLen) {
// We need a new meta-file.
tname := "tmp." + fn + strconv.FormatInt(time.Now().UnixNano(), 10)
s.mftmp = filepath.Join(s.outdir, tname)
s.mf, err = os.Create(s.mftmp)
if err != nil {
return fmt.Errorf("creating meta-data file %s: %v", s.mftmp, err)
}
}
return nil
}
// openCounterFile opens an output file for the counter data portion
// of a test coverage run. If updates the 'cfname' and 'cf' fields in
// 's', returning an error if something went wrong.
func (s *emitState) openCounterFile(metaHash [16]byte) error {
processID := os.Getpid()
fn := fmt.Sprintf(coverage.CounterFileTempl, coverage.CounterFilePref, metaHash, processID, time.Now().UnixNano())
s.cfname = filepath.Join(s.outdir, fn)
s.cftmp = filepath.Join(s.outdir, "tmp."+fn)
var err error
s.cf, err = os.Create(s.cftmp)
if err != nil {
return fmt.Errorf("creating counter data file %s: %v", s.cftmp, err)
}
return nil
}
// openOutputFiles opens output files in preparation for emitting
// coverage data. In the case of the meta-data file, openOutputFiles
// may determine that we can reuse an existing meta-data file in the
// outdir, in which case it will leave the 'mf' field in the state
// struct as nil. If a new meta-file is needed, the field 'mfname'
// will be the final desired path of the meta file, 'mftmp' will be a
// temporary file, and 'mf' will be an open os.File pointer for
// 'mftmp'. The idea is that the client/caller will write content into
// 'mf', close it, and then rename 'mftmp' to 'mfname'. This function
// also opens the counter data output file, setting 'cf' and 'cfname'
// in the state struct.
func (s *emitState) openOutputFiles(metaHash [16]byte, metaLen uint64, which fileType) error {
fi, err := os.Stat(s.outdir)
if err != nil {
return fmt.Errorf("output directory %q inaccessible (err: %v); no coverage data written", s.outdir, err)
}
if !fi.IsDir() {
return fmt.Errorf("output directory %q not a directory; no coverage data written", s.outdir)
}
if (which & metaDataFile) != 0 {
if err := s.openMetaFile(metaHash, metaLen); err != nil {
return err
}
}
if (which & counterDataFile) != 0 {
if err := s.openCounterFile(metaHash); err != nil {
return err
}
}
return nil
}
// emitMetaDataFile emits coverage meta-data to a previously opened
// temporary file (s.mftmp), then renames the generated file to the
// final path (s.mfname).
func (s *emitState) emitMetaDataFile(finalHash [16]byte, tlen uint64) error {
if err := writeMetaData(s.mf, s.metalist, cmode, cgran, finalHash); err != nil {
return fmt.Errorf("writing %s: %v\n", s.mftmp, err)
}
if err := s.mf.Close(); err != nil {
return fmt.Errorf("closing meta data temp file: %v", err)
}
// Temp file has now been flushed and closed. Rename the temp to the
// final desired path.
if err := os.Rename(s.mftmp, s.mfname); err != nil {
return fmt.Errorf("writing %s: rename from %s failed: %v\n", s.mfname, s.mftmp, err)
}
return nil
}
// needMetaDataFile returns TRUE if we need to emit a meta-data file
// for this program run. It should be used only after
// openOutputFiles() has been invoked.
func (s *emitState) needMetaDataFile() bool {
return s.mf != nil
}
func writeMetaData(w io.Writer, metalist []rtcov.CovMetaBlob, cmode coverage.CounterMode, gran coverage.CounterGranularity, finalHash [16]byte) error {
mfw := encodemeta.NewCoverageMetaFileWriter("<io.Writer>", w)
var blobs [][]byte
for _, e := range metalist {
sd := unsafe.Slice(e.P, int(e.Len))
blobs = append(blobs, sd)
}
return mfw.Write(finalHash, blobs, cmode, gran)
}
func (s *emitState) VisitFuncs(f encodecounter.CounterVisitorFn) error {
var tcounters []uint32
rdCounters := func(actrs []atomic.Uint32, ctrs []uint32) []uint32 {
ctrs = ctrs[:0]
for i := range actrs {
ctrs = append(ctrs, actrs[i].Load())
}
return ctrs
}
dpkg := uint32(0)
for _, c := range s.counterlist {
sd := unsafe.Slice((*atomic.Uint32)(unsafe.Pointer(c.Counters)), int(c.Len))
for i := 0; i < len(sd); i++ {
// Skip ahead until the next non-zero value.
sdi := sd[i].Load()
if sdi == 0 {
continue
}
// We found a function that was executed.
nCtrs := sd[i+coverage.NumCtrsOffset].Load()
pkgId := sd[i+coverage.PkgIdOffset].Load()
funcId := sd[i+coverage.FuncIdOffset].Load()
cst := i + coverage.FirstCtrOffset
counters := sd[cst : cst+int(nCtrs)]
// Check to make sure that we have at least one live
// counter. See the implementation note in ClearCoverageCounters
// for a description of why this is needed.
isLive := false
for i := 0; i < len(counters); i++ {
if counters[i].Load() != 0 {
isLive = true
break
}
}
if !isLive {
// Skip this function.
i += coverage.FirstCtrOffset + int(nCtrs) - 1
continue
}
if s.debug {
if pkgId != dpkg {
dpkg = pkgId
fmt.Fprintf(os.Stderr, "\n=+= %d: pk=%d visit live fcn",
i, pkgId)
}
fmt.Fprintf(os.Stderr, " {i=%d F%d NC%d}", i, funcId, nCtrs)
}
// Vet and/or fix up package ID. A package ID of zero
// indicates that there is some new package X that is a
// runtime dependency, and this package has code that
// executes before its corresponding init package runs.
// This is a fatal error that we should only see during
// Go development (e.g. tip).
ipk := int32(pkgId)
if ipk == 0 {
fmt.Fprintf(os.Stderr, "\n")
reportErrorInHardcodedList(int32(i), ipk, funcId, nCtrs)
} else if ipk < 0 {
if newId, ok := s.pkgmap[int(ipk)]; ok {
pkgId = uint32(newId)
} else {
fmt.Fprintf(os.Stderr, "\n")
reportErrorInHardcodedList(int32(i), ipk, funcId, nCtrs)
}
} else {
// The package ID value stored in the counter array
// has 1 added to it (so as to preclude the
// possibility of a zero value ; see
// runtime.addCovMeta), so subtract off 1 here to form
// the real package ID.
pkgId--
}
tcounters = rdCounters(counters, tcounters)
if err := f(pkgId, funcId, tcounters); err != nil {
return err
}
// Skip over this function.
i += coverage.FirstCtrOffset + int(nCtrs) - 1
}
if s.debug {
fmt.Fprintf(os.Stderr, "\n")
}
}
return nil
}
// captureOsArgs converts os.Args() into the format we use to store
// this info in the counter data file (counter data file "args"
// section is a generic key-value collection). See the 'args' section
// in internal/coverage/defs.go for more info. The args map
// is also used to capture GOOS + GOARCH values as well.
func captureOsArgs() map[string]string {
m := make(map[string]string)
m["argc"] = strconv.Itoa(len(os.Args))
for k, a := range os.Args {
m[fmt.Sprintf("argv%d", k)] = a
}
m["GOOS"] = runtime.GOOS
m["GOARCH"] = runtime.GOARCH
return m
}
// emitCounterDataFile emits the counter data portion of a
// coverage output file (to the file 's.cf').
func (s *emitState) emitCounterDataFile(finalHash [16]byte, w io.Writer) error {
cfw := encodecounter.NewCoverageDataWriter(w, coverage.CtrULeb128)
if err := cfw.Write(finalHash, capturedOsArgs, s); err != nil {
return err
}
return nil
}
// MarkProfileEmitted signals the coverage machinery that
// coverage data output files have already been written out, and there
// is no need to take any additional action at exit time. This
// function is called from the coverage-related boilerplate code in _testmain.go
// emitted for go unit tests.
func MarkProfileEmitted(val bool) {
covProfileAlreadyEmitted = val
}
func reportErrorInHardcodedList(slot, pkgID int32, fnID, nCtrs uint32) {
metaList := rtcov.Meta.List
pkgMap := rtcov.Meta.PkgMap
println("internal error in coverage meta-data tracking:")
println("encountered bad pkgID:", pkgID, " at slot:", slot,
" fnID:", fnID, " numCtrs:", nCtrs)
println("list of hard-coded runtime package IDs needs revising.")
println("[see the comment on the 'rtPkgs' var in ")
println(" <goroot>/src/internal/coverage/pkid.go]")
println("registered list:")
for k, b := range metaList {
print("slot: ", k, " path='", b.PkgPath, "' ")
if b.PkgID != -1 {
print(" hard-coded id: ", b.PkgID)
}
println("")
}
println("remap table:")
for from, to := range pkgMap {
println("from ", from, " to ", to)
}
}
| go/src/internal/coverage/cfile/emit.go/0 | {
"file_path": "go/src/internal/coverage/cfile/emit.go",
"repo_id": "go",
"token_count": 6890
} | 276 |
// Copyright 2021 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 decodemeta
// This package contains APIs and helpers for decoding a single package's
// meta data "blob" emitted by the compiler when coverage instrumentation
// is turned on.
import (
"encoding/binary"
"fmt"
"internal/coverage"
"internal/coverage/slicereader"
"internal/coverage/stringtab"
"io"
"os"
)
// See comments in the encodecovmeta package for details on the format.
type CoverageMetaDataDecoder struct {
r *slicereader.Reader
hdr coverage.MetaSymbolHeader
strtab *stringtab.Reader
tmp []byte
debug bool
}
func NewCoverageMetaDataDecoder(b []byte, readonly bool) (*CoverageMetaDataDecoder, error) {
slr := slicereader.NewReader(b, readonly)
x := &CoverageMetaDataDecoder{
r: slr,
tmp: make([]byte, 0, 256),
}
if err := x.readHeader(); err != nil {
return nil, err
}
if err := x.readStringTable(); err != nil {
return nil, err
}
return x, nil
}
func (d *CoverageMetaDataDecoder) readHeader() error {
if err := binary.Read(d.r, binary.LittleEndian, &d.hdr); err != nil {
return err
}
if d.debug {
fmt.Fprintf(os.Stderr, "=-= after readHeader: %+v\n", d.hdr)
}
return nil
}
func (d *CoverageMetaDataDecoder) readStringTable() error {
// Seek to the correct location to read the string table.
stringTableLocation := int64(coverage.CovMetaHeaderSize + 4*d.hdr.NumFuncs)
if _, err := d.r.Seek(stringTableLocation, io.SeekStart); err != nil {
return err
}
// Read the table itself.
d.strtab = stringtab.NewReader(d.r)
d.strtab.Read()
return nil
}
func (d *CoverageMetaDataDecoder) PackagePath() string {
return d.strtab.Get(d.hdr.PkgPath)
}
func (d *CoverageMetaDataDecoder) PackageName() string {
return d.strtab.Get(d.hdr.PkgName)
}
func (d *CoverageMetaDataDecoder) ModulePath() string {
return d.strtab.Get(d.hdr.ModulePath)
}
func (d *CoverageMetaDataDecoder) NumFuncs() uint32 {
return d.hdr.NumFuncs
}
// ReadFunc reads the coverage meta-data for the function with index
// 'findex', filling it into the FuncDesc pointed to by 'f'.
func (d *CoverageMetaDataDecoder) ReadFunc(fidx uint32, f *coverage.FuncDesc) error {
if fidx >= d.hdr.NumFuncs {
return fmt.Errorf("illegal function index")
}
// Seek to the correct location to read the function offset and read it.
funcOffsetLocation := int64(coverage.CovMetaHeaderSize + 4*fidx)
if _, err := d.r.Seek(funcOffsetLocation, io.SeekStart); err != nil {
return err
}
foff := d.r.ReadUint32()
// Check assumptions
if foff < uint32(funcOffsetLocation) || foff > d.hdr.Length {
return fmt.Errorf("malformed func offset %d", foff)
}
// Seek to the correct location to read the function.
floc := int64(foff)
if _, err := d.r.Seek(floc, io.SeekStart); err != nil {
return err
}
// Preamble containing number of units, file, and function.
numUnits := uint32(d.r.ReadULEB128())
fnameidx := uint32(d.r.ReadULEB128())
fileidx := uint32(d.r.ReadULEB128())
f.Srcfile = d.strtab.Get(fileidx)
f.Funcname = d.strtab.Get(fnameidx)
// Now the units
f.Units = f.Units[:0]
if cap(f.Units) < int(numUnits) {
f.Units = make([]coverage.CoverableUnit, 0, numUnits)
}
for k := uint32(0); k < numUnits; k++ {
f.Units = append(f.Units,
coverage.CoverableUnit{
StLine: uint32(d.r.ReadULEB128()),
StCol: uint32(d.r.ReadULEB128()),
EnLine: uint32(d.r.ReadULEB128()),
EnCol: uint32(d.r.ReadULEB128()),
NxStmts: uint32(d.r.ReadULEB128()),
})
}
lit := d.r.ReadULEB128()
f.Lit = lit != 0
return nil
}
| go/src/internal/coverage/decodemeta/decode.go/0 | {
"file_path": "go/src/internal/coverage/decodemeta/decode.go",
"repo_id": "go",
"token_count": 1429
} | 277 |
// Copyright 2021 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 test
import (
"fmt"
"internal/coverage"
"internal/coverage/decodemeta"
"internal/coverage/encodemeta"
"internal/coverage/slicewriter"
"io"
"os"
"path/filepath"
"testing"
)
func cmpFuncDesc(want, got coverage.FuncDesc) string {
swant := fmt.Sprintf("%+v", want)
sgot := fmt.Sprintf("%+v", got)
if swant == sgot {
return ""
}
return fmt.Sprintf("wanted %q got %q", swant, sgot)
}
func TestMetaDataEmptyPackage(t *testing.T) {
// Make sure that encoding/decoding works properly with packages
// that don't actually have any functions.
p := "empty/package"
pn := "package"
mp := "m"
b, err := encodemeta.NewCoverageMetaDataBuilder(p, pn, mp)
if err != nil {
t.Fatalf("making builder: %v", err)
}
drws := &slicewriter.WriteSeeker{}
b.Emit(drws)
drws.Seek(0, io.SeekStart)
dec, err := decodemeta.NewCoverageMetaDataDecoder(drws.BytesWritten(), false)
if err != nil {
t.Fatalf("making decoder: %v", err)
}
nf := dec.NumFuncs()
if nf != 0 {
t.Errorf("dec.NumFuncs(): got %d want %d", nf, 0)
}
pp := dec.PackagePath()
if pp != p {
t.Errorf("dec.PackagePath(): got %s want %s", pp, p)
}
ppn := dec.PackageName()
if ppn != pn {
t.Errorf("dec.PackageName(): got %s want %s", ppn, pn)
}
pmp := dec.ModulePath()
if pmp != mp {
t.Errorf("dec.ModulePath(): got %s want %s", pmp, mp)
}
}
func TestMetaDataEncoderDecoder(t *testing.T) {
// Test encode path.
pp := "foo/bar/pkg"
pn := "pkg"
mp := "barmod"
b, err := encodemeta.NewCoverageMetaDataBuilder(pp, pn, mp)
if err != nil {
t.Fatalf("making builder: %v", err)
}
f1 := coverage.FuncDesc{
Funcname: "func",
Srcfile: "foo.go",
Units: []coverage.CoverableUnit{
coverage.CoverableUnit{StLine: 1, StCol: 2, EnLine: 3, EnCol: 4, NxStmts: 5},
coverage.CoverableUnit{StLine: 6, StCol: 7, EnLine: 8, EnCol: 9, NxStmts: 10},
},
}
idx := b.AddFunc(f1)
if idx != 0 {
t.Errorf("b.AddFunc(f1) got %d want %d", idx, 0)
}
f2 := coverage.FuncDesc{
Funcname: "xfunc",
Srcfile: "bar.go",
Units: []coverage.CoverableUnit{
coverage.CoverableUnit{StLine: 1, StCol: 2, EnLine: 3, EnCol: 4, NxStmts: 5},
coverage.CoverableUnit{StLine: 6, StCol: 7, EnLine: 8, EnCol: 9, NxStmts: 10},
coverage.CoverableUnit{StLine: 11, StCol: 12, EnLine: 13, EnCol: 14, NxStmts: 15},
},
}
idx = b.AddFunc(f2)
if idx != 1 {
t.Errorf("b.AddFunc(f2) got %d want %d", idx, 0)
}
// Emit into a writer.
drws := &slicewriter.WriteSeeker{}
b.Emit(drws)
// Test decode path.
drws.Seek(0, io.SeekStart)
dec, err := decodemeta.NewCoverageMetaDataDecoder(drws.BytesWritten(), false)
if err != nil {
t.Fatalf("NewCoverageMetaDataDecoder error: %v", err)
}
nf := dec.NumFuncs()
if nf != 2 {
t.Errorf("dec.NumFuncs(): got %d want %d", nf, 2)
}
gotpp := dec.PackagePath()
if gotpp != pp {
t.Errorf("packagepath: got %s want %s", gotpp, pp)
}
gotpn := dec.PackageName()
if gotpn != pn {
t.Errorf("packagename: got %s want %s", gotpn, pn)
}
cases := []coverage.FuncDesc{f1, f2}
for i := uint32(0); i < uint32(len(cases)); i++ {
var fn coverage.FuncDesc
if err := dec.ReadFunc(i, &fn); err != nil {
t.Fatalf("err reading function %d: %v", i, err)
}
res := cmpFuncDesc(cases[i], fn)
if res != "" {
t.Errorf("ReadFunc(%d): %s", i, res)
}
}
}
func createFuncs(i int) []coverage.FuncDesc {
res := []coverage.FuncDesc{}
lc := uint32(1)
for fi := 0; fi < i+1; fi++ {
units := []coverage.CoverableUnit{}
for ui := 0; ui < (fi+1)*(i+1); ui++ {
units = append(units,
coverage.CoverableUnit{StLine: lc, StCol: lc + 1,
EnLine: lc + 2, EnCol: lc + 3, NxStmts: lc + 4,
})
lc += 5
}
f := coverage.FuncDesc{
Funcname: fmt.Sprintf("func_%d_%d", i, fi),
Srcfile: fmt.Sprintf("foo_%d.go", i),
Units: units,
}
res = append(res, f)
}
return res
}
func createBlob(t *testing.T, i int) []byte {
nomodule := ""
b, err := encodemeta.NewCoverageMetaDataBuilder("foo/pkg", "pkg", nomodule)
if err != nil {
t.Fatalf("making builder: %v", err)
}
funcs := createFuncs(i)
for _, f := range funcs {
b.AddFunc(f)
}
drws := &slicewriter.WriteSeeker{}
b.Emit(drws)
return drws.BytesWritten()
}
func createMetaDataBlobs(t *testing.T, nb int) [][]byte {
res := [][]byte{}
for i := 0; i < nb; i++ {
res = append(res, createBlob(t, i))
}
return res
}
func TestMetaDataWriterReader(t *testing.T) {
d := t.TempDir()
// Emit a meta-file...
mfpath := filepath.Join(d, "covmeta.hash.0")
of, err := os.OpenFile(mfpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
if err != nil {
t.Fatalf("opening covmeta: %v", err)
}
//t.Logf("meta-file path is %s", mfpath)
blobs := createMetaDataBlobs(t, 7)
gran := coverage.CtrGranularityPerBlock
mfw := encodemeta.NewCoverageMetaFileWriter(mfpath, of)
finalHash := [16]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
err = mfw.Write(finalHash, blobs, coverage.CtrModeAtomic, gran)
if err != nil {
t.Fatalf("writing meta-file: %v", err)
}
if err = of.Close(); err != nil {
t.Fatalf("closing meta-file: %v", err)
}
// ... then read it back in, first time without setting fileView,
// second time setting it.
for k := 0; k < 2; k++ {
var fileView []byte
inf, err := os.Open(mfpath)
if err != nil {
t.Fatalf("open() on meta-file: %v", err)
}
if k != 0 {
// Use fileview to exercise different paths in reader.
fi, err := os.Stat(mfpath)
if err != nil {
t.Fatalf("stat() on meta-file: %v", err)
}
fileView = make([]byte, fi.Size())
if _, err := inf.Read(fileView); err != nil {
t.Fatalf("read() on meta-file: %v", err)
}
if _, err := inf.Seek(int64(0), io.SeekStart); err != nil {
t.Fatalf("seek() on meta-file: %v", err)
}
}
mfr, err := decodemeta.NewCoverageMetaFileReader(inf, fileView)
if err != nil {
t.Fatalf("k=%d NewCoverageMetaFileReader failed with: %v", k, err)
}
np := mfr.NumPackages()
if np != 7 {
t.Fatalf("k=%d wanted 7 packages got %d", k, np)
}
md := mfr.CounterMode()
wmd := coverage.CtrModeAtomic
if md != wmd {
t.Fatalf("k=%d wanted mode %d got %d", k, wmd, md)
}
gran := mfr.CounterGranularity()
wgran := coverage.CtrGranularityPerBlock
if gran != wgran {
t.Fatalf("k=%d wanted gran %d got %d", k, wgran, gran)
}
payload := []byte{}
for pi := 0; pi < int(np); pi++ {
var pd *decodemeta.CoverageMetaDataDecoder
var err error
pd, payload, err = mfr.GetPackageDecoder(uint32(pi), payload)
if err != nil {
t.Fatalf("GetPackageDecoder(%d) failed with: %v", pi, err)
}
efuncs := createFuncs(pi)
nf := pd.NumFuncs()
if len(efuncs) != int(nf) {
t.Fatalf("decoding pk %d wanted %d funcs got %d",
pi, len(efuncs), nf)
}
var f coverage.FuncDesc
for fi := 0; fi < int(nf); fi++ {
if err := pd.ReadFunc(uint32(fi), &f); err != nil {
t.Fatalf("ReadFunc(%d) pk %d got error %v",
fi, pi, err)
}
res := cmpFuncDesc(efuncs[fi], f)
if res != "" {
t.Errorf("ReadFunc(%d) pk %d: %s", fi, pi, res)
}
}
}
inf.Close()
}
}
func TestMetaDataDecodeLitFlagIssue57942(t *testing.T) {
// Encode a package with a few functions. The funcs alternate
// between regular functions and function literals.
pp := "foo/bar/pkg"
pn := "pkg"
mp := "barmod"
b, err := encodemeta.NewCoverageMetaDataBuilder(pp, pn, mp)
if err != nil {
t.Fatalf("making builder: %v", err)
}
const NF = 6
const NCU = 1
ln := uint32(10)
wantfds := []coverage.FuncDesc{}
for fi := uint32(0); fi < NF; fi++ {
fis := fmt.Sprintf("%d", fi)
fd := coverage.FuncDesc{
Funcname: "func" + fis,
Srcfile: "foo" + fis + ".go",
Units: []coverage.CoverableUnit{
coverage.CoverableUnit{StLine: ln + 1, StCol: 2, EnLine: ln + 3, EnCol: 4, NxStmts: fi + 2},
},
Lit: (fi % 2) == 0,
}
wantfds = append(wantfds, fd)
b.AddFunc(fd)
}
// Emit into a writer.
drws := &slicewriter.WriteSeeker{}
b.Emit(drws)
// Decode the result.
drws.Seek(0, io.SeekStart)
dec, err := decodemeta.NewCoverageMetaDataDecoder(drws.BytesWritten(), false)
if err != nil {
t.Fatalf("making decoder: %v", err)
}
nf := dec.NumFuncs()
if nf != NF {
t.Fatalf("decoder number of functions: got %d want %d", nf, NF)
}
var fn coverage.FuncDesc
for i := uint32(0); i < uint32(NF); i++ {
if err := dec.ReadFunc(i, &fn); err != nil {
t.Fatalf("err reading function %d: %v", i, err)
}
res := cmpFuncDesc(wantfds[i], fn)
if res != "" {
t.Errorf("ReadFunc(%d): %s", i, res)
}
}
}
| go/src/internal/coverage/test/roundtrip_test.go/0 | {
"file_path": "go/src/internal/coverage/test/roundtrip_test.go",
"repo_id": "go",
"token_count": 3978
} | 278 |
// Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build mips64 || mips64le
package cpu
const CacheLinePadSize = 32
// This is initialized by archauxv and should not be changed after it is
// initialized.
var HWCap uint
// HWCAP bits. These are exposed by the Linux kernel 5.4.
const (
// CPU features
hwcap_MIPS_MSA = 1 << 1
)
func doinit() {
options = []option{
{Name: "msa", Feature: &MIPS64X.HasMSA},
}
// HWCAP feature bits
MIPS64X.HasMSA = isSet(HWCap, hwcap_MIPS_MSA)
}
func isSet(hwc uint, value uint) bool {
return hwc&value != 0
}
| go/src/internal/cpu/cpu_mips64x.go/0 | {
"file_path": "go/src/internal/cpu/cpu_mips64x.go",
"repo_id": "go",
"token_count": 241
} | 279 |
// Copyright 2021 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 fuzz
import (
"math"
"strconv"
"testing"
"unicode"
)
func TestUnmarshalMarshal(t *testing.T) {
var tests = []struct {
desc string
in string
reject bool
want string // if different from in
}{
{
desc: "missing version",
in: "int(1234)",
reject: true,
},
{
desc: "malformed string",
in: `go test fuzz v1
string("a"bcad")`,
reject: true,
},
{
desc: "empty value",
in: `go test fuzz v1
int()`,
reject: true,
},
{
desc: "negative uint",
in: `go test fuzz v1
uint(-32)`,
reject: true,
},
{
desc: "int8 too large",
in: `go test fuzz v1
int8(1234456)`,
reject: true,
},
{
desc: "multiplication in int value",
in: `go test fuzz v1
int(20*5)`,
reject: true,
},
{
desc: "double negation",
in: `go test fuzz v1
int(--5)`,
reject: true,
},
{
desc: "malformed bool",
in: `go test fuzz v1
bool(0)`,
reject: true,
},
{
desc: "malformed byte",
in: `go test fuzz v1
byte('aa)`,
reject: true,
},
{
desc: "byte out of range",
in: `go test fuzz v1
byte('☃')`,
reject: true,
},
{
desc: "extra newline",
in: `go test fuzz v1
string("has extra newline")
`,
want: `go test fuzz v1
string("has extra newline")`,
},
{
desc: "trailing spaces",
in: `go test fuzz v1
string("extra")
[]byte("spacing")
`,
want: `go test fuzz v1
string("extra")
[]byte("spacing")`,
},
{
desc: "float types",
in: `go test fuzz v1
float64(0)
float32(0)`,
},
{
desc: "various types",
in: `go test fuzz v1
int(-23)
int8(-2)
int64(2342425)
uint(1)
uint16(234)
uint32(352342)
uint64(123)
rune('œ')
byte('K')
byte('ÿ')
[]byte("hello¿")
[]byte("a")
bool(true)
string("hello\\xbd\\xb2=\\xbc ⌘")
float64(-12.5)
float32(2.5)`,
},
{
desc: "float edge cases",
// The two IEEE 754 bit patterns used for the math.Float{64,32}frombits
// encodings are non-math.NAN quiet-NaN values. Since they are not equal
// to math.NaN(), they should be re-encoded to their bit patterns. They
// are, respectively:
// * math.Float64bits(math.NaN())+1
// * math.Float32bits(float32(math.NaN()))+1
in: `go test fuzz v1
float32(-0)
float64(-0)
float32(+Inf)
float32(-Inf)
float32(NaN)
float64(+Inf)
float64(-Inf)
float64(NaN)
math.Float64frombits(0x7ff8000000000002)
math.Float32frombits(0x7fc00001)`,
},
{
desc: "int variations",
// Although we arbitrarily choose default integer bases (0 or 16), we may
// want to change those arbitrary choices in the future and should not
// break the parser. Verify that integers in the opposite bases still
// parse correctly.
in: `go test fuzz v1
int(0x0)
int32(0x41)
int64(0xfffffffff)
uint32(0xcafef00d)
uint64(0xffffffffffffffff)
uint8(0b0000000)
byte(0x0)
byte('\000')
byte('\u0000')
byte('\'')
math.Float64frombits(9221120237041090562)
math.Float32frombits(2143289345)`,
want: `go test fuzz v1
int(0)
rune('A')
int64(68719476735)
uint32(3405705229)
uint64(18446744073709551615)
byte('\x00')
byte('\x00')
byte('\x00')
byte('\x00')
byte('\'')
math.Float64frombits(0x7ff8000000000002)
math.Float32frombits(0x7fc00001)`,
},
{
desc: "rune validation",
in: `go test fuzz v1
rune(0)
rune(0x41)
rune(-1)
rune(0xfffd)
rune(0xd800)
rune(0x10ffff)
rune(0x110000)
`,
want: `go test fuzz v1
rune('\x00')
rune('A')
int32(-1)
rune('�')
int32(55296)
rune('\U0010ffff')
int32(1114112)`,
},
{
desc: "int overflow",
in: `go test fuzz v1
int(0x7fffffffffffffff)
uint(0xffffffffffffffff)`,
want: func() string {
switch strconv.IntSize {
case 32:
return `go test fuzz v1
int(-1)
uint(4294967295)`
case 64:
return `go test fuzz v1
int(9223372036854775807)
uint(18446744073709551615)`
default:
panic("unreachable")
}
}(),
},
{
desc: "windows new line",
in: "go test fuzz v1\r\nint(0)\r\n",
want: "go test fuzz v1\nint(0)",
},
}
for _, test := range tests {
t.Run(test.desc, func(t *testing.T) {
vals, err := unmarshalCorpusFile([]byte(test.in))
if test.reject {
if err == nil {
t.Fatalf("unmarshal unexpected success")
}
return
}
if err != nil {
t.Fatalf("unmarshal unexpected error: %v", err)
}
newB := marshalCorpusFile(vals...)
if newB[len(newB)-1] != '\n' {
t.Error("didn't write final newline to corpus file")
}
want := test.want
if want == "" {
want = test.in
}
want += "\n"
got := string(newB)
if got != want {
t.Errorf("unexpected marshaled value\ngot:\n%s\nwant:\n%s", got, want)
}
})
}
}
// BenchmarkMarshalCorpusFile measures the time it takes to serialize byte
// slices of various sizes to a corpus file. The slice contains a repeating
// sequence of bytes 0-255 to mix escaped and non-escaped characters.
func BenchmarkMarshalCorpusFile(b *testing.B) {
buf := make([]byte, 1024*1024)
for i := 0; i < len(buf); i++ {
buf[i] = byte(i)
}
for sz := 1; sz <= len(buf); sz <<= 1 {
sz := sz
b.Run(strconv.Itoa(sz), func(b *testing.B) {
for i := 0; i < b.N; i++ {
b.SetBytes(int64(sz))
marshalCorpusFile(buf[:sz])
}
})
}
}
// BenchmarkUnmarshalCorpusfile measures the time it takes to deserialize
// files encoding byte slices of various sizes. The slice contains a repeating
// sequence of bytes 0-255 to mix escaped and non-escaped characters.
func BenchmarkUnmarshalCorpusFile(b *testing.B) {
buf := make([]byte, 1024*1024)
for i := 0; i < len(buf); i++ {
buf[i] = byte(i)
}
for sz := 1; sz <= len(buf); sz <<= 1 {
sz := sz
data := marshalCorpusFile(buf[:sz])
b.Run(strconv.Itoa(sz), func(b *testing.B) {
for i := 0; i < b.N; i++ {
b.SetBytes(int64(sz))
unmarshalCorpusFile(data)
}
})
}
}
func TestByteRoundTrip(t *testing.T) {
for x := 0; x < 256; x++ {
b1 := byte(x)
buf := marshalCorpusFile(b1)
vs, err := unmarshalCorpusFile(buf)
if err != nil {
t.Fatal(err)
}
b2 := vs[0].(byte)
if b2 != b1 {
t.Fatalf("unmarshaled %v, want %v:\n%s", b2, b1, buf)
}
}
}
func TestInt8RoundTrip(t *testing.T) {
for x := -128; x < 128; x++ {
i1 := int8(x)
buf := marshalCorpusFile(i1)
vs, err := unmarshalCorpusFile(buf)
if err != nil {
t.Fatal(err)
}
i2 := vs[0].(int8)
if i2 != i1 {
t.Fatalf("unmarshaled %v, want %v:\n%s", i2, i1, buf)
}
}
}
func FuzzFloat64RoundTrip(f *testing.F) {
f.Add(math.Float64bits(0))
f.Add(math.Float64bits(math.Copysign(0, -1)))
f.Add(math.Float64bits(math.MaxFloat64))
f.Add(math.Float64bits(math.SmallestNonzeroFloat64))
f.Add(math.Float64bits(math.NaN()))
f.Add(uint64(0x7FF0000000000001)) // signaling NaN
f.Add(math.Float64bits(math.Inf(1)))
f.Add(math.Float64bits(math.Inf(-1)))
f.Fuzz(func(t *testing.T, u1 uint64) {
x1 := math.Float64frombits(u1)
b := marshalCorpusFile(x1)
t.Logf("marshaled math.Float64frombits(0x%x):\n%s", u1, b)
xs, err := unmarshalCorpusFile(b)
if err != nil {
t.Fatal(err)
}
if len(xs) != 1 {
t.Fatalf("unmarshaled %d values", len(xs))
}
x2 := xs[0].(float64)
u2 := math.Float64bits(x2)
if u2 != u1 {
t.Errorf("unmarshaled %v (bits 0x%x)", x2, u2)
}
})
}
func FuzzRuneRoundTrip(f *testing.F) {
f.Add(rune(-1))
f.Add(rune(0xd800))
f.Add(rune(0xdfff))
f.Add(rune(unicode.ReplacementChar))
f.Add(rune(unicode.MaxASCII))
f.Add(rune(unicode.MaxLatin1))
f.Add(rune(unicode.MaxRune))
f.Add(rune(unicode.MaxRune + 1))
f.Add(rune(-0x80000000))
f.Add(rune(0x7fffffff))
f.Fuzz(func(t *testing.T, r1 rune) {
b := marshalCorpusFile(r1)
t.Logf("marshaled rune(0x%x):\n%s", r1, b)
rs, err := unmarshalCorpusFile(b)
if err != nil {
t.Fatal(err)
}
if len(rs) != 1 {
t.Fatalf("unmarshaled %d values", len(rs))
}
r2 := rs[0].(rune)
if r2 != r1 {
t.Errorf("unmarshaled rune(0x%x)", r2)
}
})
}
func FuzzStringRoundTrip(f *testing.F) {
f.Add("")
f.Add("\x00")
f.Add(string([]rune{unicode.ReplacementChar}))
f.Fuzz(func(t *testing.T, s1 string) {
b := marshalCorpusFile(s1)
t.Logf("marshaled %q:\n%s", s1, b)
rs, err := unmarshalCorpusFile(b)
if err != nil {
t.Fatal(err)
}
if len(rs) != 1 {
t.Fatalf("unmarshaled %d values", len(rs))
}
s2 := rs[0].(string)
if s2 != s1 {
t.Errorf("unmarshaled %q", s2)
}
})
}
| go/src/internal/fuzz/encoding_test.go/0 | {
"file_path": "go/src/internal/fuzz/encoding_test.go",
"repo_id": "go",
"token_count": 4025
} | 280 |
// Copyright 2020 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 fuzz
import (
"bytes"
"context"
"crypto/sha256"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"os/exec"
"reflect"
"runtime"
"sync"
"time"
)
const (
// workerFuzzDuration is the amount of time a worker can spend testing random
// variations of an input given by the coordinator.
workerFuzzDuration = 100 * time.Millisecond
// workerTimeoutDuration is the amount of time a worker can go without
// responding to the coordinator before being stopped.
workerTimeoutDuration = 1 * time.Second
// workerExitCode is used as an exit code by fuzz worker processes after an internal error.
// This distinguishes internal errors from uncontrolled panics and other crashes.
// Keep in sync with internal/fuzz.workerExitCode.
workerExitCode = 70
// workerSharedMemSize is the maximum size of the shared memory file used to
// communicate with workers. This limits the size of fuzz inputs.
workerSharedMemSize = 100 << 20 // 100 MB
)
// worker manages a worker process running a test binary. The worker object
// exists only in the coordinator (the process started by 'go test -fuzz').
// workerClient is used by the coordinator to send RPCs to the worker process,
// which handles them with workerServer.
type worker struct {
dir string // working directory, same as package directory
binPath string // path to test executable
args []string // arguments for test executable
env []string // environment for test executable
coordinator *coordinator
memMu chan *sharedMem // mutex guarding shared memory with worker; persists across processes.
cmd *exec.Cmd // current worker process
client *workerClient // used to communicate with worker process
waitErr error // last error returned by wait, set before termC is closed.
interrupted bool // true after stop interrupts a running worker.
termC chan struct{} // closed by wait when worker process terminates
}
func newWorker(c *coordinator, dir, binPath string, args, env []string) (*worker, error) {
mem, err := sharedMemTempFile(workerSharedMemSize)
if err != nil {
return nil, err
}
memMu := make(chan *sharedMem, 1)
memMu <- mem
return &worker{
dir: dir,
binPath: binPath,
args: args,
env: env[:len(env):len(env)], // copy on append to ensure workers don't overwrite each other.
coordinator: c,
memMu: memMu,
}, nil
}
// cleanup releases persistent resources associated with the worker.
func (w *worker) cleanup() error {
mem := <-w.memMu
if mem == nil {
return nil
}
close(w.memMu)
return mem.Close()
}
// coordinate runs the test binary to perform fuzzing.
//
// coordinate loops until ctx is canceled or a fatal error is encountered.
// If a test process terminates unexpectedly while fuzzing, coordinate will
// attempt to restart and continue unless the termination can be attributed
// to an interruption (from a timer or the user).
//
// While looping, coordinate receives inputs from the coordinator, passes
// those inputs to the worker process, then passes the results back to
// the coordinator.
func (w *worker) coordinate(ctx context.Context) error {
// Main event loop.
for {
// Start or restart the worker if it's not running.
if !w.isRunning() {
if err := w.startAndPing(ctx); err != nil {
return err
}
}
select {
case <-ctx.Done():
// Worker was told to stop.
err := w.stop()
if err != nil && !w.interrupted && !isInterruptError(err) {
return err
}
return ctx.Err()
case <-w.termC:
// Worker process terminated unexpectedly while waiting for input.
err := w.stop()
if w.interrupted {
panic("worker interrupted after unexpected termination")
}
if err == nil || isInterruptError(err) {
// Worker stopped, either by exiting with status 0 or after being
// interrupted with a signal that was not sent by the coordinator.
//
// When the user presses ^C, on POSIX platforms, SIGINT is delivered to
// all processes in the group concurrently, and the worker may see it
// before the coordinator. The worker should exit 0 gracefully (in
// theory).
//
// This condition is probably intended by the user, so suppress
// the error.
return nil
}
if exitErr, ok := err.(*exec.ExitError); ok && exitErr.ExitCode() == workerExitCode {
// Worker exited with a code indicating F.Fuzz was not called correctly,
// for example, F.Fail was called first.
return fmt.Errorf("fuzzing process exited unexpectedly due to an internal failure: %w", err)
}
// Worker exited non-zero or was terminated by a non-interrupt
// signal (for example, SIGSEGV) while fuzzing.
return fmt.Errorf("fuzzing process hung or terminated unexpectedly: %w", err)
// TODO(jayconrod,katiehockman): if -keepfuzzing, restart worker.
case input := <-w.coordinator.inputC:
// Received input from coordinator.
args := fuzzArgs{
Limit: input.limit,
Timeout: input.timeout,
Warmup: input.warmup,
CoverageData: input.coverageData,
}
entry, resp, isInternalError, err := w.client.fuzz(ctx, input.entry, args)
canMinimize := true
if err != nil {
// Error communicating with worker.
w.stop()
if ctx.Err() != nil {
// Timeout or interruption.
return ctx.Err()
}
if w.interrupted {
// Communication error before we stopped the worker.
// Report an error, but don't record a crasher.
return fmt.Errorf("communicating with fuzzing process: %v", err)
}
if sig, ok := terminationSignal(w.waitErr); ok && !isCrashSignal(sig) {
// Worker terminated by a signal that probably wasn't caused by a
// specific input to the fuzz function. For example, on Linux,
// the kernel (OOM killer) may send SIGKILL to a process using a lot
// of memory. Or the shell might send SIGHUP when the terminal
// is closed. Don't record a crasher.
return fmt.Errorf("fuzzing process terminated by unexpected signal; no crash will be recorded: %v", w.waitErr)
}
if isInternalError {
// An internal error occurred which shouldn't be considered
// a crash.
return err
}
// Unexpected termination. Set error message and fall through.
// We'll restart the worker on the next iteration.
// Don't attempt to minimize this since it crashed the worker.
resp.Err = fmt.Sprintf("fuzzing process hung or terminated unexpectedly: %v", w.waitErr)
canMinimize = false
}
result := fuzzResult{
limit: input.limit,
count: resp.Count,
totalDuration: resp.TotalDuration,
entryDuration: resp.InterestingDuration,
entry: entry,
crasherMsg: resp.Err,
coverageData: resp.CoverageData,
canMinimize: canMinimize,
}
w.coordinator.resultC <- result
case input := <-w.coordinator.minimizeC:
// Received input to minimize from coordinator.
result, err := w.minimize(ctx, input)
if err != nil {
// Error minimizing. Send back the original input. If it didn't cause
// an error before, report it as causing an error now.
// TODO: double-check this is handled correctly when
// implementing -keepfuzzing.
result = fuzzResult{
entry: input.entry,
crasherMsg: input.crasherMsg,
canMinimize: false,
limit: input.limit,
}
if result.crasherMsg == "" {
result.crasherMsg = err.Error()
}
}
if shouldPrintDebugInfo() {
w.coordinator.debugLogf(
"input minimized, id: %s, original id: %s, crasher: %t, originally crasher: %t, minimizing took: %s",
result.entry.Path,
input.entry.Path,
result.crasherMsg != "",
input.crasherMsg != "",
result.totalDuration,
)
}
w.coordinator.resultC <- result
}
}
}
// minimize tells a worker process to attempt to find a smaller value that
// either causes an error (if we started minimizing because we found an input
// that causes an error) or preserves new coverage (if we started minimizing
// because we found an input that expands coverage).
func (w *worker) minimize(ctx context.Context, input fuzzMinimizeInput) (min fuzzResult, err error) {
if w.coordinator.opts.MinimizeTimeout != 0 {
var cancel func()
ctx, cancel = context.WithTimeout(ctx, w.coordinator.opts.MinimizeTimeout)
defer cancel()
}
args := minimizeArgs{
Limit: input.limit,
Timeout: input.timeout,
KeepCoverage: input.keepCoverage,
}
entry, resp, err := w.client.minimize(ctx, input.entry, args)
if err != nil {
// Error communicating with worker.
w.stop()
if ctx.Err() != nil || w.interrupted || isInterruptError(w.waitErr) {
// Worker was interrupted, possibly by the user pressing ^C.
// Normally, workers can handle interrupts and timeouts gracefully and
// will return without error. An error here indicates the worker
// may not have been in a good state, but the error won't be meaningful
// to the user. Just return the original crasher without logging anything.
return fuzzResult{
entry: input.entry,
crasherMsg: input.crasherMsg,
coverageData: input.keepCoverage,
canMinimize: false,
limit: input.limit,
}, nil
}
return fuzzResult{
entry: entry,
crasherMsg: fmt.Sprintf("fuzzing process hung or terminated unexpectedly while minimizing: %v", err),
canMinimize: false,
limit: input.limit,
count: resp.Count,
totalDuration: resp.Duration,
}, nil
}
if input.crasherMsg != "" && resp.Err == "" {
return fuzzResult{}, fmt.Errorf("attempted to minimize a crash but could not reproduce")
}
return fuzzResult{
entry: entry,
crasherMsg: resp.Err,
coverageData: resp.CoverageData,
canMinimize: false,
limit: input.limit,
count: resp.Count,
totalDuration: resp.Duration,
}, nil
}
func (w *worker) isRunning() bool {
return w.cmd != nil
}
// startAndPing starts the worker process and sends it a message to make sure it
// can communicate.
//
// startAndPing returns an error if any part of this didn't work, including if
// the context is expired or the worker process was interrupted before it
// responded. Errors that happen after start but before the ping response
// likely indicate that the worker did not call F.Fuzz or called F.Fail first.
// We don't record crashers for these errors.
func (w *worker) startAndPing(ctx context.Context) error {
if ctx.Err() != nil {
return ctx.Err()
}
if err := w.start(); err != nil {
return err
}
if err := w.client.ping(ctx); err != nil {
w.stop()
if ctx.Err() != nil {
return ctx.Err()
}
if isInterruptError(err) {
// User may have pressed ^C before worker responded.
return err
}
// TODO: record and return stderr.
return fmt.Errorf("fuzzing process terminated without fuzzing: %w", err)
}
return nil
}
// start runs a new worker process.
//
// If the process couldn't be started, start returns an error. Start won't
// return later termination errors from the process if they occur.
//
// If the process starts successfully, start returns nil. stop must be called
// once later to clean up, even if the process terminates on its own.
//
// When the process terminates, w.waitErr is set to the error (if any), and
// w.termC is closed.
func (w *worker) start() (err error) {
if w.isRunning() {
panic("worker already started")
}
w.waitErr = nil
w.interrupted = false
w.termC = nil
cmd := exec.Command(w.binPath, w.args...)
cmd.Dir = w.dir
cmd.Env = w.env[:len(w.env):len(w.env)] // copy on append to ensure workers don't overwrite each other.
// Create the "fuzz_in" and "fuzz_out" pipes so we can communicate with
// the worker. We don't use stdin and stdout, since the test binary may
// do something else with those.
//
// Each pipe has a reader and a writer. The coordinator writes to fuzzInW
// and reads from fuzzOutR. The worker inherits fuzzInR and fuzzOutW.
// The coordinator closes fuzzInR and fuzzOutW after starting the worker,
// since we have no further need of them.
fuzzInR, fuzzInW, err := os.Pipe()
if err != nil {
return err
}
defer fuzzInR.Close()
fuzzOutR, fuzzOutW, err := os.Pipe()
if err != nil {
fuzzInW.Close()
return err
}
defer fuzzOutW.Close()
setWorkerComm(cmd, workerComm{fuzzIn: fuzzInR, fuzzOut: fuzzOutW, memMu: w.memMu})
// Start the worker process.
if err := cmd.Start(); err != nil {
fuzzInW.Close()
fuzzOutR.Close()
return err
}
// Worker started successfully.
// After this, w.client owns fuzzInW and fuzzOutR, so w.client.Close must be
// called later by stop.
w.cmd = cmd
w.termC = make(chan struct{})
comm := workerComm{fuzzIn: fuzzInW, fuzzOut: fuzzOutR, memMu: w.memMu}
m := newMutator()
w.client = newWorkerClient(comm, m)
go func() {
w.waitErr = w.cmd.Wait()
close(w.termC)
}()
return nil
}
// stop tells the worker process to exit by closing w.client, then blocks until
// it terminates. If the worker doesn't terminate after a short time, stop
// signals it with os.Interrupt (where supported), then os.Kill.
//
// stop returns the error the process terminated with, if any (same as
// w.waitErr).
//
// stop must be called at least once after start returns successfully, even if
// the worker process terminates unexpectedly.
func (w *worker) stop() error {
if w.termC == nil {
panic("worker was not started successfully")
}
select {
case <-w.termC:
// Worker already terminated.
if w.client == nil {
// stop already called.
return w.waitErr
}
// Possible unexpected termination.
w.client.Close()
w.cmd = nil
w.client = nil
return w.waitErr
default:
// Worker still running.
}
// Tell the worker to stop by closing fuzz_in. It won't actually stop until it
// finishes with earlier calls.
closeC := make(chan struct{})
go func() {
w.client.Close()
close(closeC)
}()
sig := os.Interrupt
if runtime.GOOS == "windows" {
// Per https://golang.org/pkg/os/#Signal, “Interrupt is not implemented on
// Windows; using it with os.Process.Signal will return an error.”
// Fall back to Kill instead.
sig = os.Kill
}
t := time.NewTimer(workerTimeoutDuration)
for {
select {
case <-w.termC:
// Worker terminated.
t.Stop()
<-closeC
w.cmd = nil
w.client = nil
return w.waitErr
case <-t.C:
// Timer fired before worker terminated.
w.interrupted = true
switch sig {
case os.Interrupt:
// Try to stop the worker with SIGINT and wait a little longer.
w.cmd.Process.Signal(sig)
sig = os.Kill
t.Reset(workerTimeoutDuration)
case os.Kill:
// Try to stop the worker with SIGKILL and keep waiting.
w.cmd.Process.Signal(sig)
sig = nil
t.Reset(workerTimeoutDuration)
case nil:
// Still waiting. Print a message to let the user know why.
fmt.Fprintf(w.coordinator.opts.Log, "waiting for fuzzing process to terminate...\n")
}
}
}
}
// RunFuzzWorker is called in a worker process to communicate with the
// coordinator process in order to fuzz random inputs. RunFuzzWorker loops
// until the coordinator tells it to stop.
//
// fn is a wrapper on the fuzz function. It may return an error to indicate
// a given input "crashed". The coordinator will also record a crasher if
// the function times out or terminates the process.
//
// RunFuzzWorker returns an error if it could not communicate with the
// coordinator process.
func RunFuzzWorker(ctx context.Context, fn func(CorpusEntry) error) error {
comm, err := getWorkerComm()
if err != nil {
return err
}
srv := &workerServer{
workerComm: comm,
fuzzFn: func(e CorpusEntry) (time.Duration, error) {
timer := time.AfterFunc(10*time.Second, func() {
panic("deadlocked!") // this error message won't be printed
})
defer timer.Stop()
start := time.Now()
err := fn(e)
return time.Since(start), err
},
m: newMutator(),
}
return srv.serve(ctx)
}
// call is serialized and sent from the coordinator on fuzz_in. It acts as
// a minimalist RPC mechanism. Exactly one of its fields must be set to indicate
// which method to call.
type call struct {
Ping *pingArgs
Fuzz *fuzzArgs
Minimize *minimizeArgs
}
// minimizeArgs contains arguments to workerServer.minimize. The value to
// minimize is already in shared memory.
type minimizeArgs struct {
// Timeout is the time to spend minimizing. This may include time to start up,
// especially if the input causes the worker process to terminated, requiring
// repeated restarts.
Timeout time.Duration
// Limit is the maximum number of values to test, without spending more time
// than Duration. 0 indicates no limit.
Limit int64
// KeepCoverage is a set of coverage counters the worker should attempt to
// keep in minimized values. When provided, the worker will reject inputs that
// don't cause at least one of these bits to be set.
KeepCoverage []byte
// Index is the index of the fuzz target parameter to be minimized.
Index int
}
// minimizeResponse contains results from workerServer.minimize.
type minimizeResponse struct {
// WroteToMem is true if the worker found a smaller input and wrote it to
// shared memory. If minimizeArgs.KeepCoverage was set, the minimized input
// preserved at least one coverage bit and did not cause an error.
// Otherwise, the minimized input caused some error, recorded in Err.
WroteToMem bool
// Err is the error string caused by the value in shared memory, if any.
Err string
// CoverageData is the set of coverage bits activated by the minimized value
// in shared memory. When set, it contains at least one bit from KeepCoverage.
// CoverageData will be nil if Err is set or if minimization failed.
CoverageData []byte
// Duration is the time spent minimizing, not including starting or cleaning up.
Duration time.Duration
// Count is the number of values tested.
Count int64
}
// fuzzArgs contains arguments to workerServer.fuzz. The value to fuzz is
// passed in shared memory.
type fuzzArgs struct {
// Timeout is the time to spend fuzzing, not including starting or
// cleaning up.
Timeout time.Duration
// Limit is the maximum number of values to test, without spending more time
// than Duration. 0 indicates no limit.
Limit int64
// Warmup indicates whether this is part of a warmup run, meaning that
// fuzzing should not occur. If coverageEnabled is true, then coverage data
// should be reported.
Warmup bool
// CoverageData is the coverage data. If set, the worker should update its
// local coverage data prior to fuzzing.
CoverageData []byte
}
// fuzzResponse contains results from workerServer.fuzz.
type fuzzResponse struct {
// Duration is the time spent fuzzing, not including starting or cleaning up.
TotalDuration time.Duration
InterestingDuration time.Duration
// Count is the number of values tested.
Count int64
// CoverageData is set if the value in shared memory expands coverage
// and therefore may be interesting to the coordinator.
CoverageData []byte
// Err is the error string caused by the value in shared memory, which is
// non-empty if the value in shared memory caused a crash.
Err string
// InternalErr is the error string caused by an internal error in the
// worker. This shouldn't be considered a crasher.
InternalErr string
}
// pingArgs contains arguments to workerServer.ping.
type pingArgs struct{}
// pingResponse contains results from workerServer.ping.
type pingResponse struct{}
// workerComm holds pipes and shared memory used for communication
// between the coordinator process (client) and a worker process (server).
// These values are unique to each worker; they are shared only with the
// coordinator, not with other workers.
//
// Access to shared memory is synchronized implicitly over the RPC protocol
// implemented in workerServer and workerClient. During a call, the client
// (worker) has exclusive access to shared memory; at other times, the server
// (coordinator) has exclusive access.
type workerComm struct {
fuzzIn, fuzzOut *os.File
memMu chan *sharedMem // mutex guarding shared memory
}
// workerServer is a minimalist RPC server, run by fuzz worker processes.
// It allows the coordinator process (using workerClient) to call methods in a
// worker process. This system allows the coordinator to run multiple worker
// processes in parallel and to collect inputs that caused crashes from shared
// memory after a worker process terminates unexpectedly.
type workerServer struct {
workerComm
m *mutator
// coverageMask is the local coverage data for the worker. It is
// periodically updated to reflect the data in the coordinator when new
// coverage is found.
coverageMask []byte
// fuzzFn runs the worker's fuzz target on the given input and returns an
// error if it finds a crasher (the process may also exit or crash), and the
// time it took to run the input. It sets a deadline of 10 seconds, at which
// point it will panic with the assumption that the process is hanging or
// deadlocked.
fuzzFn func(CorpusEntry) (time.Duration, error)
}
// serve reads serialized RPC messages on fuzzIn. When serve receives a message,
// it calls the corresponding method, then sends the serialized result back
// on fuzzOut.
//
// serve handles RPC calls synchronously; it will not attempt to read a message
// until the previous call has finished.
//
// serve returns errors that occurred when communicating over pipes. serve
// does not return errors from method calls; those are passed through serialized
// responses.
func (ws *workerServer) serve(ctx context.Context) error {
enc := json.NewEncoder(ws.fuzzOut)
dec := json.NewDecoder(&contextReader{ctx: ctx, r: ws.fuzzIn})
for {
var c call
if err := dec.Decode(&c); err != nil {
if err == io.EOF || err == ctx.Err() {
return nil
} else {
return err
}
}
var resp any
switch {
case c.Fuzz != nil:
resp = ws.fuzz(ctx, *c.Fuzz)
case c.Minimize != nil:
resp = ws.minimize(ctx, *c.Minimize)
case c.Ping != nil:
resp = ws.ping(ctx, *c.Ping)
default:
return errors.New("no arguments provided for any call")
}
if err := enc.Encode(resp); err != nil {
return err
}
}
}
// chainedMutations is how many mutations are applied before the worker
// resets the input to it's original state.
// NOTE: this number was picked without much thought. It is low enough that
// it seems to create a significant diversity in mutated inputs. We may want
// to consider looking into this more closely once we have a proper performance
// testing framework. Another option is to randomly pick the number of chained
// mutations on each invocation of the workerServer.fuzz method (this appears to
// be what libFuzzer does, although there seems to be no documentation which
// explains why this choice was made.)
const chainedMutations = 5
// fuzz runs the test function on random variations of the input value in shared
// memory for a limited duration or number of iterations.
//
// fuzz returns early if it finds an input that crashes the fuzz function (with
// fuzzResponse.Err set) or an input that expands coverage (with
// fuzzResponse.InterestingDuration set).
//
// fuzz does not modify the input in shared memory. Instead, it saves the
// initial PRNG state in shared memory and increments a counter in shared
// memory before each call to the test function. The caller may reconstruct
// the crashing input with this information, since the PRNG is deterministic.
func (ws *workerServer) fuzz(ctx context.Context, args fuzzArgs) (resp fuzzResponse) {
if args.CoverageData != nil {
if ws.coverageMask != nil && len(args.CoverageData) != len(ws.coverageMask) {
resp.InternalErr = fmt.Sprintf("unexpected size for CoverageData: got %d, expected %d", len(args.CoverageData), len(ws.coverageMask))
return resp
}
ws.coverageMask = args.CoverageData
}
start := time.Now()
defer func() { resp.TotalDuration = time.Since(start) }()
if args.Timeout != 0 {
var cancel func()
ctx, cancel = context.WithTimeout(ctx, args.Timeout)
defer cancel()
}
mem := <-ws.memMu
ws.m.r.save(&mem.header().randState, &mem.header().randInc)
defer func() {
resp.Count = mem.header().count
ws.memMu <- mem
}()
if args.Limit > 0 && mem.header().count >= args.Limit {
resp.InternalErr = fmt.Sprintf("mem.header().count %d already exceeds args.Limit %d", mem.header().count, args.Limit)
return resp
}
originalVals, err := unmarshalCorpusFile(mem.valueCopy())
if err != nil {
resp.InternalErr = err.Error()
return resp
}
vals := make([]any, len(originalVals))
copy(vals, originalVals)
shouldStop := func() bool {
return args.Limit > 0 && mem.header().count >= args.Limit
}
fuzzOnce := func(entry CorpusEntry) (dur time.Duration, cov []byte, errMsg string) {
mem.header().count++
var err error
dur, err = ws.fuzzFn(entry)
if err != nil {
errMsg = err.Error()
if errMsg == "" {
errMsg = "fuzz function failed with no input"
}
return dur, nil, errMsg
}
if ws.coverageMask != nil && countNewCoverageBits(ws.coverageMask, coverageSnapshot) > 0 {
return dur, coverageSnapshot, ""
}
return dur, nil, ""
}
if args.Warmup {
dur, _, errMsg := fuzzOnce(CorpusEntry{Values: vals})
if errMsg != "" {
resp.Err = errMsg
return resp
}
resp.InterestingDuration = dur
if coverageEnabled {
resp.CoverageData = coverageSnapshot
}
return resp
}
for {
select {
case <-ctx.Done():
return resp
default:
if mem.header().count%chainedMutations == 0 {
copy(vals, originalVals)
ws.m.r.save(&mem.header().randState, &mem.header().randInc)
}
ws.m.mutate(vals, cap(mem.valueRef()))
entry := CorpusEntry{Values: vals}
dur, cov, errMsg := fuzzOnce(entry)
if errMsg != "" {
resp.Err = errMsg
return resp
}
if cov != nil {
resp.CoverageData = cov
resp.InterestingDuration = dur
return resp
}
if shouldStop() {
return resp
}
}
}
}
func (ws *workerServer) minimize(ctx context.Context, args minimizeArgs) (resp minimizeResponse) {
start := time.Now()
defer func() { resp.Duration = time.Since(start) }()
mem := <-ws.memMu
defer func() { ws.memMu <- mem }()
vals, err := unmarshalCorpusFile(mem.valueCopy())
if err != nil {
panic(err)
}
inpHash := sha256.Sum256(mem.valueCopy())
if args.Timeout != 0 {
var cancel func()
ctx, cancel = context.WithTimeout(ctx, args.Timeout)
defer cancel()
}
// Minimize the values in vals, then write to shared memory. We only write
// to shared memory after completing minimization.
success, err := ws.minimizeInput(ctx, vals, mem, args)
if success {
writeToMem(vals, mem)
outHash := sha256.Sum256(mem.valueCopy())
mem.header().rawInMem = false
resp.WroteToMem = true
if err != nil {
resp.Err = err.Error()
} else {
// If the values didn't change during minimization then coverageSnapshot is likely
// a dirty snapshot which represents the very last step of minimization, not the
// coverage for the initial input. In that case just return the coverage we were
// given initially, since it more accurately represents the coverage map for the
// input we are returning.
if outHash != inpHash {
resp.CoverageData = coverageSnapshot
} else {
resp.CoverageData = args.KeepCoverage
}
}
}
return resp
}
// minimizeInput applies a series of minimizing transformations on the provided
// vals, ensuring that each minimization still causes an error, or keeps
// coverage, in fuzzFn. It uses the context to determine how long to run,
// stopping once closed. It returns a bool indicating whether minimization was
// successful and an error if one was found.
func (ws *workerServer) minimizeInput(ctx context.Context, vals []any, mem *sharedMem, args minimizeArgs) (success bool, retErr error) {
keepCoverage := args.KeepCoverage
memBytes := mem.valueRef()
bPtr := &memBytes
count := &mem.header().count
shouldStop := func() bool {
return ctx.Err() != nil ||
(args.Limit > 0 && *count >= args.Limit)
}
if shouldStop() {
return false, nil
}
// Check that the original value preserves coverage or causes an error.
// If not, then whatever caused us to think the value was interesting may
// have been a flake, and we can't minimize it.
*count++
_, retErr = ws.fuzzFn(CorpusEntry{Values: vals})
if keepCoverage != nil {
if !hasCoverageBit(keepCoverage, coverageSnapshot) || retErr != nil {
return false, nil
}
} else if retErr == nil {
return false, nil
}
mem.header().rawInMem = true
// tryMinimized runs the fuzz function with candidate replacing the value
// at index valI. tryMinimized returns whether the input with candidate is
// interesting for the same reason as the original input: it returns
// an error if one was expected, or it preserves coverage.
tryMinimized := func(candidate []byte) bool {
prev := vals[args.Index]
switch prev.(type) {
case []byte:
vals[args.Index] = candidate
case string:
vals[args.Index] = string(candidate)
default:
panic("impossible")
}
copy(*bPtr, candidate)
*bPtr = (*bPtr)[:len(candidate)]
mem.setValueLen(len(candidate))
*count++
_, err := ws.fuzzFn(CorpusEntry{Values: vals})
if err != nil {
retErr = err
if keepCoverage != nil {
// Now that we've found a crash, that's more important than any
// minimization of interesting inputs that was being done. Clear out
// keepCoverage to only minimize the crash going forward.
keepCoverage = nil
}
return true
}
// Minimization should preserve coverage bits.
if keepCoverage != nil && isCoverageSubset(keepCoverage, coverageSnapshot) {
return true
}
vals[args.Index] = prev
return false
}
switch v := vals[args.Index].(type) {
case string:
minimizeBytes([]byte(v), tryMinimized, shouldStop)
case []byte:
minimizeBytes(v, tryMinimized, shouldStop)
default:
panic("impossible")
}
return true, retErr
}
func writeToMem(vals []any, mem *sharedMem) {
b := marshalCorpusFile(vals...)
mem.setValue(b)
}
// ping does nothing. The coordinator calls this method to ensure the worker
// has called F.Fuzz and can communicate.
func (ws *workerServer) ping(ctx context.Context, args pingArgs) pingResponse {
return pingResponse{}
}
// workerClient is a minimalist RPC client. The coordinator process uses a
// workerClient to call methods in each worker process (handled by
// workerServer).
type workerClient struct {
workerComm
m *mutator
// mu is the mutex protecting the workerComm.fuzzIn pipe. This must be
// locked before making calls to the workerServer. It prevents
// workerClient.Close from closing fuzzIn while workerClient methods are
// writing to it concurrently, and prevents multiple callers from writing to
// fuzzIn concurrently.
mu sync.Mutex
}
func newWorkerClient(comm workerComm, m *mutator) *workerClient {
return &workerClient{workerComm: comm, m: m}
}
// Close shuts down the connection to the RPC server (the worker process) by
// closing fuzz_in. Close drains fuzz_out (avoiding a SIGPIPE in the worker),
// and closes it after the worker process closes the other end.
func (wc *workerClient) Close() error {
wc.mu.Lock()
defer wc.mu.Unlock()
// Close fuzzIn. This signals to the server that there are no more calls,
// and it should exit.
if err := wc.fuzzIn.Close(); err != nil {
wc.fuzzOut.Close()
return err
}
// Drain fuzzOut and close it. When the server exits, the kernel will close
// its end of fuzzOut, and we'll get EOF.
if _, err := io.Copy(io.Discard, wc.fuzzOut); err != nil {
wc.fuzzOut.Close()
return err
}
return wc.fuzzOut.Close()
}
// errSharedMemClosed is returned by workerClient methods that cannot access
// shared memory because it was closed and unmapped by another goroutine. That
// can happen when worker.cleanup is called in the worker goroutine while a
// workerClient.fuzz call runs concurrently.
//
// This error should not be reported. It indicates the operation was
// interrupted.
var errSharedMemClosed = errors.New("internal error: shared memory was closed and unmapped")
// minimize tells the worker to call the minimize method. See
// workerServer.minimize.
func (wc *workerClient) minimize(ctx context.Context, entryIn CorpusEntry, args minimizeArgs) (entryOut CorpusEntry, resp minimizeResponse, retErr error) {
wc.mu.Lock()
defer wc.mu.Unlock()
mem, ok := <-wc.memMu
if !ok {
return CorpusEntry{}, minimizeResponse{}, errSharedMemClosed
}
defer func() { wc.memMu <- mem }()
mem.header().count = 0
inp, err := corpusEntryData(entryIn)
if err != nil {
return CorpusEntry{}, minimizeResponse{}, err
}
mem.setValue(inp)
entryOut = entryIn
entryOut.Values, err = unmarshalCorpusFile(inp)
if err != nil {
return CorpusEntry{}, minimizeResponse{}, fmt.Errorf("workerClient.minimize unmarshaling provided value: %v", err)
}
for i, v := range entryOut.Values {
if !isMinimizable(reflect.TypeOf(v)) {
continue
}
wc.memMu <- mem
args.Index = i
c := call{Minimize: &args}
callErr := wc.callLocked(ctx, c, &resp)
mem, ok = <-wc.memMu
if !ok {
return CorpusEntry{}, minimizeResponse{}, errSharedMemClosed
}
if callErr != nil {
retErr = callErr
if !mem.header().rawInMem {
// An unrecoverable error occurred before minimization began.
return entryIn, minimizeResponse{}, retErr
}
// An unrecoverable error occurred during minimization. mem now
// holds the raw, unmarshaled bytes of entryIn.Values[i] that
// caused the error.
switch entryOut.Values[i].(type) {
case string:
entryOut.Values[i] = string(mem.valueCopy())
case []byte:
entryOut.Values[i] = mem.valueCopy()
default:
panic("impossible")
}
entryOut.Data = marshalCorpusFile(entryOut.Values...)
// Stop minimizing; another unrecoverable error is likely to occur.
break
}
if resp.WroteToMem {
// Minimization succeeded, and mem holds the marshaled data.
entryOut.Data = mem.valueCopy()
entryOut.Values, err = unmarshalCorpusFile(entryOut.Data)
if err != nil {
return CorpusEntry{}, minimizeResponse{}, fmt.Errorf("workerClient.minimize unmarshaling minimized value: %v", err)
}
}
// Prepare for next iteration of the loop.
if args.Timeout != 0 {
args.Timeout -= resp.Duration
if args.Timeout <= 0 {
break
}
}
if args.Limit != 0 {
args.Limit -= mem.header().count
if args.Limit <= 0 {
break
}
}
}
resp.Count = mem.header().count
h := sha256.Sum256(entryOut.Data)
entryOut.Path = fmt.Sprintf("%x", h[:4])
return entryOut, resp, retErr
}
// fuzz tells the worker to call the fuzz method. See workerServer.fuzz.
func (wc *workerClient) fuzz(ctx context.Context, entryIn CorpusEntry, args fuzzArgs) (entryOut CorpusEntry, resp fuzzResponse, isInternalError bool, err error) {
wc.mu.Lock()
defer wc.mu.Unlock()
mem, ok := <-wc.memMu
if !ok {
return CorpusEntry{}, fuzzResponse{}, true, errSharedMemClosed
}
mem.header().count = 0
inp, err := corpusEntryData(entryIn)
if err != nil {
wc.memMu <- mem
return CorpusEntry{}, fuzzResponse{}, true, err
}
mem.setValue(inp)
wc.memMu <- mem
c := call{Fuzz: &args}
callErr := wc.callLocked(ctx, c, &resp)
if resp.InternalErr != "" {
return CorpusEntry{}, fuzzResponse{}, true, errors.New(resp.InternalErr)
}
mem, ok = <-wc.memMu
if !ok {
return CorpusEntry{}, fuzzResponse{}, true, errSharedMemClosed
}
defer func() { wc.memMu <- mem }()
resp.Count = mem.header().count
if !bytes.Equal(inp, mem.valueRef()) {
return CorpusEntry{}, fuzzResponse{}, true, errors.New("workerServer.fuzz modified input")
}
needEntryOut := callErr != nil || resp.Err != "" ||
(!args.Warmup && resp.CoverageData != nil)
if needEntryOut {
valuesOut, err := unmarshalCorpusFile(inp)
if err != nil {
return CorpusEntry{}, fuzzResponse{}, true, fmt.Errorf("unmarshaling fuzz input value after call: %v", err)
}
wc.m.r.restore(mem.header().randState, mem.header().randInc)
if !args.Warmup {
// Only mutate the valuesOut if fuzzing actually occurred.
numMutations := ((resp.Count - 1) % chainedMutations) + 1
for i := int64(0); i < numMutations; i++ {
wc.m.mutate(valuesOut, cap(mem.valueRef()))
}
}
dataOut := marshalCorpusFile(valuesOut...)
h := sha256.Sum256(dataOut)
name := fmt.Sprintf("%x", h[:4])
entryOut = CorpusEntry{
Parent: entryIn.Path,
Path: name,
Data: dataOut,
Generation: entryIn.Generation + 1,
}
if args.Warmup {
// The bytes weren't mutated, so if entryIn was a seed corpus value,
// then entryOut is too.
entryOut.IsSeed = entryIn.IsSeed
}
}
return entryOut, resp, false, callErr
}
// ping tells the worker to call the ping method. See workerServer.ping.
func (wc *workerClient) ping(ctx context.Context) error {
wc.mu.Lock()
defer wc.mu.Unlock()
c := call{Ping: &pingArgs{}}
var resp pingResponse
return wc.callLocked(ctx, c, &resp)
}
// callLocked sends an RPC from the coordinator to the worker process and waits
// for the response. The callLocked may be canceled with ctx.
func (wc *workerClient) callLocked(ctx context.Context, c call, resp any) (err error) {
enc := json.NewEncoder(wc.fuzzIn)
dec := json.NewDecoder(&contextReader{ctx: ctx, r: wc.fuzzOut})
if err := enc.Encode(c); err != nil {
return err
}
return dec.Decode(resp)
}
// contextReader wraps a Reader with a Context. If the context is canceled
// while the underlying reader is blocked, Read returns immediately.
//
// This is useful for reading from a pipe. Closing a pipe file descriptor does
// not unblock pending Reads on that file descriptor. All copies of the pipe's
// other file descriptor (the write end) must be closed in all processes that
// inherit it. This is difficult to do correctly in the situation we care about
// (process group termination).
type contextReader struct {
ctx context.Context
r io.Reader
}
func (cr *contextReader) Read(b []byte) (int, error) {
if ctxErr := cr.ctx.Err(); ctxErr != nil {
return 0, ctxErr
}
done := make(chan struct{})
// This goroutine may stay blocked after Read returns because the underlying
// read is blocked.
var n int
var err error
go func() {
n, err = cr.r.Read(b)
close(done)
}()
select {
case <-cr.ctx.Done():
return 0, cr.ctx.Err()
case <-done:
return n, err
}
}
| go/src/internal/fuzz/worker.go/0 | {
"file_path": "go/src/internal/fuzz/worker.go",
"repo_id": "go",
"token_count": 12850
} | 281 |
// Code generated by mkconsts.go. DO NOT EDIT.
//go:build goexperiment.arenas
package goexperiment
const Arenas = true
const ArenasInt = 1
| go/src/internal/goexperiment/exp_arenas_on.go/0 | {
"file_path": "go/src/internal/goexperiment/exp_arenas_on.go",
"repo_id": "go",
"token_count": 47
} | 282 |
// Code generated by mkconsts.go. DO NOT EDIT.
//go:build goexperiment.newinliner
package goexperiment
const NewInliner = true
const NewInlinerInt = 1
| go/src/internal/goexperiment/exp_newinliner_on.go/0 | {
"file_path": "go/src/internal/goexperiment/exp_newinliner_on.go",
"repo_id": "go",
"token_count": 50
} | 283 |
// Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package oserror defines errors values used in the os package.
//
// These types are defined here to permit the syscall package to reference them.
package oserror
import "errors"
var (
ErrInvalid = errors.New("invalid argument")
ErrPermission = errors.New("permission denied")
ErrExist = errors.New("file already exists")
ErrNotExist = errors.New("file does not exist")
ErrClosed = errors.New("file already closed")
)
| go/src/internal/oserror/errors.go/0 | {
"file_path": "go/src/internal/oserror/errors.go",
"repo_id": "go",
"token_count": 183
} | 284 |
// Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package poll_test
import (
"errors"
"internal/poll"
"os"
"syscall"
)
func badStateFile() (*os.File, error) {
if os.Getuid() != 0 {
return nil, errors.New("must be root")
}
// Using OpenFile for a device file is an easy way to make a
// file attached to the runtime-integrated network poller and
// configured in halfway.
return os.OpenFile("/dev/net/tun", os.O_RDWR, 0)
}
func isBadStateFileError(err error) (string, bool) {
switch err {
case poll.ErrNotPollable, syscall.EBADFD:
return "", true
default:
return "not pollable or file in bad state error", false
}
}
| go/src/internal/poll/error_linux_test.go/0 | {
"file_path": "go/src/internal/poll/error_linux_test.go",
"repo_id": "go",
"token_count": 257
} | 285 |
// Copyright 2013 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 js && wasm
package poll
import (
"syscall"
"time"
)
type pollDesc struct {
fd *FD
closing bool
}
func (pd *pollDesc) init(fd *FD) error { pd.fd = fd; return nil }
func (pd *pollDesc) close() {}
func (pd *pollDesc) evict() {
pd.closing = true
if pd.fd != nil {
syscall.StopIO(pd.fd.Sysfd)
}
}
func (pd *pollDesc) prepare(mode int, isFile bool) error {
if pd.closing {
return errClosing(isFile)
}
return nil
}
func (pd *pollDesc) prepareRead(isFile bool) error { return pd.prepare('r', isFile) }
func (pd *pollDesc) prepareWrite(isFile bool) error { return pd.prepare('w', isFile) }
func (pd *pollDesc) wait(mode int, isFile bool) error {
if pd.closing {
return errClosing(isFile)
}
if isFile { // TODO(neelance): js/wasm: Use callbacks from JS to block until the read/write finished.
return nil
}
return ErrDeadlineExceeded
}
func (pd *pollDesc) waitRead(isFile bool) error { return pd.wait('r', isFile) }
func (pd *pollDesc) waitWrite(isFile bool) error { return pd.wait('w', isFile) }
func (pd *pollDesc) waitCanceled(mode int) {}
func (pd *pollDesc) pollable() bool { return true }
// SetDeadline sets the read and write deadlines associated with fd.
func (fd *FD) SetDeadline(t time.Time) error {
return setDeadlineImpl(fd, t, 'r'+'w')
}
// SetReadDeadline sets the read deadline associated with fd.
func (fd *FD) SetReadDeadline(t time.Time) error {
return setDeadlineImpl(fd, t, 'r')
}
// SetWriteDeadline sets the write deadline associated with fd.
func (fd *FD) SetWriteDeadline(t time.Time) error {
return setDeadlineImpl(fd, t, 'w')
}
func setDeadlineImpl(fd *FD, t time.Time, mode int) error {
d := t.UnixNano()
if t.IsZero() {
d = 0
}
if err := fd.incref(); err != nil {
return err
}
switch mode {
case 'r':
syscall.SetReadDeadline(fd.Sysfd, d)
case 'w':
syscall.SetWriteDeadline(fd.Sysfd, d)
case 'r' + 'w':
syscall.SetReadDeadline(fd.Sysfd, d)
syscall.SetWriteDeadline(fd.Sysfd, d)
}
fd.decref()
return nil
}
// IsPollDescriptor reports whether fd is the descriptor being used by the poller.
// This is only used for testing.
func IsPollDescriptor(fd uintptr) bool {
return false
}
| go/src/internal/poll/fd_poll_js.go/0 | {
"file_path": "go/src/internal/poll/fd_poll_js.go",
"repo_id": "go",
"token_count": 886
} | 286 |
// Copyright 2021 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 poll_test
import (
"internal/poll"
"runtime"
"sync"
"sync/atomic"
"testing"
"time"
)
var closeHook atomic.Value // func(fd int)
func init() {
closeFunc := poll.CloseFunc
poll.CloseFunc = func(fd int) (err error) {
if v := closeHook.Load(); v != nil {
if hook := v.(func(int)); hook != nil {
hook(fd)
}
}
return closeFunc(fd)
}
}
func TestSplicePipePool(t *testing.T) {
const N = 64
var (
p *poll.SplicePipe
ps []*poll.SplicePipe
allFDs []int
pendingFDs sync.Map // fd → struct{}{}
err error
)
closeHook.Store(func(fd int) { pendingFDs.Delete(fd) })
t.Cleanup(func() { closeHook.Store((func(int))(nil)) })
for i := 0; i < N; i++ {
p, err = poll.GetPipe()
if err != nil {
t.Skipf("failed to create pipe due to error(%v), skip this test", err)
}
_, pwfd := poll.GetPipeFds(p)
allFDs = append(allFDs, pwfd)
pendingFDs.Store(pwfd, struct{}{})
ps = append(ps, p)
}
for _, p = range ps {
poll.PutPipe(p)
}
ps = nil
p = nil
// Exploit the timeout of "go test" as a timer for the subsequent verification.
timeout := 5 * time.Minute
if deadline, ok := t.Deadline(); ok {
timeout = deadline.Sub(time.Now())
timeout -= timeout / 10 // Leave 10% headroom for cleanup.
}
expiredTime := time.NewTimer(timeout)
defer expiredTime.Stop()
// Trigger garbage collection repeatedly, waiting for all pipes in sync.Pool
// to either be deallocated and closed, or to time out.
for {
runtime.GC()
time.Sleep(10 * time.Millisecond)
// Detect whether all pipes are closed properly.
var leakedFDs []int
pendingFDs.Range(func(k, v any) bool {
leakedFDs = append(leakedFDs, k.(int))
return true
})
if len(leakedFDs) == 0 {
break
}
select {
case <-expiredTime.C:
t.Logf("all descriptors: %v", allFDs)
t.Fatalf("leaked descriptors: %v", leakedFDs)
default:
}
}
}
func BenchmarkSplicePipe(b *testing.B) {
b.Run("SplicePipeWithPool", func(b *testing.B) {
for i := 0; i < b.N; i++ {
p, err := poll.GetPipe()
if err != nil {
continue
}
poll.PutPipe(p)
}
})
b.Run("SplicePipeWithoutPool", func(b *testing.B) {
for i := 0; i < b.N; i++ {
p := poll.NewPipe()
if p == nil {
b.Skip("newPipe returned nil")
}
poll.DestroyPipe(p)
}
})
}
func BenchmarkSplicePipePoolParallel(b *testing.B) {
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
p, err := poll.GetPipe()
if err != nil {
continue
}
poll.PutPipe(p)
}
})
}
func BenchmarkSplicePipeNativeParallel(b *testing.B) {
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
p := poll.NewPipe()
if p == nil {
b.Skip("newPipe returned nil")
}
poll.DestroyPipe(p)
}
})
}
| go/src/internal/poll/splice_linux_test.go/0 | {
"file_path": "go/src/internal/poll/splice_linux_test.go",
"repo_id": "go",
"token_count": 1271
} | 287 |
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package reflectlite_test
import (
"encoding/base64"
"fmt"
"internal/abi"
. "internal/reflectlite"
"math"
"reflect"
"runtime"
"testing"
"unsafe"
)
func ToValue(v Value) reflect.Value {
return reflect.ValueOf(ToInterface(v))
}
func TypeString(t Type) string {
return fmt.Sprintf("%T", ToInterface(Zero(t)))
}
type integer int
type T struct {
a int
b float64
c string
d *int
}
type pair struct {
i any
s string
}
func assert(t *testing.T, s, want string) {
t.Helper()
if s != want {
t.Errorf("have %#q want %#q", s, want)
}
}
var typeTests = []pair{
{struct{ x int }{}, "int"},
{struct{ x int8 }{}, "int8"},
{struct{ x int16 }{}, "int16"},
{struct{ x int32 }{}, "int32"},
{struct{ x int64 }{}, "int64"},
{struct{ x uint }{}, "uint"},
{struct{ x uint8 }{}, "uint8"},
{struct{ x uint16 }{}, "uint16"},
{struct{ x uint32 }{}, "uint32"},
{struct{ x uint64 }{}, "uint64"},
{struct{ x float32 }{}, "float32"},
{struct{ x float64 }{}, "float64"},
{struct{ x int8 }{}, "int8"},
{struct{ x (**int8) }{}, "**int8"},
{struct{ x (**integer) }{}, "**reflectlite_test.integer"},
{struct{ x ([32]int32) }{}, "[32]int32"},
{struct{ x ([]int8) }{}, "[]int8"},
{struct{ x (map[string]int32) }{}, "map[string]int32"},
{struct{ x (chan<- string) }{}, "chan<- string"},
{struct {
x struct {
c chan *int32
d float32
}
}{},
"struct { c chan *int32; d float32 }",
},
{struct{ x (func(a int8, b int32)) }{}, "func(int8, int32)"},
{struct {
x struct {
c func(chan *integer, *int8)
}
}{},
"struct { c func(chan *reflectlite_test.integer, *int8) }",
},
{struct {
x struct {
a int8
b int32
}
}{},
"struct { a int8; b int32 }",
},
{struct {
x struct {
a int8
b int8
c int32
}
}{},
"struct { a int8; b int8; c int32 }",
},
{struct {
x struct {
a int8
b int8
c int8
d int32
}
}{},
"struct { a int8; b int8; c int8; d int32 }",
},
{struct {
x struct {
a int8
b int8
c int8
d int8
e int32
}
}{},
"struct { a int8; b int8; c int8; d int8; e int32 }",
},
{struct {
x struct {
a int8
b int8
c int8
d int8
e int8
f int32
}
}{},
"struct { a int8; b int8; c int8; d int8; e int8; f int32 }",
},
{struct {
x struct {
a int8 `reflect:"hi there"`
}
}{},
`struct { a int8 "reflect:\"hi there\"" }`,
},
{struct {
x struct {
a int8 `reflect:"hi \x00there\t\n\"\\"`
}
}{},
`struct { a int8 "reflect:\"hi \\x00there\\t\\n\\\"\\\\\"" }`,
},
{struct {
x struct {
f func(args ...int)
}
}{},
"struct { f func(...int) }",
},
// {struct {
// x (interface {
// a(func(func(int) int) func(func(int)) int)
// b()
// })
// }{},
// "interface { reflectlite_test.a(func(func(int) int) func(func(int)) int); reflectlite_test.b() }",
// },
{struct {
x struct {
int32
int64
}
}{},
"struct { int32; int64 }",
},
}
var valueTests = []pair{
{new(int), "132"},
{new(int8), "8"},
{new(int16), "16"},
{new(int32), "32"},
{new(int64), "64"},
{new(uint), "132"},
{new(uint8), "8"},
{new(uint16), "16"},
{new(uint32), "32"},
{new(uint64), "64"},
{new(float32), "256.25"},
{new(float64), "512.125"},
{new(complex64), "532.125+10i"},
{new(complex128), "564.25+1i"},
{new(string), "stringy cheese"},
{new(bool), "true"},
{new(*int8), "*int8(0)"},
{new(**int8), "**int8(0)"},
{new([5]int32), "[5]int32{0, 0, 0, 0, 0}"},
{new(**integer), "**reflectlite_test.integer(0)"},
{new(map[string]int32), "map[string]int32{<can't iterate on maps>}"},
{new(chan<- string), "chan<- string"},
{new(func(a int8, b int32)), "func(int8, int32)(arg)"},
{new(struct {
c chan *int32
d float32
}),
"struct { c chan *int32; d float32 }{chan *int32, 0}",
},
{new(struct{ c func(chan *integer, *int8) }),
"struct { c func(chan *reflectlite_test.integer, *int8) }{func(chan *reflectlite_test.integer, *int8)(arg)}",
},
{new(struct {
a int8
b int32
}),
"struct { a int8; b int32 }{0, 0}",
},
{new(struct {
a int8
b int8
c int32
}),
"struct { a int8; b int8; c int32 }{0, 0, 0}",
},
}
func testType(t *testing.T, i int, typ Type, want string) {
s := TypeString(typ)
if s != want {
t.Errorf("#%d: have %#q, want %#q", i, s, want)
}
}
func testReflectType(t *testing.T, i int, typ Type, want string) {
s := TypeString(typ)
if s != want {
t.Errorf("#%d: have %#q, want %#q", i, s, want)
}
}
func TestTypes(t *testing.T) {
for i, tt := range typeTests {
testReflectType(t, i, Field(ValueOf(tt.i), 0).Type(), tt.s)
}
}
func TestSetValue(t *testing.T) {
for i, tt := range valueTests {
v := ValueOf(tt.i).Elem()
switch v.Kind() {
case abi.Int:
v.Set(ValueOf(int(132)))
case abi.Int8:
v.Set(ValueOf(int8(8)))
case abi.Int16:
v.Set(ValueOf(int16(16)))
case abi.Int32:
v.Set(ValueOf(int32(32)))
case abi.Int64:
v.Set(ValueOf(int64(64)))
case abi.Uint:
v.Set(ValueOf(uint(132)))
case abi.Uint8:
v.Set(ValueOf(uint8(8)))
case abi.Uint16:
v.Set(ValueOf(uint16(16)))
case abi.Uint32:
v.Set(ValueOf(uint32(32)))
case abi.Uint64:
v.Set(ValueOf(uint64(64)))
case abi.Float32:
v.Set(ValueOf(float32(256.25)))
case abi.Float64:
v.Set(ValueOf(512.125))
case abi.Complex64:
v.Set(ValueOf(complex64(532.125 + 10i)))
case abi.Complex128:
v.Set(ValueOf(complex128(564.25 + 1i)))
case abi.String:
v.Set(ValueOf("stringy cheese"))
case abi.Bool:
v.Set(ValueOf(true))
}
s := valueToString(v)
if s != tt.s {
t.Errorf("#%d: have %#q, want %#q", i, s, tt.s)
}
}
}
func TestCanSetField(t *testing.T) {
type embed struct{ x, X int }
type Embed struct{ x, X int }
type S1 struct {
embed
x, X int
}
type S2 struct {
*embed
x, X int
}
type S3 struct {
Embed
x, X int
}
type S4 struct {
*Embed
x, X int
}
type testCase struct {
index []int
canSet bool
}
tests := []struct {
val Value
cases []testCase
}{{
val: ValueOf(&S1{}),
cases: []testCase{
{[]int{0}, false},
{[]int{0, 0}, false},
{[]int{0, 1}, true},
{[]int{1}, false},
{[]int{2}, true},
},
}, {
val: ValueOf(&S2{embed: &embed{}}),
cases: []testCase{
{[]int{0}, false},
{[]int{0, 0}, false},
{[]int{0, 1}, true},
{[]int{1}, false},
{[]int{2}, true},
},
}, {
val: ValueOf(&S3{}),
cases: []testCase{
{[]int{0}, true},
{[]int{0, 0}, false},
{[]int{0, 1}, true},
{[]int{1}, false},
{[]int{2}, true},
},
}, {
val: ValueOf(&S4{Embed: &Embed{}}),
cases: []testCase{
{[]int{0}, true},
{[]int{0, 0}, false},
{[]int{0, 1}, true},
{[]int{1}, false},
{[]int{2}, true},
},
}}
for _, tt := range tests {
t.Run(tt.val.Type().Name(), func(t *testing.T) {
for _, tc := range tt.cases {
f := tt.val
for _, i := range tc.index {
if f.Kind() == Ptr {
f = f.Elem()
}
f = Field(f, i)
}
if got := f.CanSet(); got != tc.canSet {
t.Errorf("CanSet() = %v, want %v", got, tc.canSet)
}
}
})
}
}
var _i = 7
var valueToStringTests = []pair{
{123, "123"},
{123.5, "123.5"},
{byte(123), "123"},
{"abc", "abc"},
{T{123, 456.75, "hello", &_i}, "reflectlite_test.T{123, 456.75, hello, *int(&7)}"},
{new(chan *T), "*chan *reflectlite_test.T(&chan *reflectlite_test.T)"},
{[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
{&[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "*[10]int(&[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})"},
{[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
{&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "*[]int(&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})"},
}
func TestValueToString(t *testing.T) {
for i, test := range valueToStringTests {
s := valueToString(ValueOf(test.i))
if s != test.s {
t.Errorf("#%d: have %#q, want %#q", i, s, test.s)
}
}
}
func TestPtrSetNil(t *testing.T) {
var i int32 = 1234
ip := &i
vip := ValueOf(&ip)
vip.Elem().Set(Zero(vip.Elem().Type()))
if ip != nil {
t.Errorf("got non-nil (%d), want nil", *ip)
}
}
func TestMapSetNil(t *testing.T) {
m := make(map[string]int)
vm := ValueOf(&m)
vm.Elem().Set(Zero(vm.Elem().Type()))
if m != nil {
t.Errorf("got non-nil (%p), want nil", m)
}
}
func TestAll(t *testing.T) {
testType(t, 1, TypeOf((int8)(0)), "int8")
testType(t, 2, TypeOf((*int8)(nil)).Elem(), "int8")
typ := TypeOf((*struct {
c chan *int32
d float32
})(nil))
testType(t, 3, typ, "*struct { c chan *int32; d float32 }")
etyp := typ.Elem()
testType(t, 4, etyp, "struct { c chan *int32; d float32 }")
}
func TestInterfaceValue(t *testing.T) {
var inter struct {
E any
}
inter.E = 123.456
v1 := ValueOf(&inter)
v2 := Field(v1.Elem(), 0)
// assert(t, TypeString(v2.Type()), "interface {}")
v3 := v2.Elem()
assert(t, TypeString(v3.Type()), "float64")
i3 := ToInterface(v2)
if _, ok := i3.(float64); !ok {
t.Error("v2.Interface() did not return float64, got ", TypeOf(i3))
}
}
func TestFunctionValue(t *testing.T) {
var x any = func() {}
v := ValueOf(x)
if fmt.Sprint(ToInterface(v)) != fmt.Sprint(x) {
t.Fatalf("TestFunction returned wrong pointer")
}
assert(t, TypeString(v.Type()), "func()")
}
var appendTests = []struct {
orig, extra []int
}{
{make([]int, 2, 4), []int{22}},
{make([]int, 2, 4), []int{22, 33, 44}},
}
func sameInts(x, y []int) bool {
if len(x) != len(y) {
return false
}
for i, xx := range x {
if xx != y[i] {
return false
}
}
return true
}
func TestBigUnnamedStruct(t *testing.T) {
b := struct{ a, b, c, d int64 }{1, 2, 3, 4}
v := ValueOf(b)
b1 := ToInterface(v).(struct {
a, b, c, d int64
})
if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d {
t.Errorf("ValueOf(%v).Interface().(*Big) = %v", b, b1)
}
}
type big struct {
a, b, c, d, e int64
}
func TestBigStruct(t *testing.T) {
b := big{1, 2, 3, 4, 5}
v := ValueOf(b)
b1 := ToInterface(v).(big)
if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d || b1.e != b.e {
t.Errorf("ValueOf(%v).Interface().(big) = %v", b, b1)
}
}
type Basic struct {
x int
y float32
}
type NotBasic Basic
type DeepEqualTest struct {
a, b any
eq bool
}
// Simple functions for DeepEqual tests.
var (
fn1 func() // nil.
fn2 func() // nil.
fn3 = func() { fn1() } // Not nil.
)
type self struct{}
type Loop *Loop
type Loopy any
var loop1, loop2 Loop
var loopy1, loopy2 Loopy
func init() {
loop1 = &loop2
loop2 = &loop1
loopy1 = &loopy2
loopy2 = &loopy1
}
var typeOfTests = []DeepEqualTest{
// Equalities
{nil, nil, true},
{1, 1, true},
{int32(1), int32(1), true},
{0.5, 0.5, true},
{float32(0.5), float32(0.5), true},
{"hello", "hello", true},
{make([]int, 10), make([]int, 10), true},
{&[3]int{1, 2, 3}, &[3]int{1, 2, 3}, true},
{Basic{1, 0.5}, Basic{1, 0.5}, true},
{error(nil), error(nil), true},
{map[int]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, true},
{fn1, fn2, true},
// Inequalities
{1, 2, false},
{int32(1), int32(2), false},
{0.5, 0.6, false},
{float32(0.5), float32(0.6), false},
{"hello", "hey", false},
{make([]int, 10), make([]int, 11), false},
{&[3]int{1, 2, 3}, &[3]int{1, 2, 4}, false},
{Basic{1, 0.5}, Basic{1, 0.6}, false},
{Basic{1, 0}, Basic{2, 0}, false},
{map[int]string{1: "one", 3: "two"}, map[int]string{2: "two", 1: "one"}, false},
{map[int]string{1: "one", 2: "txo"}, map[int]string{2: "two", 1: "one"}, false},
{map[int]string{1: "one"}, map[int]string{2: "two", 1: "one"}, false},
{map[int]string{2: "two", 1: "one"}, map[int]string{1: "one"}, false},
{nil, 1, false},
{1, nil, false},
{fn1, fn3, false},
{fn3, fn3, false},
{[][]int{{1}}, [][]int{{2}}, false},
{math.NaN(), math.NaN(), false},
{&[1]float64{math.NaN()}, &[1]float64{math.NaN()}, false},
{&[1]float64{math.NaN()}, self{}, true},
{[]float64{math.NaN()}, []float64{math.NaN()}, false},
{[]float64{math.NaN()}, self{}, true},
{map[float64]float64{math.NaN(): 1}, map[float64]float64{1: 2}, false},
{map[float64]float64{math.NaN(): 1}, self{}, true},
// Nil vs empty: not the same.
{[]int{}, []int(nil), false},
{[]int{}, []int{}, true},
{[]int(nil), []int(nil), true},
{map[int]int{}, map[int]int(nil), false},
{map[int]int{}, map[int]int{}, true},
{map[int]int(nil), map[int]int(nil), true},
// Mismatched types
{1, 1.0, false},
{int32(1), int64(1), false},
{0.5, "hello", false},
{[]int{1, 2, 3}, [3]int{1, 2, 3}, false},
{&[3]any{1, 2, 4}, &[3]any{1, 2, "s"}, false},
{Basic{1, 0.5}, NotBasic{1, 0.5}, false},
{map[uint]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, false},
// Possible loops.
{&loop1, &loop1, true},
{&loop1, &loop2, true},
{&loopy1, &loopy1, true},
{&loopy1, &loopy2, true},
}
func TestTypeOf(t *testing.T) {
// Special case for nil
if typ := TypeOf(nil); typ != nil {
t.Errorf("expected nil type for nil value; got %v", typ)
}
for _, test := range typeOfTests {
v := ValueOf(test.a)
if !v.IsValid() {
continue
}
typ := TypeOf(test.a)
if typ != v.Type() {
t.Errorf("TypeOf(%v) = %v, but ValueOf(%v).Type() = %v", test.a, typ, test.a, v.Type())
}
}
}
func Nil(a any, t *testing.T) {
n := Field(ValueOf(a), 0)
if !n.IsNil() {
t.Errorf("%v should be nil", a)
}
}
func NotNil(a any, t *testing.T) {
n := Field(ValueOf(a), 0)
if n.IsNil() {
t.Errorf("value of type %v should not be nil", TypeString(ValueOf(a).Type()))
}
}
func TestIsNil(t *testing.T) {
// These implement IsNil.
// Wrap in extra struct to hide interface type.
doNil := []any{
struct{ x *int }{},
struct{ x any }{},
struct{ x map[string]int }{},
struct{ x func() bool }{},
struct{ x chan int }{},
struct{ x []string }{},
struct{ x unsafe.Pointer }{},
}
for _, ts := range doNil {
ty := TField(TypeOf(ts), 0)
v := Zero(ty)
v.IsNil() // panics if not okay to call
}
// Check the implementations
var pi struct {
x *int
}
Nil(pi, t)
pi.x = new(int)
NotNil(pi, t)
var si struct {
x []int
}
Nil(si, t)
si.x = make([]int, 10)
NotNil(si, t)
var ci struct {
x chan int
}
Nil(ci, t)
ci.x = make(chan int)
NotNil(ci, t)
var mi struct {
x map[int]int
}
Nil(mi, t)
mi.x = make(map[int]int)
NotNil(mi, t)
var ii struct {
x any
}
Nil(ii, t)
ii.x = 2
NotNil(ii, t)
var fi struct {
x func(t *testing.T)
}
Nil(fi, t)
fi.x = TestIsNil
NotNil(fi, t)
}
// Indirect returns the value that v points to.
// If v is a nil pointer, Indirect returns a zero Value.
// If v is not a pointer, Indirect returns v.
func Indirect(v Value) Value {
if v.Kind() != Ptr {
return v
}
return v.Elem()
}
func TestNilPtrValueSub(t *testing.T) {
var pi *int
if pv := ValueOf(pi); pv.Elem().IsValid() {
t.Error("ValueOf((*int)(nil)).Elem().IsValid()")
}
}
type Point struct {
x, y int
}
// This will be index 0.
func (p Point) AnotherMethod(scale int) int {
return -1
}
// This will be index 1.
func (p Point) Dist(scale int) int {
//println("Point.Dist", p.x, p.y, scale)
return p.x*p.x*scale + p.y*p.y*scale
}
// This will be index 2.
func (p Point) GCMethod(k int) int {
runtime.GC()
return k + p.x
}
// This will be index 3.
func (p Point) NoArgs() {
// Exercise no-argument/no-result paths.
}
// This will be index 4.
func (p Point) TotalDist(points ...Point) int {
tot := 0
for _, q := range points {
dx := q.x - p.x
dy := q.y - p.y
tot += dx*dx + dy*dy // Should call Sqrt, but it's just a test.
}
return tot
}
type D1 struct {
d int
}
type D2 struct {
d int
}
func TestImportPath(t *testing.T) {
tests := []struct {
t Type
path string
}{
{TypeOf(&base64.Encoding{}).Elem(), "encoding/base64"},
{TypeOf(int(0)), ""},
{TypeOf(int8(0)), ""},
{TypeOf(int16(0)), ""},
{TypeOf(int32(0)), ""},
{TypeOf(int64(0)), ""},
{TypeOf(uint(0)), ""},
{TypeOf(uint8(0)), ""},
{TypeOf(uint16(0)), ""},
{TypeOf(uint32(0)), ""},
{TypeOf(uint64(0)), ""},
{TypeOf(uintptr(0)), ""},
{TypeOf(float32(0)), ""},
{TypeOf(float64(0)), ""},
{TypeOf(complex64(0)), ""},
{TypeOf(complex128(0)), ""},
{TypeOf(byte(0)), ""},
{TypeOf(rune(0)), ""},
{TypeOf([]byte(nil)), ""},
{TypeOf([]rune(nil)), ""},
{TypeOf(string("")), ""},
{TypeOf((*any)(nil)).Elem(), ""},
{TypeOf((*byte)(nil)), ""},
{TypeOf((*rune)(nil)), ""},
{TypeOf((*int64)(nil)), ""},
{TypeOf(map[string]int{}), ""},
{TypeOf((*error)(nil)).Elem(), ""},
{TypeOf((*Point)(nil)), ""},
{TypeOf((*Point)(nil)).Elem(), "internal/reflectlite_test"},
}
for _, test := range tests {
if path := test.t.PkgPath(); path != test.path {
t.Errorf("%v.PkgPath() = %q, want %q", test.t, path, test.path)
}
}
}
func noAlloc(t *testing.T, n int, f func(int)) {
if testing.Short() {
t.Skip("skipping malloc count in short mode")
}
if runtime.GOMAXPROCS(0) > 1 {
t.Skip("skipping; GOMAXPROCS>1")
}
i := -1
allocs := testing.AllocsPerRun(n, func() {
f(i)
i++
})
if allocs > 0 {
t.Errorf("%d iterations: got %v mallocs, want 0", n, allocs)
}
}
func TestAllocations(t *testing.T) {
noAlloc(t, 100, func(j int) {
var i any
var v Value
i = []int{j, j, j}
v = ValueOf(i)
if v.Len() != 3 {
panic("wrong length")
}
})
noAlloc(t, 100, func(j int) {
var i any
var v Value
i = func(j int) int { return j }
v = ValueOf(i)
if ToInterface(v).(func(int) int)(j) != j {
panic("wrong result")
}
})
}
func TestSetPanic(t *testing.T) {
ok := func(f func()) { f() }
bad := shouldPanic
clear := func(v Value) { v.Set(Zero(v.Type())) }
type t0 struct {
W int
}
type t1 struct {
Y int
t0
}
type T2 struct {
Z int
namedT0 t0
}
type T struct {
X int
t1
T2
NamedT1 t1
NamedT2 T2
namedT1 t1
namedT2 T2
}
// not addressable
v := ValueOf(T{})
bad(func() { clear(Field(v, 0)) }) // .X
bad(func() { clear(Field(v, 1)) }) // .t1
bad(func() { clear(Field(Field(v, 1), 0)) }) // .t1.Y
bad(func() { clear(Field(Field(v, 1), 1)) }) // .t1.t0
bad(func() { clear(Field(Field(Field(v, 1), 1), 0)) }) // .t1.t0.W
bad(func() { clear(Field(v, 2)) }) // .T2
bad(func() { clear(Field(Field(v, 2), 0)) }) // .T2.Z
bad(func() { clear(Field(Field(v, 2), 1)) }) // .T2.namedT0
bad(func() { clear(Field(Field(Field(v, 2), 1), 0)) }) // .T2.namedT0.W
bad(func() { clear(Field(v, 3)) }) // .NamedT1
bad(func() { clear(Field(Field(v, 3), 0)) }) // .NamedT1.Y
bad(func() { clear(Field(Field(v, 3), 1)) }) // .NamedT1.t0
bad(func() { clear(Field(Field(Field(v, 3), 1), 0)) }) // .NamedT1.t0.W
bad(func() { clear(Field(v, 4)) }) // .NamedT2
bad(func() { clear(Field(Field(v, 4), 0)) }) // .NamedT2.Z
bad(func() { clear(Field(Field(v, 4), 1)) }) // .NamedT2.namedT0
bad(func() { clear(Field(Field(Field(v, 4), 1), 0)) }) // .NamedT2.namedT0.W
bad(func() { clear(Field(v, 5)) }) // .namedT1
bad(func() { clear(Field(Field(v, 5), 0)) }) // .namedT1.Y
bad(func() { clear(Field(Field(v, 5), 1)) }) // .namedT1.t0
bad(func() { clear(Field(Field(Field(v, 5), 1), 0)) }) // .namedT1.t0.W
bad(func() { clear(Field(v, 6)) }) // .namedT2
bad(func() { clear(Field(Field(v, 6), 0)) }) // .namedT2.Z
bad(func() { clear(Field(Field(v, 6), 1)) }) // .namedT2.namedT0
bad(func() { clear(Field(Field(Field(v, 6), 1), 0)) }) // .namedT2.namedT0.W
// addressable
v = ValueOf(&T{}).Elem()
ok(func() { clear(Field(v, 0)) }) // .X
bad(func() { clear(Field(v, 1)) }) // .t1
ok(func() { clear(Field(Field(v, 1), 0)) }) // .t1.Y
bad(func() { clear(Field(Field(v, 1), 1)) }) // .t1.t0
ok(func() { clear(Field(Field(Field(v, 1), 1), 0)) }) // .t1.t0.W
ok(func() { clear(Field(v, 2)) }) // .T2
ok(func() { clear(Field(Field(v, 2), 0)) }) // .T2.Z
bad(func() { clear(Field(Field(v, 2), 1)) }) // .T2.namedT0
bad(func() { clear(Field(Field(Field(v, 2), 1), 0)) }) // .T2.namedT0.W
ok(func() { clear(Field(v, 3)) }) // .NamedT1
ok(func() { clear(Field(Field(v, 3), 0)) }) // .NamedT1.Y
bad(func() { clear(Field(Field(v, 3), 1)) }) // .NamedT1.t0
ok(func() { clear(Field(Field(Field(v, 3), 1), 0)) }) // .NamedT1.t0.W
ok(func() { clear(Field(v, 4)) }) // .NamedT2
ok(func() { clear(Field(Field(v, 4), 0)) }) // .NamedT2.Z
bad(func() { clear(Field(Field(v, 4), 1)) }) // .NamedT2.namedT0
bad(func() { clear(Field(Field(Field(v, 4), 1), 0)) }) // .NamedT2.namedT0.W
bad(func() { clear(Field(v, 5)) }) // .namedT1
bad(func() { clear(Field(Field(v, 5), 0)) }) // .namedT1.Y
bad(func() { clear(Field(Field(v, 5), 1)) }) // .namedT1.t0
bad(func() { clear(Field(Field(Field(v, 5), 1), 0)) }) // .namedT1.t0.W
bad(func() { clear(Field(v, 6)) }) // .namedT2
bad(func() { clear(Field(Field(v, 6), 0)) }) // .namedT2.Z
bad(func() { clear(Field(Field(v, 6), 1)) }) // .namedT2.namedT0
bad(func() { clear(Field(Field(Field(v, 6), 1), 0)) }) // .namedT2.namedT0.W
}
func shouldPanic(f func()) {
defer func() {
if recover() == nil {
panic("did not panic")
}
}()
f()
}
type S struct {
i1 int64
i2 int64
}
func TestBigZero(t *testing.T) {
const size = 1 << 10
var v [size]byte
z := ToInterface(Zero(ValueOf(v).Type())).([size]byte)
for i := 0; i < size; i++ {
if z[i] != 0 {
t.Fatalf("Zero object not all zero, index %d", i)
}
}
}
func TestInvalid(t *testing.T) {
// Used to have inconsistency between IsValid() and Kind() != Invalid.
type T struct{ v any }
v := Field(ValueOf(T{}), 0)
if v.IsValid() != true || v.Kind() != Interface {
t.Errorf("field: IsValid=%v, Kind=%v, want true, Interface", v.IsValid(), v.Kind())
}
v = v.Elem()
if v.IsValid() != false || v.Kind() != abi.Invalid {
t.Errorf("field elem: IsValid=%v, Kind=%v, want false, Invalid", v.IsValid(), v.Kind())
}
}
type TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678 int
type nameTest struct {
v any
want string
}
type A struct{}
type B[T any] struct{}
var nameTests = []nameTest{
{(*int32)(nil), "int32"},
{(*D1)(nil), "D1"},
{(*[]D1)(nil), ""},
{(*chan D1)(nil), ""},
{(*func() D1)(nil), ""},
{(*<-chan D1)(nil), ""},
{(*chan<- D1)(nil), ""},
{(*any)(nil), ""},
{(*interface {
F()
})(nil), ""},
{(*TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678)(nil), "TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678"},
{(*B[A])(nil), "B[internal/reflectlite_test.A]"},
{(*B[B[A]])(nil), "B[internal/reflectlite_test.B[internal/reflectlite_test.A]]"},
}
func TestNames(t *testing.T) {
for _, test := range nameTests {
typ := TypeOf(test.v).Elem()
if got := typ.Name(); got != test.want {
t.Errorf("%v Name()=%q, want %q", typ, got, test.want)
}
}
}
// TestUnaddressableField tests that the reflect package will not allow
// a type from another package to be used as a named type with an
// unexported field.
//
// This ensures that unexported fields cannot be modified by other packages.
func TestUnaddressableField(t *testing.T) {
var b Buffer // type defined in reflect, a different package
var localBuffer struct {
buf []byte
}
lv := ValueOf(&localBuffer).Elem()
rv := ValueOf(b)
shouldPanic(func() {
lv.Set(rv)
})
}
type Tint int
type Tint2 = Tint
type Talias1 struct {
byte
uint8
int
int32
rune
}
type Talias2 struct {
Tint
Tint2
}
func TestAliasNames(t *testing.T) {
t1 := Talias1{byte: 1, uint8: 2, int: 3, int32: 4, rune: 5}
out := fmt.Sprintf("%#v", t1)
want := "reflectlite_test.Talias1{byte:0x1, uint8:0x2, int:3, int32:4, rune:5}"
if out != want {
t.Errorf("Talias1 print:\nhave: %s\nwant: %s", out, want)
}
t2 := Talias2{Tint: 1, Tint2: 2}
out = fmt.Sprintf("%#v", t2)
want = "reflectlite_test.Talias2{Tint:1, Tint2:2}"
if out != want {
t.Errorf("Talias2 print:\nhave: %s\nwant: %s", out, want)
}
}
| go/src/internal/reflectlite/all_test.go/0 | {
"file_path": "go/src/internal/reflectlite/all_test.go",
"repo_id": "go",
"token_count": 11960
} | 288 |
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
#include "go_asm.h"
#include "textflag.h"
#include "funcdata.h"
// bool armcas(int32 *val, int32 old, int32 new)
// Atomically:
// if(*val == old){
// *val = new;
// return 1;
// }else
// return 0;
//
// To implement ·cas in sys_$GOOS_arm.s
// using the native instructions, use:
//
// TEXT ·cas(SB),NOSPLIT,$0
// B ·armcas(SB)
//
TEXT ·armcas(SB),NOSPLIT,$0-13
MOVW ptr+0(FP), R1
MOVW old+4(FP), R2
MOVW new+8(FP), R3
casl:
LDREX (R1), R0
CMP R0, R2
BNE casfail
#ifndef GOARM_7
MOVB internal∕cpu·ARM+const_offsetARMHasV7Atomics(SB), R11
CMP $0, R11
BEQ 2(PC)
#endif
DMB MB_ISHST
STREX R3, (R1), R0
CMP $0, R0
BNE casl
MOVW $1, R0
#ifndef GOARM_7
CMP $0, R11
BEQ 2(PC)
#endif
DMB MB_ISH
MOVB R0, ret+12(FP)
RET
casfail:
MOVW $0, R0
MOVB R0, ret+12(FP)
RET
// stubs
TEXT ·Loadp(SB),NOSPLIT|NOFRAME,$0-8
B ·Load(SB)
TEXT ·LoadAcq(SB),NOSPLIT|NOFRAME,$0-8
B ·Load(SB)
TEXT ·LoadAcquintptr(SB),NOSPLIT|NOFRAME,$0-8
B ·Load(SB)
TEXT ·Casint32(SB),NOSPLIT,$0-13
B ·Cas(SB)
TEXT ·Casint64(SB),NOSPLIT,$-4-21
B ·Cas64(SB)
TEXT ·Casuintptr(SB),NOSPLIT,$0-13
B ·Cas(SB)
TEXT ·Casp1(SB),NOSPLIT,$0-13
B ·Cas(SB)
TEXT ·CasRel(SB),NOSPLIT,$0-13
B ·Cas(SB)
TEXT ·Loadint32(SB),NOSPLIT,$0-8
B ·Load(SB)
TEXT ·Loadint64(SB),NOSPLIT,$-4-12
B ·Load64(SB)
TEXT ·Loaduintptr(SB),NOSPLIT,$0-8
B ·Load(SB)
TEXT ·Loaduint(SB),NOSPLIT,$0-8
B ·Load(SB)
TEXT ·Storeint32(SB),NOSPLIT,$0-8
B ·Store(SB)
TEXT ·Storeint64(SB),NOSPLIT,$0-12
B ·Store64(SB)
TEXT ·Storeuintptr(SB),NOSPLIT,$0-8
B ·Store(SB)
TEXT ·StorepNoWB(SB),NOSPLIT,$0-8
B ·Store(SB)
TEXT ·StoreRel(SB),NOSPLIT,$0-8
B ·Store(SB)
TEXT ·StoreReluintptr(SB),NOSPLIT,$0-8
B ·Store(SB)
TEXT ·Xaddint32(SB),NOSPLIT,$0-12
B ·Xadd(SB)
TEXT ·Xaddint64(SB),NOSPLIT,$-4-20
B ·Xadd64(SB)
TEXT ·Xadduintptr(SB),NOSPLIT,$0-12
B ·Xadd(SB)
TEXT ·Xchgint32(SB),NOSPLIT,$0-12
B ·Xchg(SB)
TEXT ·Xchgint64(SB),NOSPLIT,$-4-20
B ·Xchg64(SB)
// 64-bit atomics
// The native ARM implementations use LDREXD/STREXD, which are
// available on ARMv6k or later. We use them only on ARMv7.
// On older ARM, we use Go implementations which simulate 64-bit
// atomics with locks.
TEXT armCas64<>(SB),NOSPLIT,$0-21
// addr is already in R1
MOVW old_lo+4(FP), R2
MOVW old_hi+8(FP), R3
MOVW new_lo+12(FP), R4
MOVW new_hi+16(FP), R5
cas64loop:
LDREXD (R1), R6 // loads R6 and R7
CMP R2, R6
BNE cas64fail
CMP R3, R7
BNE cas64fail
DMB MB_ISHST
STREXD R4, (R1), R0 // stores R4 and R5
CMP $0, R0
BNE cas64loop
MOVW $1, R0
DMB MB_ISH
MOVBU R0, swapped+20(FP)
RET
cas64fail:
MOVW $0, R0
MOVBU R0, swapped+20(FP)
RET
TEXT armXadd64<>(SB),NOSPLIT,$0-20
// addr is already in R1
MOVW delta_lo+4(FP), R2
MOVW delta_hi+8(FP), R3
add64loop:
LDREXD (R1), R4 // loads R4 and R5
ADD.S R2, R4
ADC R3, R5
DMB MB_ISHST
STREXD R4, (R1), R0 // stores R4 and R5
CMP $0, R0
BNE add64loop
DMB MB_ISH
MOVW R4, new_lo+12(FP)
MOVW R5, new_hi+16(FP)
RET
TEXT armXchg64<>(SB),NOSPLIT,$0-20
// addr is already in R1
MOVW new_lo+4(FP), R2
MOVW new_hi+8(FP), R3
swap64loop:
LDREXD (R1), R4 // loads R4 and R5
DMB MB_ISHST
STREXD R2, (R1), R0 // stores R2 and R3
CMP $0, R0
BNE swap64loop
DMB MB_ISH
MOVW R4, old_lo+12(FP)
MOVW R5, old_hi+16(FP)
RET
TEXT armLoad64<>(SB),NOSPLIT,$0-12
// addr is already in R1
LDREXD (R1), R2 // loads R2 and R3
DMB MB_ISH
MOVW R2, val_lo+4(FP)
MOVW R3, val_hi+8(FP)
RET
TEXT armStore64<>(SB),NOSPLIT,$0-12
// addr is already in R1
MOVW val_lo+4(FP), R2
MOVW val_hi+8(FP), R3
store64loop:
LDREXD (R1), R4 // loads R4 and R5
DMB MB_ISHST
STREXD R2, (R1), R0 // stores R2 and R3
CMP $0, R0
BNE store64loop
DMB MB_ISH
RET
// The following functions all panic if their address argument isn't
// 8-byte aligned. Since we're calling back into Go code to do this,
// we have to cooperate with stack unwinding. In the normal case, the
// functions tail-call into the appropriate implementation, which
// means they must not open a frame. Hence, when they go down the
// panic path, at that point they push the LR to create a real frame
// (they don't need to pop it because panic won't return; however, we
// do need to set the SP delta back).
// Check if R1 is 8-byte aligned, panic if not.
// Clobbers R2.
#define CHECK_ALIGN \
AND.S $7, R1, R2 \
BEQ 4(PC) \
MOVW.W R14, -4(R13) /* prepare a real frame */ \
BL ·panicUnaligned(SB) \
ADD $4, R13 /* compensate SP delta */
TEXT ·Cas64(SB),NOSPLIT,$-4-21
NO_LOCAL_POINTERS
MOVW addr+0(FP), R1
CHECK_ALIGN
#ifndef GOARM_7
MOVB internal∕cpu·ARM+const_offsetARMHasV7Atomics(SB), R11
CMP $1, R11
BEQ 2(PC)
JMP ·goCas64(SB)
#endif
JMP armCas64<>(SB)
TEXT ·Xadd64(SB),NOSPLIT,$-4-20
NO_LOCAL_POINTERS
MOVW addr+0(FP), R1
CHECK_ALIGN
#ifndef GOARM_7
MOVB internal∕cpu·ARM+const_offsetARMHasV7Atomics(SB), R11
CMP $1, R11
BEQ 2(PC)
JMP ·goXadd64(SB)
#endif
JMP armXadd64<>(SB)
TEXT ·Xchg64(SB),NOSPLIT,$-4-20
NO_LOCAL_POINTERS
MOVW addr+0(FP), R1
CHECK_ALIGN
#ifndef GOARM_7
MOVB internal∕cpu·ARM+const_offsetARMHasV7Atomics(SB), R11
CMP $1, R11
BEQ 2(PC)
JMP ·goXchg64(SB)
#endif
JMP armXchg64<>(SB)
TEXT ·Load64(SB),NOSPLIT,$-4-12
NO_LOCAL_POINTERS
MOVW addr+0(FP), R1
CHECK_ALIGN
#ifndef GOARM_7
MOVB internal∕cpu·ARM+const_offsetARMHasV7Atomics(SB), R11
CMP $1, R11
BEQ 2(PC)
JMP ·goLoad64(SB)
#endif
JMP armLoad64<>(SB)
TEXT ·Store64(SB),NOSPLIT,$-4-12
NO_LOCAL_POINTERS
MOVW addr+0(FP), R1
CHECK_ALIGN
#ifndef GOARM_7
MOVB internal∕cpu·ARM+const_offsetARMHasV7Atomics(SB), R11
CMP $1, R11
BEQ 2(PC)
JMP ·goStore64(SB)
#endif
JMP armStore64<>(SB)
| go/src/internal/runtime/atomic/atomic_arm.s/0 | {
"file_path": "go/src/internal/runtime/atomic/atomic_arm.s",
"repo_id": "go",
"token_count": 3057
} | 289 |
// 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.
// TODO(neelance): implement with actual atomic operations as soon as threads are available
// See https://github.com/WebAssembly/design/issues/1073
// Export some functions via linkname to assembly in sync/atomic.
//
//go:linkname Load
//go:linkname Loadp
//go:linkname Load64
//go:linkname Loadint32
//go:linkname Loadint64
//go:linkname Loaduintptr
//go:linkname LoadAcquintptr
//go:linkname Xadd
//go:linkname Xaddint32
//go:linkname Xaddint64
//go:linkname Xadd64
//go:linkname Xadduintptr
//go:linkname Xchg
//go:linkname Xchg64
//go:linkname Xchgint32
//go:linkname Xchgint64
//go:linkname Xchguintptr
//go:linkname Cas
//go:linkname Cas64
//go:linkname Casint32
//go:linkname Casint64
//go:linkname Casuintptr
//go:linkname Store
//go:linkname Store64
//go:linkname Storeint32
//go:linkname Storeint64
//go:linkname Storeuintptr
//go:linkname StoreReluintptr
package atomic
import "unsafe"
//go:nosplit
//go:noinline
func Load(ptr *uint32) uint32 {
return *ptr
}
//go:nosplit
//go:noinline
func Loadp(ptr unsafe.Pointer) unsafe.Pointer {
return *(*unsafe.Pointer)(ptr)
}
//go:nosplit
//go:noinline
func LoadAcq(ptr *uint32) uint32 {
return *ptr
}
//go:nosplit
//go:noinline
func LoadAcq64(ptr *uint64) uint64 {
return *ptr
}
//go:nosplit
//go:noinline
func LoadAcquintptr(ptr *uintptr) uintptr {
return *ptr
}
//go:nosplit
//go:noinline
func Load8(ptr *uint8) uint8 {
return *ptr
}
//go:nosplit
//go:noinline
func Load64(ptr *uint64) uint64 {
return *ptr
}
//go:nosplit
//go:noinline
func Xadd(ptr *uint32, delta int32) uint32 {
new := *ptr + uint32(delta)
*ptr = new
return new
}
//go:nosplit
//go:noinline
func Xadd64(ptr *uint64, delta int64) uint64 {
new := *ptr + uint64(delta)
*ptr = new
return new
}
//go:nosplit
//go:noinline
func Xadduintptr(ptr *uintptr, delta uintptr) uintptr {
new := *ptr + delta
*ptr = new
return new
}
//go:nosplit
//go:noinline
func Xchg(ptr *uint32, new uint32) uint32 {
old := *ptr
*ptr = new
return old
}
//go:nosplit
//go:noinline
func Xchg64(ptr *uint64, new uint64) uint64 {
old := *ptr
*ptr = new
return old
}
//go:nosplit
//go:noinline
func Xchgint32(ptr *int32, new int32) int32 {
old := *ptr
*ptr = new
return old
}
//go:nosplit
//go:noinline
func Xchgint64(ptr *int64, new int64) int64 {
old := *ptr
*ptr = new
return old
}
//go:nosplit
//go:noinline
func Xchguintptr(ptr *uintptr, new uintptr) uintptr {
old := *ptr
*ptr = new
return old
}
//go:nosplit
//go:noinline
func And8(ptr *uint8, val uint8) {
*ptr = *ptr & val
}
//go:nosplit
//go:noinline
func Or8(ptr *uint8, val uint8) {
*ptr = *ptr | val
}
// NOTE: Do not add atomicxor8 (XOR is not idempotent).
//go:nosplit
//go:noinline
func And(ptr *uint32, val uint32) {
*ptr = *ptr & val
}
//go:nosplit
//go:noinline
func Or(ptr *uint32, val uint32) {
*ptr = *ptr | val
}
//go:nosplit
//go:noinline
func Cas64(ptr *uint64, old, new uint64) bool {
if *ptr == old {
*ptr = new
return true
}
return false
}
//go:nosplit
//go:noinline
func Store(ptr *uint32, val uint32) {
*ptr = val
}
//go:nosplit
//go:noinline
func StoreRel(ptr *uint32, val uint32) {
*ptr = val
}
//go:nosplit
//go:noinline
func StoreRel64(ptr *uint64, val uint64) {
*ptr = val
}
//go:nosplit
//go:noinline
func StoreReluintptr(ptr *uintptr, val uintptr) {
*ptr = val
}
//go:nosplit
//go:noinline
func Store8(ptr *uint8, val uint8) {
*ptr = val
}
//go:nosplit
//go:noinline
func Store64(ptr *uint64, val uint64) {
*ptr = val
}
// StorepNoWB performs *ptr = val atomically and without a write
// barrier.
//
// NO go:noescape annotation; see atomic_pointer.go.
func StorepNoWB(ptr unsafe.Pointer, val unsafe.Pointer)
//go:nosplit
//go:noinline
func Casint32(ptr *int32, old, new int32) bool {
if *ptr == old {
*ptr = new
return true
}
return false
}
//go:nosplit
//go:noinline
func Casint64(ptr *int64, old, new int64) bool {
if *ptr == old {
*ptr = new
return true
}
return false
}
//go:nosplit
//go:noinline
func Cas(ptr *uint32, old, new uint32) bool {
if *ptr == old {
*ptr = new
return true
}
return false
}
//go:nosplit
//go:noinline
func Casp1(ptr *unsafe.Pointer, old, new unsafe.Pointer) bool {
if *ptr == old {
*ptr = new
return true
}
return false
}
//go:nosplit
//go:noinline
func Casuintptr(ptr *uintptr, old, new uintptr) bool {
if *ptr == old {
*ptr = new
return true
}
return false
}
//go:nosplit
//go:noinline
func CasRel(ptr *uint32, old, new uint32) bool {
if *ptr == old {
*ptr = new
return true
}
return false
}
//go:nosplit
//go:noinline
func Storeint32(ptr *int32, new int32) {
*ptr = new
}
//go:nosplit
//go:noinline
func Storeint64(ptr *int64, new int64) {
*ptr = new
}
//go:nosplit
//go:noinline
func Storeuintptr(ptr *uintptr, new uintptr) {
*ptr = new
}
//go:nosplit
//go:noinline
func Loaduintptr(ptr *uintptr) uintptr {
return *ptr
}
//go:nosplit
//go:noinline
func Loaduint(ptr *uint) uint {
return *ptr
}
//go:nosplit
//go:noinline
func Loadint32(ptr *int32) int32 {
return *ptr
}
//go:nosplit
//go:noinline
func Loadint64(ptr *int64) int64 {
return *ptr
}
//go:nosplit
//go:noinline
func Xaddint32(ptr *int32, delta int32) int32 {
new := *ptr + delta
*ptr = new
return new
}
//go:nosplit
//go:noinline
func Xaddint64(ptr *int64, delta int64) int64 {
new := *ptr + delta
*ptr = new
return new
}
| go/src/internal/runtime/atomic/atomic_wasm.go/0 | {
"file_path": "go/src/internal/runtime/atomic/atomic_wasm.go",
"repo_id": "go",
"token_count": 2297
} | 290 |
// Copyright 2016 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 sys
// Copied from math/bits to avoid dependence.
var deBruijn32tab = [32]byte{
0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9,
}
const deBruijn32 = 0x077CB531
var deBruijn64tab = [64]byte{
0, 1, 56, 2, 57, 49, 28, 3, 61, 58, 42, 50, 38, 29, 17, 4,
62, 47, 59, 36, 45, 43, 51, 22, 53, 39, 33, 30, 24, 18, 12, 5,
63, 55, 48, 27, 60, 41, 37, 16, 46, 35, 44, 21, 52, 32, 23, 11,
54, 26, 40, 15, 34, 20, 31, 10, 25, 14, 19, 9, 13, 8, 7, 6,
}
const deBruijn64 = 0x03f79d71b4ca8b09
const ntz8tab = "" +
"\x08\x00\x01\x00\x02\x00\x01\x00\x03\x00\x01\x00\x02\x00\x01\x00" +
"\x04\x00\x01\x00\x02\x00\x01\x00\x03\x00\x01\x00\x02\x00\x01\x00" +
"\x05\x00\x01\x00\x02\x00\x01\x00\x03\x00\x01\x00\x02\x00\x01\x00" +
"\x04\x00\x01\x00\x02\x00\x01\x00\x03\x00\x01\x00\x02\x00\x01\x00" +
"\x06\x00\x01\x00\x02\x00\x01\x00\x03\x00\x01\x00\x02\x00\x01\x00" +
"\x04\x00\x01\x00\x02\x00\x01\x00\x03\x00\x01\x00\x02\x00\x01\x00" +
"\x05\x00\x01\x00\x02\x00\x01\x00\x03\x00\x01\x00\x02\x00\x01\x00" +
"\x04\x00\x01\x00\x02\x00\x01\x00\x03\x00\x01\x00\x02\x00\x01\x00" +
"\x07\x00\x01\x00\x02\x00\x01\x00\x03\x00\x01\x00\x02\x00\x01\x00" +
"\x04\x00\x01\x00\x02\x00\x01\x00\x03\x00\x01\x00\x02\x00\x01\x00" +
"\x05\x00\x01\x00\x02\x00\x01\x00\x03\x00\x01\x00\x02\x00\x01\x00" +
"\x04\x00\x01\x00\x02\x00\x01\x00\x03\x00\x01\x00\x02\x00\x01\x00" +
"\x06\x00\x01\x00\x02\x00\x01\x00\x03\x00\x01\x00\x02\x00\x01\x00" +
"\x04\x00\x01\x00\x02\x00\x01\x00\x03\x00\x01\x00\x02\x00\x01\x00" +
"\x05\x00\x01\x00\x02\x00\x01\x00\x03\x00\x01\x00\x02\x00\x01\x00" +
"\x04\x00\x01\x00\x02\x00\x01\x00\x03\x00\x01\x00\x02\x00\x01\x00"
// TrailingZeros32 returns the number of trailing zero bits in x; the result is 32 for x == 0.
func TrailingZeros32(x uint32) int {
if x == 0 {
return 32
}
// see comment in TrailingZeros64
return int(deBruijn32tab[(x&-x)*deBruijn32>>(32-5)])
}
// TrailingZeros64 returns the number of trailing zero bits in x; the result is 64 for x == 0.
func TrailingZeros64(x uint64) int {
if x == 0 {
return 64
}
// If popcount is fast, replace code below with return popcount(^x & (x - 1)).
//
// x & -x leaves only the right-most bit set in the word. Let k be the
// index of that bit. Since only a single bit is set, the value is two
// to the power of k. Multiplying by a power of two is equivalent to
// left shifting, in this case by k bits. The de Bruijn (64 bit) constant
// is such that all six bit, consecutive substrings are distinct.
// Therefore, if we have a left shifted version of this constant we can
// find by how many bits it was shifted by looking at which six bit
// substring ended up at the top of the word.
// (Knuth, volume 4, section 7.3.1)
return int(deBruijn64tab[(x&-x)*deBruijn64>>(64-6)])
}
// TrailingZeros8 returns the number of trailing zero bits in x; the result is 8 for x == 0.
func TrailingZeros8(x uint8) int {
return int(ntz8tab[x])
}
const len8tab = "" +
"\x00\x01\x02\x02\x03\x03\x03\x03\x04\x04\x04\x04\x04\x04\x04\x04" +
"\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05" +
"\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06" +
"\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06" +
"\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07" +
"\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07" +
"\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07" +
"\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07" +
"\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08" +
"\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08" +
"\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08" +
"\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08" +
"\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08" +
"\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08" +
"\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08" +
"\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08"
// Len64 returns the minimum number of bits required to represent x; the result is 0 for x == 0.
//
// nosplit because this is used in src/runtime/histogram.go, which make run in sensitive contexts.
//
//go:nosplit
func Len64(x uint64) (n int) {
if x >= 1<<32 {
x >>= 32
n = 32
}
if x >= 1<<16 {
x >>= 16
n += 16
}
if x >= 1<<8 {
x >>= 8
n += 8
}
return n + int(len8tab[x])
}
// --- OnesCount ---
const m0 = 0x5555555555555555 // 01010101 ...
const m1 = 0x3333333333333333 // 00110011 ...
const m2 = 0x0f0f0f0f0f0f0f0f // 00001111 ...
// OnesCount64 returns the number of one bits ("population count") in x.
func OnesCount64(x uint64) int {
// Implementation: Parallel summing of adjacent bits.
// See "Hacker's Delight", Chap. 5: Counting Bits.
// The following pattern shows the general approach:
//
// x = x>>1&(m0&m) + x&(m0&m)
// x = x>>2&(m1&m) + x&(m1&m)
// x = x>>4&(m2&m) + x&(m2&m)
// x = x>>8&(m3&m) + x&(m3&m)
// x = x>>16&(m4&m) + x&(m4&m)
// x = x>>32&(m5&m) + x&(m5&m)
// return int(x)
//
// Masking (& operations) can be left away when there's no
// danger that a field's sum will carry over into the next
// field: Since the result cannot be > 64, 8 bits is enough
// and we can ignore the masks for the shifts by 8 and up.
// Per "Hacker's Delight", the first line can be simplified
// more, but it saves at best one instruction, so we leave
// it alone for clarity.
const m = 1<<64 - 1
x = x>>1&(m0&m) + x&(m0&m)
x = x>>2&(m1&m) + x&(m1&m)
x = (x>>4 + x) & (m2 & m)
x += x >> 8
x += x >> 16
x += x >> 32
return int(x) & (1<<7 - 1)
}
// LeadingZeros64 returns the number of leading zero bits in x; the result is 64 for x == 0.
func LeadingZeros64(x uint64) int { return 64 - Len64(x) }
// LeadingZeros8 returns the number of leading zero bits in x; the result is 8 for x == 0.
func LeadingZeros8(x uint8) int { return 8 - Len8(x) }
// Len8 returns the minimum number of bits required to represent x; the result is 0 for x == 0.
func Len8(x uint8) int {
return int(len8tab[x])
}
// Bswap64 returns its input with byte order reversed
// 0x0102030405060708 -> 0x0807060504030201
func Bswap64(x uint64) uint64 {
c8 := uint64(0x00ff00ff00ff00ff)
a := x >> 8 & c8
b := (x & c8) << 8
x = a | b
c16 := uint64(0x0000ffff0000ffff)
a = x >> 16 & c16
b = (x & c16) << 16
x = a | b
c32 := uint64(0x00000000ffffffff)
a = x >> 32 & c32
b = (x & c32) << 32
x = a | b
return x
}
// Bswap32 returns its input with byte order reversed
// 0x01020304 -> 0x04030201
func Bswap32(x uint32) uint32 {
c8 := uint32(0x00ff00ff)
a := x >> 8 & c8
b := (x & c8) << 8
x = a | b
c16 := uint32(0x0000ffff)
a = x >> 16 & c16
b = (x & c16) << 16
x = a | b
return x
}
// Prefetch prefetches data from memory addr to cache
//
// AMD64: Produce PREFETCHT0 instruction
//
// ARM64: Produce PRFM instruction with PLDL1KEEP option
func Prefetch(addr uintptr) {}
// PrefetchStreamed prefetches data from memory addr, with a hint that this data is being streamed.
// That is, it is likely to be accessed very soon, but only once. If possible, this will avoid polluting the cache.
//
// AMD64: Produce PREFETCHNTA instruction
//
// ARM64: Produce PRFM instruction with PLDL1STRM option
func PrefetchStreamed(addr uintptr) {}
| go/src/internal/runtime/sys/intrinsics.go/0 | {
"file_path": "go/src/internal/runtime/sys/intrinsics.go",
"repo_id": "go",
"token_count": 3811
} | 291 |
// Copyright 2020 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 !windows
package execenv
import "syscall"
// Default will return the default environment
// variables based on the process attributes
// provided.
//
// Defaults to syscall.Environ() on all platforms
// other than Windows.
func Default(sys *syscall.SysProcAttr) ([]string, error) {
return syscall.Environ(), nil
}
| go/src/internal/syscall/execenv/execenv_default.go/0 | {
"file_path": "go/src/internal/syscall/execenv/execenv_default.go",
"repo_id": "go",
"token_count": 139
} | 292 |
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package unix
import "syscall"
func PosixFallocate(fd int, off int64, size int64) error {
// If successful, posix_fallocate() returns zero. It returns an error on failure, without
// setting errno. See https://man.freebsd.org/cgi/man.cgi?query=posix_fallocate&sektion=2&n=1
r1, _, _ := syscall.Syscall6(posixFallocateTrap, uintptr(fd), uintptr(off), uintptr(off>>32), uintptr(size), uintptr(size>>32), 0)
if r1 != 0 {
return syscall.Errno(r1)
}
return nil
}
| go/src/internal/syscall/unix/fallocate_freebsd_386.go/0 | {
"file_path": "go/src/internal/syscall/unix/fallocate_freebsd_386.go",
"repo_id": "go",
"token_count": 225
} | 293 |
// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package windows
import (
"errors"
"sync"
"syscall"
"unsafe"
)
// https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/ns-wdm-_osversioninfow
type _OSVERSIONINFOW struct {
osVersionInfoSize uint32
majorVersion uint32
minorVersion uint32
buildNumber uint32
platformId uint32
csdVersion [128]uint16
}
// According to documentation, RtlGetVersion function always succeeds.
//sys rtlGetVersion(info *_OSVERSIONINFOW) = ntdll.RtlGetVersion
// version retrieves the major, minor, and build version numbers
// of the current Windows OS from the RtlGetVersion API.
func version() (major, minor, build uint32) {
info := _OSVERSIONINFOW{}
info.osVersionInfoSize = uint32(unsafe.Sizeof(info))
rtlGetVersion(&info)
return info.majorVersion, info.minorVersion, info.buildNumber
}
var (
supportTCPKeepAliveIdle bool
supportTCPKeepAliveInterval bool
supportTCPKeepAliveCount bool
)
var initTCPKeepAlive = sync.OnceFunc(func() {
s, err := WSASocket(syscall.AF_INET, syscall.SOCK_STREAM, syscall.IPPROTO_TCP, nil, 0, WSA_FLAG_NO_HANDLE_INHERIT)
if err != nil {
// Fallback to checking the Windows version.
major, _, build := version()
supportTCPKeepAliveIdle = major >= 10 && build >= 16299
supportTCPKeepAliveInterval = major >= 10 && build >= 16299
supportTCPKeepAliveCount = major >= 10 && build >= 15063
return
}
defer syscall.Closesocket(s)
var optSupported = func(opt int) bool {
err := syscall.SetsockoptInt(s, syscall.IPPROTO_TCP, opt, 1)
return !errors.Is(err, syscall.WSAENOPROTOOPT)
}
supportTCPKeepAliveIdle = optSupported(TCP_KEEPIDLE)
supportTCPKeepAliveInterval = optSupported(TCP_KEEPINTVL)
supportTCPKeepAliveCount = optSupported(TCP_KEEPCNT)
})
// SupportTCPKeepAliveInterval indicates whether TCP_KEEPIDLE is supported.
// The minimal requirement is Windows 10.0.16299.
func SupportTCPKeepAliveIdle() bool {
initTCPKeepAlive()
return supportTCPKeepAliveIdle
}
// SupportTCPKeepAliveInterval indicates whether TCP_KEEPINTVL is supported.
// The minimal requirement is Windows 10.0.16299.
func SupportTCPKeepAliveInterval() bool {
initTCPKeepAlive()
return supportTCPKeepAliveInterval
}
// SupportTCPKeepAliveCount indicates whether TCP_KEEPCNT is supported.
// supports TCP_KEEPCNT.
// The minimal requirement is Windows 10.0.15063.
func SupportTCPKeepAliveCount() bool {
initTCPKeepAlive()
return supportTCPKeepAliveCount
}
// SupportTCPInitialRTONoSYNRetransmissions indicates whether the current
// Windows version supports the TCP_INITIAL_RTO_NO_SYN_RETRANSMISSIONS.
// The minimal requirement is Windows 10.0.16299.
var SupportTCPInitialRTONoSYNRetransmissions = sync.OnceValue(func() bool {
major, _, build := version()
return major >= 10 && build >= 16299
})
// SupportUnixSocket indicates whether the current Windows version supports
// Unix Domain Sockets.
// The minimal requirement is Windows 10.0.17063.
var SupportUnixSocket = sync.OnceValue(func() bool {
var size uint32
// First call to get the required buffer size in bytes.
// Ignore the error, it will always fail.
_, _ = syscall.WSAEnumProtocols(nil, nil, &size)
n := int32(size) / int32(unsafe.Sizeof(syscall.WSAProtocolInfo{}))
// Second call to get the actual protocols.
buf := make([]syscall.WSAProtocolInfo, n)
n, err := syscall.WSAEnumProtocols(nil, &buf[0], &size)
if err != nil {
return false
}
for i := int32(0); i < n; i++ {
if buf[i].AddressFamily == syscall.AF_UNIX {
return true
}
}
return false
})
| go/src/internal/syscall/windows/version_windows.go/0 | {
"file_path": "go/src/internal/syscall/windows/version_windows.go",
"repo_id": "go",
"token_count": 1307
} | 294 |
// Copyright 2021 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build unix
package testenv
import (
"errors"
"io/fs"
"syscall"
)
// Sigquit is the signal to send to kill a hanging subprocess.
// Send SIGQUIT to get a stack trace.
var Sigquit = syscall.SIGQUIT
func syscallIsNotSupported(err error) bool {
if err == nil {
return false
}
var errno syscall.Errno
if errors.As(err, &errno) {
switch errno {
case syscall.EPERM, syscall.EROFS:
// User lacks permission: either the call requires root permission and the
// user is not root, or the call is denied by a container security policy.
return true
case syscall.EINVAL:
// Some containers return EINVAL instead of EPERM if a system call is
// denied by security policy.
return true
}
}
if errors.Is(err, fs.ErrPermission) || errors.Is(err, errors.ErrUnsupported) {
return true
}
return false
}
| go/src/internal/testenv/testenv_unix.go/0 | {
"file_path": "go/src/internal/testenv/testenv_unix.go",
"repo_id": "go",
"token_count": 346
} | 295 |
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package trace
import "testing"
func TestPanicEvent(t *testing.T) {
// Use a sync event for this because it doesn't have any extra metadata.
ev := syncEvent(nil, 0)
mustPanic(t, func() {
_ = ev.Range()
})
mustPanic(t, func() {
_ = ev.Metric()
})
mustPanic(t, func() {
_ = ev.Log()
})
mustPanic(t, func() {
_ = ev.Task()
})
mustPanic(t, func() {
_ = ev.Region()
})
mustPanic(t, func() {
_ = ev.Label()
})
mustPanic(t, func() {
_ = ev.RangeAttributes()
})
}
func mustPanic(t *testing.T, f func()) {
defer func() {
if r := recover(); r == nil {
t.Fatal("failed to panic")
}
}()
f()
}
| go/src/internal/trace/event_test.go/0 | {
"file_path": "go/src/internal/trace/event_test.go",
"repo_id": "go",
"token_count": 323
} | 296 |
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package raw
import (
"fmt"
"io"
"internal/trace/version"
)
// TextWriter emits the text format of a trace.
type TextWriter struct {
w io.Writer
v version.Version
}
// NewTextWriter creates a new write for the trace text format.
func NewTextWriter(w io.Writer, v version.Version) (*TextWriter, error) {
_, err := fmt.Fprintf(w, "Trace Go1.%d\n", v)
if err != nil {
return nil, err
}
return &TextWriter{w: w, v: v}, nil
}
// WriteEvent writes a single event to the stream.
func (w *TextWriter) WriteEvent(e Event) error {
// Check version.
if e.Version != w.v {
return fmt.Errorf("mismatched version between writer (go 1.%d) and event (go 1.%d)", w.v, e.Version)
}
// Write event.
_, err := fmt.Fprintln(w.w, e.String())
return err
}
| go/src/internal/trace/raw/textwriter.go/0 | {
"file_path": "go/src/internal/trace/raw/textwriter.go",
"repo_id": "go",
"token_count": 323
} | 297 |
go test fuzz v1
[]byte("go 1.22 trace\x00\x00\x00\x01\x0100\x85\x00\x1f0000\x01\x0100\x88\x00\b0000000") | go/src/internal/trace/testdata/fuzz/FuzzReader/56f073e57903588c/0 | {
"file_path": "go/src/internal/trace/testdata/fuzz/FuzzReader/56f073e57903588c",
"repo_id": "go",
"token_count": 56
} | 298 |
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Tests syscall P stealing at a generation boundary.
package main
import (
"internal/trace"
"internal/trace/event/go122"
testgen "internal/trace/internal/testgen/go122"
)
func main() {
testgen.Main(gen)
}
func gen(t *testgen.Trace) {
g := t.Generation(1)
// One goroutine is exiting with a syscall. It already
// acquired a new P.
b0 := g.Batch(trace.ThreadID(0), 0)
b0.Event("ProcStatus", trace.ProcID(1), go122.ProcRunning)
b0.Event("GoStatus", trace.GoID(1), trace.ThreadID(0), go122.GoSyscall)
b0.Event("GoSyscallEndBlocked")
// A bare M stole the goroutine's P at the generation boundary.
b1 := g.Batch(trace.ThreadID(1), 0)
b1.Event("ProcStatus", trace.ProcID(0), go122.ProcSyscallAbandoned)
b1.Event("ProcSteal", trace.ProcID(0), testgen.Seq(1), trace.ThreadID(0))
}
| go/src/internal/trace/testdata/generators/go122-syscall-steal-proc-gen-boundary-bare-m.go/0 | {
"file_path": "go/src/internal/trace/testdata/generators/go122-syscall-steal-proc-gen-boundary-bare-m.go",
"repo_id": "go",
"token_count": 360
} | 299 |
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Tests to make sure the runtime doesn't generate futile wakeups. For example,
// it makes sure that a block on a channel send that unblocks briefly only to
// immediately go back to sleep (in such a way that doesn't reveal any useful
// information, and is purely an artifact of the runtime implementation) doesn't
// make it into the trace.
//go:build ignore
package main
import (
"context"
"log"
"os"
"runtime"
"runtime/trace"
"sync"
)
func main() {
if err := trace.Start(os.Stdout); err != nil {
log.Fatalf("failed to start tracing: %v", err)
}
defer runtime.GOMAXPROCS(runtime.GOMAXPROCS(8))
c0 := make(chan int, 1)
c1 := make(chan int, 1)
c2 := make(chan int, 1)
const procs = 2
var done sync.WaitGroup
done.Add(4 * procs)
for p := 0; p < procs; p++ {
const iters = 1e3
go func() {
trace.WithRegion(context.Background(), "special", func() {
for i := 0; i < iters; i++ {
runtime.Gosched()
c0 <- 0
}
done.Done()
})
}()
go func() {
trace.WithRegion(context.Background(), "special", func() {
for i := 0; i < iters; i++ {
runtime.Gosched()
<-c0
}
done.Done()
})
}()
go func() {
trace.WithRegion(context.Background(), "special", func() {
for i := 0; i < iters; i++ {
runtime.Gosched()
select {
case c1 <- 0:
case c2 <- 0:
}
}
done.Done()
})
}()
go func() {
trace.WithRegion(context.Background(), "special", func() {
for i := 0; i < iters; i++ {
runtime.Gosched()
select {
case <-c1:
case <-c2:
}
}
done.Done()
})
}()
}
done.Wait()
trace.Stop()
}
| go/src/internal/trace/testdata/testprog/futile-wakeup.go/0 | {
"file_path": "go/src/internal/trace/testdata/testprog/futile-wakeup.go",
"repo_id": "go",
"token_count": 763
} | 300 |
-- expect --
SUCCESS
-- trace --
Trace Go1.22
EventBatch gen=1 m=0 time=0 size=17
ProcStatus dt=1 p=0 pstatus=1
GoCreate dt=1 new_g=5 new_stack=0 stack=0
GoStart dt=1 g=5 g_seq=1
GoStop dt=1 reason_string=1 stack=0
EventBatch gen=1 m=18446744073709551615 time=0 size=5
Frequency freq=15625000
EventBatch gen=1 m=18446744073709551615 time=0 size=1
Stacks
EventBatch gen=1 m=18446744073709551615 time=0 size=12
Strings
String id=1
data="whatever"
| go/src/internal/trace/testdata/tests/go122-go-create-without-running-g.test/0 | {
"file_path": "go/src/internal/trace/testdata/tests/go122-go-create-without-running-g.test",
"repo_id": "go",
"token_count": 198
} | 301 |
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package trace_test
import (
"bufio"
"bytes"
"fmt"
"internal/race"
"internal/testenv"
"internal/trace"
"internal/trace/testtrace"
"io"
"os"
"path/filepath"
"runtime"
"strings"
"testing"
)
func TestTraceAnnotations(t *testing.T) {
testTraceProg(t, "annotations.go", func(t *testing.T, tb, _ []byte, _ bool) {
type evDesc struct {
kind trace.EventKind
task trace.TaskID
args []string
}
want := []evDesc{
{trace.EventTaskBegin, trace.TaskID(1), []string{"task0"}},
{trace.EventRegionBegin, trace.TaskID(1), []string{"region0"}},
{trace.EventRegionBegin, trace.TaskID(1), []string{"region1"}},
{trace.EventLog, trace.TaskID(1), []string{"key0", "0123456789abcdef"}},
{trace.EventRegionEnd, trace.TaskID(1), []string{"region1"}},
{trace.EventRegionEnd, trace.TaskID(1), []string{"region0"}},
{trace.EventTaskEnd, trace.TaskID(1), []string{"task0"}},
// Currently, pre-existing region is not recorded to avoid allocations.
{trace.EventRegionBegin, trace.BackgroundTask, []string{"post-existing region"}},
}
r, err := trace.NewReader(bytes.NewReader(tb))
if err != nil {
t.Error(err)
}
for {
ev, err := r.ReadEvent()
if err == io.EOF {
break
}
if err != nil {
t.Fatal(err)
}
for i, wantEv := range want {
if wantEv.kind != ev.Kind() {
continue
}
match := false
switch ev.Kind() {
case trace.EventTaskBegin, trace.EventTaskEnd:
task := ev.Task()
match = task.ID == wantEv.task && task.Type == wantEv.args[0]
case trace.EventRegionBegin, trace.EventRegionEnd:
reg := ev.Region()
match = reg.Task == wantEv.task && reg.Type == wantEv.args[0]
case trace.EventLog:
log := ev.Log()
match = log.Task == wantEv.task && log.Category == wantEv.args[0] && log.Message == wantEv.args[1]
}
if match {
want[i] = want[len(want)-1]
want = want[:len(want)-1]
break
}
}
}
if len(want) != 0 {
for _, ev := range want {
t.Errorf("no match for %s TaskID=%d Args=%#v", ev.kind, ev.task, ev.args)
}
}
})
}
func TestTraceAnnotationsStress(t *testing.T) {
testTraceProg(t, "annotations-stress.go", nil)
}
func TestTraceCgoCallback(t *testing.T) {
testenv.MustHaveCGO(t)
switch runtime.GOOS {
case "plan9", "windows":
t.Skipf("cgo callback test requires pthreads and is not supported on %s", runtime.GOOS)
}
testTraceProg(t, "cgo-callback.go", nil)
}
func TestTraceCPUProfile(t *testing.T) {
testTraceProg(t, "cpu-profile.go", func(t *testing.T, tb, stderr []byte, _ bool) {
// Parse stderr which has a CPU profile summary, if everything went well.
// (If it didn't, we shouldn't even make it here.)
scanner := bufio.NewScanner(bytes.NewReader(stderr))
pprofSamples := 0
pprofStacks := make(map[string]int)
for scanner.Scan() {
var stack string
var samples int
_, err := fmt.Sscanf(scanner.Text(), "%s\t%d", &stack, &samples)
if err != nil {
t.Fatalf("failed to parse CPU profile summary in stderr: %s\n\tfull:\n%s", scanner.Text(), stderr)
}
pprofStacks[stack] = samples
pprofSamples += samples
}
if err := scanner.Err(); err != nil {
t.Fatalf("failed to parse CPU profile summary in stderr: %v", err)
}
if pprofSamples == 0 {
t.Skip("CPU profile did not include any samples while tracing was active")
}
// Examine the execution tracer's view of the CPU profile samples. Filter it
// to only include samples from the single test goroutine. Use the goroutine
// ID that was recorded in the events: that should reflect getg().m.curg,
// same as the profiler's labels (even when the M is using its g0 stack).
totalTraceSamples := 0
traceSamples := 0
traceStacks := make(map[string]int)
r, err := trace.NewReader(bytes.NewReader(tb))
if err != nil {
t.Error(err)
}
var hogRegion *trace.Event
var hogRegionClosed bool
for {
ev, err := r.ReadEvent()
if err == io.EOF {
break
}
if err != nil {
t.Fatal(err)
}
if ev.Kind() == trace.EventRegionBegin && ev.Region().Type == "cpuHogger" {
hogRegion = &ev
}
if ev.Kind() == trace.EventStackSample {
totalTraceSamples++
if hogRegion != nil && ev.Goroutine() == hogRegion.Goroutine() {
traceSamples++
var fns []string
ev.Stack().Frames(func(frame trace.StackFrame) bool {
if frame.Func != "runtime.goexit" {
fns = append(fns, fmt.Sprintf("%s:%d", frame.Func, frame.Line))
}
return true
})
stack := strings.Join(fns, "|")
traceStacks[stack]++
}
}
if ev.Kind() == trace.EventRegionEnd && ev.Region().Type == "cpuHogger" {
hogRegionClosed = true
}
}
if hogRegion == nil {
t.Fatalf("execution trace did not identify cpuHogger goroutine")
} else if !hogRegionClosed {
t.Fatalf("execution trace did not close cpuHogger region")
}
// The execution trace may drop CPU profile samples if the profiling buffer
// overflows. Based on the size of profBufWordCount, that takes a bit over
// 1900 CPU samples or 19 thread-seconds at a 100 Hz sample rate. If we've
// hit that case, then we definitely have at least one full buffer's worth
// of CPU samples, so we'll call that success.
overflowed := totalTraceSamples >= 1900
if traceSamples < pprofSamples {
t.Logf("execution trace did not include all CPU profile samples; %d in profile, %d in trace", pprofSamples, traceSamples)
if !overflowed {
t.Fail()
}
}
for stack, traceSamples := range traceStacks {
pprofSamples := pprofStacks[stack]
delete(pprofStacks, stack)
if traceSamples < pprofSamples {
t.Logf("execution trace did not include all CPU profile samples for stack %q; %d in profile, %d in trace",
stack, pprofSamples, traceSamples)
if !overflowed {
t.Fail()
}
}
}
for stack, pprofSamples := range pprofStacks {
t.Logf("CPU profile included %d samples at stack %q not present in execution trace", pprofSamples, stack)
if !overflowed {
t.Fail()
}
}
if t.Failed() {
t.Logf("execution trace CPU samples:")
for stack, samples := range traceStacks {
t.Logf("%d: %q", samples, stack)
}
t.Logf("CPU profile:\n%s", stderr)
}
})
}
func TestTraceFutileWakeup(t *testing.T) {
testTraceProg(t, "futile-wakeup.go", func(t *testing.T, tb, _ []byte, _ bool) {
// Check to make sure that no goroutine in the "special" trace region
// ends up blocking, unblocking, then immediately blocking again.
//
// The goroutines are careful to call runtime.Gosched in between blocking,
// so there should never be a clean block/unblock on the goroutine unless
// the runtime was generating extraneous events.
const (
entered = iota
blocked
runnable
running
)
gs := make(map[trace.GoID]int)
seenSpecialGoroutines := false
r, err := trace.NewReader(bytes.NewReader(tb))
if err != nil {
t.Error(err)
}
for {
ev, err := r.ReadEvent()
if err == io.EOF {
break
}
if err != nil {
t.Fatal(err)
}
// Only track goroutines in the special region we control, so runtime
// goroutines don't interfere (it's totally valid in traces for a
// goroutine to block, run, and block again; that's not what we care about).
if ev.Kind() == trace.EventRegionBegin && ev.Region().Type == "special" {
seenSpecialGoroutines = true
gs[ev.Goroutine()] = entered
}
if ev.Kind() == trace.EventRegionEnd && ev.Region().Type == "special" {
delete(gs, ev.Goroutine())
}
// Track state transitions for goroutines we care about.
//
// The goroutines we care about will advance through the state machine
// of entered -> blocked -> runnable -> running. If in the running state
// we block, then we have a futile wakeup. Because of the runtime.Gosched
// on these specially marked goroutines, we should end up back in runnable
// first. If at any point we go to a different state, switch back to entered
// and wait for the next time the goroutine blocks.
if ev.Kind() != trace.EventStateTransition {
continue
}
st := ev.StateTransition()
if st.Resource.Kind != trace.ResourceGoroutine {
continue
}
id := st.Resource.Goroutine()
state, ok := gs[id]
if !ok {
continue
}
_, new := st.Goroutine()
switch state {
case entered:
if new == trace.GoWaiting {
state = blocked
} else {
state = entered
}
case blocked:
if new == trace.GoRunnable {
state = runnable
} else {
state = entered
}
case runnable:
if new == trace.GoRunning {
state = running
} else {
state = entered
}
case running:
if new == trace.GoWaiting {
t.Fatalf("found futile wakeup on goroutine %d", id)
} else {
state = entered
}
}
gs[id] = state
}
if !seenSpecialGoroutines {
t.Fatal("did not see a goroutine in a the region 'special'")
}
})
}
func TestTraceGCStress(t *testing.T) {
testTraceProg(t, "gc-stress.go", nil)
}
func TestTraceGOMAXPROCS(t *testing.T) {
testTraceProg(t, "gomaxprocs.go", nil)
}
func TestTraceStacks(t *testing.T) {
testTraceProg(t, "stacks.go", func(t *testing.T, tb, _ []byte, stress bool) {
type frame struct {
fn string
line int
}
type evDesc struct {
kind trace.EventKind
match string
frames []frame
}
// mainLine is the line number of `func main()` in testprog/stacks.go.
const mainLine = 21
want := []evDesc{
{trace.EventStateTransition, "Goroutine Running->Runnable", []frame{
{"main.main", mainLine + 82},
}},
{trace.EventStateTransition, "Goroutine NotExist->Runnable", []frame{
{"main.main", mainLine + 11},
}},
{trace.EventStateTransition, "Goroutine Running->Waiting", []frame{
{"runtime.block", 0},
{"main.main.func1", 0},
}},
{trace.EventStateTransition, "Goroutine Running->Waiting", []frame{
{"runtime.chansend1", 0},
{"main.main.func2", 0},
}},
{trace.EventStateTransition, "Goroutine Running->Waiting", []frame{
{"runtime.chanrecv1", 0},
{"main.main.func3", 0},
}},
{trace.EventStateTransition, "Goroutine Running->Waiting", []frame{
{"runtime.chanrecv1", 0},
{"main.main.func4", 0},
}},
{trace.EventStateTransition, "Goroutine Waiting->Runnable", []frame{
{"runtime.chansend1", 0},
{"main.main", mainLine + 84},
}},
{trace.EventStateTransition, "Goroutine Running->Waiting", []frame{
{"runtime.chansend1", 0},
{"main.main.func5", 0},
}},
{trace.EventStateTransition, "Goroutine Waiting->Runnable", []frame{
{"runtime.chanrecv1", 0},
{"main.main", mainLine + 85},
}},
{trace.EventStateTransition, "Goroutine Running->Waiting", []frame{
{"runtime.selectgo", 0},
{"main.main.func6", 0},
}},
{trace.EventStateTransition, "Goroutine Waiting->Runnable", []frame{
{"runtime.selectgo", 0},
{"main.main", mainLine + 86},
}},
{trace.EventStateTransition, "Goroutine Running->Waiting", []frame{
{"sync.(*Mutex).Lock", 0},
{"main.main.func7", 0},
}},
{trace.EventStateTransition, "Goroutine Waiting->Runnable", []frame{
{"sync.(*Mutex).Unlock", 0},
{"main.main", 0},
}},
{trace.EventStateTransition, "Goroutine Running->Waiting", []frame{
{"sync.(*WaitGroup).Wait", 0},
{"main.main.func8", 0},
}},
{trace.EventStateTransition, "Goroutine Waiting->Runnable", []frame{
{"sync.(*WaitGroup).Add", 0},
{"sync.(*WaitGroup).Done", 0},
{"main.main", mainLine + 91},
}},
{trace.EventStateTransition, "Goroutine Running->Waiting", []frame{
{"sync.(*Cond).Wait", 0},
{"main.main.func9", 0},
}},
{trace.EventStateTransition, "Goroutine Waiting->Runnable", []frame{
{"sync.(*Cond).Signal", 0},
{"main.main", 0},
}},
{trace.EventStateTransition, "Goroutine Running->Waiting", []frame{
{"time.Sleep", 0},
{"main.main", 0},
}},
{trace.EventMetric, "/sched/gomaxprocs:threads", []frame{
{"runtime.startTheWorld", 0}, // this is when the current gomaxprocs is logged.
{"runtime.startTheWorldGC", 0},
{"runtime.GOMAXPROCS", 0},
{"main.main", 0},
}},
}
if !stress {
// Only check for this stack if !stress because traceAdvance alone could
// allocate enough memory to trigger a GC if called frequently enough.
// This might cause the runtime.GC call we're trying to match against to
// coalesce with an active GC triggered this by traceAdvance. In that case
// we won't have an EventRangeBegin event that matches the stace trace we're
// looking for, since runtime.GC will not have triggered the GC.
gcEv := evDesc{trace.EventRangeBegin, "GC concurrent mark phase", []frame{
{"runtime.GC", 0},
{"main.main", 0},
}}
want = append(want, gcEv)
}
if runtime.GOOS != "windows" && runtime.GOOS != "plan9" {
want = append(want, []evDesc{
{trace.EventStateTransition, "Goroutine Running->Waiting", []frame{
{"internal/poll.(*FD).Accept", 0},
{"net.(*netFD).accept", 0},
{"net.(*TCPListener).accept", 0},
{"net.(*TCPListener).Accept", 0},
{"main.main.func10", 0},
}},
{trace.EventStateTransition, "Goroutine Running->Syscall", []frame{
{"syscall.read", 0},
{"syscall.Read", 0},
{"internal/poll.ignoringEINTRIO", 0},
{"internal/poll.(*FD).Read", 0},
{"os.(*File).read", 0},
{"os.(*File).Read", 0},
{"main.main.func11", 0},
}},
}...)
}
stackMatches := func(stk trace.Stack, frames []frame) bool {
i := 0
match := true
stk.Frames(func(f trace.StackFrame) bool {
if f.Func != frames[i].fn {
match = false
return false
}
if line := uint64(frames[i].line); line != 0 && line != f.Line {
match = false
return false
}
i++
return true
})
return match
}
r, err := trace.NewReader(bytes.NewReader(tb))
if err != nil {
t.Error(err)
}
for {
ev, err := r.ReadEvent()
if err == io.EOF {
break
}
if err != nil {
t.Fatal(err)
}
for i, wantEv := range want {
if wantEv.kind != ev.Kind() {
continue
}
match := false
switch ev.Kind() {
case trace.EventStateTransition:
st := ev.StateTransition()
str := ""
switch st.Resource.Kind {
case trace.ResourceGoroutine:
old, new := st.Goroutine()
str = fmt.Sprintf("%s %s->%s", st.Resource.Kind, old, new)
}
match = str == wantEv.match
case trace.EventRangeBegin:
rng := ev.Range()
match = rng.Name == wantEv.match
case trace.EventMetric:
metric := ev.Metric()
match = metric.Name == wantEv.match
}
match = match && stackMatches(ev.Stack(), wantEv.frames)
if match {
want[i] = want[len(want)-1]
want = want[:len(want)-1]
break
}
}
}
if len(want) != 0 {
for _, ev := range want {
t.Errorf("no match for %s Match=%s Stack=%#v", ev.kind, ev.match, ev.frames)
}
}
})
}
func TestTraceStress(t *testing.T) {
switch runtime.GOOS {
case "js", "wasip1":
t.Skip("no os.Pipe on " + runtime.GOOS)
}
testTraceProg(t, "stress.go", checkReaderDeterminism)
}
func TestTraceStressStartStop(t *testing.T) {
switch runtime.GOOS {
case "js", "wasip1":
t.Skip("no os.Pipe on " + runtime.GOOS)
}
testTraceProg(t, "stress-start-stop.go", nil)
}
func TestTraceManyStartStop(t *testing.T) {
testTraceProg(t, "many-start-stop.go", nil)
}
func TestTraceWaitOnPipe(t *testing.T) {
switch runtime.GOOS {
case "dragonfly", "freebsd", "linux", "netbsd", "openbsd", "solaris":
testTraceProg(t, "wait-on-pipe.go", nil)
return
}
t.Skip("no applicable syscall.Pipe on " + runtime.GOOS)
}
func TestTraceIterPull(t *testing.T) {
testTraceProg(t, "iter-pull.go", nil)
}
func checkReaderDeterminism(t *testing.T, tb, _ []byte, _ bool) {
events := func() []trace.Event {
var evs []trace.Event
r, err := trace.NewReader(bytes.NewReader(tb))
if err != nil {
t.Error(err)
}
for {
ev, err := r.ReadEvent()
if err == io.EOF {
break
}
if err != nil {
t.Fatal(err)
}
evs = append(evs, ev)
}
return evs
}
evs1 := events()
evs2 := events()
if l1, l2 := len(evs1), len(evs2); l1 != l2 {
t.Fatalf("re-reading trace gives different event count (%d != %d)", l1, l2)
}
for i, ev1 := range evs1 {
ev2 := evs2[i]
if s1, s2 := ev1.String(), ev2.String(); s1 != s2 {
t.Errorf("re-reading trace gives different event %d:\n%s\n%s\n", i, s1, s2)
break
}
}
}
func testTraceProg(t *testing.T, progName string, extra func(t *testing.T, trace, stderr []byte, stress bool)) {
testenv.MustHaveGoRun(t)
// Check if we're on a builder.
onBuilder := testenv.Builder() != ""
onOldBuilder := !strings.Contains(testenv.Builder(), "gotip") && !strings.Contains(testenv.Builder(), "go1")
testPath := filepath.Join("./testdata/testprog", progName)
testName := progName
runTest := func(t *testing.T, stress bool, extraGODEBUG string) {
// Run the program and capture the trace, which is always written to stdout.
cmd := testenv.Command(t, testenv.GoToolPath(t), "run")
if race.Enabled {
cmd.Args = append(cmd.Args, "-race")
}
cmd.Args = append(cmd.Args, testPath)
cmd.Env = append(os.Environ(), "GOEXPERIMENT=rangefunc")
// Add a stack ownership check. This is cheap enough for testing.
godebug := "tracecheckstackownership=1"
if stress {
// Advance a generation constantly to stress the tracer.
godebug += ",traceadvanceperiod=0"
}
if extraGODEBUG != "" {
// Add extra GODEBUG flags.
godebug += "," + extraGODEBUG
}
cmd.Env = append(cmd.Env, "GODEBUG="+godebug)
// Capture stdout and stderr.
//
// The protocol for these programs is that stdout contains the trace data
// and stderr is an expectation in string format.
var traceBuf, errBuf bytes.Buffer
cmd.Stdout = &traceBuf
cmd.Stderr = &errBuf
// Run the program.
if err := cmd.Run(); err != nil {
if errBuf.Len() != 0 {
t.Logf("stderr: %s", string(errBuf.Bytes()))
}
t.Fatal(err)
}
tb := traceBuf.Bytes()
// Test the trace and the parser.
testReader(t, bytes.NewReader(tb), testtrace.ExpectSuccess())
// Run some extra validation.
if !t.Failed() && extra != nil {
extra(t, tb, errBuf.Bytes(), stress)
}
// Dump some more information on failure.
if t.Failed() && onBuilder {
// Dump directly to the test log on the builder, since this
// data is critical for debugging and this is the only way
// we can currently make sure it's retained.
t.Log("found bad trace; dumping to test log...")
s := dumpTraceToText(t, tb)
if onOldBuilder && len(s) > 1<<20+512<<10 {
// The old build infrastructure truncates logs at ~2 MiB.
// Let's assume we're the only failure and give ourselves
// up to 1.5 MiB to dump the trace.
//
// TODO(mknyszek): Remove this when we've migrated off of
// the old infrastructure.
t.Logf("text trace too large to dump (%d bytes)", len(s))
} else {
t.Log(s)
}
} else if t.Failed() || *dumpTraces {
// We asked to dump the trace or failed. Write the trace to a file.
t.Logf("wrote trace to file: %s", dumpTraceToFile(t, testName, stress, tb))
}
}
t.Run("Default", func(t *testing.T) {
runTest(t, false, "")
})
t.Run("Stress", func(t *testing.T) {
if testing.Short() {
t.Skip("skipping trace stress tests in short mode")
}
runTest(t, true, "")
})
t.Run("AllocFree", func(t *testing.T) {
if testing.Short() {
t.Skip("skipping trace alloc/free tests in short mode")
}
runTest(t, false, "traceallocfree=1")
})
}
| go/src/internal/trace/trace_test.go/0 | {
"file_path": "go/src/internal/trace/trace_test.go",
"repo_id": "go",
"token_count": 8212
} | 302 |
//go:build ignore
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// generrordocs creates a Markdown file for each (compiler) error code
// and its associated documentation.
// Note: this program must be run in this directory.
// go run generrordocs.go <dir>
//go:generate go run generrordocs.go errors_markdown
package main
import (
"bytes"
"fmt"
"go/ast"
"go/importer"
"go/parser"
"go/token"
"log"
"os"
"path"
"strings"
"text/template"
. "go/types"
)
func main() {
if len(os.Args) != 2 {
log.Fatal("missing argument: generrordocs <dir>")
}
outDir := os.Args[1]
if err := os.MkdirAll(outDir, 0755); err != nil {
log.Fatal("unable to create output directory: %s", err)
}
walkCodes(func(name string, vs *ast.ValueSpec) {
// ignore unused errors
if name == "_" {
return
}
// Ensure that < are represented correctly when its included in code
// blocks. The goldmark Markdown parser converts them to &lt;
// when not escaped. It is the only known string with this issue.
desc := strings.ReplaceAll(vs.Doc.Text(), "<", `{{raw "<"}}`)
e := struct {
Name string
Description string
}{
Name: name,
Description: fmt.Sprintf("```\n%s```\n", desyc),
}
var buf bytes.Buffer
err := template.Must(template.New("eachError").Parse(markdownTemplate)).Execute(&buf, e)
if err != nil {
log.Fatalf("template.Must: %s", err)
}
if err := os.WriteFile(path.Join(outDir, name+".md"), buf.Bytes(), 0660); err != nil {
log.Fatalf("os.WriteFile: %s\n", err)
}
})
log.Printf("output directory: %s\n", outDir)
}
func walkCodes(f func(string, *ast.ValueSpec)) {
fset := token.NewFileSet()
file, err := parser.ParseFile(fset, "codes.go", nil, parser.ParseComments)
if err != nil {
log.Fatalf("ParseFile failed: %s", err)
}
conf := Config{Importer: importer.Default()}
info := &Info{
Types: make(map[ast.Expr]TypeAndValue),
Defs: make(map[*ast.Ident]Object),
Uses: make(map[*ast.Ident]Object),
}
_, err = conf.Check("types", fset, []*ast.File{file}, info)
if err != nil {
log.Fatalf("Check failed: %s", err)
}
for _, decl := range file.Decls {
decl, ok := decl.(*ast.GenDecl)
if !ok || decl.Tok != token.CONST {
continue
}
for _, spec := range decl.Specs {
spec, ok := spec.(*ast.ValueSpec)
if !ok || len(spec.Names) == 0 {
continue
}
obj := info.ObjectOf(spec.Names[0])
if named, ok := obj.Type().(*Named); ok && named.Obj().Name() == "Code" {
if len(spec.Names) != 1 {
log.Fatalf("bad Code declaration for %q: got %d names, want exactly 1", spec.Names[0].Name, len(spec.Names))
}
codename := spec.Names[0].Name
f(codename, spec)
}
}
}
}
const markdownTemplate = `---
title: {{.Name}}
layout: article
---
<!-- Copyright 2023 The Go Authors. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file. -->
<!-- Code generated by generrordocs.go; DO NOT EDIT. -->
{{.Description}}
`
| go/src/internal/types/errors/generrordocs.go/0 | {
"file_path": "go/src/internal/types/errors/generrordocs.go",
"repo_id": "go",
"token_count": 1232
} | 303 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.